babylon.max.js 4.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980929819298292983929849298592986929879298892989929909299192992929939299492995929969299792998929999300093001930029300393004930059300693007930089300993010930119301293013930149301593016930179301893019930209302193022930239302493025930269302793028930299303093031930329303393034930359303693037930389303993040930419304293043930449304593046930479304893049930509305193052930539305493055930569305793058930599306093061930629306393064930659306693067930689306993070930719307293073930749307593076930779307893079930809308193082930839308493085930869308793088930899309093091930929309393094930959309693097930989309993100931019310293103931049310593106931079310893109931109311193112931139311493115931169311793118931199312093121931229312393124931259312693127931289312993130931319313293133931349313593136931379313893139931409314193142931439314493145931469314793148931499315093151931529315393154931559315693157931589315993160931619316293163931649316593166931679316893169931709317193172931739317493175931769317793178931799318093181931829318393184931859318693187931889318993190931919319293193931949319593196931979319893199932009320193202932039320493205932069320793208932099321093211932129321393214932159321693217932189321993220932219322293223932249322593226932279322893229932309323193232932339323493235932369323793238932399324093241932429324393244932459324693247932489324993250932519325293253932549325593256932579325893259932609326193262932639326493265932669326793268932699327093271932729327393274932759327693277932789327993280932819328293283932849328593286932879328893289932909329193292932939329493295932969329793298932999330093301933029330393304933059330693307933089330993310933119331293313933149331593316933179331893319933209332193322933239332493325933269332793328933299333093331933329333393334933359333693337933389333993340933419334293343933449334593346933479334893349933509335193352933539335493355933569335793358933599336093361933629336393364933659336693367933689336993370933719337293373933749337593376933779337893379933809338193382933839338493385933869338793388933899339093391933929339393394933959339693397933989339993400934019340293403934049340593406934079340893409934109341193412934139341493415934169341793418934199342093421934229342393424934259342693427934289342993430934319343293433934349343593436934379343893439934409344193442934439344493445934469344793448934499345093451934529345393454934559345693457934589345993460934619346293463934649346593466934679346893469934709347193472934739347493475934769347793478934799348093481934829348393484934859348693487934889348993490934919349293493934949349593496934979349893499935009350193502935039350493505935069350793508935099351093511935129351393514935159351693517935189351993520935219352293523935249352593526935279352893529935309353193532935339353493535935369353793538935399354093541935429354393544935459354693547935489354993550935519355293553935549355593556935579355893559935609356193562935639356493565935669356793568935699357093571935729357393574935759357693577935789357993580935819358293583935849358593586935879358893589935909359193592935939359493595935969359793598935999360093601936029360393604936059360693607936089360993610936119361293613936149361593616936179361893619936209362193622936239362493625936269362793628936299363093631936329363393634936359363693637936389363993640936419364293643936449364593646936479364893649936509365193652936539365493655936569365793658936599366093661936629366393664936659366693667936689366993670936719367293673936749367593676936779367893679936809368193682936839368493685936869368793688936899369093691936929369393694936959369693697936989369993700937019370293703937049370593706937079370893709937109371193712937139371493715937169371793718937199372093721937229372393724937259372693727937289372993730937319373293733937349373593736937379373893739937409374193742937439374493745937469374793748937499375093751937529375393754937559375693757937589375993760937619376293763937649376593766937679376893769937709377193772937739377493775937769377793778937799378093781937829378393784937859378693787937889378993790937919379293793937949379593796937979379893799938009380193802938039380493805938069380793808938099381093811938129381393814938159381693817938189381993820938219382293823938249382593826938279382893829938309383193832938339383493835938369383793838938399384093841938429384393844938459384693847938489384993850938519385293853938549385593856938579385893859938609386193862938639386493865938669386793868938699387093871938729387393874938759387693877938789387993880938819388293883938849388593886938879388893889938909389193892938939389493895938969389793898938999390093901939029390393904939059390693907939089390993910939119391293913939149391593916939179391893919939209392193922939239392493925939269392793928939299393093931939329393393934939359393693937939389393993940939419394293943939449394593946939479394893949939509395193952939539395493955939569395793958939599396093961939629396393964939659396693967939689396993970939719397293973939749397593976939779397893979939809398193982939839398493985939869398793988939899399093991939929399393994939959399693997939989399994000940019400294003940049400594006940079400894009940109401194012940139401494015940169401794018940199402094021940229402394024940259402694027940289402994030940319403294033940349403594036940379403894039940409404194042940439404494045940469404794048940499405094051940529405394054940559405694057940589405994060940619406294063940649406594066940679406894069940709407194072940739407494075940769407794078940799408094081940829408394084940859408694087940889408994090940919409294093940949409594096940979409894099941009410194102941039410494105941069410794108941099411094111941129411394114941159411694117941189411994120941219412294123941249412594126941279412894129941309413194132941339413494135941369413794138941399414094141941429414394144941459414694147941489414994150941519415294153941549415594156941579415894159941609416194162941639416494165941669416794168941699417094171941729417394174941759417694177941789417994180941819418294183941849418594186941879418894189941909419194192941939419494195941969419794198941999420094201942029420394204942059420694207942089420994210942119421294213942149421594216942179421894219942209422194222942239422494225942269422794228942299423094231942329423394234942359423694237942389423994240942419424294243942449424594246942479424894249942509425194252942539425494255942569425794258942599426094261942629426394264942659426694267942689426994270942719427294273942749427594276942779427894279942809428194282942839428494285942869428794288942899429094291942929429394294942959429694297942989429994300943019430294303943049430594306943079430894309943109431194312943139431494315943169431794318943199432094321943229432394324943259432694327943289432994330943319433294333943349433594336943379433894339943409434194342943439434494345943469434794348943499435094351943529435394354943559435694357943589435994360943619436294363943649436594366943679436894369943709437194372943739437494375943769437794378943799438094381943829438394384943859438694387943889438994390943919439294393943949439594396943979439894399944009440194402944039440494405944069440794408944099441094411944129441394414944159441694417944189441994420944219442294423944249442594426944279442894429944309443194432944339443494435944369443794438944399444094441944429444394444944459444694447944489444994450944519445294453944549445594456944579445894459944609446194462944639446494465944669446794468944699447094471944729447394474944759447694477944789447994480944819448294483944849448594486944879448894489944909449194492944939449494495944969449794498944999450094501945029450394504945059450694507945089450994510945119451294513945149451594516945179451894519945209452194522945239452494525945269452794528945299453094531945329453394534945359453694537945389453994540945419454294543945449454594546945479454894549945509455194552945539455494555945569455794558945599456094561945629456394564945659456694567945689456994570945719457294573945749457594576945779457894579945809458194582945839458494585945869458794588945899459094591945929459394594945959459694597945989459994600946019460294603946049460594606946079460894609946109461194612946139461494615946169461794618946199462094621946229462394624946259462694627946289462994630946319463294633946349463594636946379463894639946409464194642946439464494645946469464794648946499465094651946529465394654946559465694657946589465994660946619466294663946649466594666946679466894669946709467194672946739467494675946769467794678946799468094681946829468394684946859468694687946889468994690946919469294693946949469594696946979469894699947009470194702947039470494705947069470794708947099471094711947129471394714947159471694717947189471994720947219472294723947249472594726947279472894729947309473194732947339473494735947369473794738947399474094741947429474394744947459474694747947489474994750947519475294753947549475594756947579475894759947609476194762947639476494765947669476794768947699477094771947729477394774947759477694777947789477994780947819478294783947849478594786947879478894789947909479194792947939479494795947969479794798947999480094801948029480394804948059480694807948089480994810948119481294813948149481594816948179481894819948209482194822948239482494825948269482794828948299483094831948329483394834948359483694837948389483994840948419484294843948449484594846948479484894849948509485194852948539485494855948569485794858948599486094861948629486394864948659486694867948689486994870948719487294873948749487594876948779487894879948809488194882948839488494885948869488794888948899489094891948929489394894948959489694897948989489994900949019490294903949049490594906949079490894909949109491194912949139491494915949169491794918949199492094921949229492394924949259492694927949289492994930949319493294933949349493594936949379493894939949409494194942949439494494945949469494794948949499495094951949529495394954949559495694957949589495994960949619496294963949649496594966949679496894969949709497194972949739497494975949769497794978949799498094981949829498394984949859498694987949889498994990949919499294993949949499594996949979499894999950009500195002950039500495005950069500795008950099501095011950129501395014950159501695017950189501995020950219502295023950249502595026950279502895029950309503195032950339503495035950369503795038950399504095041950429504395044950459504695047950489504995050950519505295053950549505595056950579505895059950609506195062950639506495065950669506795068950699507095071950729507395074950759507695077950789507995080950819508295083950849508595086950879508895089950909509195092950939509495095950969509795098950999510095101951029510395104951059510695107951089510995110951119511295113951149511595116951179511895119951209512195122951239512495125951269512795128951299513095131951329513395134951359513695137951389513995140951419514295143951449514595146951479514895149951509515195152951539515495155951569515795158951599516095161951629516395164951659516695167951689516995170951719517295173951749517595176951779517895179951809518195182951839518495185951869518795188951899519095191951929519395194951959519695197951989519995200952019520295203952049520595206952079520895209952109521195212952139521495215952169521795218952199522095221952229522395224952259522695227952289522995230952319523295233952349523595236952379523895239952409524195242952439524495245952469524795248952499525095251952529525395254952559525695257952589525995260952619526295263952649526595266952679526895269952709527195272952739527495275952769527795278952799528095281952829528395284952859528695287952889528995290952919529295293952949529595296952979529895299953009530195302953039530495305953069530795308953099531095311953129531395314953159531695317953189531995320953219532295323953249532595326953279532895329953309533195332953339533495335953369533795338953399534095341953429534395344953459534695347953489534995350953519535295353953549535595356953579535895359953609536195362953639536495365953669536795368953699537095371953729537395374953759537695377953789537995380953819538295383953849538595386953879538895389953909539195392953939539495395953969539795398953999540095401954029540395404954059540695407954089540995410954119541295413954149541595416954179541895419954209542195422954239542495425954269542795428954299543095431954329543395434954359543695437954389543995440954419544295443954449544595446954479544895449954509545195452954539545495455954569545795458954599546095461954629546395464954659546695467954689546995470954719547295473954749547595476954779547895479954809548195482954839548495485954869548795488954899549095491954929549395494954959549695497954989549995500955019550295503955049550595506955079550895509955109551195512955139551495515955169551795518955199552095521955229552395524955259552695527955289552995530955319553295533955349553595536955379553895539955409554195542955439554495545955469554795548955499555095551955529555395554955559555695557955589555995560955619556295563955649556595566955679556895569955709557195572955739557495575955769557795578955799558095581955829558395584955859558695587955889558995590955919559295593955949559595596955979559895599956009560195602956039560495605956069560795608956099561095611956129561395614956159561695617956189561995620956219562295623956249562595626956279562895629956309563195632956339563495635956369563795638956399564095641956429564395644956459564695647956489564995650956519565295653956549565595656956579565895659956609566195662956639566495665956669566795668956699567095671956729567395674956759567695677956789567995680956819568295683956849568595686956879568895689956909569195692956939569495695956969569795698956999570095701957029570395704957059570695707957089570995710957119571295713957149571595716957179571895719957209572195722957239572495725957269572795728957299573095731957329573395734957359573695737957389573995740957419574295743957449574595746957479574895749957509575195752957539575495755957569575795758957599576095761957629576395764957659576695767957689576995770957719577295773957749577595776957779577895779957809578195782957839578495785957869578795788957899579095791957929579395794957959579695797957989579995800958019580295803958049580595806958079580895809958109581195812958139581495815958169581795818958199582095821958229582395824958259582695827958289582995830958319583295833958349583595836958379583895839958409584195842958439584495845958469584795848958499585095851958529585395854958559585695857958589585995860958619586295863958649586595866958679586895869958709587195872958739587495875958769587795878958799588095881958829588395884958859588695887958889588995890958919589295893958949589595896958979589895899959009590195902959039590495905959069590795908959099591095911959129591395914959159591695917959189591995920959219592295923959249592595926959279592895929959309593195932959339593495935959369593795938959399594095941959429594395944959459594695947959489594995950959519595295953959549595595956959579595895959959609596195962959639596495965959669596795968959699597095971959729597395974959759597695977959789597995980959819598295983959849598595986959879598895989959909599195992959939599495995959969599795998959999600096001960029600396004960059600696007960089600996010960119601296013960149601596016960179601896019960209602196022960239602496025960269602796028960299603096031960329603396034960359603696037960389603996040960419604296043960449604596046960479604896049960509605196052960539605496055960569605796058960599606096061960629606396064960659606696067960689606996070960719607296073960749607596076960779607896079960809608196082960839608496085960869608796088960899609096091960929609396094960959609696097960989609996100961019610296103961049610596106961079610896109961109611196112961139611496115961169611796118961199612096121961229612396124961259612696127961289612996130961319613296133961349613596136961379613896139961409614196142961439614496145961469614796148961499615096151961529615396154961559615696157961589615996160961619616296163961649616596166961679616896169961709617196172961739617496175961769617796178961799618096181961829618396184961859618696187961889618996190961919619296193961949619596196961979619896199962009620196202962039620496205962069620796208962099621096211962129621396214962159621696217962189621996220962219622296223962249622596226962279622896229962309623196232962339623496235962369623796238962399624096241962429624396244962459624696247962489624996250962519625296253962549625596256962579625896259962609626196262962639626496265962669626796268962699627096271962729627396274962759627696277962789627996280962819628296283962849628596286962879628896289962909629196292962939629496295962969629796298962999630096301963029630396304963059630696307963089630996310963119631296313963149631596316963179631896319963209632196322963239632496325963269632796328963299633096331963329633396334963359633696337963389633996340963419634296343963449634596346963479634896349963509635196352963539635496355963569635796358963599636096361963629636396364963659636696367963689636996370963719637296373963749637596376963779637896379963809638196382963839638496385963869638796388963899639096391963929639396394963959639696397963989639996400964019640296403964049640596406964079640896409964109641196412964139641496415964169641796418964199642096421964229642396424964259642696427964289642996430964319643296433964349643596436964379643896439964409644196442964439644496445964469644796448964499645096451964529645396454964559645696457964589645996460964619646296463964649646596466964679646896469964709647196472964739647496475964769647796478964799648096481964829648396484964859648696487964889648996490964919649296493964949649596496964979649896499965009650196502965039650496505965069650796508965099651096511965129651396514965159651696517965189651996520965219652296523965249652596526965279652896529965309653196532965339653496535965369653796538965399654096541965429654396544965459654696547965489654996550965519655296553965549655596556965579655896559965609656196562965639656496565965669656796568965699657096571965729657396574965759657696577965789657996580965819658296583965849658596586965879658896589965909659196592965939659496595965969659796598965999660096601966029660396604966059660696607966089660996610966119661296613966149661596616966179661896619966209662196622966239662496625966269662796628966299663096631966329663396634966359663696637966389663996640966419664296643966449664596646966479664896649966509665196652966539665496655966569665796658966599666096661966629666396664966659666696667966689666996670966719667296673966749667596676966779667896679966809668196682966839668496685966869668796688966899669096691966929669396694966959669696697966989669996700967019670296703967049670596706967079670896709967109671196712967139671496715967169671796718967199672096721967229672396724967259672696727967289672996730967319673296733967349673596736967379673896739967409674196742967439674496745967469674796748967499675096751967529675396754967559675696757967589675996760967619676296763967649676596766967679676896769967709677196772967739677496775967769677796778967799678096781967829678396784967859678696787967889678996790967919679296793967949679596796967979679896799968009680196802968039680496805968069680796808968099681096811968129681396814968159681696817968189681996820968219682296823968249682596826968279682896829968309683196832968339683496835968369683796838968399684096841968429684396844968459684696847968489684996850968519685296853968549685596856968579685896859968609686196862968639686496865968669686796868968699687096871968729687396874968759687696877968789687996880968819688296883968849688596886968879688896889968909689196892968939689496895968969689796898968999690096901969029690396904969059690696907969089690996910969119691296913969149691596916969179691896919969209692196922969239692496925969269692796928969299693096931969329693396934969359693696937969389693996940969419694296943969449694596946969479694896949969509695196952969539695496955969569695796958969599696096961969629696396964969659696696967969689696996970969719697296973969749697596976969779697896979969809698196982969839698496985969869698796988969899699096991969929699396994969959699696997969989699997000970019700297003970049700597006970079700897009970109701197012970139701497015970169701797018970199702097021970229702397024970259702697027970289702997030970319703297033970349703597036970379703897039970409704197042970439704497045970469704797048970499705097051970529705397054970559705697057970589705997060970619706297063970649706597066970679706897069970709707197072970739707497075970769707797078970799708097081970829708397084970859708697087970889708997090970919709297093970949709597096970979709897099971009710197102971039710497105971069710797108971099711097111971129711397114971159711697117971189711997120971219712297123971249712597126971279712897129971309713197132971339713497135971369713797138971399714097141971429714397144971459714697147971489714997150971519715297153971549715597156971579715897159971609716197162971639716497165971669716797168971699717097171971729717397174971759717697177971789717997180971819718297183971849718597186971879718897189971909719197192971939719497195971969719797198971999720097201972029720397204972059720697207972089720997210972119721297213972149721597216972179721897219972209722197222972239722497225972269722797228972299723097231972329723397234972359723697237972389723997240972419724297243972449724597246972479724897249972509725197252972539725497255972569725797258972599726097261972629726397264972659726697267972689726997270972719727297273972749727597276972779727897279972809728197282972839728497285972869728797288972899729097291972929729397294972959729697297972989729997300973019730297303973049730597306973079730897309973109731197312973139731497315973169731797318973199732097321973229732397324973259732697327973289732997330973319733297333973349733597336973379733897339973409734197342973439734497345973469734797348973499735097351973529735397354973559735697357973589735997360973619736297363973649736597366973679736897369973709737197372973739737497375973769737797378973799738097381973829738397384973859738697387973889738997390973919739297393973949739597396973979739897399974009740197402974039740497405974069740797408974099741097411974129741397414974159741697417974189741997420974219742297423974249742597426974279742897429974309743197432974339743497435974369743797438974399744097441974429744397444974459744697447974489744997450974519745297453974549745597456974579745897459974609746197462974639746497465974669746797468974699747097471974729747397474974759747697477974789747997480974819748297483974849748597486974879748897489974909749197492974939749497495974969749797498974999750097501975029750397504975059750697507975089750997510975119751297513975149751597516975179751897519975209752197522975239752497525975269752797528975299753097531975329753397534975359753697537975389753997540975419754297543975449754597546975479754897549975509755197552975539755497555975569755797558975599756097561975629756397564975659756697567975689756997570975719757297573975749757597576975779757897579975809758197582975839758497585975869758797588975899759097591975929759397594975959759697597975989759997600976019760297603976049760597606976079760897609976109761197612976139761497615976169761797618976199762097621976229762397624976259762697627976289762997630976319763297633976349763597636976379763897639976409764197642976439764497645976469764797648976499765097651976529765397654976559765697657976589765997660976619766297663976649766597666976679766897669976709767197672976739767497675976769767797678976799768097681976829768397684976859768697687976889768997690976919769297693976949769597696976979769897699977009770197702977039770497705977069770797708977099771097711977129771397714977159771697717977189771997720977219772297723977249772597726977279772897729977309773197732977339773497735977369773797738977399774097741977429774397744977459774697747977489774997750977519775297753977549775597756977579775897759977609776197762977639776497765977669776797768977699777097771977729777397774977759777697777977789777997780977819778297783977849778597786977879778897789977909779197792977939779497795977969779797798977999780097801978029780397804978059780697807978089780997810978119781297813978149781597816978179781897819978209782197822978239782497825978269782797828978299783097831978329783397834978359783697837978389783997840978419784297843978449784597846978479784897849978509785197852978539785497855978569785797858978599786097861978629786397864978659786697867978689786997870978719787297873978749787597876978779787897879978809788197882978839788497885978869788797888978899789097891978929789397894978959789697897978989789997900979019790297903979049790597906979079790897909979109791197912979139791497915979169791797918979199792097921979229792397924979259792697927979289792997930979319793297933979349793597936979379793897939979409794197942979439794497945979469794797948979499795097951979529795397954979559795697957979589795997960979619796297963979649796597966979679796897969979709797197972979739797497975979769797797978979799798097981979829798397984979859798697987979889798997990979919799297993979949799597996979979799897999980009800198002980039800498005980069800798008980099801098011980129801398014980159801698017980189801998020980219802298023980249802598026980279802898029980309803198032980339803498035980369803798038980399804098041980429804398044980459804698047980489804998050980519805298053980549805598056980579805898059980609806198062980639806498065980669806798068980699807098071980729807398074980759807698077980789807998080980819808298083980849808598086980879808898089980909809198092980939809498095980969809798098980999810098101981029810398104981059810698107981089810998110981119811298113981149811598116981179811898119981209812198122981239812498125981269812798128981299813098131981329813398134981359813698137981389813998140981419814298143981449814598146981479814898149981509815198152981539815498155981569815798158981599816098161981629816398164981659816698167981689816998170981719817298173981749817598176981779817898179981809818198182981839818498185981869818798188981899819098191981929819398194981959819698197981989819998200982019820298203982049820598206982079820898209982109821198212982139821498215982169821798218982199822098221982229822398224982259822698227982289822998230982319823298233982349823598236982379823898239982409824198242982439824498245982469824798248982499825098251982529825398254982559825698257982589825998260982619826298263982649826598266982679826898269982709827198272982739827498275982769827798278982799828098281982829828398284982859828698287982889828998290982919829298293982949829598296982979829898299983009830198302983039830498305983069830798308983099831098311983129831398314983159831698317983189831998320983219832298323983249832598326983279832898329983309833198332983339833498335983369833798338983399834098341983429834398344983459834698347983489834998350983519835298353983549835598356983579835898359983609836198362983639836498365983669836798368983699837098371983729837398374983759837698377983789837998380
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. var scene = this._mesh.getScene();
  101. for (var index = 0; index < scene.meshes.length; index++) {
  102. var otherMesh = scene.meshes[index];
  103. if (!otherMesh.material) {
  104. continue;
  105. }
  106. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  107. continue;
  108. }
  109. if (otherMesh.material.getEffect() === effect) {
  110. otherMesh.computeBonesUsingShaders = false;
  111. }
  112. else {
  113. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  114. var subMesh = _a[_i];
  115. var subMeshEffect = subMesh.effect;
  116. if (subMeshEffect === effect) {
  117. otherMesh.computeBonesUsingShaders = false;
  118. break;
  119. }
  120. }
  121. }
  122. }
  123. }
  124. else {
  125. var currentFallbacks = this._defines[this._currentRank];
  126. if (currentFallbacks) {
  127. for (var index = 0; index < currentFallbacks.length; index++) {
  128. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  129. }
  130. }
  131. this._currentRank++;
  132. }
  133. return currentDefines;
  134. };
  135. return EffectFallbacks;
  136. }());
  137. BABYLON.EffectFallbacks = EffectFallbacks;
  138. /**
  139. * Options to be used when creating an effect.
  140. */
  141. var EffectCreationOptions = /** @class */ (function () {
  142. function EffectCreationOptions() {
  143. }
  144. return EffectCreationOptions;
  145. }());
  146. BABYLON.EffectCreationOptions = EffectCreationOptions;
  147. /**
  148. * Effect containing vertex and fragment shader that can be executed on an object.
  149. */
  150. var Effect = /** @class */ (function () {
  151. /**
  152. * Instantiates an effect.
  153. * An effect can be used to create/manage/execute vertex and fragment shaders.
  154. * @param baseName Name of the effect.
  155. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  156. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  157. * @param samplers List of sampler variables that will be passed to the shader.
  158. * @param engine Engine to be used to render the effect
  159. * @param defines Define statements to be added to the shader.
  160. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  161. * @param onCompiled Callback that will be called when the shader is compiled.
  162. * @param onError Callback that will be called if an error occurs during shader compilation.
  163. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  164. */
  165. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  166. if (samplers === void 0) { samplers = null; }
  167. if (defines === void 0) { defines = null; }
  168. if (fallbacks === void 0) { fallbacks = null; }
  169. if (onCompiled === void 0) { onCompiled = null; }
  170. if (onError === void 0) { onError = null; }
  171. var _this = this;
  172. /**
  173. * Unique ID of the effect.
  174. */
  175. this.uniqueId = 0;
  176. /**
  177. * Observable that will be called when the shader is compiled.
  178. */
  179. this.onCompileObservable = new BABYLON.Observable();
  180. /**
  181. * Observable that will be called if an error occurs during shader compilation.
  182. */
  183. this.onErrorObservable = new BABYLON.Observable();
  184. /**
  185. * Observable that will be called when effect is bound.
  186. */
  187. this.onBindObservable = new BABYLON.Observable();
  188. this._uniformBuffersNames = {};
  189. this._isReady = false;
  190. this._compilationError = "";
  191. this.name = baseName;
  192. if (attributesNamesOrOptions.attributes) {
  193. var options = attributesNamesOrOptions;
  194. this._engine = uniformsNamesOrEngine;
  195. this._attributesNames = options.attributes;
  196. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  197. this._samplers = options.samplers.slice();
  198. this.defines = options.defines;
  199. this.onError = options.onError;
  200. this.onCompiled = options.onCompiled;
  201. this._fallbacks = options.fallbacks;
  202. this._indexParameters = options.indexParameters;
  203. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  204. if (options.uniformBuffersNames) {
  205. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  206. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  207. }
  208. }
  209. }
  210. else {
  211. this._engine = engine;
  212. this.defines = defines;
  213. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  214. this._samplers = samplers ? samplers.slice() : [];
  215. this._attributesNames = attributesNamesOrOptions;
  216. this.onError = onError;
  217. this.onCompiled = onCompiled;
  218. this._indexParameters = indexParameters;
  219. this._fallbacks = fallbacks;
  220. }
  221. this.uniqueId = Effect._uniqueIdSeed++;
  222. var vertexSource;
  223. var fragmentSource;
  224. if (baseName.vertexElement) {
  225. vertexSource = document.getElementById(baseName.vertexElement);
  226. if (!vertexSource) {
  227. vertexSource = baseName.vertexElement;
  228. }
  229. }
  230. else {
  231. vertexSource = baseName.vertex || baseName;
  232. }
  233. if (baseName.fragmentElement) {
  234. fragmentSource = document.getElementById(baseName.fragmentElement);
  235. if (!fragmentSource) {
  236. fragmentSource = baseName.fragmentElement;
  237. }
  238. }
  239. else {
  240. fragmentSource = baseName.fragment || baseName;
  241. }
  242. this._loadVertexShader(vertexSource, function (vertexCode) {
  243. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  244. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  245. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  246. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  247. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  248. if (baseName) {
  249. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  250. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  251. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  252. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  253. }
  254. else {
  255. _this._vertexSourceCode = migratedVertexCode;
  256. _this._fragmentSourceCode = migratedFragmentCode;
  257. }
  258. _this._prepareEffect();
  259. });
  260. });
  261. });
  262. });
  263. });
  264. });
  265. }
  266. Object.defineProperty(Effect.prototype, "key", {
  267. /**
  268. * Unique key for this effect
  269. */
  270. get: function () {
  271. return this._key;
  272. },
  273. enumerable: true,
  274. configurable: true
  275. });
  276. /**
  277. * If the effect has been compiled and prepared.
  278. * @returns if the effect is compiled and prepared.
  279. */
  280. Effect.prototype.isReady = function () {
  281. return this._isReady;
  282. };
  283. /**
  284. * The engine the effect was initialized with.
  285. * @returns the engine.
  286. */
  287. Effect.prototype.getEngine = function () {
  288. return this._engine;
  289. };
  290. /**
  291. * The compiled webGL program for the effect
  292. * @returns the webGL program.
  293. */
  294. Effect.prototype.getProgram = function () {
  295. return this._program;
  296. };
  297. /**
  298. * The set of names of attribute variables for the shader.
  299. * @returns An array of attribute names.
  300. */
  301. Effect.prototype.getAttributesNames = function () {
  302. return this._attributesNames;
  303. };
  304. /**
  305. * Returns the attribute at the given index.
  306. * @param index The index of the attribute.
  307. * @returns The location of the attribute.
  308. */
  309. Effect.prototype.getAttributeLocation = function (index) {
  310. return this._attributes[index];
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param name of the attribute to look up.
  315. * @returns the attribute location.
  316. */
  317. Effect.prototype.getAttributeLocationByName = function (name) {
  318. var index = this._attributesNames.indexOf(name);
  319. return this._attributes[index];
  320. };
  321. /**
  322. * The number of attributes.
  323. * @returns the numnber of attributes.
  324. */
  325. Effect.prototype.getAttributesCount = function () {
  326. return this._attributes.length;
  327. };
  328. /**
  329. * Gets the index of a uniform variable.
  330. * @param uniformName of the uniform to look up.
  331. * @returns the index.
  332. */
  333. Effect.prototype.getUniformIndex = function (uniformName) {
  334. return this._uniformsNames.indexOf(uniformName);
  335. };
  336. /**
  337. * Returns the attribute based on the name of the variable.
  338. * @param uniformName of the uniform to look up.
  339. * @returns the location of the uniform.
  340. */
  341. Effect.prototype.getUniform = function (uniformName) {
  342. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  343. };
  344. /**
  345. * Returns an array of sampler variable names
  346. * @returns The array of sampler variable neames.
  347. */
  348. Effect.prototype.getSamplers = function () {
  349. return this._samplers;
  350. };
  351. /**
  352. * The error from the last compilation.
  353. * @returns the error string.
  354. */
  355. Effect.prototype.getCompilationError = function () {
  356. return this._compilationError;
  357. };
  358. /**
  359. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  360. * @param func The callback to be used.
  361. */
  362. Effect.prototype.executeWhenCompiled = function (func) {
  363. if (this.isReady()) {
  364. func(this);
  365. return;
  366. }
  367. this.onCompileObservable.add(function (effect) {
  368. func(effect);
  369. });
  370. };
  371. /** @hidden */
  372. Effect.prototype._loadVertexShader = function (vertex, callback) {
  373. if (BABYLON.Tools.IsWindowObjectExist()) {
  374. // DOM element ?
  375. if (vertex instanceof HTMLElement) {
  376. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  377. callback(vertexCode);
  378. return;
  379. }
  380. }
  381. // Base64 encoded ?
  382. if (vertex.substr(0, 7) === "base64:") {
  383. var vertexBinary = window.atob(vertex.substr(7));
  384. callback(vertexBinary);
  385. return;
  386. }
  387. // Is in local store ?
  388. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  389. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  390. return;
  391. }
  392. var vertexShaderUrl;
  393. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  394. vertexShaderUrl = vertex;
  395. }
  396. else {
  397. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  398. }
  399. // Vertex shader
  400. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  401. };
  402. /** @hidden */
  403. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  404. if (BABYLON.Tools.IsWindowObjectExist()) {
  405. // DOM element ?
  406. if (fragment instanceof HTMLElement) {
  407. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  408. callback(fragmentCode);
  409. return;
  410. }
  411. }
  412. // Base64 encoded ?
  413. if (fragment.substr(0, 7) === "base64:") {
  414. var fragmentBinary = window.atob(fragment.substr(7));
  415. callback(fragmentBinary);
  416. return;
  417. }
  418. // Is in local store ?
  419. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  420. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  421. return;
  422. }
  423. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  424. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  425. return;
  426. }
  427. var fragmentShaderUrl;
  428. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  429. fragmentShaderUrl = fragment;
  430. }
  431. else {
  432. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  433. }
  434. // Fragment shader
  435. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  436. };
  437. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  438. // Rebuild shaders source code
  439. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  440. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  441. vertexCode = prefix + vertexCode;
  442. fragmentCode = prefix + fragmentCode;
  443. // Number lines of shaders source code
  444. var i = 2;
  445. var regex = /\n/gm;
  446. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  447. i = 2;
  448. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  449. // Dump shaders name and formatted source code
  450. if (this.name.vertexElement) {
  451. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  452. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  453. }
  454. else if (this.name.vertex) {
  455. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  456. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  457. }
  458. else {
  459. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  460. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  461. }
  462. };
  463. ;
  464. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  465. var preparedSourceCode = this._processPrecision(sourceCode);
  466. if (this._engine.webGLVersion == 1) {
  467. callback(preparedSourceCode);
  468. return;
  469. }
  470. // Already converted
  471. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  472. callback(preparedSourceCode.replace("#version 300 es", ""));
  473. return;
  474. }
  475. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  476. // Remove extensions
  477. // #extension GL_OES_standard_derivatives : enable
  478. // #extension GL_EXT_shader_texture_lod : enable
  479. // #extension GL_EXT_frag_depth : enable
  480. // #extension GL_EXT_draw_buffers : require
  481. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  482. var result = preparedSourceCode.replace(regex, "");
  483. // Migrate to GLSL v300
  484. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  485. result = result.replace(/attribute[ \t]/g, "in ");
  486. result = result.replace(/[ \t]attribute/g, " in");
  487. if (isFragment) {
  488. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  489. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  490. result = result.replace(/texture2D\s*\(/g, "texture(");
  491. result = result.replace(/textureCube\s*\(/g, "texture(");
  492. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  493. result = result.replace(/gl_FragColor/g, "glFragColor");
  494. result = result.replace(/gl_FragData/g, "glFragData");
  495. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  496. }
  497. callback(result);
  498. };
  499. Effect.prototype._processIncludes = function (sourceCode, callback) {
  500. var _this = this;
  501. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  502. var match = regex.exec(sourceCode);
  503. var returnValue = new String(sourceCode);
  504. while (match != null) {
  505. var includeFile = match[1];
  506. // Uniform declaration
  507. if (includeFile.indexOf("__decl__") !== -1) {
  508. includeFile = includeFile.replace(/__decl__/, "");
  509. if (this._engine.supportsUniformBuffers) {
  510. includeFile = includeFile.replace(/Vertex/, "Ubo");
  511. includeFile = includeFile.replace(/Fragment/, "Ubo");
  512. }
  513. includeFile = includeFile + "Declaration";
  514. }
  515. if (Effect.IncludesShadersStore[includeFile]) {
  516. // Substitution
  517. var includeContent = Effect.IncludesShadersStore[includeFile];
  518. if (match[2]) {
  519. var splits = match[3].split(",");
  520. for (var index = 0; index < splits.length; index += 2) {
  521. var source = new RegExp(splits[index], "g");
  522. var dest = splits[index + 1];
  523. includeContent = includeContent.replace(source, dest);
  524. }
  525. }
  526. if (match[4]) {
  527. var indexString = match[5];
  528. if (indexString.indexOf("..") !== -1) {
  529. var indexSplits = indexString.split("..");
  530. var minIndex = parseInt(indexSplits[0]);
  531. var maxIndex = parseInt(indexSplits[1]);
  532. var sourceIncludeContent = includeContent.slice(0);
  533. includeContent = "";
  534. if (isNaN(maxIndex)) {
  535. maxIndex = this._indexParameters[indexSplits[1]];
  536. }
  537. for (var i = minIndex; i < maxIndex; i++) {
  538. if (!this._engine.supportsUniformBuffers) {
  539. // Ubo replacement
  540. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  541. return p1 + "{X}";
  542. });
  543. }
  544. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  545. }
  546. }
  547. else {
  548. if (!this._engine.supportsUniformBuffers) {
  549. // Ubo replacement
  550. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  551. return p1 + "{X}";
  552. });
  553. }
  554. includeContent = includeContent.replace(/\{X\}/g, indexString);
  555. }
  556. }
  557. // Replace
  558. returnValue = returnValue.replace(match[0], includeContent);
  559. }
  560. else {
  561. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  562. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  563. Effect.IncludesShadersStore[includeFile] = fileContent;
  564. _this._processIncludes(returnValue, callback);
  565. });
  566. return;
  567. }
  568. match = regex.exec(sourceCode);
  569. }
  570. callback(returnValue);
  571. };
  572. Effect.prototype._processPrecision = function (source) {
  573. if (source.indexOf("precision highp float") === -1) {
  574. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  575. source = "precision mediump float;\n" + source;
  576. }
  577. else {
  578. source = "precision highp float;\n" + source;
  579. }
  580. }
  581. else {
  582. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  583. source = source.replace("precision highp float", "precision mediump float");
  584. }
  585. }
  586. return source;
  587. };
  588. /**
  589. * Recompiles the webGL program
  590. * @param vertexSourceCode The source code for the vertex shader.
  591. * @param fragmentSourceCode The source code for the fragment shader.
  592. * @param onCompiled Callback called when completed.
  593. * @param onError Callback called on error.
  594. */
  595. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  596. var _this = this;
  597. this._isReady = false;
  598. this._vertexSourceCodeOverride = vertexSourceCode;
  599. this._fragmentSourceCodeOverride = fragmentSourceCode;
  600. this.onError = function (effect, error) {
  601. if (onError) {
  602. onError(error);
  603. }
  604. };
  605. this.onCompiled = function () {
  606. var scenes = _this.getEngine().scenes;
  607. for (var i = 0; i < scenes.length; i++) {
  608. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  609. }
  610. if (onCompiled) {
  611. onCompiled(_this._program);
  612. }
  613. };
  614. this._fallbacks = null;
  615. this._prepareEffect();
  616. };
  617. /**
  618. * Gets the uniform locations of the the specified variable names
  619. * @param names THe names of the variables to lookup.
  620. * @returns Array of locations in the same order as variable names.
  621. */
  622. Effect.prototype.getSpecificUniformLocations = function (names) {
  623. var engine = this._engine;
  624. return engine.getUniforms(this._program, names);
  625. };
  626. /**
  627. * Prepares the effect
  628. */
  629. Effect.prototype._prepareEffect = function () {
  630. var attributesNames = this._attributesNames;
  631. var defines = this.defines;
  632. var fallbacks = this._fallbacks;
  633. this._valueCache = {};
  634. var previousProgram = this._program;
  635. try {
  636. var engine = this._engine;
  637. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  638. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  639. }
  640. else {
  641. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  642. }
  643. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  644. if (engine.supportsUniformBuffers) {
  645. for (var name in this._uniformBuffersNames) {
  646. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  647. }
  648. }
  649. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  650. this._attributes = engine.getAttributes(this._program, attributesNames);
  651. var index;
  652. for (index = 0; index < this._samplers.length; index++) {
  653. var sampler = this.getUniform(this._samplers[index]);
  654. if (sampler == null) {
  655. this._samplers.splice(index, 1);
  656. index--;
  657. }
  658. }
  659. engine.bindSamplers(this);
  660. this._compilationError = "";
  661. this._isReady = true;
  662. if (this.onCompiled) {
  663. this.onCompiled(this);
  664. }
  665. this.onCompileObservable.notifyObservers(this);
  666. this.onCompileObservable.clear();
  667. // Unbind mesh reference in fallbacks
  668. if (this._fallbacks) {
  669. this._fallbacks.unBindMesh();
  670. }
  671. if (previousProgram) {
  672. this.getEngine()._deleteProgram(previousProgram);
  673. }
  674. }
  675. catch (e) {
  676. this._compilationError = e.message;
  677. // Let's go through fallbacks then
  678. BABYLON.Tools.Error("Unable to compile effect:");
  679. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  680. return " " + uniform;
  681. }));
  682. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  683. return " " + attribute;
  684. }));
  685. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  686. BABYLON.Tools.Error("Error: " + this._compilationError);
  687. if (previousProgram) {
  688. this._program = previousProgram;
  689. this._isReady = true;
  690. if (this.onError) {
  691. this.onError(this, this._compilationError);
  692. }
  693. this.onErrorObservable.notifyObservers(this);
  694. }
  695. if (fallbacks && fallbacks.isMoreFallbacks) {
  696. BABYLON.Tools.Error("Trying next fallback.");
  697. this.defines = fallbacks.reduce(this.defines, this);
  698. this._prepareEffect();
  699. }
  700. else { // Sorry we did everything we can
  701. if (this.onError) {
  702. this.onError(this, this._compilationError);
  703. }
  704. this.onErrorObservable.notifyObservers(this);
  705. this.onErrorObservable.clear();
  706. // Unbind mesh reference in fallbacks
  707. if (this._fallbacks) {
  708. this._fallbacks.unBindMesh();
  709. }
  710. }
  711. }
  712. };
  713. Object.defineProperty(Effect.prototype, "isSupported", {
  714. /**
  715. * Checks if the effect is supported. (Must be called after compilation)
  716. */
  717. get: function () {
  718. return this._compilationError === "";
  719. },
  720. enumerable: true,
  721. configurable: true
  722. });
  723. /**
  724. * Binds a texture to the engine to be used as output of the shader.
  725. * @param channel Name of the output variable.
  726. * @param texture Texture to bind.
  727. */
  728. Effect.prototype._bindTexture = function (channel, texture) {
  729. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  730. };
  731. /**
  732. * Sets a texture on the engine to be used in the shader.
  733. * @param channel Name of the sampler variable.
  734. * @param texture Texture to set.
  735. */
  736. Effect.prototype.setTexture = function (channel, texture) {
  737. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  738. };
  739. /**
  740. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  741. * @param channel Name of the sampler variable.
  742. * @param texture Texture to set.
  743. */
  744. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  745. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  746. };
  747. /**
  748. * Sets an array of textures on the engine to be used in the shader.
  749. * @param channel Name of the variable.
  750. * @param textures Textures to set.
  751. */
  752. Effect.prototype.setTextureArray = function (channel, textures) {
  753. if (this._samplers.indexOf(channel + "Ex") === -1) {
  754. var initialPos = this._samplers.indexOf(channel);
  755. for (var index = 1; index < textures.length; index++) {
  756. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  757. }
  758. }
  759. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  760. };
  761. /**
  762. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  763. * @param channel Name of the sampler variable.
  764. * @param postProcess Post process to get the input texture from.
  765. */
  766. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  767. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  768. };
  769. /**
  770. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  771. * 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)
  772. * @param channel Name of the sampler variable.
  773. * @param postProcess Post process to get the output texture from.
  774. */
  775. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  776. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  777. };
  778. /** @hidden */
  779. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  780. var cache = this._valueCache[uniformName];
  781. var flag = matrix.updateFlag;
  782. if (cache !== undefined && cache === flag) {
  783. return false;
  784. }
  785. this._valueCache[uniformName] = flag;
  786. return true;
  787. };
  788. /** @hidden */
  789. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  790. var cache = this._valueCache[uniformName];
  791. if (!cache) {
  792. cache = [x, y];
  793. this._valueCache[uniformName] = cache;
  794. return true;
  795. }
  796. var changed = false;
  797. if (cache[0] !== x) {
  798. cache[0] = x;
  799. changed = true;
  800. }
  801. if (cache[1] !== y) {
  802. cache[1] = y;
  803. changed = true;
  804. }
  805. return changed;
  806. };
  807. /** @hidden */
  808. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  809. var cache = this._valueCache[uniformName];
  810. if (!cache) {
  811. cache = [x, y, z];
  812. this._valueCache[uniformName] = cache;
  813. return true;
  814. }
  815. var changed = false;
  816. if (cache[0] !== x) {
  817. cache[0] = x;
  818. changed = true;
  819. }
  820. if (cache[1] !== y) {
  821. cache[1] = y;
  822. changed = true;
  823. }
  824. if (cache[2] !== z) {
  825. cache[2] = z;
  826. changed = true;
  827. }
  828. return changed;
  829. };
  830. /** @hidden */
  831. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  832. var cache = this._valueCache[uniformName];
  833. if (!cache) {
  834. cache = [x, y, z, w];
  835. this._valueCache[uniformName] = cache;
  836. return true;
  837. }
  838. var changed = false;
  839. if (cache[0] !== x) {
  840. cache[0] = x;
  841. changed = true;
  842. }
  843. if (cache[1] !== y) {
  844. cache[1] = y;
  845. changed = true;
  846. }
  847. if (cache[2] !== z) {
  848. cache[2] = z;
  849. changed = true;
  850. }
  851. if (cache[3] !== w) {
  852. cache[3] = w;
  853. changed = true;
  854. }
  855. return changed;
  856. };
  857. /**
  858. * Binds a buffer to a uniform.
  859. * @param buffer Buffer to bind.
  860. * @param name Name of the uniform variable to bind to.
  861. */
  862. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  863. var bufferName = this._uniformBuffersNames[name];
  864. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  865. return;
  866. }
  867. Effect._baseCache[bufferName] = buffer;
  868. this._engine.bindUniformBufferBase(buffer, bufferName);
  869. };
  870. /**
  871. * Binds block to a uniform.
  872. * @param blockName Name of the block to bind.
  873. * @param index Index to bind.
  874. */
  875. Effect.prototype.bindUniformBlock = function (blockName, index) {
  876. this._engine.bindUniformBlock(this._program, blockName, index);
  877. };
  878. /**
  879. * Sets an interger value on a uniform variable.
  880. * @param uniformName Name of the variable.
  881. * @param value Value to be set.
  882. * @returns this effect.
  883. */
  884. Effect.prototype.setInt = function (uniformName, value) {
  885. var cache = this._valueCache[uniformName];
  886. if (cache !== undefined && cache === value)
  887. return this;
  888. this._valueCache[uniformName] = value;
  889. this._engine.setInt(this.getUniform(uniformName), value);
  890. return this;
  891. };
  892. /**
  893. * Sets an int array on a uniform variable.
  894. * @param uniformName Name of the variable.
  895. * @param array array to be set.
  896. * @returns this effect.
  897. */
  898. Effect.prototype.setIntArray = function (uniformName, array) {
  899. this._valueCache[uniformName] = null;
  900. this._engine.setIntArray(this.getUniform(uniformName), array);
  901. return this;
  902. };
  903. /**
  904. * 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)
  905. * @param uniformName Name of the variable.
  906. * @param array array to be set.
  907. * @returns this effect.
  908. */
  909. Effect.prototype.setIntArray2 = function (uniformName, array) {
  910. this._valueCache[uniformName] = null;
  911. this._engine.setIntArray2(this.getUniform(uniformName), array);
  912. return this;
  913. };
  914. /**
  915. * 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)
  916. * @param uniformName Name of the variable.
  917. * @param array array to be set.
  918. * @returns this effect.
  919. */
  920. Effect.prototype.setIntArray3 = function (uniformName, array) {
  921. this._valueCache[uniformName] = null;
  922. this._engine.setIntArray3(this.getUniform(uniformName), array);
  923. return this;
  924. };
  925. /**
  926. * 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)
  927. * @param uniformName Name of the variable.
  928. * @param array array to be set.
  929. * @returns this effect.
  930. */
  931. Effect.prototype.setIntArray4 = function (uniformName, array) {
  932. this._valueCache[uniformName] = null;
  933. this._engine.setIntArray4(this.getUniform(uniformName), array);
  934. return this;
  935. };
  936. /**
  937. * Sets an float array on a uniform variable.
  938. * @param uniformName Name of the variable.
  939. * @param array array to be set.
  940. * @returns this effect.
  941. */
  942. Effect.prototype.setFloatArray = function (uniformName, array) {
  943. this._valueCache[uniformName] = null;
  944. this._engine.setFloatArray(this.getUniform(uniformName), array);
  945. return this;
  946. };
  947. /**
  948. * 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)
  949. * @param uniformName Name of the variable.
  950. * @param array array to be set.
  951. * @returns this effect.
  952. */
  953. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  954. this._valueCache[uniformName] = null;
  955. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  956. return this;
  957. };
  958. /**
  959. * 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)
  960. * @param uniformName Name of the variable.
  961. * @param array array to be set.
  962. * @returns this effect.
  963. */
  964. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  965. this._valueCache[uniformName] = null;
  966. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  967. return this;
  968. };
  969. /**
  970. * 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)
  971. * @param uniformName Name of the variable.
  972. * @param array array to be set.
  973. * @returns this effect.
  974. */
  975. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  976. this._valueCache[uniformName] = null;
  977. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  978. return this;
  979. };
  980. /**
  981. * Sets an array on a uniform variable.
  982. * @param uniformName Name of the variable.
  983. * @param array array to be set.
  984. * @returns this effect.
  985. */
  986. Effect.prototype.setArray = function (uniformName, array) {
  987. this._valueCache[uniformName] = null;
  988. this._engine.setArray(this.getUniform(uniformName), array);
  989. return this;
  990. };
  991. /**
  992. * 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)
  993. * @param uniformName Name of the variable.
  994. * @param array array to be set.
  995. * @returns this effect.
  996. */
  997. Effect.prototype.setArray2 = function (uniformName, array) {
  998. this._valueCache[uniformName] = null;
  999. this._engine.setArray2(this.getUniform(uniformName), array);
  1000. return this;
  1001. };
  1002. /**
  1003. * 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)
  1004. * @param uniformName Name of the variable.
  1005. * @param array array to be set.
  1006. * @returns this effect.
  1007. */
  1008. Effect.prototype.setArray3 = function (uniformName, array) {
  1009. this._valueCache[uniformName] = null;
  1010. this._engine.setArray3(this.getUniform(uniformName), array);
  1011. return this;
  1012. };
  1013. /**
  1014. * 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)
  1015. * @param uniformName Name of the variable.
  1016. * @param array array to be set.
  1017. * @returns this effect.
  1018. */
  1019. Effect.prototype.setArray4 = function (uniformName, array) {
  1020. this._valueCache[uniformName] = null;
  1021. this._engine.setArray4(this.getUniform(uniformName), array);
  1022. return this;
  1023. };
  1024. /**
  1025. * Sets matrices on a uniform variable.
  1026. * @param uniformName Name of the variable.
  1027. * @param matrices matrices to be set.
  1028. * @returns this effect.
  1029. */
  1030. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1031. if (!matrices) {
  1032. return this;
  1033. }
  1034. this._valueCache[uniformName] = null;
  1035. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1036. return this;
  1037. };
  1038. /**
  1039. * Sets matrix on a uniform variable.
  1040. * @param uniformName Name of the variable.
  1041. * @param matrix matrix to be set.
  1042. * @returns this effect.
  1043. */
  1044. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1045. if (this._cacheMatrix(uniformName, matrix)) {
  1046. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1047. }
  1048. return this;
  1049. };
  1050. /**
  1051. * 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)
  1052. * @param uniformName Name of the variable.
  1053. * @param matrix matrix to be set.
  1054. * @returns this effect.
  1055. */
  1056. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1057. this._valueCache[uniformName] = null;
  1058. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1059. return this;
  1060. };
  1061. /**
  1062. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1063. * @param uniformName Name of the variable.
  1064. * @param matrix matrix to be set.
  1065. * @returns this effect.
  1066. */
  1067. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1068. this._valueCache[uniformName] = null;
  1069. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1070. return this;
  1071. };
  1072. /**
  1073. * Sets a float on a uniform variable.
  1074. * @param uniformName Name of the variable.
  1075. * @param value value to be set.
  1076. * @returns this effect.
  1077. */
  1078. Effect.prototype.setFloat = function (uniformName, value) {
  1079. var cache = this._valueCache[uniformName];
  1080. if (cache !== undefined && cache === value)
  1081. return this;
  1082. this._valueCache[uniformName] = value;
  1083. this._engine.setFloat(this.getUniform(uniformName), value);
  1084. return this;
  1085. };
  1086. /**
  1087. * Sets a boolean on a uniform variable.
  1088. * @param uniformName Name of the variable.
  1089. * @param bool value to be set.
  1090. * @returns this effect.
  1091. */
  1092. Effect.prototype.setBool = function (uniformName, bool) {
  1093. var cache = this._valueCache[uniformName];
  1094. if (cache !== undefined && cache === bool)
  1095. return this;
  1096. this._valueCache[uniformName] = bool;
  1097. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1098. return this;
  1099. };
  1100. /**
  1101. * Sets a Vector2 on a uniform variable.
  1102. * @param uniformName Name of the variable.
  1103. * @param vector2 vector2 to be set.
  1104. * @returns this effect.
  1105. */
  1106. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1107. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1108. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1109. }
  1110. return this;
  1111. };
  1112. /**
  1113. * Sets a float2 on a uniform variable.
  1114. * @param uniformName Name of the variable.
  1115. * @param x First float in float2.
  1116. * @param y Second float in float2.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1120. if (this._cacheFloat2(uniformName, x, y)) {
  1121. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a Vector3 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param vector3 Value to be set.
  1129. * @returns this effect.
  1130. */
  1131. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1132. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1133. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1134. }
  1135. return this;
  1136. };
  1137. /**
  1138. * Sets a float3 on a uniform variable.
  1139. * @param uniformName Name of the variable.
  1140. * @param x First float in float3.
  1141. * @param y Second float in float3.
  1142. * @param z Third float in float3.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1146. if (this._cacheFloat3(uniformName, x, y, z)) {
  1147. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a Vector4 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param vector4 Value to be set.
  1155. * @returns this effect.
  1156. */
  1157. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1158. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1159. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1160. }
  1161. return this;
  1162. };
  1163. /**
  1164. * Sets a float4 on a uniform variable.
  1165. * @param uniformName Name of the variable.
  1166. * @param x First float in float4.
  1167. * @param y Second float in float4.
  1168. * @param z Third float in float4.
  1169. * @param w Fourth float in float4.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1173. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1174. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a Color3 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param color3 Value to be set.
  1182. * @returns this effect.
  1183. */
  1184. Effect.prototype.setColor3 = function (uniformName, color3) {
  1185. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1186. this._engine.setColor3(this.getUniform(uniformName), color3);
  1187. }
  1188. return this;
  1189. };
  1190. /**
  1191. * Sets a Color4 on a uniform variable.
  1192. * @param uniformName Name of the variable.
  1193. * @param color3 Value to be set.
  1194. * @param alpha Alpha value to be set.
  1195. * @returns this effect.
  1196. */
  1197. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1198. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1199. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1200. }
  1201. return this;
  1202. };
  1203. /**
  1204. * Sets a Color4 on a uniform variable
  1205. * @param uniformName defines the name of the variable
  1206. * @param color4 defines the value to be set
  1207. * @returns this effect.
  1208. */
  1209. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1210. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1211. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1212. }
  1213. return this;
  1214. };
  1215. /**
  1216. * Resets the cache of effects.
  1217. */
  1218. Effect.ResetCache = function () {
  1219. Effect._baseCache = {};
  1220. };
  1221. Effect._uniqueIdSeed = 0;
  1222. Effect._baseCache = {};
  1223. /**
  1224. * Store of each shader (The can be looked up using effect.key)
  1225. */
  1226. Effect.ShadersStore = {};
  1227. /**
  1228. * Store of each included file for a shader (The can be looked up using effect.key)
  1229. */
  1230. Effect.IncludesShadersStore = {};
  1231. return Effect;
  1232. }());
  1233. BABYLON.Effect = Effect;
  1234. })(BABYLON || (BABYLON = {}));
  1235. //# sourceMappingURL=babylon.effect.js.map
  1236. //# sourceMappingURL=babylon.types.js.map
  1237. var BABYLON;
  1238. (function (BABYLON) {
  1239. var KeyboardEventTypes = /** @class */ (function () {
  1240. function KeyboardEventTypes() {
  1241. }
  1242. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1243. get: function () {
  1244. return KeyboardEventTypes._KEYDOWN;
  1245. },
  1246. enumerable: true,
  1247. configurable: true
  1248. });
  1249. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1250. get: function () {
  1251. return KeyboardEventTypes._KEYUP;
  1252. },
  1253. enumerable: true,
  1254. configurable: true
  1255. });
  1256. KeyboardEventTypes._KEYDOWN = 0x01;
  1257. KeyboardEventTypes._KEYUP = 0x02;
  1258. return KeyboardEventTypes;
  1259. }());
  1260. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1261. var KeyboardInfo = /** @class */ (function () {
  1262. function KeyboardInfo(type, event) {
  1263. this.type = type;
  1264. this.event = event;
  1265. }
  1266. return KeyboardInfo;
  1267. }());
  1268. BABYLON.KeyboardInfo = KeyboardInfo;
  1269. /**
  1270. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1271. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1272. */
  1273. var KeyboardInfoPre = /** @class */ (function (_super) {
  1274. __extends(KeyboardInfoPre, _super);
  1275. function KeyboardInfoPre(type, event) {
  1276. var _this = _super.call(this, type, event) || this;
  1277. _this.skipOnPointerObservable = false;
  1278. return _this;
  1279. }
  1280. return KeyboardInfoPre;
  1281. }(KeyboardInfo));
  1282. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1283. })(BABYLON || (BABYLON = {}));
  1284. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1285. var BABYLON;
  1286. (function (BABYLON) {
  1287. var PointerEventTypes = /** @class */ (function () {
  1288. function PointerEventTypes() {
  1289. }
  1290. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1291. get: function () {
  1292. return PointerEventTypes._POINTERDOWN;
  1293. },
  1294. enumerable: true,
  1295. configurable: true
  1296. });
  1297. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1298. get: function () {
  1299. return PointerEventTypes._POINTERUP;
  1300. },
  1301. enumerable: true,
  1302. configurable: true
  1303. });
  1304. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1305. get: function () {
  1306. return PointerEventTypes._POINTERMOVE;
  1307. },
  1308. enumerable: true,
  1309. configurable: true
  1310. });
  1311. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1312. get: function () {
  1313. return PointerEventTypes._POINTERWHEEL;
  1314. },
  1315. enumerable: true,
  1316. configurable: true
  1317. });
  1318. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1319. get: function () {
  1320. return PointerEventTypes._POINTERPICK;
  1321. },
  1322. enumerable: true,
  1323. configurable: true
  1324. });
  1325. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1326. get: function () {
  1327. return PointerEventTypes._POINTERTAP;
  1328. },
  1329. enumerable: true,
  1330. configurable: true
  1331. });
  1332. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1333. get: function () {
  1334. return PointerEventTypes._POINTERDOUBLETAP;
  1335. },
  1336. enumerable: true,
  1337. configurable: true
  1338. });
  1339. PointerEventTypes._POINTERDOWN = 0x01;
  1340. PointerEventTypes._POINTERUP = 0x02;
  1341. PointerEventTypes._POINTERMOVE = 0x04;
  1342. PointerEventTypes._POINTERWHEEL = 0x08;
  1343. PointerEventTypes._POINTERPICK = 0x10;
  1344. PointerEventTypes._POINTERTAP = 0x20;
  1345. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1346. return PointerEventTypes;
  1347. }());
  1348. BABYLON.PointerEventTypes = PointerEventTypes;
  1349. var PointerInfoBase = /** @class */ (function () {
  1350. function PointerInfoBase(type, event) {
  1351. this.type = type;
  1352. this.event = event;
  1353. }
  1354. return PointerInfoBase;
  1355. }());
  1356. BABYLON.PointerInfoBase = PointerInfoBase;
  1357. /**
  1358. * This class is used to store pointer related info for the onPrePointerObservable event.
  1359. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1360. */
  1361. var PointerInfoPre = /** @class */ (function (_super) {
  1362. __extends(PointerInfoPre, _super);
  1363. function PointerInfoPre(type, event, localX, localY) {
  1364. var _this = _super.call(this, type, event) || this;
  1365. _this.skipOnPointerObservable = false;
  1366. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1367. return _this;
  1368. }
  1369. return PointerInfoPre;
  1370. }(PointerInfoBase));
  1371. BABYLON.PointerInfoPre = PointerInfoPre;
  1372. /**
  1373. * This type contains all the data related to a pointer event in Babylon.js.
  1374. * 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.
  1375. */
  1376. var PointerInfo = /** @class */ (function (_super) {
  1377. __extends(PointerInfo, _super);
  1378. function PointerInfo(type, event, pickInfo) {
  1379. var _this = _super.call(this, type, event) || this;
  1380. _this.pickInfo = pickInfo;
  1381. return _this;
  1382. }
  1383. return PointerInfo;
  1384. }(PointerInfoBase));
  1385. BABYLON.PointerInfo = PointerInfo;
  1386. })(BABYLON || (BABYLON = {}));
  1387. //# sourceMappingURL=babylon.pointerEvents.js.map
  1388. var BABYLON;
  1389. (function (BABYLON) {
  1390. BABYLON.ToGammaSpace = 1 / 2.2;
  1391. BABYLON.ToLinearSpace = 2.2;
  1392. BABYLON.Epsilon = 0.001;
  1393. /**
  1394. * Class used to hold a RBG color
  1395. */
  1396. var Color3 = /** @class */ (function () {
  1397. /**
  1398. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1399. * @param r defines the red component (between 0 and 1, default is 0)
  1400. * @param g defines the green component (between 0 and 1, default is 0)
  1401. * @param b defines the blue component (between 0 and 1, default is 0)
  1402. */
  1403. function Color3(
  1404. /**
  1405. * Defines the red component (between 0 and 1, default is 0)
  1406. */
  1407. r,
  1408. /**
  1409. * Defines the green component (between 0 and 1, default is 0)
  1410. */
  1411. g,
  1412. /**
  1413. * Defines the blue component (between 0 and 1, default is 0)
  1414. */
  1415. b) {
  1416. if (r === void 0) { r = 0; }
  1417. if (g === void 0) { g = 0; }
  1418. if (b === void 0) { b = 0; }
  1419. this.r = r;
  1420. this.g = g;
  1421. this.b = b;
  1422. }
  1423. /**
  1424. * Creates a string with the Color3 current values
  1425. * @returns the string representation of the Color3 object
  1426. */
  1427. Color3.prototype.toString = function () {
  1428. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1429. };
  1430. /**
  1431. * Returns the string "Color3"
  1432. * @returns "Color3"
  1433. */
  1434. Color3.prototype.getClassName = function () {
  1435. return "Color3";
  1436. };
  1437. /**
  1438. * Compute the Color3 hash code
  1439. * @returns an unique number that can be used to hash Color3 objects
  1440. */
  1441. Color3.prototype.getHashCode = function () {
  1442. var hash = this.r || 0;
  1443. hash = (hash * 397) ^ (this.g || 0);
  1444. hash = (hash * 397) ^ (this.b || 0);
  1445. return hash;
  1446. };
  1447. // Operators
  1448. /**
  1449. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1450. * @param array defines the array where to store the r,g,b components
  1451. * @param index defines an optional index in the target array to define where to start storing values
  1452. * @returns the current Color3 object
  1453. */
  1454. Color3.prototype.toArray = function (array, index) {
  1455. if (index === undefined) {
  1456. index = 0;
  1457. }
  1458. array[index] = this.r;
  1459. array[index + 1] = this.g;
  1460. array[index + 2] = this.b;
  1461. return this;
  1462. };
  1463. /**
  1464. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1465. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1466. * @returns a new {BABYLON.Color4} object
  1467. */
  1468. Color3.prototype.toColor4 = function (alpha) {
  1469. if (alpha === void 0) { alpha = 1; }
  1470. return new Color4(this.r, this.g, this.b, alpha);
  1471. };
  1472. /**
  1473. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1474. * @returns the new array
  1475. */
  1476. Color3.prototype.asArray = function () {
  1477. var result = new Array();
  1478. this.toArray(result, 0);
  1479. return result;
  1480. };
  1481. /**
  1482. * Returns the luminance value
  1483. * @returns a float value
  1484. */
  1485. Color3.prototype.toLuminance = function () {
  1486. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1487. };
  1488. /**
  1489. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1490. * @param otherColor defines the second operand
  1491. * @returns the new Color3 object
  1492. */
  1493. Color3.prototype.multiply = function (otherColor) {
  1494. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1495. };
  1496. /**
  1497. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1498. * @param otherColor defines the second operand
  1499. * @param result defines the Color3 object where to store the result
  1500. * @returns the current Color3
  1501. */
  1502. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1503. result.r = this.r * otherColor.r;
  1504. result.g = this.g * otherColor.g;
  1505. result.b = this.b * otherColor.b;
  1506. return this;
  1507. };
  1508. /**
  1509. * Determines equality between Color3 objects
  1510. * @param otherColor defines the second operand
  1511. * @returns true if the rgb values are equal to the given ones
  1512. */
  1513. Color3.prototype.equals = function (otherColor) {
  1514. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1515. };
  1516. /**
  1517. * Determines equality between the current Color3 object and a set of r,b,g values
  1518. * @param r defines the red component to check
  1519. * @param g defines the green component to check
  1520. * @param b defines the blue component to check
  1521. * @returns true if the rgb values are equal to the given ones
  1522. */
  1523. Color3.prototype.equalsFloats = function (r, g, b) {
  1524. return this.r === r && this.g === g && this.b === b;
  1525. };
  1526. /**
  1527. * Multiplies in place each rgb value by scale
  1528. * @param scale defines the scaling factor
  1529. * @returns the updated Color3
  1530. */
  1531. Color3.prototype.scale = function (scale) {
  1532. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1533. };
  1534. /**
  1535. * Multiplies the rgb values by scale and stores the result into "result"
  1536. * @param scale defines the scaling factor
  1537. * @param result defines the Color3 object where to store the result
  1538. * @returns the unmodified current Color3
  1539. */
  1540. Color3.prototype.scaleToRef = function (scale, result) {
  1541. result.r = this.r * scale;
  1542. result.g = this.g * scale;
  1543. result.b = this.b * scale;
  1544. return this;
  1545. };
  1546. /**
  1547. * Scale the current Color3 values by a factor and add the result to a given Color3
  1548. * @param scale defines the scale factor
  1549. * @param result defines color to store the result into
  1550. * @returns the unmodified current Color3
  1551. */
  1552. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1553. result.r += this.r * scale;
  1554. result.g += this.g * scale;
  1555. result.b += this.b * scale;
  1556. return this;
  1557. };
  1558. /**
  1559. * Clamps the rgb values by the min and max values and stores the result into "result"
  1560. * @param min defines minimum clamping value (default is 0)
  1561. * @param max defines maximum clamping value (default is 1)
  1562. * @param result defines color to store the result into
  1563. * @returns the original Color3
  1564. */
  1565. Color3.prototype.clampToRef = function (min, max, result) {
  1566. if (min === void 0) { min = 0; }
  1567. if (max === void 0) { max = 1; }
  1568. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1569. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1570. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1571. return this;
  1572. };
  1573. /**
  1574. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3
  1577. */
  1578. Color3.prototype.add = function (otherColor) {
  1579. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1580. };
  1581. /**
  1582. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines Color3 object to store the result into
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.addToRef = function (otherColor, result) {
  1588. result.r = this.r + otherColor.r;
  1589. result.g = this.g + otherColor.g;
  1590. result.b = this.b + otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1595. * @param otherColor defines the second operand
  1596. * @returns the new Color3
  1597. */
  1598. Color3.prototype.subtract = function (otherColor) {
  1599. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1600. };
  1601. /**
  1602. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1603. * @param otherColor defines the second operand
  1604. * @param result defines Color3 object to store the result into
  1605. * @returns the unmodified current Color3
  1606. */
  1607. Color3.prototype.subtractToRef = function (otherColor, result) {
  1608. result.r = this.r - otherColor.r;
  1609. result.g = this.g - otherColor.g;
  1610. result.b = this.b - otherColor.b;
  1611. return this;
  1612. };
  1613. /**
  1614. * Copy the current object
  1615. * @returns a new Color3 copied the current one
  1616. */
  1617. Color3.prototype.clone = function () {
  1618. return new Color3(this.r, this.g, this.b);
  1619. };
  1620. /**
  1621. * Copies the rgb values from the source in the current Color3
  1622. * @param source defines the source Color3 object
  1623. * @returns the updated Color3 object
  1624. */
  1625. Color3.prototype.copyFrom = function (source) {
  1626. this.r = source.r;
  1627. this.g = source.g;
  1628. this.b = source.b;
  1629. return this;
  1630. };
  1631. /**
  1632. * Updates the Color3 rgb values from the given floats
  1633. * @param r defines the red component to read from
  1634. * @param g defines the green component to read from
  1635. * @param b defines the blue component to read from
  1636. * @returns the current Color3 object
  1637. */
  1638. Color3.prototype.copyFromFloats = function (r, g, b) {
  1639. this.r = r;
  1640. this.g = g;
  1641. this.b = b;
  1642. return this;
  1643. };
  1644. /**
  1645. * Updates the Color3 rgb values from the given floats
  1646. * @param r defines the red component to read from
  1647. * @param g defines the green component to read from
  1648. * @param b defines the blue component to read from
  1649. * @returns the current Color3 object
  1650. */
  1651. Color3.prototype.set = function (r, g, b) {
  1652. return this.copyFromFloats(r, g, b);
  1653. };
  1654. /**
  1655. * Compute the Color3 hexadecimal code as a string
  1656. * @returns a string containing the hexadecimal representation of the Color3 object
  1657. */
  1658. Color3.prototype.toHexString = function () {
  1659. var intR = (this.r * 255) | 0;
  1660. var intG = (this.g * 255) | 0;
  1661. var intB = (this.b * 255) | 0;
  1662. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1663. };
  1664. /**
  1665. * Computes a new Color3 converted from the current one to linear space
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.prototype.toLinearSpace = function () {
  1669. var convertedColor = new Color3();
  1670. this.toLinearSpaceToRef(convertedColor);
  1671. return convertedColor;
  1672. };
  1673. /**
  1674. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1675. * @param convertedColor defines the Color3 object where to store the linear space version
  1676. * @returns the unmodified Color3
  1677. */
  1678. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1679. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1680. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1681. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1682. return this;
  1683. };
  1684. /**
  1685. * Computes a new Color3 converted from the current one to gamma space
  1686. * @returns a new Color3 object
  1687. */
  1688. Color3.prototype.toGammaSpace = function () {
  1689. var convertedColor = new Color3();
  1690. this.toGammaSpaceToRef(convertedColor);
  1691. return convertedColor;
  1692. };
  1693. /**
  1694. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1695. * @param convertedColor defines the Color3 object where to store the gamma space version
  1696. * @returns the unmodified Color3
  1697. */
  1698. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1699. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1700. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1701. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1702. return this;
  1703. };
  1704. // Statics
  1705. /**
  1706. * Creates a new Color3 from the string containing valid hexadecimal values
  1707. * @param hex defines a string containing valid hexadecimal values
  1708. * @returns a new Color3 object
  1709. */
  1710. Color3.FromHexString = function (hex) {
  1711. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1712. return new Color3(0, 0, 0);
  1713. }
  1714. var r = parseInt(hex.substring(1, 3), 16);
  1715. var g = parseInt(hex.substring(3, 5), 16);
  1716. var b = parseInt(hex.substring(5, 7), 16);
  1717. return Color3.FromInts(r, g, b);
  1718. };
  1719. /**
  1720. * Creates a new Vector3 from the starting index of the given array
  1721. * @param array defines the source array
  1722. * @param offset defines an offset in the source array
  1723. * @returns a new Color3 object
  1724. */
  1725. Color3.FromArray = function (array, offset) {
  1726. if (offset === void 0) { offset = 0; }
  1727. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1728. };
  1729. /**
  1730. * Creates a new Color3 from integer values (< 256)
  1731. * @param r defines the red component to read from (value between 0 and 255)
  1732. * @param g defines the green component to read from (value between 0 and 255)
  1733. * @param b defines the blue component to read from (value between 0 and 255)
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.FromInts = function (r, g, b) {
  1737. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1738. };
  1739. /**
  1740. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1741. * @param start defines the start Color3 value
  1742. * @param end defines the end Color3 value
  1743. * @param amount defines the gradient value between start and end
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Lerp = function (start, end, amount) {
  1747. var r = start.r + ((end.r - start.r) * amount);
  1748. var g = start.g + ((end.g - start.g) * amount);
  1749. var b = start.b + ((end.b - start.b) * amount);
  1750. return new Color3(r, g, b);
  1751. };
  1752. /**
  1753. * Returns a Color3 value containing a red color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.Red = function () { return new Color3(1, 0, 0); };
  1757. /**
  1758. * Returns a Color3 value containing a green color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Green = function () { return new Color3(0, 1, 0); };
  1762. /**
  1763. * Returns a Color3 value containing a blue color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1767. /**
  1768. * Returns a Color3 value containing a black color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Black = function () { return new Color3(0, 0, 0); };
  1772. /**
  1773. * Returns a Color3 value containing a white color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.White = function () { return new Color3(1, 1, 1); };
  1777. /**
  1778. * Returns a Color3 value containing a purple color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1782. /**
  1783. * Returns a Color3 value containing a magenta color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1787. /**
  1788. * Returns a Color3 value containing a yellow color
  1789. * @returns a new Color3 object
  1790. */
  1791. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1792. /**
  1793. * Returns a Color3 value containing a gray color
  1794. * @returns a new Color3 object
  1795. */
  1796. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1797. /**
  1798. * Returns a Color3 value containing a teal color
  1799. * @returns a new Color3 object
  1800. */
  1801. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1802. /**
  1803. * Returns a Color3 value containing a random color
  1804. * @returns a new Color3 object
  1805. */
  1806. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1807. return Color3;
  1808. }());
  1809. BABYLON.Color3 = Color3;
  1810. /**
  1811. * Class used to hold a RBGA color
  1812. */
  1813. var Color4 = /** @class */ (function () {
  1814. /**
  1815. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1816. * @param r defines the red component (between 0 and 1, default is 0)
  1817. * @param g defines the green component (between 0 and 1, default is 0)
  1818. * @param b defines the blue component (between 0 and 1, default is 0)
  1819. * @param a defines the alpha component (between 0 and 1, default is 1)
  1820. */
  1821. function Color4(
  1822. /**
  1823. * Defines the red component (between 0 and 1, default is 0)
  1824. */
  1825. r,
  1826. /**
  1827. * Defines the green component (between 0 and 1, default is 0)
  1828. */
  1829. g,
  1830. /**
  1831. * Defines the blue component (between 0 and 1, default is 0)
  1832. */
  1833. b,
  1834. /**
  1835. * Defines the alpha component (between 0 and 1, default is 1)
  1836. */
  1837. a) {
  1838. if (r === void 0) { r = 0; }
  1839. if (g === void 0) { g = 0; }
  1840. if (b === void 0) { b = 0; }
  1841. if (a === void 0) { a = 1; }
  1842. this.r = r;
  1843. this.g = g;
  1844. this.b = b;
  1845. this.a = a;
  1846. }
  1847. // Operators
  1848. /**
  1849. * Adds in place the given Color4 values to the current Color4 object
  1850. * @param right defines the second operand
  1851. * @returns the current updated Color4 object
  1852. */
  1853. Color4.prototype.addInPlace = function (right) {
  1854. this.r += right.r;
  1855. this.g += right.g;
  1856. this.b += right.b;
  1857. this.a += right.a;
  1858. return this;
  1859. };
  1860. /**
  1861. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1862. * @returns the new array
  1863. */
  1864. Color4.prototype.asArray = function () {
  1865. var result = new Array();
  1866. this.toArray(result, 0);
  1867. return result;
  1868. };
  1869. /**
  1870. * Stores from the starting index in the given array the Color4 successive values
  1871. * @param array defines the array where to store the r,g,b components
  1872. * @param index defines an optional index in the target array to define where to start storing values
  1873. * @returns the current Color4 object
  1874. */
  1875. Color4.prototype.toArray = function (array, index) {
  1876. if (index === undefined) {
  1877. index = 0;
  1878. }
  1879. array[index] = this.r;
  1880. array[index + 1] = this.g;
  1881. array[index + 2] = this.b;
  1882. array[index + 3] = this.a;
  1883. return this;
  1884. };
  1885. /**
  1886. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1887. * @param right defines the second operand
  1888. * @returns a new Color4 object
  1889. */
  1890. Color4.prototype.add = function (right) {
  1891. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1892. };
  1893. /**
  1894. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1895. * @param right defines the second operand
  1896. * @returns a new Color4 object
  1897. */
  1898. Color4.prototype.subtract = function (right) {
  1899. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1900. };
  1901. /**
  1902. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1903. * @param right defines the second operand
  1904. * @param result defines the Color4 object where to store the result
  1905. * @returns the current Color4 object
  1906. */
  1907. Color4.prototype.subtractToRef = function (right, result) {
  1908. result.r = this.r - right.r;
  1909. result.g = this.g - right.g;
  1910. result.b = this.b - right.b;
  1911. result.a = this.a - right.a;
  1912. return this;
  1913. };
  1914. /**
  1915. * Creates a new Color4 with the current Color4 values multiplied by scale
  1916. * @param scale defines the scaling factor to apply
  1917. * @returns a new Color4 object
  1918. */
  1919. Color4.prototype.scale = function (scale) {
  1920. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1921. };
  1922. /**
  1923. * Multiplies the current Color4 values by scale and stores the result in "result"
  1924. * @param scale defines the scaling factor to apply
  1925. * @param result defines the Color4 object where to store the result
  1926. * @returns the current unmodified Color4
  1927. */
  1928. Color4.prototype.scaleToRef = function (scale, result) {
  1929. result.r = this.r * scale;
  1930. result.g = this.g * scale;
  1931. result.b = this.b * scale;
  1932. result.a = this.a * scale;
  1933. return this;
  1934. };
  1935. /**
  1936. * Scale the current Color4 values by a factor and add the result to a given Color4
  1937. * @param scale defines the scale factor
  1938. * @param result defines the Color4 object where to store the result
  1939. * @returns the unmodified current Color4
  1940. */
  1941. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1942. result.r += this.r * scale;
  1943. result.g += this.g * scale;
  1944. result.b += this.b * scale;
  1945. result.a += this.a * scale;
  1946. return this;
  1947. };
  1948. /**
  1949. * Clamps the rgb values by the min and max values and stores the result into "result"
  1950. * @param min defines minimum clamping value (default is 0)
  1951. * @param max defines maximum clamping value (default is 1)
  1952. * @param result defines color to store the result into.
  1953. * @returns the cuurent Color4
  1954. */
  1955. Color4.prototype.clampToRef = function (min, max, result) {
  1956. if (min === void 0) { min = 0; }
  1957. if (max === void 0) { max = 1; }
  1958. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1959. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1960. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1961. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1962. return this;
  1963. };
  1964. /**
  1965. * Multipy an Color4 value by another and return a new Color4 object
  1966. * @param color defines the Color4 value to multiply by
  1967. * @returns a new Color4 object
  1968. */
  1969. Color4.prototype.multiply = function (color) {
  1970. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1971. };
  1972. /**
  1973. * Multipy a Color4 value by another and push the result in a reference value
  1974. * @param color defines the Color4 value to multiply by
  1975. * @param result defines the Color4 to fill the result in
  1976. * @returns the result Color4
  1977. */
  1978. Color4.prototype.multiplyToRef = function (color, result) {
  1979. result.r = this.r * color.r;
  1980. result.g = this.g * color.g;
  1981. result.b = this.b * color.b;
  1982. result.a = this.a * color.a;
  1983. return result;
  1984. };
  1985. /**
  1986. * Creates a string with the Color4 current values
  1987. * @returns the string representation of the Color4 object
  1988. */
  1989. Color4.prototype.toString = function () {
  1990. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1991. };
  1992. /**
  1993. * Returns the string "Color4"
  1994. * @returns "Color4"
  1995. */
  1996. Color4.prototype.getClassName = function () {
  1997. return "Color4";
  1998. };
  1999. /**
  2000. * Compute the Color4 hash code
  2001. * @returns an unique number that can be used to hash Color4 objects
  2002. */
  2003. Color4.prototype.getHashCode = function () {
  2004. var hash = this.r || 0;
  2005. hash = (hash * 397) ^ (this.g || 0);
  2006. hash = (hash * 397) ^ (this.b || 0);
  2007. hash = (hash * 397) ^ (this.a || 0);
  2008. return hash;
  2009. };
  2010. /**
  2011. * Creates a new Color4 copied from the current one
  2012. * @returns a new Color4 object
  2013. */
  2014. Color4.prototype.clone = function () {
  2015. return new Color4(this.r, this.g, this.b, this.a);
  2016. };
  2017. /**
  2018. * Copies the given Color4 values into the current one
  2019. * @param source defines the source Color4 object
  2020. * @returns the current updated Color4 object
  2021. */
  2022. Color4.prototype.copyFrom = function (source) {
  2023. this.r = source.r;
  2024. this.g = source.g;
  2025. this.b = source.b;
  2026. this.a = source.a;
  2027. return this;
  2028. };
  2029. /**
  2030. * Copies the given float values into the current one
  2031. * @param r defines the red component to read from
  2032. * @param g defines the green component to read from
  2033. * @param b defines the blue component to read from
  2034. * @param a defines the alpha component to read from
  2035. * @returns the current updated Color4 object
  2036. */
  2037. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2038. this.r = r;
  2039. this.g = g;
  2040. this.b = b;
  2041. this.a = a;
  2042. return this;
  2043. };
  2044. /**
  2045. * Copies the given float values into the current one
  2046. * @param r defines the red component to read from
  2047. * @param g defines the green component to read from
  2048. * @param b defines the blue component to read from
  2049. * @param a defines the alpha component to read from
  2050. * @returns the current updated Color4 object
  2051. */
  2052. Color4.prototype.set = function (r, g, b, a) {
  2053. return this.copyFromFloats(r, g, b, a);
  2054. };
  2055. /**
  2056. * Compute the Color4 hexadecimal code as a string
  2057. * @returns a string containing the hexadecimal representation of the Color4 object
  2058. */
  2059. Color4.prototype.toHexString = function () {
  2060. var intR = (this.r * 255) | 0;
  2061. var intG = (this.g * 255) | 0;
  2062. var intB = (this.b * 255) | 0;
  2063. var intA = (this.a * 255) | 0;
  2064. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2065. };
  2066. /**
  2067. * Computes a new Color4 converted from the current one to linear space
  2068. * @returns a new Color4 object
  2069. */
  2070. Color4.prototype.toLinearSpace = function () {
  2071. var convertedColor = new Color4();
  2072. this.toLinearSpaceToRef(convertedColor);
  2073. return convertedColor;
  2074. };
  2075. /**
  2076. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2077. * @param convertedColor defines the Color4 object where to store the linear space version
  2078. * @returns the unmodified Color4
  2079. */
  2080. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2081. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2082. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2083. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2084. convertedColor.a = this.a;
  2085. return this;
  2086. };
  2087. /**
  2088. * Computes a new Color4 converted from the current one to gamma space
  2089. * @returns a new Color4 object
  2090. */
  2091. Color4.prototype.toGammaSpace = function () {
  2092. var convertedColor = new Color4();
  2093. this.toGammaSpaceToRef(convertedColor);
  2094. return convertedColor;
  2095. };
  2096. /**
  2097. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2098. * @param convertedColor defines the Color4 object where to store the gamma space version
  2099. * @returns the unmodified Color4
  2100. */
  2101. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2102. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2103. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2104. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2105. convertedColor.a = this.a;
  2106. return this;
  2107. };
  2108. // Statics
  2109. /**
  2110. * Creates a new Color4 from the string containing valid hexadecimal values
  2111. * @param hex defines a string containing valid hexadecimal values
  2112. * @returns a new Color4 object
  2113. */
  2114. Color4.FromHexString = function (hex) {
  2115. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2116. return new Color4(0.0, 0.0, 0.0, 0.0);
  2117. }
  2118. var r = parseInt(hex.substring(1, 3), 16);
  2119. var g = parseInt(hex.substring(3, 5), 16);
  2120. var b = parseInt(hex.substring(5, 7), 16);
  2121. var a = parseInt(hex.substring(7, 9), 16);
  2122. return Color4.FromInts(r, g, b, a);
  2123. };
  2124. /**
  2125. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2126. * @param left defines the start value
  2127. * @param right defines the end value
  2128. * @param amount defines the gradient factor
  2129. * @returns a new Color4 object
  2130. */
  2131. Color4.Lerp = function (left, right, amount) {
  2132. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2133. Color4.LerpToRef(left, right, amount, result);
  2134. return result;
  2135. };
  2136. /**
  2137. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2138. * @param left defines the start value
  2139. * @param right defines the end value
  2140. * @param amount defines the gradient factor
  2141. * @param result defines the Color4 object where to store data
  2142. */
  2143. Color4.LerpToRef = function (left, right, amount, result) {
  2144. result.r = left.r + (right.r - left.r) * amount;
  2145. result.g = left.g + (right.g - left.g) * amount;
  2146. result.b = left.b + (right.b - left.b) * amount;
  2147. result.a = left.a + (right.a - left.a) * amount;
  2148. };
  2149. /**
  2150. * Creates a new Color4 from the starting index element of the given array
  2151. * @param array defines the source array to read from
  2152. * @param offset defines the offset in the source array
  2153. * @returns a new Color4 object
  2154. */
  2155. Color4.FromArray = function (array, offset) {
  2156. if (offset === void 0) { offset = 0; }
  2157. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2158. };
  2159. /**
  2160. * Creates a new Color3 from integer values (< 256)
  2161. * @param r defines the red component to read from (value between 0 and 255)
  2162. * @param g defines the green component to read from (value between 0 and 255)
  2163. * @param b defines the blue component to read from (value between 0 and 255)
  2164. * @param a defines the alpha component to read from (value between 0 and 255)
  2165. * @returns a new Color3 object
  2166. */
  2167. Color4.FromInts = function (r, g, b, a) {
  2168. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2169. };
  2170. /**
  2171. * Check the content of a given array and convert it to an array containing RGBA data
  2172. * If the original array was already containing count * 4 values then it is returned directly
  2173. * @param colors defines the array to check
  2174. * @param count defines the number of RGBA data to expect
  2175. * @returns an array containing count * 4 values (RGBA)
  2176. */
  2177. Color4.CheckColors4 = function (colors, count) {
  2178. // Check if color3 was used
  2179. if (colors.length === count * 3) {
  2180. var colors4 = [];
  2181. for (var index = 0; index < colors.length; index += 3) {
  2182. var newIndex = (index / 3) * 4;
  2183. colors4[newIndex] = colors[index];
  2184. colors4[newIndex + 1] = colors[index + 1];
  2185. colors4[newIndex + 2] = colors[index + 2];
  2186. colors4[newIndex + 3] = 1.0;
  2187. }
  2188. return colors4;
  2189. }
  2190. return colors;
  2191. };
  2192. return Color4;
  2193. }());
  2194. BABYLON.Color4 = Color4;
  2195. /**
  2196. * Class representing a vector containing 2 coordinates
  2197. */
  2198. var Vector2 = /** @class */ (function () {
  2199. /**
  2200. * Creates a new Vector2 from the given x and y coordinates
  2201. * @param x defines the first coordinate
  2202. * @param y defines the second coordinate
  2203. */
  2204. function Vector2(
  2205. /** defines the first coordinate */
  2206. x,
  2207. /** defines the second coordinate */
  2208. y) {
  2209. this.x = x;
  2210. this.y = y;
  2211. }
  2212. /**
  2213. * Gets a string with the Vector2 coordinates
  2214. * @returns a string with the Vector2 coordinates
  2215. */
  2216. Vector2.prototype.toString = function () {
  2217. return "{X: " + this.x + " Y:" + this.y + "}";
  2218. };
  2219. /**
  2220. * Gets class name
  2221. * @returns the string "Vector2"
  2222. */
  2223. Vector2.prototype.getClassName = function () {
  2224. return "Vector2";
  2225. };
  2226. /**
  2227. * Gets current vector hash code
  2228. * @returns the Vector2 hash code as a number
  2229. */
  2230. Vector2.prototype.getHashCode = function () {
  2231. var hash = this.x || 0;
  2232. hash = (hash * 397) ^ (this.y || 0);
  2233. return hash;
  2234. };
  2235. // Operators
  2236. /**
  2237. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2238. * @param array defines the source array
  2239. * @param index defines the offset in source array
  2240. * @returns the current Vector2
  2241. */
  2242. Vector2.prototype.toArray = function (array, index) {
  2243. if (index === void 0) { index = 0; }
  2244. array[index] = this.x;
  2245. array[index + 1] = this.y;
  2246. return this;
  2247. };
  2248. /**
  2249. * Copy the current vector to an array
  2250. * @returns a new array with 2 elements: the Vector2 coordinates.
  2251. */
  2252. Vector2.prototype.asArray = function () {
  2253. var result = new Array();
  2254. this.toArray(result, 0);
  2255. return result;
  2256. };
  2257. /**
  2258. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2259. * @param source defines the source Vector2
  2260. * @returns the current updated Vector2
  2261. */
  2262. Vector2.prototype.copyFrom = function (source) {
  2263. this.x = source.x;
  2264. this.y = source.y;
  2265. return this;
  2266. };
  2267. /**
  2268. * Sets the Vector2 coordinates with the given floats
  2269. * @param x defines the first coordinate
  2270. * @param y defines the second coordinate
  2271. * @returns the current updated Vector2
  2272. */
  2273. Vector2.prototype.copyFromFloats = function (x, y) {
  2274. this.x = x;
  2275. this.y = y;
  2276. return this;
  2277. };
  2278. /**
  2279. * Sets the Vector2 coordinates with the given floats
  2280. * @param x defines the first coordinate
  2281. * @param y defines the second coordinate
  2282. * @returns the current updated Vector2
  2283. */
  2284. Vector2.prototype.set = function (x, y) {
  2285. return this.copyFromFloats(x, y);
  2286. };
  2287. /**
  2288. * Add another vector with the current one
  2289. * @param otherVector defines the other vector
  2290. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2291. */
  2292. Vector2.prototype.add = function (otherVector) {
  2293. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2294. };
  2295. /**
  2296. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2297. * @param otherVector defines the other vector
  2298. * @param result defines the target vector
  2299. * @returns the unmodified current Vector2
  2300. */
  2301. Vector2.prototype.addToRef = function (otherVector, result) {
  2302. result.x = this.x + otherVector.x;
  2303. result.y = this.y + otherVector.y;
  2304. return this;
  2305. };
  2306. /**
  2307. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2308. * @param otherVector defines the other vector
  2309. * @returns the current updated Vector2
  2310. */
  2311. Vector2.prototype.addInPlace = function (otherVector) {
  2312. this.x += otherVector.x;
  2313. this.y += otherVector.y;
  2314. return this;
  2315. };
  2316. /**
  2317. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2318. * @param otherVector defines the other vector
  2319. * @returns a new Vector2
  2320. */
  2321. Vector2.prototype.addVector3 = function (otherVector) {
  2322. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2323. };
  2324. /**
  2325. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2326. * @param otherVector defines the other vector
  2327. * @returns a new Vector2
  2328. */
  2329. Vector2.prototype.subtract = function (otherVector) {
  2330. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2331. };
  2332. /**
  2333. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2334. * @param otherVector defines the other vector
  2335. * @param result defines the target vector
  2336. * @returns the unmodified current Vector2
  2337. */
  2338. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2339. result.x = this.x - otherVector.x;
  2340. result.y = this.y - otherVector.y;
  2341. return this;
  2342. };
  2343. /**
  2344. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2345. * @param otherVector defines the other vector
  2346. * @returns the current updated Vector2
  2347. */
  2348. Vector2.prototype.subtractInPlace = function (otherVector) {
  2349. this.x -= otherVector.x;
  2350. this.y -= otherVector.y;
  2351. return this;
  2352. };
  2353. /**
  2354. * Multiplies in place the current Vector2 coordinates by the given ones
  2355. * @param otherVector defines the other vector
  2356. * @returns the current updated Vector2
  2357. */
  2358. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2359. this.x *= otherVector.x;
  2360. this.y *= otherVector.y;
  2361. return this;
  2362. };
  2363. /**
  2364. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2365. * @param otherVector defines the other vector
  2366. * @returns a new Vector2
  2367. */
  2368. Vector2.prototype.multiply = function (otherVector) {
  2369. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2370. };
  2371. /**
  2372. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2373. * @param otherVector defines the other vector
  2374. * @param result defines the target vector
  2375. * @returns the unmodified current Vector2
  2376. */
  2377. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2378. result.x = this.x * otherVector.x;
  2379. result.y = this.y * otherVector.y;
  2380. return this;
  2381. };
  2382. /**
  2383. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2384. * @param x defines the first coordinate
  2385. * @param y defines the second coordinate
  2386. * @returns a new Vector2
  2387. */
  2388. Vector2.prototype.multiplyByFloats = function (x, y) {
  2389. return new Vector2(this.x * x, this.y * y);
  2390. };
  2391. /**
  2392. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2393. * @param otherVector defines the other vector
  2394. * @returns a new Vector2
  2395. */
  2396. Vector2.prototype.divide = function (otherVector) {
  2397. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2398. };
  2399. /**
  2400. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2401. * @param otherVector defines the other vector
  2402. * @param result defines the target vector
  2403. * @returns the unmodified current Vector2
  2404. */
  2405. Vector2.prototype.divideToRef = function (otherVector, result) {
  2406. result.x = this.x / otherVector.x;
  2407. result.y = this.y / otherVector.y;
  2408. return this;
  2409. };
  2410. /**
  2411. * Divides the current Vector3 coordinates by the given ones
  2412. * @param otherVector defines the other vector
  2413. * @returns the current updated Vector2
  2414. */
  2415. Vector2.prototype.divideInPlace = function (otherVector) {
  2416. return this.divideToRef(otherVector, this);
  2417. };
  2418. /**
  2419. * Gets a new Vector2 with current Vector2 negated coordinates
  2420. * @returns a new Vector2
  2421. */
  2422. Vector2.prototype.negate = function () {
  2423. return new Vector2(-this.x, -this.y);
  2424. };
  2425. /**
  2426. * Multiply the Vector2 coordinates by scale
  2427. * @param scale defines the scaling factor
  2428. * @returns the current updated Vector2
  2429. */
  2430. Vector2.prototype.scaleInPlace = function (scale) {
  2431. this.x *= scale;
  2432. this.y *= scale;
  2433. return this;
  2434. };
  2435. /**
  2436. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2437. * @param scale defines the scaling factor
  2438. * @returns a new Vector2
  2439. */
  2440. Vector2.prototype.scale = function (scale) {
  2441. var result = new Vector2(0, 0);
  2442. this.scaleToRef(scale, result);
  2443. return result;
  2444. };
  2445. /**
  2446. * Scale the current Vector2 values by a factor to a given Vector2
  2447. * @param scale defines the scale factor
  2448. * @param result defines the Vector2 object where to store the result
  2449. * @returns the unmodified current Vector2
  2450. */
  2451. Vector2.prototype.scaleToRef = function (scale, result) {
  2452. result.x = this.x * scale;
  2453. result.y = this.y * scale;
  2454. return this;
  2455. };
  2456. /**
  2457. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2458. * @param scale defines the scale factor
  2459. * @param result defines the Vector2 object where to store the result
  2460. * @returns the unmodified current Vector2
  2461. */
  2462. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2463. result.x += this.x * scale;
  2464. result.y += this.y * scale;
  2465. return this;
  2466. };
  2467. /**
  2468. * Gets a boolean if two vectors are equals
  2469. * @param otherVector defines the other vector
  2470. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2471. */
  2472. Vector2.prototype.equals = function (otherVector) {
  2473. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2474. };
  2475. /**
  2476. * Gets a boolean if two vectors are equals (using an epsilon value)
  2477. * @param otherVector defines the other vector
  2478. * @param epsilon defines the minimal distance to consider equality
  2479. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2480. */
  2481. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2482. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2483. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2484. };
  2485. // Properties
  2486. /**
  2487. * Gets the length of the vector
  2488. * @returns the vector length (float)
  2489. */
  2490. Vector2.prototype.length = function () {
  2491. return Math.sqrt(this.x * this.x + this.y * this.y);
  2492. };
  2493. /**
  2494. * Gets the vector squared length
  2495. * @returns the vector squared length (float)
  2496. */
  2497. Vector2.prototype.lengthSquared = function () {
  2498. return (this.x * this.x + this.y * this.y);
  2499. };
  2500. // Methods
  2501. /**
  2502. * Normalize the vector
  2503. * @returns the current updated Vector2
  2504. */
  2505. Vector2.prototype.normalize = function () {
  2506. var len = this.length();
  2507. if (len === 0)
  2508. return this;
  2509. var num = 1.0 / len;
  2510. this.x *= num;
  2511. this.y *= num;
  2512. return this;
  2513. };
  2514. /**
  2515. * Gets a new Vector2 copied from the Vector2
  2516. * @returns a new Vector2
  2517. */
  2518. Vector2.prototype.clone = function () {
  2519. return new Vector2(this.x, this.y);
  2520. };
  2521. // Statics
  2522. /**
  2523. * Gets a new Vector2(0, 0)
  2524. * @returns a new Vector2
  2525. */
  2526. Vector2.Zero = function () {
  2527. return new Vector2(0, 0);
  2528. };
  2529. /**
  2530. * Gets a new Vector2(1, 1)
  2531. * @returns a new Vector2
  2532. */
  2533. Vector2.One = function () {
  2534. return new Vector2(1, 1);
  2535. };
  2536. /**
  2537. * Gets a new Vector2 set from the given index element of the given array
  2538. * @param array defines the data source
  2539. * @param offset defines the offset in the data source
  2540. * @returns a new Vector2
  2541. */
  2542. Vector2.FromArray = function (array, offset) {
  2543. if (offset === void 0) { offset = 0; }
  2544. return new Vector2(array[offset], array[offset + 1]);
  2545. };
  2546. /**
  2547. * Sets "result" from the given index element of the given array
  2548. * @param array defines the data source
  2549. * @param offset defines the offset in the data source
  2550. * @param result defines the target vector
  2551. */
  2552. Vector2.FromArrayToRef = function (array, offset, result) {
  2553. result.x = array[offset];
  2554. result.y = array[offset + 1];
  2555. };
  2556. /**
  2557. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2558. * @param value1 defines 1st point of control
  2559. * @param value2 defines 2nd point of control
  2560. * @param value3 defines 3rd point of control
  2561. * @param value4 defines 4th point of control
  2562. * @param amount defines the interpolation factor
  2563. * @returns a new Vector2
  2564. */
  2565. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2566. var squared = amount * amount;
  2567. var cubed = amount * squared;
  2568. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2569. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2570. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2571. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2572. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2573. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2574. return new Vector2(x, y);
  2575. };
  2576. /**
  2577. * 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".
  2578. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2579. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2580. * @param value defines the value to clamp
  2581. * @param min defines the lower limit
  2582. * @param max defines the upper limit
  2583. * @returns a new Vector2
  2584. */
  2585. Vector2.Clamp = function (value, min, max) {
  2586. var x = value.x;
  2587. x = (x > max.x) ? max.x : x;
  2588. x = (x < min.x) ? min.x : x;
  2589. var y = value.y;
  2590. y = (y > max.y) ? max.y : y;
  2591. y = (y < min.y) ? min.y : y;
  2592. return new Vector2(x, y);
  2593. };
  2594. /**
  2595. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2596. * @param value1 defines the 1st control point
  2597. * @param tangent1 defines the outgoing tangent
  2598. * @param value2 defines the 2nd control point
  2599. * @param tangent2 defines the incoming tangent
  2600. * @param amount defines the interpolation factor
  2601. * @returns a new Vector2
  2602. */
  2603. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2604. var squared = amount * amount;
  2605. var cubed = amount * squared;
  2606. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2607. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2608. var part3 = (cubed - (2.0 * squared)) + amount;
  2609. var part4 = cubed - squared;
  2610. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2611. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2612. return new Vector2(x, y);
  2613. };
  2614. /**
  2615. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2616. * @param start defines the start vector
  2617. * @param end defines the end vector
  2618. * @param amount defines the interpolation factor
  2619. * @returns a new Vector2
  2620. */
  2621. Vector2.Lerp = function (start, end, amount) {
  2622. var x = start.x + ((end.x - start.x) * amount);
  2623. var y = start.y + ((end.y - start.y) * amount);
  2624. return new Vector2(x, y);
  2625. };
  2626. /**
  2627. * Gets the dot product of the vector "left" and the vector "right"
  2628. * @param left defines first vector
  2629. * @param right defines second vector
  2630. * @returns the dot product (float)
  2631. */
  2632. Vector2.Dot = function (left, right) {
  2633. return left.x * right.x + left.y * right.y;
  2634. };
  2635. /**
  2636. * Returns a new Vector2 equal to the normalized given vector
  2637. * @param vector defines the vector to normalize
  2638. * @returns a new Vector2
  2639. */
  2640. Vector2.Normalize = function (vector) {
  2641. var newVector = vector.clone();
  2642. newVector.normalize();
  2643. return newVector;
  2644. };
  2645. /**
  2646. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2647. * @param left defines 1st vector
  2648. * @param right defines 2nd vector
  2649. * @returns a new Vector2
  2650. */
  2651. Vector2.Minimize = function (left, right) {
  2652. var x = (left.x < right.x) ? left.x : right.x;
  2653. var y = (left.y < right.y) ? left.y : right.y;
  2654. return new Vector2(x, y);
  2655. };
  2656. /**
  2657. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2658. * @param left defines 1st vector
  2659. * @param right defines 2nd vector
  2660. * @returns a new Vector2
  2661. */
  2662. Vector2.Maximize = function (left, right) {
  2663. var x = (left.x > right.x) ? left.x : right.x;
  2664. var y = (left.y > right.y) ? left.y : right.y;
  2665. return new Vector2(x, y);
  2666. };
  2667. /**
  2668. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2669. * @param vector defines the vector to transform
  2670. * @param transformation defines the matrix to apply
  2671. * @returns a new Vector2
  2672. */
  2673. Vector2.Transform = function (vector, transformation) {
  2674. var r = Vector2.Zero();
  2675. Vector2.TransformToRef(vector, transformation, r);
  2676. return r;
  2677. };
  2678. /**
  2679. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2680. * @param vector defines the vector to transform
  2681. * @param transformation defines the matrix to apply
  2682. * @param result defines the target vector
  2683. */
  2684. Vector2.TransformToRef = function (vector, transformation, result) {
  2685. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2686. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2687. result.x = x;
  2688. result.y = y;
  2689. };
  2690. /**
  2691. * Determines if a given vector is included in a triangle
  2692. * @param p defines the vector to test
  2693. * @param p0 defines 1st triangle point
  2694. * @param p1 defines 2nd triangle point
  2695. * @param p2 defines 3rd triangle point
  2696. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2697. */
  2698. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2699. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2700. var sign = a < 0 ? -1 : 1;
  2701. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2702. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2703. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2704. };
  2705. /**
  2706. * Gets the distance between the vectors "value1" and "value2"
  2707. * @param value1 defines first vector
  2708. * @param value2 defines second vector
  2709. * @returns the distance between vectors
  2710. */
  2711. Vector2.Distance = function (value1, value2) {
  2712. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2713. };
  2714. /**
  2715. * Returns the squared distance between the vectors "value1" and "value2"
  2716. * @param value1 defines first vector
  2717. * @param value2 defines second vector
  2718. * @returns the squared distance between vectors
  2719. */
  2720. Vector2.DistanceSquared = function (value1, value2) {
  2721. var x = value1.x - value2.x;
  2722. var y = value1.y - value2.y;
  2723. return (x * x) + (y * y);
  2724. };
  2725. /**
  2726. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2727. * @param value1 defines first vector
  2728. * @param value2 defines second vector
  2729. * @returns a new Vector2
  2730. */
  2731. Vector2.Center = function (value1, value2) {
  2732. var center = value1.add(value2);
  2733. center.scaleInPlace(0.5);
  2734. return center;
  2735. };
  2736. /**
  2737. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2738. * @param p defines the middle point
  2739. * @param segA defines one point of the segment
  2740. * @param segB defines the other point of the segment
  2741. * @returns the shortest distance
  2742. */
  2743. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2744. var l2 = Vector2.DistanceSquared(segA, segB);
  2745. if (l2 === 0.0) {
  2746. return Vector2.Distance(p, segA);
  2747. }
  2748. var v = segB.subtract(segA);
  2749. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2750. var proj = segA.add(v.multiplyByFloats(t, t));
  2751. return Vector2.Distance(p, proj);
  2752. };
  2753. return Vector2;
  2754. }());
  2755. BABYLON.Vector2 = Vector2;
  2756. /**
  2757. * Classed used to store (x,y,z) vector representation
  2758. * A Vector3 is the main object used in 3D geometry
  2759. * It can represent etiher the coordinates of a point the space, either a direction
  2760. * Reminder: Babylon.js uses a left handed forward facing system
  2761. */
  2762. var Vector3 = /** @class */ (function () {
  2763. /**
  2764. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2765. * @param x defines the first coordinates (on X axis)
  2766. * @param y defines the second coordinates (on Y axis)
  2767. * @param z defines the third coordinates (on Z axis)
  2768. */
  2769. function Vector3(
  2770. /**
  2771. * Defines the first coordinates (on X axis)
  2772. */
  2773. x,
  2774. /**
  2775. * Defines the second coordinates (on Y axis)
  2776. */
  2777. y,
  2778. /**
  2779. * Defines the third coordinates (on Z axis)
  2780. */
  2781. z) {
  2782. this.x = x;
  2783. this.y = y;
  2784. this.z = z;
  2785. }
  2786. /**
  2787. * Creates a string representation of the Vector3
  2788. * @returns a string with the Vector3 coordinates.
  2789. */
  2790. Vector3.prototype.toString = function () {
  2791. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2792. };
  2793. /**
  2794. * Gets the class name
  2795. * @returns the string "Vector3"
  2796. */
  2797. Vector3.prototype.getClassName = function () {
  2798. return "Vector3";
  2799. };
  2800. /**
  2801. * Creates the Vector3 hash code
  2802. * @returns a number which tends to be unique between Vector3 instances
  2803. */
  2804. Vector3.prototype.getHashCode = function () {
  2805. var hash = this.x || 0;
  2806. hash = (hash * 397) ^ (this.y || 0);
  2807. hash = (hash * 397) ^ (this.z || 0);
  2808. return hash;
  2809. };
  2810. // Operators
  2811. /**
  2812. * Creates an array containing three elements : the coordinates of the Vector3
  2813. * @returns a new array of numbers
  2814. */
  2815. Vector3.prototype.asArray = function () {
  2816. var result = [];
  2817. this.toArray(result, 0);
  2818. return result;
  2819. };
  2820. /**
  2821. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2822. * @param array defines the destination array
  2823. * @param index defines the offset in the destination array
  2824. * @returns the current Vector3
  2825. */
  2826. Vector3.prototype.toArray = function (array, index) {
  2827. if (index === void 0) { index = 0; }
  2828. array[index] = this.x;
  2829. array[index + 1] = this.y;
  2830. array[index + 2] = this.z;
  2831. return this;
  2832. };
  2833. /**
  2834. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2835. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2836. */
  2837. Vector3.prototype.toQuaternion = function () {
  2838. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2839. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2840. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2841. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2842. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2843. var cosy = Math.cos(this.y * 0.5);
  2844. var siny = Math.sin(this.y * 0.5);
  2845. result.x = coszMinusx * siny;
  2846. result.y = -sinzMinusx * siny;
  2847. result.z = sinxPlusz * cosy;
  2848. result.w = cosxPlusz * cosy;
  2849. return result;
  2850. };
  2851. /**
  2852. * Adds the given vector to the current Vector3
  2853. * @param otherVector defines the second operand
  2854. * @returns the current updated Vector3
  2855. */
  2856. Vector3.prototype.addInPlace = function (otherVector) {
  2857. this.x += otherVector.x;
  2858. this.y += otherVector.y;
  2859. this.z += otherVector.z;
  2860. return this;
  2861. };
  2862. /**
  2863. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2864. * @param otherVector defines the second operand
  2865. * @returns the resulting Vector3
  2866. */
  2867. Vector3.prototype.add = function (otherVector) {
  2868. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2869. };
  2870. /**
  2871. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2872. * @param otherVector defines the second operand
  2873. * @param result defines the Vector3 object where to store the result
  2874. * @returns the current Vector3
  2875. */
  2876. Vector3.prototype.addToRef = function (otherVector, result) {
  2877. result.x = this.x + otherVector.x;
  2878. result.y = this.y + otherVector.y;
  2879. result.z = this.z + otherVector.z;
  2880. return this;
  2881. };
  2882. /**
  2883. * Subtract the given vector from the current Vector3
  2884. * @param otherVector defines the second operand
  2885. * @returns the current updated Vector3
  2886. */
  2887. Vector3.prototype.subtractInPlace = function (otherVector) {
  2888. this.x -= otherVector.x;
  2889. this.y -= otherVector.y;
  2890. this.z -= otherVector.z;
  2891. return this;
  2892. };
  2893. /**
  2894. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2895. * @param otherVector defines the second operand
  2896. * @returns the resulting Vector3
  2897. */
  2898. Vector3.prototype.subtract = function (otherVector) {
  2899. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2900. };
  2901. /**
  2902. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2903. * @param otherVector defines the second operand
  2904. * @param result defines the Vector3 object where to store the result
  2905. * @returns the current Vector3
  2906. */
  2907. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2908. result.x = this.x - otherVector.x;
  2909. result.y = this.y - otherVector.y;
  2910. result.z = this.z - otherVector.z;
  2911. return this;
  2912. };
  2913. /**
  2914. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2915. * @param x defines the x coordinate of the operand
  2916. * @param y defines the y coordinate of the operand
  2917. * @param z defines the z coordinate of the operand
  2918. * @returns the resulting Vector3
  2919. */
  2920. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2921. return new Vector3(this.x - x, this.y - y, this.z - z);
  2922. };
  2923. /**
  2924. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2925. * @param x defines the x coordinate of the operand
  2926. * @param y defines the y coordinate of the operand
  2927. * @param z defines the z coordinate of the operand
  2928. * @param result defines the Vector3 object where to store the result
  2929. * @returns the current Vector3
  2930. */
  2931. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2932. result.x = this.x - x;
  2933. result.y = this.y - y;
  2934. result.z = this.z - z;
  2935. return this;
  2936. };
  2937. /**
  2938. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2939. * @returns a new Vector3
  2940. */
  2941. Vector3.prototype.negate = function () {
  2942. return new Vector3(-this.x, -this.y, -this.z);
  2943. };
  2944. /**
  2945. * Multiplies the Vector3 coordinates by the float "scale"
  2946. * @param scale defines the multiplier factor
  2947. * @returns the current updated Vector3
  2948. */
  2949. Vector3.prototype.scaleInPlace = function (scale) {
  2950. this.x *= scale;
  2951. this.y *= scale;
  2952. this.z *= scale;
  2953. return this;
  2954. };
  2955. /**
  2956. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2957. * @param scale defines the multiplier factor
  2958. * @returns a new Vector3
  2959. */
  2960. Vector3.prototype.scale = function (scale) {
  2961. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2962. };
  2963. /**
  2964. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2965. * @param scale defines the multiplier factor
  2966. * @param result defines the Vector3 object where to store the result
  2967. * @returns the current Vector3
  2968. */
  2969. Vector3.prototype.scaleToRef = function (scale, result) {
  2970. result.x = this.x * scale;
  2971. result.y = this.y * scale;
  2972. result.z = this.z * scale;
  2973. return this;
  2974. };
  2975. /**
  2976. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2977. * @param scale defines the scale factor
  2978. * @param result defines the Vector3 object where to store the result
  2979. * @returns the unmodified current Vector3
  2980. */
  2981. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2982. result.x += this.x * scale;
  2983. result.y += this.y * scale;
  2984. result.z += this.z * scale;
  2985. return this;
  2986. };
  2987. /**
  2988. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2989. * @param otherVector defines the second operand
  2990. * @returns true if both vectors are equals
  2991. */
  2992. Vector3.prototype.equals = function (otherVector) {
  2993. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2994. };
  2995. /**
  2996. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2997. * @param otherVector defines the second operand
  2998. * @param epsilon defines the minimal distance to define values as equals
  2999. * @returns true if both vectors are distant less than epsilon
  3000. */
  3001. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3002. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3003. 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);
  3004. };
  3005. /**
  3006. * Returns true if the current Vector3 coordinates equals the given floats
  3007. * @param x defines the x coordinate of the operand
  3008. * @param y defines the y coordinate of the operand
  3009. * @param z defines the z coordinate of the operand
  3010. * @returns true if both vectors are equals
  3011. */
  3012. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3013. return this.x === x && this.y === y && this.z === z;
  3014. };
  3015. /**
  3016. * Multiplies the current Vector3 coordinates by the given ones
  3017. * @param otherVector defines the second operand
  3018. * @returns the current updated Vector3
  3019. */
  3020. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3021. this.x *= otherVector.x;
  3022. this.y *= otherVector.y;
  3023. this.z *= otherVector.z;
  3024. return this;
  3025. };
  3026. /**
  3027. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3028. * @param otherVector defines the second operand
  3029. * @returns the new Vector3
  3030. */
  3031. Vector3.prototype.multiply = function (otherVector) {
  3032. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3033. };
  3034. /**
  3035. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3036. * @param otherVector defines the second operand
  3037. * @param result defines the Vector3 object where to store the result
  3038. * @returns the current Vector3
  3039. */
  3040. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3041. result.x = this.x * otherVector.x;
  3042. result.y = this.y * otherVector.y;
  3043. result.z = this.z * otherVector.z;
  3044. return this;
  3045. };
  3046. /**
  3047. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3048. * @param x defines the x coordinate of the operand
  3049. * @param y defines the y coordinate of the operand
  3050. * @param z defines the z coordinate of the operand
  3051. * @returns the new Vector3
  3052. */
  3053. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3054. return new Vector3(this.x * x, this.y * y, this.z * z);
  3055. };
  3056. /**
  3057. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3058. * @param otherVector defines the second operand
  3059. * @returns the new Vector3
  3060. */
  3061. Vector3.prototype.divide = function (otherVector) {
  3062. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3063. };
  3064. /**
  3065. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3066. * @param otherVector defines the second operand
  3067. * @param result defines the Vector3 object where to store the result
  3068. * @returns the current Vector3
  3069. */
  3070. Vector3.prototype.divideToRef = function (otherVector, result) {
  3071. result.x = this.x / otherVector.x;
  3072. result.y = this.y / otherVector.y;
  3073. result.z = this.z / otherVector.z;
  3074. return this;
  3075. };
  3076. /**
  3077. * Divides the current Vector3 coordinates by the given ones.
  3078. * @param otherVector defines the second operand
  3079. * @returns the current updated Vector3
  3080. */
  3081. Vector3.prototype.divideInPlace = function (otherVector) {
  3082. return this.divideToRef(otherVector, this);
  3083. };
  3084. /**
  3085. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3086. * @param other defines the second operand
  3087. * @returns the current updated Vector3
  3088. */
  3089. Vector3.prototype.minimizeInPlace = function (other) {
  3090. if (other.x < this.x)
  3091. this.x = other.x;
  3092. if (other.y < this.y)
  3093. this.y = other.y;
  3094. if (other.z < this.z)
  3095. this.z = other.z;
  3096. return this;
  3097. };
  3098. /**
  3099. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3100. * @param other defines the second operand
  3101. * @returns the current updated Vector3
  3102. */
  3103. Vector3.prototype.maximizeInPlace = function (other) {
  3104. if (other.x > this.x)
  3105. this.x = other.x;
  3106. if (other.y > this.y)
  3107. this.y = other.y;
  3108. if (other.z > this.z)
  3109. this.z = other.z;
  3110. return this;
  3111. };
  3112. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3113. /**
  3114. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3115. */
  3116. get: function () {
  3117. var absX = Math.abs(this.x);
  3118. var absY = Math.abs(this.y);
  3119. if (absX !== absY) {
  3120. return true;
  3121. }
  3122. var absZ = Math.abs(this.z);
  3123. if (absX !== absZ) {
  3124. return true;
  3125. }
  3126. if (absY !== absZ) {
  3127. return true;
  3128. }
  3129. return false;
  3130. },
  3131. enumerable: true,
  3132. configurable: true
  3133. });
  3134. // Properties
  3135. /**
  3136. * Gets the length of the Vector3
  3137. * @returns the length of the Vecto3
  3138. */
  3139. Vector3.prototype.length = function () {
  3140. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3141. };
  3142. /**
  3143. * Gets the squared length of the Vector3
  3144. * @returns squared length of the Vector3
  3145. */
  3146. Vector3.prototype.lengthSquared = function () {
  3147. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3148. };
  3149. /**
  3150. * Normalize the current Vector3.
  3151. * Please note that this is an in place operation.
  3152. * @returns the current updated Vector3
  3153. */
  3154. Vector3.prototype.normalize = function () {
  3155. var len = this.length();
  3156. if (len === 0 || len === 1.0)
  3157. return this;
  3158. var num = 1.0 / len;
  3159. this.x *= num;
  3160. this.y *= num;
  3161. this.z *= num;
  3162. return this;
  3163. };
  3164. /**
  3165. * Normalize the current Vector3 to a new vector
  3166. * @returns the new Vector3
  3167. */
  3168. Vector3.prototype.normalizeToNew = function () {
  3169. var normalized = new Vector3(0, 0, 0);
  3170. this.normalizeToRef(normalized);
  3171. return normalized;
  3172. };
  3173. /**
  3174. * Normalize the current Vector3 to the reference
  3175. * @param reference define the Vector3 to update
  3176. * @returns the updated Vector3
  3177. */
  3178. Vector3.prototype.normalizeToRef = function (reference) {
  3179. var len = this.length();
  3180. if (len === 0 || len === 1.0) {
  3181. reference.set(this.x, this.y, this.z);
  3182. return reference;
  3183. }
  3184. var scale = 1.0 / len;
  3185. this.scaleToRef(scale, reference);
  3186. return reference;
  3187. };
  3188. /**
  3189. * Creates a new Vector3 copied from the current Vector3
  3190. * @returns the new Vector3
  3191. */
  3192. Vector3.prototype.clone = function () {
  3193. return new Vector3(this.x, this.y, this.z);
  3194. };
  3195. /**
  3196. * Copies the given vector coordinates to the current Vector3 ones
  3197. * @param source defines the source Vector3
  3198. * @returns the current updated Vector3
  3199. */
  3200. Vector3.prototype.copyFrom = function (source) {
  3201. this.x = source.x;
  3202. this.y = source.y;
  3203. this.z = source.z;
  3204. return this;
  3205. };
  3206. /**
  3207. * Copies the given floats to the current Vector3 coordinates
  3208. * @param x defines the x coordinate of the operand
  3209. * @param y defines the y coordinate of the operand
  3210. * @param z defines the z coordinate of the operand
  3211. * @returns the current updated Vector3
  3212. */
  3213. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3214. this.x = x;
  3215. this.y = y;
  3216. this.z = z;
  3217. return this;
  3218. };
  3219. /**
  3220. * Copies the given floats to the current Vector3 coordinates
  3221. * @param x defines the x coordinate of the operand
  3222. * @param y defines the y coordinate of the operand
  3223. * @param z defines the z coordinate of the operand
  3224. * @returns the current updated Vector3
  3225. */
  3226. Vector3.prototype.set = function (x, y, z) {
  3227. return this.copyFromFloats(x, y, z);
  3228. };
  3229. // Statics
  3230. /**
  3231. * Get the clip factor between two vectors
  3232. * @param vector0 defines the first operand
  3233. * @param vector1 defines the second operand
  3234. * @param axis defines the axis to use
  3235. * @param size defines the size along the axis
  3236. * @returns the clip factor
  3237. */
  3238. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3239. var d0 = Vector3.Dot(vector0, axis) - size;
  3240. var d1 = Vector3.Dot(vector1, axis) - size;
  3241. var s = d0 / (d0 - d1);
  3242. return s;
  3243. };
  3244. /**
  3245. * Get angle between two vectors
  3246. * @param vector0 angle between vector0 and vector1
  3247. * @param vector1 angle between vector0 and vector1
  3248. * @param normal direction of the normal
  3249. * @return the angle between vector0 and vector1
  3250. */
  3251. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3252. var v0 = vector0.clone().normalize();
  3253. var v1 = vector1.clone().normalize();
  3254. var dot = Vector3.Dot(v0, v1);
  3255. var n = Vector3.Cross(v0, v1);
  3256. if (Vector3.Dot(n, normal) > 0) {
  3257. return Math.acos(dot);
  3258. }
  3259. return -Math.acos(dot);
  3260. };
  3261. /**
  3262. * Returns a new Vector3 set from the index "offset" of the given array
  3263. * @param array defines the source array
  3264. * @param offset defines the offset in the source array
  3265. * @returns the new Vector3
  3266. */
  3267. Vector3.FromArray = function (array, offset) {
  3268. if (!offset) {
  3269. offset = 0;
  3270. }
  3271. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3272. };
  3273. /**
  3274. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3275. * This function is deprecated. Use FromArray instead
  3276. * @param array defines the source array
  3277. * @param offset defines the offset in the source array
  3278. * @returns the new Vector3
  3279. */
  3280. Vector3.FromFloatArray = function (array, offset) {
  3281. return Vector3.FromArray(array, offset);
  3282. };
  3283. /**
  3284. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3285. * @param array defines the source array
  3286. * @param offset defines the offset in the source array
  3287. * @param result defines the Vector3 where to store the result
  3288. */
  3289. Vector3.FromArrayToRef = function (array, offset, result) {
  3290. result.x = array[offset];
  3291. result.y = array[offset + 1];
  3292. result.z = array[offset + 2];
  3293. };
  3294. /**
  3295. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3296. * This function is deprecated. Use FromArrayToRef instead.
  3297. * @param array defines the source array
  3298. * @param offset defines the offset in the source array
  3299. * @param result defines the Vector3 where to store the result
  3300. */
  3301. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3302. return Vector3.FromArrayToRef(array, offset, result);
  3303. };
  3304. /**
  3305. * Sets the given vector "result" with the given floats.
  3306. * @param x defines the x coordinate of the source
  3307. * @param y defines the y coordinate of the source
  3308. * @param z defines the z coordinate of the source
  3309. * @param result defines the Vector3 where to store the result
  3310. */
  3311. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3312. result.x = x;
  3313. result.y = y;
  3314. result.z = z;
  3315. };
  3316. /**
  3317. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3318. * @returns a new empty Vector3
  3319. */
  3320. Vector3.Zero = function () {
  3321. return new Vector3(0.0, 0.0, 0.0);
  3322. };
  3323. /**
  3324. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3325. * @returns a new unit Vector3
  3326. */
  3327. Vector3.One = function () {
  3328. return new Vector3(1.0, 1.0, 1.0);
  3329. };
  3330. /**
  3331. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3332. * @returns a new up Vector3
  3333. */
  3334. Vector3.Up = function () {
  3335. return new Vector3(0.0, 1.0, 0.0);
  3336. };
  3337. /**
  3338. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3339. * @returns a new forward Vector3
  3340. */
  3341. Vector3.Forward = function () {
  3342. return new Vector3(0.0, 0.0, 1.0);
  3343. };
  3344. /**
  3345. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3346. * @returns a new right Vector3
  3347. */
  3348. Vector3.Right = function () {
  3349. return new Vector3(1.0, 0.0, 0.0);
  3350. };
  3351. /**
  3352. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3353. * @returns a new left Vector3
  3354. */
  3355. Vector3.Left = function () {
  3356. return new Vector3(-1.0, 0.0, 0.0);
  3357. };
  3358. /**
  3359. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3360. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3361. * @param vector defines the Vector3 to transform
  3362. * @param transformation defines the transformation matrix
  3363. * @returns the transformed Vector3
  3364. */
  3365. Vector3.TransformCoordinates = function (vector, transformation) {
  3366. var result = Vector3.Zero();
  3367. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3368. return result;
  3369. };
  3370. /**
  3371. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3372. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3373. * @param vector defines the Vector3 to transform
  3374. * @param transformation defines the transformation matrix
  3375. * @param result defines the Vector3 where to store the result
  3376. */
  3377. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3378. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3379. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3380. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3381. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3382. result.x = x / w;
  3383. result.y = y / w;
  3384. result.z = z / w;
  3385. };
  3386. /**
  3387. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3388. * This method computes tranformed coordinates only, not transformed direction vectors
  3389. * @param x define the x coordinate of the source vector
  3390. * @param y define the y coordinate of the source vector
  3391. * @param z define the z coordinate of the source vector
  3392. * @param transformation defines the transformation matrix
  3393. * @param result defines the Vector3 where to store the result
  3394. */
  3395. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3396. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3397. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3398. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3399. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3400. result.x = rx / rw;
  3401. result.y = ry / rw;
  3402. result.z = rz / rw;
  3403. };
  3404. /**
  3405. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3406. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3407. * @param vector defines the Vector3 to transform
  3408. * @param transformation defines the transformation matrix
  3409. * @returns the new Vector3
  3410. */
  3411. Vector3.TransformNormal = function (vector, transformation) {
  3412. var result = Vector3.Zero();
  3413. Vector3.TransformNormalToRef(vector, transformation, result);
  3414. return result;
  3415. };
  3416. /**
  3417. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3418. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3419. * @param vector defines the Vector3 to transform
  3420. * @param transformation defines the transformation matrix
  3421. * @param result defines the Vector3 where to store the result
  3422. */
  3423. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3424. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3425. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3426. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3427. result.x = x;
  3428. result.y = y;
  3429. result.z = z;
  3430. };
  3431. /**
  3432. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3433. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3434. * @param x define the x coordinate of the source vector
  3435. * @param y define the y coordinate of the source vector
  3436. * @param z define the z coordinate of the source vector
  3437. * @param transformation defines the transformation matrix
  3438. * @param result defines the Vector3 where to store the result
  3439. */
  3440. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3441. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3442. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3443. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3444. };
  3445. /**
  3446. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3447. * @param value1 defines the first control point
  3448. * @param value2 defines the second control point
  3449. * @param value3 defines the third control point
  3450. * @param value4 defines the fourth control point
  3451. * @param amount defines the amount on the spline to use
  3452. * @returns the new Vector3
  3453. */
  3454. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3455. var squared = amount * amount;
  3456. var cubed = amount * squared;
  3457. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3458. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3459. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3460. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3461. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3462. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3463. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3464. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3465. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3466. return new Vector3(x, y, z);
  3467. };
  3468. /**
  3469. * 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"
  3470. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3471. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3472. * @param value defines the current value
  3473. * @param min defines the lower range value
  3474. * @param max defines the upper range value
  3475. * @returns the new Vector3
  3476. */
  3477. Vector3.Clamp = function (value, min, max) {
  3478. var x = value.x;
  3479. x = (x > max.x) ? max.x : x;
  3480. x = (x < min.x) ? min.x : x;
  3481. var y = value.y;
  3482. y = (y > max.y) ? max.y : y;
  3483. y = (y < min.y) ? min.y : y;
  3484. var z = value.z;
  3485. z = (z > max.z) ? max.z : z;
  3486. z = (z < min.z) ? min.z : z;
  3487. return new Vector3(x, y, z);
  3488. };
  3489. /**
  3490. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3491. * @param value1 defines the first control point
  3492. * @param tangent1 defines the first tangent vector
  3493. * @param value2 defines the second control point
  3494. * @param tangent2 defines the second tangent vector
  3495. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3496. * @returns the new Vector3
  3497. */
  3498. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3499. var squared = amount * amount;
  3500. var cubed = amount * squared;
  3501. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3502. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3503. var part3 = (cubed - (2.0 * squared)) + amount;
  3504. var part4 = cubed - squared;
  3505. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3506. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3507. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3508. return new Vector3(x, y, z);
  3509. };
  3510. /**
  3511. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3512. * @param start defines the start value
  3513. * @param end defines the end value
  3514. * @param amount max defines amount between both (between 0 and 1)
  3515. * @returns the new Vector3
  3516. */
  3517. Vector3.Lerp = function (start, end, amount) {
  3518. var result = new Vector3(0, 0, 0);
  3519. Vector3.LerpToRef(start, end, amount, result);
  3520. return result;
  3521. };
  3522. /**
  3523. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3524. * @param start defines the start value
  3525. * @param end defines the end value
  3526. * @param amount max defines amount between both (between 0 and 1)
  3527. * @param result defines the Vector3 where to store the result
  3528. */
  3529. Vector3.LerpToRef = function (start, end, amount, result) {
  3530. result.x = start.x + ((end.x - start.x) * amount);
  3531. result.y = start.y + ((end.y - start.y) * amount);
  3532. result.z = start.z + ((end.z - start.z) * amount);
  3533. };
  3534. /**
  3535. * Returns the dot product (float) between the vectors "left" and "right"
  3536. * @param left defines the left operand
  3537. * @param right defines the right operand
  3538. * @returns the dot product
  3539. */
  3540. Vector3.Dot = function (left, right) {
  3541. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3542. };
  3543. /**
  3544. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3545. * The cross product is then orthogonal to both "left" and "right"
  3546. * @param left defines the left operand
  3547. * @param right defines the right operand
  3548. * @returns the cross product
  3549. */
  3550. Vector3.Cross = function (left, right) {
  3551. var result = Vector3.Zero();
  3552. Vector3.CrossToRef(left, right, result);
  3553. return result;
  3554. };
  3555. /**
  3556. * Sets the given vector "result" with the cross product of "left" and "right"
  3557. * The cross product is then orthogonal to both "left" and "right"
  3558. * @param left defines the left operand
  3559. * @param right defines the right operand
  3560. * @param result defines the Vector3 where to store the result
  3561. */
  3562. Vector3.CrossToRef = function (left, right, result) {
  3563. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3564. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3565. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3566. result.copyFrom(MathTmp.Vector3[0]);
  3567. };
  3568. /**
  3569. * Returns a new Vector3 as the normalization of the given vector
  3570. * @param vector defines the Vector3 to normalize
  3571. * @returns the new Vector3
  3572. */
  3573. Vector3.Normalize = function (vector) {
  3574. var result = Vector3.Zero();
  3575. Vector3.NormalizeToRef(vector, result);
  3576. return result;
  3577. };
  3578. /**
  3579. * Sets the given vector "result" with the normalization of the given first vector
  3580. * @param vector defines the Vector3 to normalize
  3581. * @param result defines the Vector3 where to store the result
  3582. */
  3583. Vector3.NormalizeToRef = function (vector, result) {
  3584. result.copyFrom(vector);
  3585. result.normalize();
  3586. };
  3587. /**
  3588. * Project a Vector3 onto screen space
  3589. * @param vector defines the Vector3 to project
  3590. * @param world defines the world matrix to use
  3591. * @param transform defines the transform (view x projection) matrix to use
  3592. * @param viewport defines the screen viewport to use
  3593. * @returns the new Vector3
  3594. */
  3595. Vector3.Project = function (vector, world, transform, viewport) {
  3596. var cw = viewport.width;
  3597. var ch = viewport.height;
  3598. var cx = viewport.x;
  3599. var cy = viewport.y;
  3600. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3601. 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);
  3602. var matrix = MathTmp.Matrix[0];
  3603. world.multiplyToRef(transform, matrix);
  3604. matrix.multiplyToRef(viewportMatrix, matrix);
  3605. return Vector3.TransformCoordinates(vector, matrix);
  3606. };
  3607. /**
  3608. * Unproject from screen space to object space
  3609. * @param source defines the screen space Vector3 to use
  3610. * @param viewportWidth defines the current width of the viewport
  3611. * @param viewportHeight defines the current height of the viewport
  3612. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3613. * @param transform defines the transform (view x projection) matrix to use
  3614. * @returns the new Vector3
  3615. */
  3616. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3617. var matrix = MathTmp.Matrix[0];
  3618. world.multiplyToRef(transform, matrix);
  3619. matrix.invert();
  3620. source.x = source.x / viewportWidth * 2 - 1;
  3621. source.y = -(source.y / viewportHeight * 2 - 1);
  3622. var vector = Vector3.TransformCoordinates(source, matrix);
  3623. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3624. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3625. vector = vector.scale(1.0 / num);
  3626. }
  3627. return vector;
  3628. };
  3629. /**
  3630. * Unproject from screen space to object space
  3631. * @param source defines the screen space Vector3 to use
  3632. * @param viewportWidth defines the current width of the viewport
  3633. * @param viewportHeight defines the current height of the viewport
  3634. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3635. * @param view defines the view matrix to use
  3636. * @param projection defines the projection matrix to use
  3637. * @returns the new Vector3
  3638. */
  3639. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3640. var result = Vector3.Zero();
  3641. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3642. return result;
  3643. };
  3644. /**
  3645. * Unproject from screen space to object space
  3646. * @param source defines the screen space Vector3 to use
  3647. * @param viewportWidth defines the current width of the viewport
  3648. * @param viewportHeight defines the current height of the viewport
  3649. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3650. * @param view defines the view matrix to use
  3651. * @param projection defines the projection matrix to use
  3652. * @param result defines the Vector3 where to store the result
  3653. */
  3654. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3655. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3656. };
  3657. /**
  3658. * Unproject from screen space to object space
  3659. * @param sourceX defines the screen space x coordinate to use
  3660. * @param sourceY defines the screen space y coordinate to use
  3661. * @param sourceZ defines the screen space z coordinate to use
  3662. * @param viewportWidth defines the current width of the viewport
  3663. * @param viewportHeight defines the current height of the viewport
  3664. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3665. * @param view defines the view matrix to use
  3666. * @param projection defines the projection matrix to use
  3667. * @param result defines the Vector3 where to store the result
  3668. */
  3669. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3670. var matrix = MathTmp.Matrix[0];
  3671. world.multiplyToRef(view, matrix);
  3672. matrix.multiplyToRef(projection, matrix);
  3673. matrix.invert();
  3674. var screenSource = MathTmp.Vector3[0];
  3675. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3676. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3677. screenSource.z = 2 * sourceZ - 1.0;
  3678. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3679. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3680. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3681. result.scaleInPlace(1.0 / num);
  3682. }
  3683. };
  3684. /**
  3685. * Gets the minimal coordinate values between two Vector3
  3686. * @param left defines the first operand
  3687. * @param right defines the second operand
  3688. * @returns the new Vector3
  3689. */
  3690. Vector3.Minimize = function (left, right) {
  3691. var min = left.clone();
  3692. min.minimizeInPlace(right);
  3693. return min;
  3694. };
  3695. /**
  3696. * Gets the maximal coordinate values between two Vector3
  3697. * @param left defines the first operand
  3698. * @param right defines the second operand
  3699. * @returns the new Vector3
  3700. */
  3701. Vector3.Maximize = function (left, right) {
  3702. var max = left.clone();
  3703. max.maximizeInPlace(right);
  3704. return max;
  3705. };
  3706. /**
  3707. * Returns the distance between the vectors "value1" and "value2"
  3708. * @param value1 defines the first operand
  3709. * @param value2 defines the second operand
  3710. * @returns the distance
  3711. */
  3712. Vector3.Distance = function (value1, value2) {
  3713. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3714. };
  3715. /**
  3716. * Returns the squared distance between the vectors "value1" and "value2"
  3717. * @param value1 defines the first operand
  3718. * @param value2 defines the second operand
  3719. * @returns the squared distance
  3720. */
  3721. Vector3.DistanceSquared = function (value1, value2) {
  3722. var x = value1.x - value2.x;
  3723. var y = value1.y - value2.y;
  3724. var z = value1.z - value2.z;
  3725. return (x * x) + (y * y) + (z * z);
  3726. };
  3727. /**
  3728. * Returns a new Vector3 located at the center between "value1" and "value2"
  3729. * @param value1 defines the first operand
  3730. * @param value2 defines the second operand
  3731. * @returns the new Vector3
  3732. */
  3733. Vector3.Center = function (value1, value2) {
  3734. var center = value1.add(value2);
  3735. center.scaleInPlace(0.5);
  3736. return center;
  3737. };
  3738. /**
  3739. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3740. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3741. * to something in order to rotate it from its local system to the given target system
  3742. * Note: axis1, axis2 and axis3 are normalized during this operation
  3743. * @param axis1 defines the first axis
  3744. * @param axis2 defines the second axis
  3745. * @param axis3 defines the third axis
  3746. * @returns a new Vector3
  3747. */
  3748. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3749. var rotation = Vector3.Zero();
  3750. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3751. return rotation;
  3752. };
  3753. /**
  3754. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3755. * @param axis1 defines the first axis
  3756. * @param axis2 defines the second axis
  3757. * @param axis3 defines the third axis
  3758. * @param ref defines the Vector3 where to store the result
  3759. */
  3760. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3761. var quat = MathTmp.Quaternion[0];
  3762. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3763. quat.toEulerAnglesToRef(ref);
  3764. };
  3765. return Vector3;
  3766. }());
  3767. BABYLON.Vector3 = Vector3;
  3768. //Vector4 class created for EulerAngle class conversion to Quaternion
  3769. var Vector4 = /** @class */ (function () {
  3770. /**
  3771. * Creates a Vector4 object from the given floats.
  3772. */
  3773. function Vector4(x, y, z, w) {
  3774. this.x = x;
  3775. this.y = y;
  3776. this.z = z;
  3777. this.w = w;
  3778. }
  3779. /**
  3780. * Returns the string with the Vector4 coordinates.
  3781. */
  3782. Vector4.prototype.toString = function () {
  3783. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3784. };
  3785. /**
  3786. * Returns the string "Vector4".
  3787. */
  3788. Vector4.prototype.getClassName = function () {
  3789. return "Vector4";
  3790. };
  3791. /**
  3792. * Returns the Vector4 hash code.
  3793. */
  3794. Vector4.prototype.getHashCode = function () {
  3795. var hash = this.x || 0;
  3796. hash = (hash * 397) ^ (this.y || 0);
  3797. hash = (hash * 397) ^ (this.z || 0);
  3798. hash = (hash * 397) ^ (this.w || 0);
  3799. return hash;
  3800. };
  3801. // Operators
  3802. /**
  3803. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3804. */
  3805. Vector4.prototype.asArray = function () {
  3806. var result = new Array();
  3807. this.toArray(result, 0);
  3808. return result;
  3809. };
  3810. /**
  3811. * Populates the given array from the given index with the Vector4 coordinates.
  3812. * Returns the Vector4.
  3813. */
  3814. Vector4.prototype.toArray = function (array, index) {
  3815. if (index === undefined) {
  3816. index = 0;
  3817. }
  3818. array[index] = this.x;
  3819. array[index + 1] = this.y;
  3820. array[index + 2] = this.z;
  3821. array[index + 3] = this.w;
  3822. return this;
  3823. };
  3824. /**
  3825. * Adds the given vector to the current Vector4.
  3826. * Returns the updated Vector4.
  3827. */
  3828. Vector4.prototype.addInPlace = function (otherVector) {
  3829. this.x += otherVector.x;
  3830. this.y += otherVector.y;
  3831. this.z += otherVector.z;
  3832. this.w += otherVector.w;
  3833. return this;
  3834. };
  3835. /**
  3836. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3837. */
  3838. Vector4.prototype.add = function (otherVector) {
  3839. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3840. };
  3841. /**
  3842. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3843. * Returns the current Vector4.
  3844. */
  3845. Vector4.prototype.addToRef = function (otherVector, result) {
  3846. result.x = this.x + otherVector.x;
  3847. result.y = this.y + otherVector.y;
  3848. result.z = this.z + otherVector.z;
  3849. result.w = this.w + otherVector.w;
  3850. return this;
  3851. };
  3852. /**
  3853. * Subtract in place the given vector from the current Vector4.
  3854. * Returns the updated Vector4.
  3855. */
  3856. Vector4.prototype.subtractInPlace = function (otherVector) {
  3857. this.x -= otherVector.x;
  3858. this.y -= otherVector.y;
  3859. this.z -= otherVector.z;
  3860. this.w -= otherVector.w;
  3861. return this;
  3862. };
  3863. /**
  3864. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3865. */
  3866. Vector4.prototype.subtract = function (otherVector) {
  3867. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3868. };
  3869. /**
  3870. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3871. * Returns the current Vector4.
  3872. */
  3873. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3874. result.x = this.x - otherVector.x;
  3875. result.y = this.y - otherVector.y;
  3876. result.z = this.z - otherVector.z;
  3877. result.w = this.w - otherVector.w;
  3878. return this;
  3879. };
  3880. /**
  3881. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3882. */
  3883. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3884. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3885. };
  3886. /**
  3887. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3888. * Returns the current Vector4.
  3889. */
  3890. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3891. result.x = this.x - x;
  3892. result.y = this.y - y;
  3893. result.z = this.z - z;
  3894. result.w = this.w - w;
  3895. return this;
  3896. };
  3897. /**
  3898. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3899. */
  3900. Vector4.prototype.negate = function () {
  3901. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3902. };
  3903. /**
  3904. * Multiplies the current Vector4 coordinates by scale (float).
  3905. * Returns the updated Vector4.
  3906. */
  3907. Vector4.prototype.scaleInPlace = function (scale) {
  3908. this.x *= scale;
  3909. this.y *= scale;
  3910. this.z *= scale;
  3911. this.w *= scale;
  3912. return this;
  3913. };
  3914. /**
  3915. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3916. */
  3917. Vector4.prototype.scale = function (scale) {
  3918. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3919. };
  3920. /**
  3921. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3922. * Returns the current Vector4.
  3923. */
  3924. Vector4.prototype.scaleToRef = function (scale, result) {
  3925. result.x = this.x * scale;
  3926. result.y = this.y * scale;
  3927. result.z = this.z * scale;
  3928. result.w = this.w * scale;
  3929. return this;
  3930. };
  3931. /**
  3932. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3933. * @param scale defines the scale factor
  3934. * @param result defines the Vector4 object where to store the result
  3935. * @returns the unmodified current Vector4
  3936. */
  3937. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3938. result.x += this.x * scale;
  3939. result.y += this.y * scale;
  3940. result.z += this.z * scale;
  3941. result.w += this.w * scale;
  3942. return this;
  3943. };
  3944. /**
  3945. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3946. */
  3947. Vector4.prototype.equals = function (otherVector) {
  3948. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3949. };
  3950. /**
  3951. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3952. */
  3953. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3954. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3955. return otherVector
  3956. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3957. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3958. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3959. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3960. };
  3961. /**
  3962. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3963. */
  3964. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3965. return this.x === x && this.y === y && this.z === z && this.w === w;
  3966. };
  3967. /**
  3968. * Multiplies in place the current Vector4 by the given one.
  3969. * Returns the updated Vector4.
  3970. */
  3971. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3972. this.x *= otherVector.x;
  3973. this.y *= otherVector.y;
  3974. this.z *= otherVector.z;
  3975. this.w *= otherVector.w;
  3976. return this;
  3977. };
  3978. /**
  3979. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3980. */
  3981. Vector4.prototype.multiply = function (otherVector) {
  3982. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3983. };
  3984. /**
  3985. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3986. * Returns the current Vector4.
  3987. */
  3988. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3989. result.x = this.x * otherVector.x;
  3990. result.y = this.y * otherVector.y;
  3991. result.z = this.z * otherVector.z;
  3992. result.w = this.w * otherVector.w;
  3993. return this;
  3994. };
  3995. /**
  3996. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3997. */
  3998. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3999. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4000. };
  4001. /**
  4002. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4003. */
  4004. Vector4.prototype.divide = function (otherVector) {
  4005. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4006. };
  4007. /**
  4008. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4009. * Returns the current Vector4.
  4010. */
  4011. Vector4.prototype.divideToRef = function (otherVector, result) {
  4012. result.x = this.x / otherVector.x;
  4013. result.y = this.y / otherVector.y;
  4014. result.z = this.z / otherVector.z;
  4015. result.w = this.w / otherVector.w;
  4016. return this;
  4017. };
  4018. /**
  4019. * Divides the current Vector3 coordinates by the given ones.
  4020. * @returns the updated Vector3.
  4021. */
  4022. Vector4.prototype.divideInPlace = function (otherVector) {
  4023. return this.divideToRef(otherVector, this);
  4024. };
  4025. /**
  4026. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4027. * @param other defines the second operand
  4028. * @returns the current updated Vector4
  4029. */
  4030. Vector4.prototype.minimizeInPlace = function (other) {
  4031. if (other.x < this.x)
  4032. this.x = other.x;
  4033. if (other.y < this.y)
  4034. this.y = other.y;
  4035. if (other.z < this.z)
  4036. this.z = other.z;
  4037. if (other.w < this.w)
  4038. this.w = other.w;
  4039. return this;
  4040. };
  4041. /**
  4042. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4043. * @param other defines the second operand
  4044. * @returns the current updated Vector4
  4045. */
  4046. Vector4.prototype.maximizeInPlace = function (other) {
  4047. if (other.x > this.x)
  4048. this.x = other.x;
  4049. if (other.y > this.y)
  4050. this.y = other.y;
  4051. if (other.z > this.z)
  4052. this.z = other.z;
  4053. if (other.w > this.w)
  4054. this.w = other.w;
  4055. return this;
  4056. };
  4057. // Properties
  4058. /**
  4059. * Returns the Vector4 length (float).
  4060. */
  4061. Vector4.prototype.length = function () {
  4062. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4063. };
  4064. /**
  4065. * Returns the Vector4 squared length (float).
  4066. */
  4067. Vector4.prototype.lengthSquared = function () {
  4068. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4069. };
  4070. // Methods
  4071. /**
  4072. * Normalizes in place the Vector4.
  4073. * Returns the updated Vector4.
  4074. */
  4075. Vector4.prototype.normalize = function () {
  4076. var len = this.length();
  4077. if (len === 0)
  4078. return this;
  4079. var num = 1.0 / len;
  4080. this.x *= num;
  4081. this.y *= num;
  4082. this.z *= num;
  4083. this.w *= num;
  4084. return this;
  4085. };
  4086. /**
  4087. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4088. */
  4089. Vector4.prototype.toVector3 = function () {
  4090. return new Vector3(this.x, this.y, this.z);
  4091. };
  4092. /**
  4093. * Returns a new Vector4 copied from the current one.
  4094. */
  4095. Vector4.prototype.clone = function () {
  4096. return new Vector4(this.x, this.y, this.z, this.w);
  4097. };
  4098. /**
  4099. * Updates the current Vector4 with the given one coordinates.
  4100. * Returns the updated Vector4.
  4101. */
  4102. Vector4.prototype.copyFrom = function (source) {
  4103. this.x = source.x;
  4104. this.y = source.y;
  4105. this.z = source.z;
  4106. this.w = source.w;
  4107. return this;
  4108. };
  4109. /**
  4110. * Updates the current Vector4 coordinates with the given floats.
  4111. * Returns the updated Vector4.
  4112. */
  4113. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4114. this.x = x;
  4115. this.y = y;
  4116. this.z = z;
  4117. this.w = w;
  4118. return this;
  4119. };
  4120. /**
  4121. * Updates the current Vector4 coordinates with the given floats.
  4122. * Returns the updated Vector4.
  4123. */
  4124. Vector4.prototype.set = function (x, y, z, w) {
  4125. return this.copyFromFloats(x, y, z, w);
  4126. };
  4127. // Statics
  4128. /**
  4129. * Returns a new Vector4 set from the starting index of the given array.
  4130. */
  4131. Vector4.FromArray = function (array, offset) {
  4132. if (!offset) {
  4133. offset = 0;
  4134. }
  4135. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4136. };
  4137. /**
  4138. * Updates the given vector "result" from the starting index of the given array.
  4139. */
  4140. Vector4.FromArrayToRef = function (array, offset, result) {
  4141. result.x = array[offset];
  4142. result.y = array[offset + 1];
  4143. result.z = array[offset + 2];
  4144. result.w = array[offset + 3];
  4145. };
  4146. /**
  4147. * Updates the given vector "result" from the starting index of the given Float32Array.
  4148. */
  4149. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4150. Vector4.FromArrayToRef(array, offset, result);
  4151. };
  4152. /**
  4153. * Updates the given vector "result" coordinates from the given floats.
  4154. */
  4155. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4156. result.x = x;
  4157. result.y = y;
  4158. result.z = z;
  4159. result.w = w;
  4160. };
  4161. /**
  4162. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4163. */
  4164. Vector4.Zero = function () {
  4165. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4166. };
  4167. /**
  4168. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4169. */
  4170. Vector4.One = function () {
  4171. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4172. };
  4173. /**
  4174. * Returns a new normalized Vector4 from the given one.
  4175. */
  4176. Vector4.Normalize = function (vector) {
  4177. var result = Vector4.Zero();
  4178. Vector4.NormalizeToRef(vector, result);
  4179. return result;
  4180. };
  4181. /**
  4182. * Updates the given vector "result" from the normalization of the given one.
  4183. */
  4184. Vector4.NormalizeToRef = function (vector, result) {
  4185. result.copyFrom(vector);
  4186. result.normalize();
  4187. };
  4188. Vector4.Minimize = function (left, right) {
  4189. var min = left.clone();
  4190. min.minimizeInPlace(right);
  4191. return min;
  4192. };
  4193. Vector4.Maximize = function (left, right) {
  4194. var max = left.clone();
  4195. max.maximizeInPlace(right);
  4196. return max;
  4197. };
  4198. /**
  4199. * Returns the distance (float) between the vectors "value1" and "value2".
  4200. */
  4201. Vector4.Distance = function (value1, value2) {
  4202. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4203. };
  4204. /**
  4205. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4206. */
  4207. Vector4.DistanceSquared = function (value1, value2) {
  4208. var x = value1.x - value2.x;
  4209. var y = value1.y - value2.y;
  4210. var z = value1.z - value2.z;
  4211. var w = value1.w - value2.w;
  4212. return (x * x) + (y * y) + (z * z) + (w * w);
  4213. };
  4214. /**
  4215. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4216. */
  4217. Vector4.Center = function (value1, value2) {
  4218. var center = value1.add(value2);
  4219. center.scaleInPlace(0.5);
  4220. return center;
  4221. };
  4222. /**
  4223. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4224. * This methods computes transformed normalized direction vectors only.
  4225. */
  4226. Vector4.TransformNormal = function (vector, transformation) {
  4227. var result = Vector4.Zero();
  4228. Vector4.TransformNormalToRef(vector, transformation, result);
  4229. return result;
  4230. };
  4231. /**
  4232. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4233. * This methods computes transformed normalized direction vectors only.
  4234. */
  4235. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4236. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4237. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4238. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4239. result.x = x;
  4240. result.y = y;
  4241. result.z = z;
  4242. result.w = vector.w;
  4243. };
  4244. /**
  4245. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4246. * This methods computes transformed normalized direction vectors only.
  4247. */
  4248. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4249. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4250. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4251. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4252. result.w = w;
  4253. };
  4254. return Vector4;
  4255. }());
  4256. BABYLON.Vector4 = Vector4;
  4257. var Size = /** @class */ (function () {
  4258. /**
  4259. * Creates a Size object from the given width and height (floats).
  4260. */
  4261. function Size(width, height) {
  4262. this.width = width;
  4263. this.height = height;
  4264. }
  4265. // Returns a string with the Size width and height.
  4266. Size.prototype.toString = function () {
  4267. return "{W: " + this.width + ", H: " + this.height + "}";
  4268. };
  4269. /**
  4270. * Returns the string "Size"
  4271. */
  4272. Size.prototype.getClassName = function () {
  4273. return "Size";
  4274. };
  4275. /**
  4276. * Returns the Size hash code.
  4277. */
  4278. Size.prototype.getHashCode = function () {
  4279. var hash = this.width || 0;
  4280. hash = (hash * 397) ^ (this.height || 0);
  4281. return hash;
  4282. };
  4283. /**
  4284. * Updates the current size from the given one.
  4285. * Returns the updated Size.
  4286. */
  4287. Size.prototype.copyFrom = function (src) {
  4288. this.width = src.width;
  4289. this.height = src.height;
  4290. };
  4291. /**
  4292. * Updates in place the current Size from the given floats.
  4293. * Returns the updated Size.
  4294. */
  4295. Size.prototype.copyFromFloats = function (width, height) {
  4296. this.width = width;
  4297. this.height = height;
  4298. return this;
  4299. };
  4300. /**
  4301. * Updates in place the current Size from the given floats.
  4302. * Returns the updated Size.
  4303. */
  4304. Size.prototype.set = function (width, height) {
  4305. return this.copyFromFloats(width, height);
  4306. };
  4307. /**
  4308. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4309. */
  4310. Size.prototype.multiplyByFloats = function (w, h) {
  4311. return new Size(this.width * w, this.height * h);
  4312. };
  4313. /**
  4314. * Returns a new Size copied from the given one.
  4315. */
  4316. Size.prototype.clone = function () {
  4317. return new Size(this.width, this.height);
  4318. };
  4319. /**
  4320. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4321. */
  4322. Size.prototype.equals = function (other) {
  4323. if (!other) {
  4324. return false;
  4325. }
  4326. return (this.width === other.width) && (this.height === other.height);
  4327. };
  4328. Object.defineProperty(Size.prototype, "surface", {
  4329. /**
  4330. * Returns the surface of the Size : width * height (float).
  4331. */
  4332. get: function () {
  4333. return this.width * this.height;
  4334. },
  4335. enumerable: true,
  4336. configurable: true
  4337. });
  4338. /**
  4339. * Returns a new Size set to (0.0, 0.0)
  4340. */
  4341. Size.Zero = function () {
  4342. return new Size(0.0, 0.0);
  4343. };
  4344. /**
  4345. * Returns a new Size set as the addition result of the current Size and the given one.
  4346. */
  4347. Size.prototype.add = function (otherSize) {
  4348. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4349. return r;
  4350. };
  4351. /**
  4352. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4353. */
  4354. Size.prototype.subtract = function (otherSize) {
  4355. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4356. return r;
  4357. };
  4358. /**
  4359. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4360. */
  4361. Size.Lerp = function (start, end, amount) {
  4362. var w = start.width + ((end.width - start.width) * amount);
  4363. var h = start.height + ((end.height - start.height) * amount);
  4364. return new Size(w, h);
  4365. };
  4366. return Size;
  4367. }());
  4368. BABYLON.Size = Size;
  4369. /**
  4370. * Class used to store quaternion data
  4371. * @see https://en.wikipedia.org/wiki/Quaternion
  4372. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4373. */
  4374. var Quaternion = /** @class */ (function () {
  4375. /**
  4376. * Creates a new Quaternion from the given floats
  4377. * @param x defines the first component (0 by default)
  4378. * @param y defines the second component (0 by default)
  4379. * @param z defines the third component (0 by default)
  4380. * @param w defines the fourth component (1.0 by default)
  4381. */
  4382. function Quaternion(
  4383. /** defines the first component (0 by default) */
  4384. x,
  4385. /** defines the second component (0 by default) */
  4386. y,
  4387. /** defines the third component (0 by default) */
  4388. z,
  4389. /** defines the fourth component (1.0 by default) */
  4390. w) {
  4391. if (x === void 0) { x = 0.0; }
  4392. if (y === void 0) { y = 0.0; }
  4393. if (z === void 0) { z = 0.0; }
  4394. if (w === void 0) { w = 1.0; }
  4395. this.x = x;
  4396. this.y = y;
  4397. this.z = z;
  4398. this.w = w;
  4399. }
  4400. /**
  4401. * Gets a string representation for the current quaternion
  4402. * @returns a string with the Quaternion coordinates
  4403. */
  4404. Quaternion.prototype.toString = function () {
  4405. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4406. };
  4407. /**
  4408. * Gets the class name of the quaternion
  4409. * @returns the string "Quaternion"
  4410. */
  4411. Quaternion.prototype.getClassName = function () {
  4412. return "Quaternion";
  4413. };
  4414. /**
  4415. * Gets a hash code for this quaternion
  4416. * @returns the quaternion hash code
  4417. */
  4418. Quaternion.prototype.getHashCode = function () {
  4419. var hash = this.x || 0;
  4420. hash = (hash * 397) ^ (this.y || 0);
  4421. hash = (hash * 397) ^ (this.z || 0);
  4422. hash = (hash * 397) ^ (this.w || 0);
  4423. return hash;
  4424. };
  4425. /**
  4426. * Copy the quaternion to an array
  4427. * @returns a new array populated with 4 elements from the quaternion coordinates
  4428. */
  4429. Quaternion.prototype.asArray = function () {
  4430. return [this.x, this.y, this.z, this.w];
  4431. };
  4432. /**
  4433. * Check if two quaternions are equals
  4434. * @param otherQuaternion defines the second operand
  4435. * @return true if the current quaternion and the given one coordinates are strictly equals
  4436. */
  4437. Quaternion.prototype.equals = function (otherQuaternion) {
  4438. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4439. };
  4440. /**
  4441. * Clone the current quaternion
  4442. * @returns a new quaternion copied from the current one
  4443. */
  4444. Quaternion.prototype.clone = function () {
  4445. return new Quaternion(this.x, this.y, this.z, this.w);
  4446. };
  4447. /**
  4448. * Copy a quaternion to the current one
  4449. * @param other defines the other quaternion
  4450. * @returns the updated current quaternion
  4451. */
  4452. Quaternion.prototype.copyFrom = function (other) {
  4453. this.x = other.x;
  4454. this.y = other.y;
  4455. this.z = other.z;
  4456. this.w = other.w;
  4457. return this;
  4458. };
  4459. /**
  4460. * Updates the current quaternion with the given float coordinates
  4461. * @param x defines the x coordinate
  4462. * @param y defines the y coordinate
  4463. * @param z defines the z coordinate
  4464. * @param w defines the w coordinate
  4465. * @returns the updated current quaternion
  4466. */
  4467. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4468. this.x = x;
  4469. this.y = y;
  4470. this.z = z;
  4471. this.w = w;
  4472. return this;
  4473. };
  4474. /**
  4475. * Updates the current quaternion from the given float coordinates
  4476. * @param x defines the x coordinate
  4477. * @param y defines the y coordinate
  4478. * @param z defines the z coordinate
  4479. * @param w defines the w coordinate
  4480. * @returns the updated current quaternion
  4481. */
  4482. Quaternion.prototype.set = function (x, y, z, w) {
  4483. return this.copyFromFloats(x, y, z, w);
  4484. };
  4485. /**
  4486. * Adds two quaternions
  4487. * @param other defines the second operand
  4488. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4489. */
  4490. Quaternion.prototype.add = function (other) {
  4491. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4492. };
  4493. /**
  4494. * Add a quaternion to the current one
  4495. * @param other defines the quaternion to add
  4496. * @returns the current quaternion
  4497. */
  4498. Quaternion.prototype.addInPlace = function (other) {
  4499. this.x += other.x;
  4500. this.y += other.y;
  4501. this.z += other.z;
  4502. this.w += other.w;
  4503. return this;
  4504. };
  4505. /**
  4506. * Subtract two quaternions
  4507. * @param other defines the second operand
  4508. * @returns a new quaternion as the subtraction result of the given one from the current one
  4509. */
  4510. Quaternion.prototype.subtract = function (other) {
  4511. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4512. };
  4513. /**
  4514. * Multiplies the current quaternion by a scale factor
  4515. * @param value defines the scale factor
  4516. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4517. */
  4518. Quaternion.prototype.scale = function (value) {
  4519. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4520. };
  4521. /**
  4522. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4523. * @param scale defines the scale factor
  4524. * @param result defines the Quaternion object where to store the result
  4525. * @returns the unmodified current quaternion
  4526. */
  4527. Quaternion.prototype.scaleToRef = function (scale, result) {
  4528. result.x = this.x * scale;
  4529. result.y = this.y * scale;
  4530. result.z = this.z * scale;
  4531. result.w = this.w * scale;
  4532. return this;
  4533. };
  4534. /**
  4535. * Multiplies in place the current quaternion by a scale factor
  4536. * @param value defines the scale factor
  4537. * @returns the current modified quaternion
  4538. */
  4539. Quaternion.prototype.scaleInPlace = function (value) {
  4540. this.x *= value;
  4541. this.y *= value;
  4542. this.z *= value;
  4543. this.w *= value;
  4544. return this;
  4545. };
  4546. /**
  4547. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4548. * @param scale defines the scale factor
  4549. * @param result defines the Quaternion object where to store the result
  4550. * @returns the unmodified current quaternion
  4551. */
  4552. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4553. result.x += this.x * scale;
  4554. result.y += this.y * scale;
  4555. result.z += this.z * scale;
  4556. result.w += this.w * scale;
  4557. return this;
  4558. };
  4559. /**
  4560. * Multiplies two quaternions
  4561. * @param q1 defines the second operand
  4562. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4563. */
  4564. Quaternion.prototype.multiply = function (q1) {
  4565. var result = new Quaternion(0, 0, 0, 1.0);
  4566. this.multiplyToRef(q1, result);
  4567. return result;
  4568. };
  4569. /**
  4570. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4571. * @param q1 defines the second operand
  4572. * @param result defines the target quaternion
  4573. * @returns the current quaternion
  4574. */
  4575. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4576. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4577. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4578. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4579. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4580. result.copyFromFloats(x, y, z, w);
  4581. return this;
  4582. };
  4583. /**
  4584. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4585. * @param q1 defines the second operand
  4586. * @returns the currentupdated quaternion
  4587. */
  4588. Quaternion.prototype.multiplyInPlace = function (q1) {
  4589. this.multiplyToRef(q1, this);
  4590. return this;
  4591. };
  4592. /**
  4593. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4594. * @param ref defines the target quaternion
  4595. * @returns the current quaternion
  4596. */
  4597. Quaternion.prototype.conjugateToRef = function (ref) {
  4598. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4599. return this;
  4600. };
  4601. /**
  4602. * Conjugates in place (1-q) the current quaternion
  4603. * @returns the current updated quaternion
  4604. */
  4605. Quaternion.prototype.conjugateInPlace = function () {
  4606. this.x *= -1;
  4607. this.y *= -1;
  4608. this.z *= -1;
  4609. return this;
  4610. };
  4611. /**
  4612. * Conjugates in place (1-q) the current quaternion
  4613. * @returns a new quaternion
  4614. */
  4615. Quaternion.prototype.conjugate = function () {
  4616. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4617. return result;
  4618. };
  4619. /**
  4620. * Gets length of current quaternion
  4621. * @returns the quaternion length (float)
  4622. */
  4623. Quaternion.prototype.length = function () {
  4624. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4625. };
  4626. /**
  4627. * Normalize in place the current quaternion
  4628. * @returns the current updated quaternion
  4629. */
  4630. Quaternion.prototype.normalize = function () {
  4631. var length = 1.0 / this.length();
  4632. this.x *= length;
  4633. this.y *= length;
  4634. this.z *= length;
  4635. this.w *= length;
  4636. return this;
  4637. };
  4638. /**
  4639. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4640. * @param order is a reserved parameter and is ignore for now
  4641. * @returns a new Vector3 containing the Euler angles
  4642. */
  4643. Quaternion.prototype.toEulerAngles = function (order) {
  4644. if (order === void 0) { order = "YZX"; }
  4645. var result = Vector3.Zero();
  4646. this.toEulerAnglesToRef(result, order);
  4647. return result;
  4648. };
  4649. /**
  4650. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4651. * @param result defines the vector which will be filled with the Euler angles
  4652. * @param order is a reserved parameter and is ignore for now
  4653. * @returns the current unchanged quaternion
  4654. */
  4655. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4656. if (order === void 0) { order = "YZX"; }
  4657. var qz = this.z;
  4658. var qx = this.x;
  4659. var qy = this.y;
  4660. var qw = this.w;
  4661. var sqw = qw * qw;
  4662. var sqz = qz * qz;
  4663. var sqx = qx * qx;
  4664. var sqy = qy * qy;
  4665. var zAxisY = qy * qz - qx * qw;
  4666. var limit = .4999999;
  4667. if (zAxisY < -limit) {
  4668. result.y = 2 * Math.atan2(qy, qw);
  4669. result.x = Math.PI / 2;
  4670. result.z = 0;
  4671. }
  4672. else if (zAxisY > limit) {
  4673. result.y = 2 * Math.atan2(qy, qw);
  4674. result.x = -Math.PI / 2;
  4675. result.z = 0;
  4676. }
  4677. else {
  4678. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4679. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4680. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4681. }
  4682. return this;
  4683. };
  4684. /**
  4685. * Updates the given rotation matrix with the current quaternion values
  4686. * @param result defines the target matrix
  4687. * @returns the current unchanged quaternion
  4688. */
  4689. Quaternion.prototype.toRotationMatrix = function (result) {
  4690. var xx = this.x * this.x;
  4691. var yy = this.y * this.y;
  4692. var zz = this.z * this.z;
  4693. var xy = this.x * this.y;
  4694. var zw = this.z * this.w;
  4695. var zx = this.z * this.x;
  4696. var yw = this.y * this.w;
  4697. var yz = this.y * this.z;
  4698. var xw = this.x * this.w;
  4699. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4700. result.m[1] = 2.0 * (xy + zw);
  4701. result.m[2] = 2.0 * (zx - yw);
  4702. result.m[3] = 0;
  4703. result.m[4] = 2.0 * (xy - zw);
  4704. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4705. result.m[6] = 2.0 * (yz + xw);
  4706. result.m[7] = 0;
  4707. result.m[8] = 2.0 * (zx + yw);
  4708. result.m[9] = 2.0 * (yz - xw);
  4709. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4710. result.m[11] = 0;
  4711. result.m[12] = 0;
  4712. result.m[13] = 0;
  4713. result.m[14] = 0;
  4714. result.m[15] = 1.0;
  4715. result._markAsUpdated();
  4716. return this;
  4717. };
  4718. /**
  4719. * Updates the current quaternion from the given rotation matrix values
  4720. * @param matrix defines the source matrix
  4721. * @returns the current updated quaternion
  4722. */
  4723. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4724. Quaternion.FromRotationMatrixToRef(matrix, this);
  4725. return this;
  4726. };
  4727. // Statics
  4728. /**
  4729. * Creates a new quaternion from a rotation matrix
  4730. * @param matrix defines the source matrix
  4731. * @returns a new quaternion created from the given rotation matrix values
  4732. */
  4733. Quaternion.FromRotationMatrix = function (matrix) {
  4734. var result = new Quaternion();
  4735. Quaternion.FromRotationMatrixToRef(matrix, result);
  4736. return result;
  4737. };
  4738. /**
  4739. * Updates the given quaternion with the given rotation matrix values
  4740. * @param matrix defines the source matrix
  4741. * @param result defines the target quaternion
  4742. */
  4743. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4744. var data = matrix.m;
  4745. var m11 = data[0], m12 = data[4], m13 = data[8];
  4746. var m21 = data[1], m22 = data[5], m23 = data[9];
  4747. var m31 = data[2], m32 = data[6], m33 = data[10];
  4748. var trace = m11 + m22 + m33;
  4749. var s;
  4750. if (trace > 0) {
  4751. s = 0.5 / Math.sqrt(trace + 1.0);
  4752. result.w = 0.25 / s;
  4753. result.x = (m32 - m23) * s;
  4754. result.y = (m13 - m31) * s;
  4755. result.z = (m21 - m12) * s;
  4756. }
  4757. else if (m11 > m22 && m11 > m33) {
  4758. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4759. result.w = (m32 - m23) / s;
  4760. result.x = 0.25 * s;
  4761. result.y = (m12 + m21) / s;
  4762. result.z = (m13 + m31) / s;
  4763. }
  4764. else if (m22 > m33) {
  4765. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4766. result.w = (m13 - m31) / s;
  4767. result.x = (m12 + m21) / s;
  4768. result.y = 0.25 * s;
  4769. result.z = (m23 + m32) / s;
  4770. }
  4771. else {
  4772. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4773. result.w = (m21 - m12) / s;
  4774. result.x = (m13 + m31) / s;
  4775. result.y = (m23 + m32) / s;
  4776. result.z = 0.25 * s;
  4777. }
  4778. };
  4779. /**
  4780. * Creates an empty quaternion
  4781. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4782. */
  4783. Quaternion.Zero = function () {
  4784. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4785. };
  4786. /**
  4787. * Inverse a given quaternion
  4788. * @param q defines the source quaternion
  4789. * @returns a new quaternion as the inverted current quaternion
  4790. */
  4791. Quaternion.Inverse = function (q) {
  4792. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4793. };
  4794. /**
  4795. * Creates an identity quaternion
  4796. * @returns the identity quaternion
  4797. */
  4798. Quaternion.Identity = function () {
  4799. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4800. };
  4801. /**
  4802. * Gets a boolean indicating if the given quaternion is identity
  4803. * @param quaternion defines the quaternion to check
  4804. * @returns true if the quaternion is identity
  4805. */
  4806. Quaternion.IsIdentity = function (quaternion) {
  4807. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4808. };
  4809. /**
  4810. * Creates a quaternion from a rotation around an axis
  4811. * @param axis defines the axis to use
  4812. * @param angle defines the angle to use
  4813. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4814. */
  4815. Quaternion.RotationAxis = function (axis, angle) {
  4816. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4817. };
  4818. /**
  4819. * Creates a rotation around an axis and stores it into the given quaternion
  4820. * @param axis defines the axis to use
  4821. * @param angle defines the angle to use
  4822. * @param result defines the target quaternion
  4823. * @returns the target quaternion
  4824. */
  4825. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4826. var sin = Math.sin(angle / 2);
  4827. axis.normalize();
  4828. result.w = Math.cos(angle / 2);
  4829. result.x = axis.x * sin;
  4830. result.y = axis.y * sin;
  4831. result.z = axis.z * sin;
  4832. return result;
  4833. };
  4834. /**
  4835. * Creates a new quaternion from data stored into an array
  4836. * @param array defines the data source
  4837. * @param offset defines the offset in the source array where the data starts
  4838. * @returns a new quaternion
  4839. */
  4840. Quaternion.FromArray = function (array, offset) {
  4841. if (!offset) {
  4842. offset = 0;
  4843. }
  4844. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4845. };
  4846. /**
  4847. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4848. * @param yaw defines the rotation around Y axis
  4849. * @param pitch defines the rotation around X axis
  4850. * @param roll defines the rotation around Z axis
  4851. * @returns the new quaternion
  4852. */
  4853. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4854. var q = new Quaternion();
  4855. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4856. return q;
  4857. };
  4858. /**
  4859. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4860. * @param yaw defines the rotation around Y axis
  4861. * @param pitch defines the rotation around X axis
  4862. * @param roll defines the rotation around Z axis
  4863. * @param result defines the target quaternion
  4864. */
  4865. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4866. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4867. var halfRoll = roll * 0.5;
  4868. var halfPitch = pitch * 0.5;
  4869. var halfYaw = yaw * 0.5;
  4870. var sinRoll = Math.sin(halfRoll);
  4871. var cosRoll = Math.cos(halfRoll);
  4872. var sinPitch = Math.sin(halfPitch);
  4873. var cosPitch = Math.cos(halfPitch);
  4874. var sinYaw = Math.sin(halfYaw);
  4875. var cosYaw = Math.cos(halfYaw);
  4876. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4877. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4878. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4879. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4880. };
  4881. /**
  4882. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4883. * @param alpha defines the rotation around first axis
  4884. * @param beta defines the rotation around second axis
  4885. * @param gamma defines the rotation around third axis
  4886. * @returns the new quaternion
  4887. */
  4888. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4889. var result = new Quaternion();
  4890. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4891. return result;
  4892. };
  4893. /**
  4894. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4895. * @param alpha defines the rotation around first axis
  4896. * @param beta defines the rotation around second axis
  4897. * @param gamma defines the rotation around third axis
  4898. * @param result defines the target quaternion
  4899. */
  4900. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4901. // Produces a quaternion from Euler angles in the z-x-z orientation
  4902. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4903. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4904. var halfBeta = beta * 0.5;
  4905. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4906. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4907. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4908. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4909. };
  4910. /**
  4911. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  4912. * @param axis1 defines the first axis
  4913. * @param axis2 defines the second axis
  4914. * @param axis3 defines the third axis
  4915. * @returns the new quaternion
  4916. */
  4917. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4918. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4919. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4920. return quat;
  4921. };
  4922. /**
  4923. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  4924. * @param axis1 defines the first axis
  4925. * @param axis2 defines the second axis
  4926. * @param axis3 defines the third axis
  4927. * @param ref defines the target quaternion
  4928. */
  4929. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4930. var rotMat = MathTmp.Matrix[0];
  4931. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4932. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4933. };
  4934. /**
  4935. * Interpolates between two quaternions
  4936. * @param left defines first quaternion
  4937. * @param right defines second quaternion
  4938. * @param amount defines the gradient to use
  4939. * @returns the new interpolated quaternion
  4940. */
  4941. Quaternion.Slerp = function (left, right, amount) {
  4942. var result = Quaternion.Identity();
  4943. Quaternion.SlerpToRef(left, right, amount, result);
  4944. return result;
  4945. };
  4946. /**
  4947. * Interpolates between two quaternions and stores it into a target quaternion
  4948. * @param left defines first quaternion
  4949. * @param right defines second quaternion
  4950. * @param amount defines the gradient to use
  4951. * @param result defines the target quaternion
  4952. */
  4953. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4954. var num2;
  4955. var num3;
  4956. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4957. var flag = false;
  4958. if (num4 < 0) {
  4959. flag = true;
  4960. num4 = -num4;
  4961. }
  4962. if (num4 > 0.999999) {
  4963. num3 = 1 - amount;
  4964. num2 = flag ? -amount : amount;
  4965. }
  4966. else {
  4967. var num5 = Math.acos(num4);
  4968. var num6 = (1.0 / Math.sin(num5));
  4969. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4970. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4971. }
  4972. result.x = (num3 * left.x) + (num2 * right.x);
  4973. result.y = (num3 * left.y) + (num2 * right.y);
  4974. result.z = (num3 * left.z) + (num2 * right.z);
  4975. result.w = (num3 * left.w) + (num2 * right.w);
  4976. };
  4977. /**
  4978. * Interpolate between two quaternions using Hermite interpolation
  4979. * @param value1 defines first quaternion
  4980. * @param tangent1 defines the incoming tangent
  4981. * @param value2 defines second quaternion
  4982. * @param tangent2 defines the outgoing tangent
  4983. * @param amount defines the target quaternion
  4984. * @returns the new interpolated quaternion
  4985. */
  4986. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4987. var squared = amount * amount;
  4988. var cubed = amount * squared;
  4989. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4990. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4991. var part3 = (cubed - (2.0 * squared)) + amount;
  4992. var part4 = cubed - squared;
  4993. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4994. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4995. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4996. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4997. return new Quaternion(x, y, z, w);
  4998. };
  4999. return Quaternion;
  5000. }());
  5001. BABYLON.Quaternion = Quaternion;
  5002. /**
  5003. * Class used to store matrix data (4x4)
  5004. */
  5005. var Matrix = /** @class */ (function () {
  5006. /**
  5007. * Creates an empty matrix (filled with zeros)
  5008. */
  5009. function Matrix() {
  5010. this._isIdentity = false;
  5011. this._isIdentityDirty = true;
  5012. /**
  5013. * Gets or sets the internal data of the matrix
  5014. */
  5015. this.m = new Float32Array(16);
  5016. this._markAsUpdated();
  5017. }
  5018. /** @hidden */
  5019. Matrix.prototype._markAsUpdated = function () {
  5020. this.updateFlag = Matrix._updateFlagSeed++;
  5021. this._isIdentityDirty = true;
  5022. };
  5023. // Properties
  5024. /**
  5025. * Check if the current matrix is indentity
  5026. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5027. * @returns true is the matrix is the identity matrix
  5028. */
  5029. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5030. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5031. if (this._isIdentityDirty) {
  5032. this._isIdentityDirty = false;
  5033. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5034. this._isIdentity = false;
  5035. }
  5036. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5037. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5038. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5039. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5040. this._isIdentity = false;
  5041. }
  5042. else {
  5043. this._isIdentity = true;
  5044. }
  5045. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5046. this._isIdentity = false;
  5047. }
  5048. }
  5049. return this._isIdentity;
  5050. };
  5051. /**
  5052. * Gets the determinant of the matrix
  5053. * @returns the matrix determinant
  5054. */
  5055. Matrix.prototype.determinant = function () {
  5056. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5057. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5058. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5059. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5060. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5061. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5062. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5063. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5064. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5065. };
  5066. // Methods
  5067. /**
  5068. * Returns the matrix as a Float32Array
  5069. * @returns the matrix underlying array
  5070. */
  5071. Matrix.prototype.toArray = function () {
  5072. return this.m;
  5073. };
  5074. /**
  5075. * Returns the matrix as a Float32Array
  5076. * @returns the matrix underlying array.
  5077. */
  5078. Matrix.prototype.asArray = function () {
  5079. return this.toArray();
  5080. };
  5081. /**
  5082. * Inverts the current matrix in place
  5083. * @returns the current inverted matrix
  5084. */
  5085. Matrix.prototype.invert = function () {
  5086. this.invertToRef(this);
  5087. return this;
  5088. };
  5089. /**
  5090. * Sets all the matrix elements to zero
  5091. * @returns the current matrix
  5092. */
  5093. Matrix.prototype.reset = function () {
  5094. for (var index = 0; index < 16; index++) {
  5095. this.m[index] = 0.0;
  5096. }
  5097. this._markAsUpdated();
  5098. return this;
  5099. };
  5100. /**
  5101. * Adds the current matrix with a second one
  5102. * @param other defines the matrix to add
  5103. * @returns a new matrix as the addition of the current matrix and the given one
  5104. */
  5105. Matrix.prototype.add = function (other) {
  5106. var result = new Matrix();
  5107. this.addToRef(other, result);
  5108. return result;
  5109. };
  5110. /**
  5111. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5112. * @param other defines the matrix to add
  5113. * @param result defines the target matrix
  5114. * @returns the current matrix
  5115. */
  5116. Matrix.prototype.addToRef = function (other, result) {
  5117. for (var index = 0; index < 16; index++) {
  5118. result.m[index] = this.m[index] + other.m[index];
  5119. }
  5120. result._markAsUpdated();
  5121. return this;
  5122. };
  5123. /**
  5124. * Adds in place the given matrix to the current matrix
  5125. * @param other defines the second operand
  5126. * @returns the current updated matrix
  5127. */
  5128. Matrix.prototype.addToSelf = function (other) {
  5129. for (var index = 0; index < 16; index++) {
  5130. this.m[index] += other.m[index];
  5131. }
  5132. this._markAsUpdated();
  5133. return this;
  5134. };
  5135. /**
  5136. * Sets the given matrix to the current inverted Matrix
  5137. * @param other defines the target matrix
  5138. * @returns the unmodified current matrix
  5139. */
  5140. Matrix.prototype.invertToRef = function (other) {
  5141. var l1 = this.m[0];
  5142. var l2 = this.m[1];
  5143. var l3 = this.m[2];
  5144. var l4 = this.m[3];
  5145. var l5 = this.m[4];
  5146. var l6 = this.m[5];
  5147. var l7 = this.m[6];
  5148. var l8 = this.m[7];
  5149. var l9 = this.m[8];
  5150. var l10 = this.m[9];
  5151. var l11 = this.m[10];
  5152. var l12 = this.m[11];
  5153. var l13 = this.m[12];
  5154. var l14 = this.m[13];
  5155. var l15 = this.m[14];
  5156. var l16 = this.m[15];
  5157. var l17 = (l11 * l16) - (l12 * l15);
  5158. var l18 = (l10 * l16) - (l12 * l14);
  5159. var l19 = (l10 * l15) - (l11 * l14);
  5160. var l20 = (l9 * l16) - (l12 * l13);
  5161. var l21 = (l9 * l15) - (l11 * l13);
  5162. var l22 = (l9 * l14) - (l10 * l13);
  5163. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5164. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5165. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5166. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5167. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5168. var l28 = (l7 * l16) - (l8 * l15);
  5169. var l29 = (l6 * l16) - (l8 * l14);
  5170. var l30 = (l6 * l15) - (l7 * l14);
  5171. var l31 = (l5 * l16) - (l8 * l13);
  5172. var l32 = (l5 * l15) - (l7 * l13);
  5173. var l33 = (l5 * l14) - (l6 * l13);
  5174. var l34 = (l7 * l12) - (l8 * l11);
  5175. var l35 = (l6 * l12) - (l8 * l10);
  5176. var l36 = (l6 * l11) - (l7 * l10);
  5177. var l37 = (l5 * l12) - (l8 * l9);
  5178. var l38 = (l5 * l11) - (l7 * l9);
  5179. var l39 = (l5 * l10) - (l6 * l9);
  5180. other.m[0] = l23 * l27;
  5181. other.m[4] = l24 * l27;
  5182. other.m[8] = l25 * l27;
  5183. other.m[12] = l26 * l27;
  5184. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5185. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5186. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5187. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5188. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5189. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5190. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5191. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5192. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5193. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5194. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5195. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5196. other._markAsUpdated();
  5197. return this;
  5198. };
  5199. /**
  5200. * Inserts the translation vector (using 3 floats) in the current matrix
  5201. * @param x defines the 1st component of the translation
  5202. * @param y defines the 2nd component of the translation
  5203. * @param z defines the 3rd component of the translation
  5204. * @returns the current updated matrix
  5205. */
  5206. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5207. this.m[12] = x;
  5208. this.m[13] = y;
  5209. this.m[14] = z;
  5210. this._markAsUpdated();
  5211. return this;
  5212. };
  5213. /**
  5214. * Inserts the translation vector in the current matrix
  5215. * @param vector3 defines the translation to insert
  5216. * @returns the current updated matrix
  5217. */
  5218. Matrix.prototype.setTranslation = function (vector3) {
  5219. this.m[12] = vector3.x;
  5220. this.m[13] = vector3.y;
  5221. this.m[14] = vector3.z;
  5222. this._markAsUpdated();
  5223. return this;
  5224. };
  5225. /**
  5226. * Gets the translation value of the current matrix
  5227. * @returns a new Vector3 as the extracted translation from the matrix
  5228. */
  5229. Matrix.prototype.getTranslation = function () {
  5230. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5231. };
  5232. /**
  5233. * Fill a Vector3 with the extracted translation from the matrix
  5234. * @param result defines the Vector3 where to store the translation
  5235. * @returns the current matrix
  5236. */
  5237. Matrix.prototype.getTranslationToRef = function (result) {
  5238. result.x = this.m[12];
  5239. result.y = this.m[13];
  5240. result.z = this.m[14];
  5241. return this;
  5242. };
  5243. /**
  5244. * Remove rotation and scaling part from the matrix
  5245. * @returns the updated matrix
  5246. */
  5247. Matrix.prototype.removeRotationAndScaling = function () {
  5248. this.setRowFromFloats(0, 1, 0, 0, 0);
  5249. this.setRowFromFloats(1, 0, 1, 0, 0);
  5250. this.setRowFromFloats(2, 0, 0, 1, 0);
  5251. return this;
  5252. };
  5253. /**
  5254. * Multiply two matrices
  5255. * @param other defines the second operand
  5256. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5257. */
  5258. Matrix.prototype.multiply = function (other) {
  5259. var result = new Matrix();
  5260. this.multiplyToRef(other, result);
  5261. return result;
  5262. };
  5263. /**
  5264. * Copy the current matrix from the given one
  5265. * @param other defines the source matrix
  5266. * @returns the current updated matrix
  5267. */
  5268. Matrix.prototype.copyFrom = function (other) {
  5269. for (var index = 0; index < 16; index++) {
  5270. this.m[index] = other.m[index];
  5271. }
  5272. this._markAsUpdated();
  5273. return this;
  5274. };
  5275. /**
  5276. * Populates the given array from the starting index with the current matrix values
  5277. * @param array defines the target array
  5278. * @param offset defines the offset in the target array where to start storing values
  5279. * @returns the current matrix
  5280. */
  5281. Matrix.prototype.copyToArray = function (array, offset) {
  5282. if (offset === void 0) { offset = 0; }
  5283. for (var index = 0; index < 16; index++) {
  5284. array[offset + index] = this.m[index];
  5285. }
  5286. return this;
  5287. };
  5288. /**
  5289. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5290. * @param other defines the second operand
  5291. * @param result defines the matrix where to store the multiplication
  5292. * @returns the current matrix
  5293. */
  5294. Matrix.prototype.multiplyToRef = function (other, result) {
  5295. this.multiplyToArray(other, result.m, 0);
  5296. result._markAsUpdated();
  5297. return this;
  5298. };
  5299. /**
  5300. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5301. * @param other defines the second operand
  5302. * @param result defines the array where to store the multiplication
  5303. * @param offset defines the offset in the target array where to start storing values
  5304. * @returns the current matrix
  5305. */
  5306. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5307. var tm0 = this.m[0];
  5308. var tm1 = this.m[1];
  5309. var tm2 = this.m[2];
  5310. var tm3 = this.m[3];
  5311. var tm4 = this.m[4];
  5312. var tm5 = this.m[5];
  5313. var tm6 = this.m[6];
  5314. var tm7 = this.m[7];
  5315. var tm8 = this.m[8];
  5316. var tm9 = this.m[9];
  5317. var tm10 = this.m[10];
  5318. var tm11 = this.m[11];
  5319. var tm12 = this.m[12];
  5320. var tm13 = this.m[13];
  5321. var tm14 = this.m[14];
  5322. var tm15 = this.m[15];
  5323. var om0 = other.m[0];
  5324. var om1 = other.m[1];
  5325. var om2 = other.m[2];
  5326. var om3 = other.m[3];
  5327. var om4 = other.m[4];
  5328. var om5 = other.m[5];
  5329. var om6 = other.m[6];
  5330. var om7 = other.m[7];
  5331. var om8 = other.m[8];
  5332. var om9 = other.m[9];
  5333. var om10 = other.m[10];
  5334. var om11 = other.m[11];
  5335. var om12 = other.m[12];
  5336. var om13 = other.m[13];
  5337. var om14 = other.m[14];
  5338. var om15 = other.m[15];
  5339. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5340. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5341. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5342. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5343. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5344. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5345. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5346. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5347. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5348. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5349. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5350. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5351. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5352. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5353. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5354. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5355. return this;
  5356. };
  5357. /**
  5358. * Check equality between this matrix and a second one
  5359. * @param value defines the second matrix to compare
  5360. * @returns true is the current matrix and the given one values are strictly equal
  5361. */
  5362. Matrix.prototype.equals = function (value) {
  5363. return value &&
  5364. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5365. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5366. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5367. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5368. };
  5369. /**
  5370. * Clone the current matrix
  5371. * @returns a new matrix from the current matrix
  5372. */
  5373. Matrix.prototype.clone = function () {
  5374. 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]);
  5375. };
  5376. /**
  5377. * Returns the name of the current matrix class
  5378. * @returns the string "Matrix"
  5379. */
  5380. Matrix.prototype.getClassName = function () {
  5381. return "Matrix";
  5382. };
  5383. /**
  5384. * Gets the hash code of the current matrix
  5385. * @returns the hash code
  5386. */
  5387. Matrix.prototype.getHashCode = function () {
  5388. var hash = this.m[0] || 0;
  5389. for (var i = 1; i < 16; i++) {
  5390. hash = (hash * 397) ^ (this.m[i] || 0);
  5391. }
  5392. return hash;
  5393. };
  5394. /**
  5395. * Decomposes the current Matrix into a translation, rotation and scaling components
  5396. * @param scale defines the scale vector3 given as a reference to update
  5397. * @param rotation defines the rotation quaternion given as a reference to update
  5398. * @param translation defines the translation vector3 given as a reference to update
  5399. * @returns true if operation was successful
  5400. */
  5401. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5402. if (translation) {
  5403. translation.x = this.m[12];
  5404. translation.y = this.m[13];
  5405. translation.z = this.m[14];
  5406. }
  5407. scale = scale || MathTmp.Vector3[0];
  5408. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5409. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5410. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5411. if (this.determinant() <= 0) {
  5412. scale.y *= -1;
  5413. }
  5414. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5415. if (rotation) {
  5416. rotation.x = 0;
  5417. rotation.y = 0;
  5418. rotation.z = 0;
  5419. rotation.w = 1;
  5420. }
  5421. return false;
  5422. }
  5423. if (rotation) {
  5424. 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]);
  5425. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5426. }
  5427. return true;
  5428. };
  5429. /**
  5430. * Gets specific row of the matrix
  5431. * @param index defines the number of the row to get
  5432. * @returns the index-th row of the current matrix as a new Vector4
  5433. */
  5434. Matrix.prototype.getRow = function (index) {
  5435. if (index < 0 || index > 3) {
  5436. return null;
  5437. }
  5438. var i = index * 4;
  5439. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5440. };
  5441. /**
  5442. * Sets the index-th row of the current matrix to the vector4 values
  5443. * @param index defines the number of the row to set
  5444. * @param row defines the target vector4
  5445. * @returns the updated current matrix
  5446. */
  5447. Matrix.prototype.setRow = function (index, row) {
  5448. if (index < 0 || index > 3) {
  5449. return this;
  5450. }
  5451. var i = index * 4;
  5452. this.m[i + 0] = row.x;
  5453. this.m[i + 1] = row.y;
  5454. this.m[i + 2] = row.z;
  5455. this.m[i + 3] = row.w;
  5456. this._markAsUpdated();
  5457. return this;
  5458. };
  5459. /**
  5460. * Compute the transpose of the matrix
  5461. * @returns the new transposed matrix
  5462. */
  5463. Matrix.prototype.transpose = function () {
  5464. return Matrix.Transpose(this);
  5465. };
  5466. /**
  5467. * Compute the transpose of the matrix and store it in a given matrix
  5468. * @param result defines the target matrix
  5469. * @returns the current matrix
  5470. */
  5471. Matrix.prototype.transposeToRef = function (result) {
  5472. Matrix.TransposeToRef(this, result);
  5473. return this;
  5474. };
  5475. /**
  5476. * Sets the index-th row of the current matrix with the given 4 x float values
  5477. * @param index defines the row index
  5478. * @param x defines the x component to set
  5479. * @param y defines the y component to set
  5480. * @param z defines the z component to set
  5481. * @param w defines the w component to set
  5482. * @returns the updated current matrix
  5483. */
  5484. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5485. if (index < 0 || index > 3) {
  5486. return this;
  5487. }
  5488. var i = index * 4;
  5489. this.m[i + 0] = x;
  5490. this.m[i + 1] = y;
  5491. this.m[i + 2] = z;
  5492. this.m[i + 3] = w;
  5493. this._markAsUpdated();
  5494. return this;
  5495. };
  5496. /**
  5497. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5498. * @param scale defines the scale factor
  5499. * @returns a new matrix
  5500. */
  5501. Matrix.prototype.scale = function (scale) {
  5502. var result = new Matrix();
  5503. this.scaleToRef(scale, result);
  5504. return result;
  5505. };
  5506. /**
  5507. * Scale the current matrix values by a factor to a given result matrix
  5508. * @param scale defines the scale factor
  5509. * @param result defines the matrix to store the result
  5510. * @returns the current matrix
  5511. */
  5512. Matrix.prototype.scaleToRef = function (scale, result) {
  5513. for (var index = 0; index < 16; index++) {
  5514. result.m[index] = this.m[index] * scale;
  5515. }
  5516. result._markAsUpdated();
  5517. return this;
  5518. };
  5519. /**
  5520. * Scale the current matrix values by a factor and add the result to a given matrix
  5521. * @param scale defines the scale factor
  5522. * @param result defines the Matrix to store the result
  5523. * @returns the current matrix
  5524. */
  5525. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5526. for (var index = 0; index < 16; index++) {
  5527. result.m[index] += this.m[index] * scale;
  5528. }
  5529. result._markAsUpdated();
  5530. return this;
  5531. };
  5532. /**
  5533. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5534. * @param ref matrix to store the result
  5535. */
  5536. Matrix.prototype.toNormalMatrix = function (ref) {
  5537. this.invertToRef(ref);
  5538. ref.transpose();
  5539. var m = ref.m;
  5540. 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);
  5541. };
  5542. /**
  5543. * Gets only rotation part of the current matrix
  5544. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5545. */
  5546. Matrix.prototype.getRotationMatrix = function () {
  5547. var result = Matrix.Identity();
  5548. this.getRotationMatrixToRef(result);
  5549. return result;
  5550. };
  5551. /**
  5552. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5553. * @param result defines the target matrix to store data to
  5554. * @returns the current matrix
  5555. */
  5556. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5557. var m = this.m;
  5558. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5559. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5560. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5561. if (this.determinant() <= 0) {
  5562. sy *= -1;
  5563. }
  5564. if (sx === 0 || sy === 0 || sz === 0) {
  5565. Matrix.IdentityToRef(result);
  5566. }
  5567. else {
  5568. 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);
  5569. }
  5570. return this;
  5571. };
  5572. // Statics
  5573. /**
  5574. * Creates a matrix from an array
  5575. * @param array defines the source array
  5576. * @param offset defines an offset in the source array
  5577. * @returns a new Matrix set from the starting index of the given array
  5578. */
  5579. Matrix.FromArray = function (array, offset) {
  5580. var result = new Matrix();
  5581. if (!offset) {
  5582. offset = 0;
  5583. }
  5584. Matrix.FromArrayToRef(array, offset, result);
  5585. return result;
  5586. };
  5587. /**
  5588. * Copy the content of an array into a given matrix
  5589. * @param array defines the source array
  5590. * @param offset defines an offset in the source array
  5591. * @param result defines the target matrix
  5592. */
  5593. Matrix.FromArrayToRef = function (array, offset, result) {
  5594. for (var index = 0; index < 16; index++) {
  5595. result.m[index] = array[index + offset];
  5596. }
  5597. result._markAsUpdated();
  5598. };
  5599. /**
  5600. * Stores an array into a matrix after having multiplied each component by a given factor
  5601. * @param array defines the source array
  5602. * @param offset defines the offset in the source array
  5603. * @param scale defines the scaling factor
  5604. * @param result defines the target matrix
  5605. */
  5606. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5607. for (var index = 0; index < 16; index++) {
  5608. result.m[index] = array[index + offset] * scale;
  5609. }
  5610. result._markAsUpdated();
  5611. };
  5612. /**
  5613. * Stores a list of values (16) inside a given matrix
  5614. * @param initialM11 defines 1st value of 1st row
  5615. * @param initialM12 defines 2nd value of 1st row
  5616. * @param initialM13 defines 3rd value of 1st row
  5617. * @param initialM14 defines 4th value of 1st row
  5618. * @param initialM21 defines 1st value of 2nd row
  5619. * @param initialM22 defines 2nd value of 2nd row
  5620. * @param initialM23 defines 3rd value of 2nd row
  5621. * @param initialM24 defines 4th value of 2nd row
  5622. * @param initialM31 defines 1st value of 3rd row
  5623. * @param initialM32 defines 2nd value of 3rd row
  5624. * @param initialM33 defines 3rd value of 3rd row
  5625. * @param initialM34 defines 4th value of 3rd row
  5626. * @param initialM41 defines 1st value of 4th row
  5627. * @param initialM42 defines 2nd value of 4th row
  5628. * @param initialM43 defines 3rd value of 4th row
  5629. * @param initialM44 defines 4th value of 4th row
  5630. * @param result defines the target matrix
  5631. */
  5632. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5633. result.m[0] = initialM11;
  5634. result.m[1] = initialM12;
  5635. result.m[2] = initialM13;
  5636. result.m[3] = initialM14;
  5637. result.m[4] = initialM21;
  5638. result.m[5] = initialM22;
  5639. result.m[6] = initialM23;
  5640. result.m[7] = initialM24;
  5641. result.m[8] = initialM31;
  5642. result.m[9] = initialM32;
  5643. result.m[10] = initialM33;
  5644. result.m[11] = initialM34;
  5645. result.m[12] = initialM41;
  5646. result.m[13] = initialM42;
  5647. result.m[14] = initialM43;
  5648. result.m[15] = initialM44;
  5649. result._markAsUpdated();
  5650. };
  5651. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5652. /**
  5653. * Gets an identity matrix that must not be updated
  5654. */
  5655. get: function () {
  5656. return Matrix._identityReadOnly;
  5657. },
  5658. enumerable: true,
  5659. configurable: true
  5660. });
  5661. /**
  5662. * Creates new matrix from a list of values (16)
  5663. * @param initialM11 defines 1st value of 1st row
  5664. * @param initialM12 defines 2nd value of 1st row
  5665. * @param initialM13 defines 3rd value of 1st row
  5666. * @param initialM14 defines 4th value of 1st row
  5667. * @param initialM21 defines 1st value of 2nd row
  5668. * @param initialM22 defines 2nd value of 2nd row
  5669. * @param initialM23 defines 3rd value of 2nd row
  5670. * @param initialM24 defines 4th value of 2nd row
  5671. * @param initialM31 defines 1st value of 3rd row
  5672. * @param initialM32 defines 2nd value of 3rd row
  5673. * @param initialM33 defines 3rd value of 3rd row
  5674. * @param initialM34 defines 4th value of 3rd row
  5675. * @param initialM41 defines 1st value of 4th row
  5676. * @param initialM42 defines 2nd value of 4th row
  5677. * @param initialM43 defines 3rd value of 4th row
  5678. * @param initialM44 defines 4th value of 4th row
  5679. * @returns the new matrix
  5680. */
  5681. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5682. var result = new Matrix();
  5683. result.m[0] = initialM11;
  5684. result.m[1] = initialM12;
  5685. result.m[2] = initialM13;
  5686. result.m[3] = initialM14;
  5687. result.m[4] = initialM21;
  5688. result.m[5] = initialM22;
  5689. result.m[6] = initialM23;
  5690. result.m[7] = initialM24;
  5691. result.m[8] = initialM31;
  5692. result.m[9] = initialM32;
  5693. result.m[10] = initialM33;
  5694. result.m[11] = initialM34;
  5695. result.m[12] = initialM41;
  5696. result.m[13] = initialM42;
  5697. result.m[14] = initialM43;
  5698. result.m[15] = initialM44;
  5699. return result;
  5700. };
  5701. /**
  5702. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5703. * @param scale defines the scale vector3
  5704. * @param rotation defines the rotation quaternion
  5705. * @param translation defines the translation vector3
  5706. * @returns a new matrix
  5707. */
  5708. Matrix.Compose = function (scale, rotation, translation) {
  5709. var result = Matrix.Identity();
  5710. Matrix.ComposeToRef(scale, rotation, translation, result);
  5711. return result;
  5712. };
  5713. /**
  5714. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5715. * @param scale defines the scale vector3
  5716. * @param rotation defines the rotation quaternion
  5717. * @param translation defines the translation vector3
  5718. * @param result defines the target matrix
  5719. */
  5720. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5721. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5722. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5723. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5724. result.setTranslation(translation);
  5725. };
  5726. /**
  5727. * Creates a new identity matrix
  5728. * @returns a new identity matrix
  5729. */
  5730. Matrix.Identity = function () {
  5731. 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);
  5732. };
  5733. /**
  5734. * Creates a new identity matrix and stores the result in a given matrix
  5735. * @param result defines the target matrix
  5736. */
  5737. Matrix.IdentityToRef = function (result) {
  5738. 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);
  5739. };
  5740. /**
  5741. * Creates a new zero matrix
  5742. * @returns a new zero matrix
  5743. */
  5744. Matrix.Zero = function () {
  5745. 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);
  5746. };
  5747. /**
  5748. * Creates a new rotation matrix for "angle" radians around the X axis
  5749. * @param angle defines the angle (in radians) to use
  5750. * @return the new matrix
  5751. */
  5752. Matrix.RotationX = function (angle) {
  5753. var result = new Matrix();
  5754. Matrix.RotationXToRef(angle, result);
  5755. return result;
  5756. };
  5757. /**
  5758. * Creates a new matrix as the invert of a given matrix
  5759. * @param source defines the source matrix
  5760. * @returns the new matrix
  5761. */
  5762. Matrix.Invert = function (source) {
  5763. var result = new Matrix();
  5764. source.invertToRef(result);
  5765. return result;
  5766. };
  5767. /**
  5768. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5769. * @param angle defines the angle (in radians) to use
  5770. * @param result defines the target matrix
  5771. */
  5772. Matrix.RotationXToRef = function (angle, result) {
  5773. var s = Math.sin(angle);
  5774. var c = Math.cos(angle);
  5775. result.m[0] = 1.0;
  5776. result.m[15] = 1.0;
  5777. result.m[5] = c;
  5778. result.m[10] = c;
  5779. result.m[9] = -s;
  5780. result.m[6] = s;
  5781. result.m[1] = 0.0;
  5782. result.m[2] = 0.0;
  5783. result.m[3] = 0.0;
  5784. result.m[4] = 0.0;
  5785. result.m[7] = 0.0;
  5786. result.m[8] = 0.0;
  5787. result.m[11] = 0.0;
  5788. result.m[12] = 0.0;
  5789. result.m[13] = 0.0;
  5790. result.m[14] = 0.0;
  5791. result._markAsUpdated();
  5792. };
  5793. /**
  5794. * Creates a new rotation matrix for "angle" radians around the Y axis
  5795. * @param angle defines the angle (in radians) to use
  5796. * @return the new matrix
  5797. */
  5798. Matrix.RotationY = function (angle) {
  5799. var result = new Matrix();
  5800. Matrix.RotationYToRef(angle, result);
  5801. return result;
  5802. };
  5803. /**
  5804. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5805. * @param angle defines the angle (in radians) to use
  5806. * @param result defines the target matrix
  5807. */
  5808. Matrix.RotationYToRef = function (angle, result) {
  5809. var s = Math.sin(angle);
  5810. var c = Math.cos(angle);
  5811. result.m[5] = 1.0;
  5812. result.m[15] = 1.0;
  5813. result.m[0] = c;
  5814. result.m[2] = -s;
  5815. result.m[8] = s;
  5816. result.m[10] = c;
  5817. result.m[1] = 0.0;
  5818. result.m[3] = 0.0;
  5819. result.m[4] = 0.0;
  5820. result.m[6] = 0.0;
  5821. result.m[7] = 0.0;
  5822. result.m[9] = 0.0;
  5823. result.m[11] = 0.0;
  5824. result.m[12] = 0.0;
  5825. result.m[13] = 0.0;
  5826. result.m[14] = 0.0;
  5827. result._markAsUpdated();
  5828. };
  5829. /**
  5830. * Creates a new rotation matrix for "angle" radians around the Z axis
  5831. * @param angle defines the angle (in radians) to use
  5832. * @return the new matrix
  5833. */
  5834. Matrix.RotationZ = function (angle) {
  5835. var result = new Matrix();
  5836. Matrix.RotationZToRef(angle, result);
  5837. return result;
  5838. };
  5839. /**
  5840. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5841. * @param angle defines the angle (in radians) to use
  5842. * @param result defines the target matrix
  5843. */
  5844. Matrix.RotationZToRef = function (angle, result) {
  5845. var s = Math.sin(angle);
  5846. var c = Math.cos(angle);
  5847. result.m[10] = 1.0;
  5848. result.m[15] = 1.0;
  5849. result.m[0] = c;
  5850. result.m[1] = s;
  5851. result.m[4] = -s;
  5852. result.m[5] = c;
  5853. result.m[2] = 0.0;
  5854. result.m[3] = 0.0;
  5855. result.m[6] = 0.0;
  5856. result.m[7] = 0.0;
  5857. result.m[8] = 0.0;
  5858. result.m[9] = 0.0;
  5859. result.m[11] = 0.0;
  5860. result.m[12] = 0.0;
  5861. result.m[13] = 0.0;
  5862. result.m[14] = 0.0;
  5863. result._markAsUpdated();
  5864. };
  5865. /**
  5866. * Creates a new rotation matrix for "angle" radians around the given axis
  5867. * @param axis defines the axis to use
  5868. * @param angle defines the angle (in radians) to use
  5869. * @return the new matrix
  5870. */
  5871. Matrix.RotationAxis = function (axis, angle) {
  5872. var result = Matrix.Zero();
  5873. Matrix.RotationAxisToRef(axis, angle, result);
  5874. return result;
  5875. };
  5876. /**
  5877. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5878. * @param axis defines the axis to use
  5879. * @param angle defines the angle (in radians) to use
  5880. * @param result defines the target matrix
  5881. */
  5882. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5883. var s = Math.sin(-angle);
  5884. var c = Math.cos(-angle);
  5885. var c1 = 1 - c;
  5886. axis.normalize();
  5887. result.m[0] = (axis.x * axis.x) * c1 + c;
  5888. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5889. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5890. result.m[3] = 0.0;
  5891. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5892. result.m[5] = (axis.y * axis.y) * c1 + c;
  5893. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5894. result.m[7] = 0.0;
  5895. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5896. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5897. result.m[10] = (axis.z * axis.z) * c1 + c;
  5898. result.m[11] = 0.0;
  5899. result.m[15] = 1.0;
  5900. result._markAsUpdated();
  5901. };
  5902. /**
  5903. * Creates a rotation matrix
  5904. * @param yaw defines the yaw angle in radians (Y axis)
  5905. * @param pitch defines the pitch angle in radians (X axis)
  5906. * @param roll defines the roll angle in radians (X axis)
  5907. * @returns the new rotation matrix
  5908. */
  5909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5910. var result = new Matrix();
  5911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5912. return result;
  5913. };
  5914. /**
  5915. * Creates a rotation matrix and stores it in a given matrix
  5916. * @param yaw defines the yaw angle in radians (Y axis)
  5917. * @param pitch defines the pitch angle in radians (X axis)
  5918. * @param roll defines the roll angle in radians (X axis)
  5919. * @param result defines the target matrix
  5920. */
  5921. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5922. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5923. this._tempQuaternion.toRotationMatrix(result);
  5924. };
  5925. /**
  5926. * Creates a scaling matrix
  5927. * @param x defines the scale factor on X axis
  5928. * @param y defines the scale factor on Y axis
  5929. * @param z defines the scale factor on Z axis
  5930. * @returns the new matrix
  5931. */
  5932. Matrix.Scaling = function (x, y, z) {
  5933. var result = Matrix.Zero();
  5934. Matrix.ScalingToRef(x, y, z, result);
  5935. return result;
  5936. };
  5937. /**
  5938. * Creates a scaling matrix and stores it in a given matrix
  5939. * @param x defines the scale factor on X axis
  5940. * @param y defines the scale factor on Y axis
  5941. * @param z defines the scale factor on Z axis
  5942. * @param result defines the target matrix
  5943. */
  5944. Matrix.ScalingToRef = function (x, y, z, result) {
  5945. result.m[0] = x;
  5946. result.m[1] = 0.0;
  5947. result.m[2] = 0.0;
  5948. result.m[3] = 0.0;
  5949. result.m[4] = 0.0;
  5950. result.m[5] = y;
  5951. result.m[6] = 0.0;
  5952. result.m[7] = 0.0;
  5953. result.m[8] = 0.0;
  5954. result.m[9] = 0.0;
  5955. result.m[10] = z;
  5956. result.m[11] = 0.0;
  5957. result.m[12] = 0.0;
  5958. result.m[13] = 0.0;
  5959. result.m[14] = 0.0;
  5960. result.m[15] = 1.0;
  5961. result._markAsUpdated();
  5962. };
  5963. /**
  5964. * Creates a translation matrix
  5965. * @param x defines the translation on X axis
  5966. * @param y defines the translation on Y axis
  5967. * @param z defines the translationon Z axis
  5968. * @returns the new matrix
  5969. */
  5970. Matrix.Translation = function (x, y, z) {
  5971. var result = Matrix.Identity();
  5972. Matrix.TranslationToRef(x, y, z, result);
  5973. return result;
  5974. };
  5975. /**
  5976. * Creates a translation matrix and stores it in a given matrix
  5977. * @param x defines the translation on X axis
  5978. * @param y defines the translation on Y axis
  5979. * @param z defines the translationon Z axis
  5980. * @param result defines the target matrix
  5981. */
  5982. Matrix.TranslationToRef = function (x, y, z, result) {
  5983. 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);
  5984. };
  5985. /**
  5986. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5987. * @param startValue defines the start value
  5988. * @param endValue defines the end value
  5989. * @param gradient defines the gradient factor
  5990. * @returns the new matrix
  5991. */
  5992. Matrix.Lerp = function (startValue, endValue, gradient) {
  5993. var result = Matrix.Zero();
  5994. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5995. return result;
  5996. };
  5997. /**
  5998. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5999. * @param startValue defines the start value
  6000. * @param endValue defines the end value
  6001. * @param gradient defines the gradient factor
  6002. * @param result defines the Matrix object where to store data
  6003. */
  6004. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6005. for (var index = 0; index < 16; index++) {
  6006. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6007. }
  6008. result._markAsUpdated();
  6009. };
  6010. /**
  6011. * Builds a new matrix whose values are computed by:
  6012. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6013. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6014. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6015. * @param startValue defines the first matrix
  6016. * @param endValue defines the second matrix
  6017. * @param gradient defines the gradient between the two matrices
  6018. * @returns the new matrix
  6019. */
  6020. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6021. var result = Matrix.Zero();
  6022. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6023. return result;
  6024. };
  6025. /**
  6026. * Update a matrix to values which are computed by:
  6027. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6028. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6029. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6030. * @param startValue defines the first matrix
  6031. * @param endValue defines the second matrix
  6032. * @param gradient defines the gradient between the two matrices
  6033. * @param result defines the target matrix
  6034. */
  6035. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6036. var startScale = MathTmp.Vector3[0];
  6037. var startRotation = MathTmp.Quaternion[0];
  6038. var startTranslation = MathTmp.Vector3[1];
  6039. startValue.decompose(startScale, startRotation, startTranslation);
  6040. var endScale = MathTmp.Vector3[2];
  6041. var endRotation = MathTmp.Quaternion[1];
  6042. var endTranslation = MathTmp.Vector3[3];
  6043. endValue.decompose(endScale, endRotation, endTranslation);
  6044. var resultScale = MathTmp.Vector3[4];
  6045. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6046. var resultRotation = MathTmp.Quaternion[2];
  6047. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6048. var resultTranslation = MathTmp.Vector3[5];
  6049. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6050. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6051. };
  6052. /**
  6053. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6054. * This function works in left handed mode
  6055. * @param eye defines the final position of the entity
  6056. * @param target defines where the entity should look at
  6057. * @param up defines the up vector for the entity
  6058. * @returns the new matrix
  6059. */
  6060. Matrix.LookAtLH = function (eye, target, up) {
  6061. var result = Matrix.Zero();
  6062. Matrix.LookAtLHToRef(eye, target, up, result);
  6063. return result;
  6064. };
  6065. /**
  6066. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6067. * This function works in left handed mode
  6068. * @param eye defines the final position of the entity
  6069. * @param target defines where the entity should look at
  6070. * @param up defines the up vector for the entity
  6071. * @param result defines the target matrix
  6072. */
  6073. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6074. // Z axis
  6075. target.subtractToRef(eye, this._zAxis);
  6076. this._zAxis.normalize();
  6077. // X axis
  6078. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6079. if (this._xAxis.lengthSquared() === 0) {
  6080. this._xAxis.x = 1.0;
  6081. }
  6082. else {
  6083. this._xAxis.normalize();
  6084. }
  6085. // Y axis
  6086. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6087. this._yAxis.normalize();
  6088. // Eye angles
  6089. var ex = -Vector3.Dot(this._xAxis, eye);
  6090. var ey = -Vector3.Dot(this._yAxis, eye);
  6091. var ez = -Vector3.Dot(this._zAxis, eye);
  6092. 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);
  6093. };
  6094. /**
  6095. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6096. * This function works in right handed mode
  6097. * @param eye defines the final position of the entity
  6098. * @param target defines where the entity should look at
  6099. * @param up defines the up vector for the entity
  6100. * @returns the new matrix
  6101. */
  6102. Matrix.LookAtRH = function (eye, target, up) {
  6103. var result = Matrix.Zero();
  6104. Matrix.LookAtRHToRef(eye, target, up, result);
  6105. return result;
  6106. };
  6107. /**
  6108. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6109. * This function works in right handed mode
  6110. * @param eye defines the final position of the entity
  6111. * @param target defines where the entity should look at
  6112. * @param up defines the up vector for the entity
  6113. * @param result defines the target matrix
  6114. */
  6115. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6116. // Z axis
  6117. eye.subtractToRef(target, this._zAxis);
  6118. this._zAxis.normalize();
  6119. // X axis
  6120. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6121. if (this._xAxis.lengthSquared() === 0) {
  6122. this._xAxis.x = 1.0;
  6123. }
  6124. else {
  6125. this._xAxis.normalize();
  6126. }
  6127. // Y axis
  6128. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6129. this._yAxis.normalize();
  6130. // Eye angles
  6131. var ex = -Vector3.Dot(this._xAxis, eye);
  6132. var ey = -Vector3.Dot(this._yAxis, eye);
  6133. var ez = -Vector3.Dot(this._zAxis, eye);
  6134. 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);
  6135. };
  6136. /**
  6137. * Create a left-handed orthographic projection matrix
  6138. * @param width defines the viewport width
  6139. * @param height defines the viewport height
  6140. * @param znear defines the near clip plane
  6141. * @param zfar defines the far clip plane
  6142. * @returns a new matrix as a left-handed orthographic projection matrix
  6143. */
  6144. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6145. var matrix = Matrix.Zero();
  6146. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6147. return matrix;
  6148. };
  6149. /**
  6150. * Store a left-handed orthographic projection to a given matrix
  6151. * @param width defines the viewport width
  6152. * @param height defines the viewport height
  6153. * @param znear defines the near clip plane
  6154. * @param zfar defines the far clip plane
  6155. * @param result defines the target matrix
  6156. */
  6157. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6158. var n = znear;
  6159. var f = zfar;
  6160. var a = 2.0 / width;
  6161. var b = 2.0 / height;
  6162. var c = 2.0 / (f - n);
  6163. var d = -(f + n) / (f - n);
  6164. 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);
  6165. };
  6166. /**
  6167. * Create a left-handed orthographic projection matrix
  6168. * @param left defines the viewport left coordinate
  6169. * @param right defines the viewport right coordinate
  6170. * @param bottom defines the viewport bottom coordinate
  6171. * @param top defines the viewport top coordinate
  6172. * @param znear defines the near clip plane
  6173. * @param zfar defines the far clip plane
  6174. * @returns a new matrix as a left-handed orthographic projection matrix
  6175. */
  6176. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6177. var matrix = Matrix.Zero();
  6178. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6179. return matrix;
  6180. };
  6181. /**
  6182. * Stores a left-handed orthographic projection into a given matrix
  6183. * @param left defines the viewport left coordinate
  6184. * @param right defines the viewport right coordinate
  6185. * @param bottom defines the viewport bottom coordinate
  6186. * @param top defines the viewport top coordinate
  6187. * @param znear defines the near clip plane
  6188. * @param zfar defines the far clip plane
  6189. * @param result defines the target matrix
  6190. */
  6191. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6192. var n = znear;
  6193. var f = zfar;
  6194. var a = 2.0 / (right - left);
  6195. var b = 2.0 / (top - bottom);
  6196. var c = 2.0 / (f - n);
  6197. var d = -(f + n) / (f - n);
  6198. var i0 = (left + right) / (left - right);
  6199. var i1 = (top + bottom) / (bottom - top);
  6200. 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);
  6201. };
  6202. /**
  6203. * Creates a right-handed orthographic projection matrix
  6204. * @param left defines the viewport left coordinate
  6205. * @param right defines the viewport right coordinate
  6206. * @param bottom defines the viewport bottom coordinate
  6207. * @param top defines the viewport top coordinate
  6208. * @param znear defines the near clip plane
  6209. * @param zfar defines the far clip plane
  6210. * @returns a new matrix as a right-handed orthographic projection matrix
  6211. */
  6212. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6213. var matrix = Matrix.Zero();
  6214. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6215. return matrix;
  6216. };
  6217. /**
  6218. * Stores a right-handed orthographic projection into a given matrix
  6219. * @param left defines the viewport left coordinate
  6220. * @param right defines the viewport right coordinate
  6221. * @param bottom defines the viewport bottom coordinate
  6222. * @param top defines the viewport top coordinate
  6223. * @param znear defines the near clip plane
  6224. * @param zfar defines the far clip plane
  6225. * @param result defines the target matrix
  6226. */
  6227. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6228. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6229. result.m[10] *= -1.0;
  6230. };
  6231. /**
  6232. * Creates a left-handed perspective projection matrix
  6233. * @param width defines the viewport width
  6234. * @param height defines the viewport height
  6235. * @param znear defines the near clip plane
  6236. * @param zfar defines the far clip plane
  6237. * @returns a new matrix as a left-handed perspective projection matrix
  6238. */
  6239. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6240. var matrix = Matrix.Zero();
  6241. var n = znear;
  6242. var f = zfar;
  6243. var a = 2.0 * n / width;
  6244. var b = 2.0 * n / height;
  6245. var c = (f + n) / (f - n);
  6246. var d = -2.0 * f * n / (f - n);
  6247. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  6248. return matrix;
  6249. };
  6250. /**
  6251. * Creates a left-handed perspective projection matrix
  6252. * @param fov defines the horizontal field of view
  6253. * @param aspect defines the aspect ratio
  6254. * @param znear defines the near clip plane
  6255. * @param zfar defines the far clip plane
  6256. * @returns a new matrix as a left-handed perspective projection matrix
  6257. */
  6258. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6259. var matrix = Matrix.Zero();
  6260. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6261. return matrix;
  6262. };
  6263. /**
  6264. * Stores a left-handed perspective projection into a given matrix
  6265. * @param fov defines the horizontal field of view
  6266. * @param aspect defines the aspect ratio
  6267. * @param znear defines the near clip plane
  6268. * @param zfar defines the far clip plane
  6269. * @param result defines the target matrix
  6270. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6271. */
  6272. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6273. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6274. var n = znear;
  6275. var f = zfar;
  6276. var t = 1.0 / (Math.tan(fov * 0.5));
  6277. var a = isVerticalFovFixed ? (t / aspect) : t;
  6278. var b = isVerticalFovFixed ? t : (t * aspect);
  6279. var c = (f + n) / (f - n);
  6280. var d = -2.0 * f * n / (f - n);
  6281. 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);
  6282. };
  6283. /**
  6284. * Creates a right-handed perspective projection matrix
  6285. * @param fov defines the horizontal field of view
  6286. * @param aspect defines the aspect ratio
  6287. * @param znear defines the near clip plane
  6288. * @param zfar defines the far clip plane
  6289. * @returns a new matrix as a right-handed perspective projection matrix
  6290. */
  6291. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6292. var matrix = Matrix.Zero();
  6293. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6294. return matrix;
  6295. };
  6296. /**
  6297. * Stores a right-handed perspective projection into a given matrix
  6298. * @param fov defines the horizontal field of view
  6299. * @param aspect defines the aspect ratio
  6300. * @param znear defines the near clip plane
  6301. * @param zfar defines the far clip plane
  6302. * @param result defines the target matrix
  6303. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6304. */
  6305. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6306. //alternatively this could be expressed as:
  6307. // m = PerspectiveFovLHToRef
  6308. // m[10] *= -1.0;
  6309. // m[11] *= -1.0;
  6310. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6311. var n = znear;
  6312. var f = zfar;
  6313. var t = 1.0 / (Math.tan(fov * 0.5));
  6314. var a = isVerticalFovFixed ? (t / aspect) : t;
  6315. var b = isVerticalFovFixed ? t : (t * aspect);
  6316. var c = -(f + n) / (f - n);
  6317. var d = -2 * f * n / (f - n);
  6318. 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);
  6319. };
  6320. /**
  6321. * Stores a perspective projection for WebVR info a given matrix
  6322. * @param fov defines the field of view
  6323. * @param znear defines the near clip plane
  6324. * @param zfar defines the far clip plane
  6325. * @param result defines the target matrix
  6326. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6327. */
  6328. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6329. if (rightHanded === void 0) { rightHanded = false; }
  6330. var rightHandedFactor = rightHanded ? -1 : 1;
  6331. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6332. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6333. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6334. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6335. var xScale = 2.0 / (leftTan + rightTan);
  6336. var yScale = 2.0 / (upTan + downTan);
  6337. result.m[0] = xScale;
  6338. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6339. result.m[5] = yScale;
  6340. result.m[6] = result.m[7] = 0.0;
  6341. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6342. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6343. result.m[10] = -zfar / (znear - zfar);
  6344. result.m[11] = 1.0 * rightHandedFactor;
  6345. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6346. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6347. result._markAsUpdated();
  6348. };
  6349. /**
  6350. * Computes a complete transformation matrix
  6351. * @param viewport defines the viewport to use
  6352. * @param world defines the world matrix
  6353. * @param view defines the view matrix
  6354. * @param projection defines the projection matrix
  6355. * @param zmin defines the near clip plane
  6356. * @param zmax defines the far clip plane
  6357. * @returns the transformation matrix
  6358. */
  6359. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6360. var cw = viewport.width;
  6361. var ch = viewport.height;
  6362. var cx = viewport.x;
  6363. var cy = viewport.y;
  6364. 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);
  6365. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6366. };
  6367. /**
  6368. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6369. * @param matrix defines the matrix to use
  6370. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6371. */
  6372. Matrix.GetAsMatrix2x2 = function (matrix) {
  6373. return new Float32Array([
  6374. matrix.m[0], matrix.m[1],
  6375. matrix.m[4], matrix.m[5]
  6376. ]);
  6377. };
  6378. /**
  6379. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6380. * @param matrix defines the matrix to use
  6381. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6382. */
  6383. Matrix.GetAsMatrix3x3 = function (matrix) {
  6384. return new Float32Array([
  6385. matrix.m[0], matrix.m[1], matrix.m[2],
  6386. matrix.m[4], matrix.m[5], matrix.m[6],
  6387. matrix.m[8], matrix.m[9], matrix.m[10]
  6388. ]);
  6389. };
  6390. /**
  6391. * Compute the transpose of a given matrix
  6392. * @param matrix defines the matrix to transpose
  6393. * @returns the new matrix
  6394. */
  6395. Matrix.Transpose = function (matrix) {
  6396. var result = new Matrix();
  6397. Matrix.TransposeToRef(matrix, result);
  6398. return result;
  6399. };
  6400. /**
  6401. * Compute the transpose of a matrix and store it in a target matrix
  6402. * @param matrix defines the matrix to transpose
  6403. * @param result defines the target matrix
  6404. */
  6405. Matrix.TransposeToRef = function (matrix, result) {
  6406. result.m[0] = matrix.m[0];
  6407. result.m[1] = matrix.m[4];
  6408. result.m[2] = matrix.m[8];
  6409. result.m[3] = matrix.m[12];
  6410. result.m[4] = matrix.m[1];
  6411. result.m[5] = matrix.m[5];
  6412. result.m[6] = matrix.m[9];
  6413. result.m[7] = matrix.m[13];
  6414. result.m[8] = matrix.m[2];
  6415. result.m[9] = matrix.m[6];
  6416. result.m[10] = matrix.m[10];
  6417. result.m[11] = matrix.m[14];
  6418. result.m[12] = matrix.m[3];
  6419. result.m[13] = matrix.m[7];
  6420. result.m[14] = matrix.m[11];
  6421. result.m[15] = matrix.m[15];
  6422. };
  6423. /**
  6424. * Computes a reflection matrix from a plane
  6425. * @param plane defines the reflection plane
  6426. * @returns a new matrix
  6427. */
  6428. Matrix.Reflection = function (plane) {
  6429. var matrix = new Matrix();
  6430. Matrix.ReflectionToRef(plane, matrix);
  6431. return matrix;
  6432. };
  6433. /**
  6434. * Computes a reflection matrix from a plane
  6435. * @param plane defines the reflection plane
  6436. * @param result defines the target matrix
  6437. */
  6438. Matrix.ReflectionToRef = function (plane, result) {
  6439. plane.normalize();
  6440. var x = plane.normal.x;
  6441. var y = plane.normal.y;
  6442. var z = plane.normal.z;
  6443. var temp = -2 * x;
  6444. var temp2 = -2 * y;
  6445. var temp3 = -2 * z;
  6446. result.m[0] = (temp * x) + 1;
  6447. result.m[1] = temp2 * x;
  6448. result.m[2] = temp3 * x;
  6449. result.m[3] = 0.0;
  6450. result.m[4] = temp * y;
  6451. result.m[5] = (temp2 * y) + 1;
  6452. result.m[6] = temp3 * y;
  6453. result.m[7] = 0.0;
  6454. result.m[8] = temp * z;
  6455. result.m[9] = temp2 * z;
  6456. result.m[10] = (temp3 * z) + 1;
  6457. result.m[11] = 0.0;
  6458. result.m[12] = temp * plane.d;
  6459. result.m[13] = temp2 * plane.d;
  6460. result.m[14] = temp3 * plane.d;
  6461. result.m[15] = 1.0;
  6462. result._markAsUpdated();
  6463. };
  6464. /**
  6465. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6466. * @param xaxis defines the value of the 1st axis
  6467. * @param yaxis defines the value of the 2nd axis
  6468. * @param zaxis defines the value of the 3rd axis
  6469. * @param result defines the target matrix
  6470. */
  6471. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6472. result.m[0] = xaxis.x;
  6473. result.m[1] = xaxis.y;
  6474. result.m[2] = xaxis.z;
  6475. result.m[3] = 0.0;
  6476. result.m[4] = yaxis.x;
  6477. result.m[5] = yaxis.y;
  6478. result.m[6] = yaxis.z;
  6479. result.m[7] = 0.0;
  6480. result.m[8] = zaxis.x;
  6481. result.m[9] = zaxis.y;
  6482. result.m[10] = zaxis.z;
  6483. result.m[11] = 0.0;
  6484. result.m[12] = 0.0;
  6485. result.m[13] = 0.0;
  6486. result.m[14] = 0.0;
  6487. result.m[15] = 1.0;
  6488. result._markAsUpdated();
  6489. };
  6490. /**
  6491. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6492. * @param quat defines the quaternion to use
  6493. * @param result defines the target matrix
  6494. */
  6495. Matrix.FromQuaternionToRef = function (quat, result) {
  6496. var xx = quat.x * quat.x;
  6497. var yy = quat.y * quat.y;
  6498. var zz = quat.z * quat.z;
  6499. var xy = quat.x * quat.y;
  6500. var zw = quat.z * quat.w;
  6501. var zx = quat.z * quat.x;
  6502. var yw = quat.y * quat.w;
  6503. var yz = quat.y * quat.z;
  6504. var xw = quat.x * quat.w;
  6505. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6506. result.m[1] = 2.0 * (xy + zw);
  6507. result.m[2] = 2.0 * (zx - yw);
  6508. result.m[3] = 0.0;
  6509. result.m[4] = 2.0 * (xy - zw);
  6510. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6511. result.m[6] = 2.0 * (yz + xw);
  6512. result.m[7] = 0.0;
  6513. result.m[8] = 2.0 * (zx + yw);
  6514. result.m[9] = 2.0 * (yz - xw);
  6515. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6516. result.m[11] = 0.0;
  6517. result.m[12] = 0.0;
  6518. result.m[13] = 0.0;
  6519. result.m[14] = 0.0;
  6520. result.m[15] = 1.0;
  6521. result._markAsUpdated();
  6522. };
  6523. Matrix._tempQuaternion = new Quaternion();
  6524. Matrix._xAxis = Vector3.Zero();
  6525. Matrix._yAxis = Vector3.Zero();
  6526. Matrix._zAxis = Vector3.Zero();
  6527. Matrix._updateFlagSeed = 0;
  6528. Matrix._identityReadOnly = Matrix.Identity();
  6529. return Matrix;
  6530. }());
  6531. BABYLON.Matrix = Matrix;
  6532. var Plane = /** @class */ (function () {
  6533. /**
  6534. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6535. */
  6536. function Plane(a, b, c, d) {
  6537. this.normal = new Vector3(a, b, c);
  6538. this.d = d;
  6539. }
  6540. /**
  6541. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6542. */
  6543. Plane.prototype.asArray = function () {
  6544. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6545. };
  6546. // Methods
  6547. /**
  6548. * Returns a new plane copied from the current Plane.
  6549. */
  6550. Plane.prototype.clone = function () {
  6551. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6552. };
  6553. /**
  6554. * Returns the string "Plane".
  6555. */
  6556. Plane.prototype.getClassName = function () {
  6557. return "Plane";
  6558. };
  6559. /**
  6560. * Returns the Plane hash code.
  6561. */
  6562. Plane.prototype.getHashCode = function () {
  6563. var hash = this.normal.getHashCode();
  6564. hash = (hash * 397) ^ (this.d || 0);
  6565. return hash;
  6566. };
  6567. /**
  6568. * Normalize the current Plane in place.
  6569. * Returns the updated Plane.
  6570. */
  6571. Plane.prototype.normalize = function () {
  6572. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6573. var magnitude = 0.0;
  6574. if (norm !== 0) {
  6575. magnitude = 1.0 / norm;
  6576. }
  6577. this.normal.x *= magnitude;
  6578. this.normal.y *= magnitude;
  6579. this.normal.z *= magnitude;
  6580. this.d *= magnitude;
  6581. return this;
  6582. };
  6583. /**
  6584. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6585. */
  6586. Plane.prototype.transform = function (transformation) {
  6587. var transposedMatrix = Matrix.Transpose(transformation);
  6588. var x = this.normal.x;
  6589. var y = this.normal.y;
  6590. var z = this.normal.z;
  6591. var d = this.d;
  6592. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6593. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6594. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6595. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6596. return new Plane(normalX, normalY, normalZ, finalD);
  6597. };
  6598. /**
  6599. * Returns the dot product (float) of the point coordinates and the plane normal.
  6600. */
  6601. Plane.prototype.dotCoordinate = function (point) {
  6602. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6603. };
  6604. /**
  6605. * Updates the current Plane from the plane defined by the three given points.
  6606. * Returns the updated Plane.
  6607. */
  6608. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6609. var x1 = point2.x - point1.x;
  6610. var y1 = point2.y - point1.y;
  6611. var z1 = point2.z - point1.z;
  6612. var x2 = point3.x - point1.x;
  6613. var y2 = point3.y - point1.y;
  6614. var z2 = point3.z - point1.z;
  6615. var yz = (y1 * z2) - (z1 * y2);
  6616. var xz = (z1 * x2) - (x1 * z2);
  6617. var xy = (x1 * y2) - (y1 * x2);
  6618. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6619. var invPyth;
  6620. if (pyth !== 0) {
  6621. invPyth = 1.0 / pyth;
  6622. }
  6623. else {
  6624. invPyth = 0.0;
  6625. }
  6626. this.normal.x = yz * invPyth;
  6627. this.normal.y = xz * invPyth;
  6628. this.normal.z = xy * invPyth;
  6629. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6630. return this;
  6631. };
  6632. /**
  6633. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6634. */
  6635. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6636. var dot = Vector3.Dot(this.normal, direction);
  6637. return (dot <= epsilon);
  6638. };
  6639. /**
  6640. * Returns the signed distance (float) from the given point to the Plane.
  6641. */
  6642. Plane.prototype.signedDistanceTo = function (point) {
  6643. return Vector3.Dot(point, this.normal) + this.d;
  6644. };
  6645. // Statics
  6646. /**
  6647. * Returns a new Plane from the given array.
  6648. */
  6649. Plane.FromArray = function (array) {
  6650. return new Plane(array[0], array[1], array[2], array[3]);
  6651. };
  6652. /**
  6653. * Returns a new Plane defined by the three given points.
  6654. */
  6655. Plane.FromPoints = function (point1, point2, point3) {
  6656. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6657. result.copyFromPoints(point1, point2, point3);
  6658. return result;
  6659. };
  6660. /**
  6661. * Returns a new Plane the normal vector to this plane at the given origin point.
  6662. * Note : the vector "normal" is updated because normalized.
  6663. */
  6664. Plane.FromPositionAndNormal = function (origin, normal) {
  6665. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6666. normal.normalize();
  6667. result.normal = normal;
  6668. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6669. return result;
  6670. };
  6671. /**
  6672. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6673. */
  6674. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6675. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6676. return Vector3.Dot(point, normal) + d;
  6677. };
  6678. return Plane;
  6679. }());
  6680. BABYLON.Plane = Plane;
  6681. var Viewport = /** @class */ (function () {
  6682. /**
  6683. * Creates a Viewport object located at (x, y) and sized (width, height).
  6684. */
  6685. function Viewport(x, y, width, height) {
  6686. this.x = x;
  6687. this.y = y;
  6688. this.width = width;
  6689. this.height = height;
  6690. }
  6691. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6692. if (renderWidthOrEngine.getRenderWidth) {
  6693. var engine = renderWidthOrEngine;
  6694. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6695. }
  6696. var renderWidth = renderWidthOrEngine;
  6697. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6698. };
  6699. /**
  6700. * Returns a new Viewport copied from the current one.
  6701. */
  6702. Viewport.prototype.clone = function () {
  6703. return new Viewport(this.x, this.y, this.width, this.height);
  6704. };
  6705. return Viewport;
  6706. }());
  6707. BABYLON.Viewport = Viewport;
  6708. var Frustum = /** @class */ (function () {
  6709. function Frustum() {
  6710. }
  6711. /**
  6712. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6713. */
  6714. Frustum.GetPlanes = function (transform) {
  6715. var frustumPlanes = [];
  6716. for (var index = 0; index < 6; index++) {
  6717. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6718. }
  6719. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6720. return frustumPlanes;
  6721. };
  6722. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6723. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6724. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6725. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6726. frustumPlane.d = transform.m[15] + transform.m[14];
  6727. frustumPlane.normalize();
  6728. };
  6729. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6730. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6731. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6732. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6733. frustumPlane.d = transform.m[15] - transform.m[14];
  6734. frustumPlane.normalize();
  6735. };
  6736. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6737. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6738. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6739. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6740. frustumPlane.d = transform.m[15] + transform.m[12];
  6741. frustumPlane.normalize();
  6742. };
  6743. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6744. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6745. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6746. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6747. frustumPlane.d = transform.m[15] - transform.m[12];
  6748. frustumPlane.normalize();
  6749. };
  6750. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6751. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6752. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6753. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6754. frustumPlane.d = transform.m[15] - transform.m[13];
  6755. frustumPlane.normalize();
  6756. };
  6757. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6758. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6759. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6760. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6761. frustumPlane.d = transform.m[15] + transform.m[13];
  6762. frustumPlane.normalize();
  6763. };
  6764. /**
  6765. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6766. */
  6767. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6768. // Near
  6769. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6770. // Far
  6771. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6772. // Left
  6773. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6774. // Right
  6775. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6776. // Top
  6777. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6778. // Bottom
  6779. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6780. };
  6781. return Frustum;
  6782. }());
  6783. BABYLON.Frustum = Frustum;
  6784. /** Defines supported spaces */
  6785. var Space;
  6786. (function (Space) {
  6787. /** Local (object) space */
  6788. Space[Space["LOCAL"] = 0] = "LOCAL";
  6789. /** World space */
  6790. Space[Space["WORLD"] = 1] = "WORLD";
  6791. /** Bone space */
  6792. Space[Space["BONE"] = 2] = "BONE";
  6793. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6794. /** Defines the 3 main axes */
  6795. var Axis = /** @class */ (function () {
  6796. function Axis() {
  6797. }
  6798. /** X axis */
  6799. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6800. /** Y axis */
  6801. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6802. /** Z axis */
  6803. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6804. return Axis;
  6805. }());
  6806. BABYLON.Axis = Axis;
  6807. ;
  6808. var BezierCurve = /** @class */ (function () {
  6809. function BezierCurve() {
  6810. }
  6811. /**
  6812. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6813. */
  6814. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6815. // Extract X (which is equal to time here)
  6816. var f0 = 1 - 3 * x2 + 3 * x1;
  6817. var f1 = 3 * x2 - 6 * x1;
  6818. var f2 = 3 * x1;
  6819. var refinedT = t;
  6820. for (var i = 0; i < 5; i++) {
  6821. var refinedT2 = refinedT * refinedT;
  6822. var refinedT3 = refinedT2 * refinedT;
  6823. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6824. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6825. refinedT -= (x - t) * slope;
  6826. refinedT = Math.min(1, Math.max(0, refinedT));
  6827. }
  6828. // Resolve cubic bezier for the given x
  6829. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6830. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6831. Math.pow(refinedT, 3);
  6832. };
  6833. return BezierCurve;
  6834. }());
  6835. BABYLON.BezierCurve = BezierCurve;
  6836. /**
  6837. * Defines potential orientation for back face culling
  6838. */
  6839. var Orientation;
  6840. (function (Orientation) {
  6841. /**
  6842. * Clockwise
  6843. */
  6844. Orientation[Orientation["CW"] = 0] = "CW";
  6845. /** Counter clockwise */
  6846. Orientation[Orientation["CCW"] = 1] = "CCW";
  6847. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6848. /**
  6849. * Defines angle representation
  6850. */
  6851. var Angle = /** @class */ (function () {
  6852. /**
  6853. * Creates an Angle object of "radians" radians (float).
  6854. */
  6855. function Angle(radians) {
  6856. this._radians = radians;
  6857. if (this._radians < 0.0)
  6858. this._radians += (2.0 * Math.PI);
  6859. }
  6860. /**
  6861. * Get value in degrees
  6862. * @returns the Angle value in degrees (float)
  6863. */
  6864. Angle.prototype.degrees = function () {
  6865. return this._radians * 180.0 / Math.PI;
  6866. };
  6867. /**
  6868. * Get value in radians
  6869. * @returns the Angle value in radians (float)
  6870. */
  6871. Angle.prototype.radians = function () {
  6872. return this._radians;
  6873. };
  6874. /**
  6875. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6876. * @param a defines first vector
  6877. * @param b defines second vector
  6878. * @returns a new Angle
  6879. */
  6880. Angle.BetweenTwoPoints = function (a, b) {
  6881. var delta = b.subtract(a);
  6882. var theta = Math.atan2(delta.y, delta.x);
  6883. return new Angle(theta);
  6884. };
  6885. /**
  6886. * Gets a new Angle object from the given float in radians
  6887. * @param radians defines the angle value in radians
  6888. * @returns a new Angle
  6889. */
  6890. Angle.FromRadians = function (radians) {
  6891. return new Angle(radians);
  6892. };
  6893. /**
  6894. * Gets a new Angle object from the given float in degrees
  6895. * @param degrees defines the angle value in degrees
  6896. * @returns a new Angle
  6897. */
  6898. Angle.FromDegrees = function (degrees) {
  6899. return new Angle(degrees * Math.PI / 180.0);
  6900. };
  6901. return Angle;
  6902. }());
  6903. BABYLON.Angle = Angle;
  6904. var Arc2 = /** @class */ (function () {
  6905. /**
  6906. * Creates an Arc object from the three given points : start, middle and end.
  6907. */
  6908. function Arc2(startPoint, midPoint, endPoint) {
  6909. this.startPoint = startPoint;
  6910. this.midPoint = midPoint;
  6911. this.endPoint = endPoint;
  6912. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6913. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6914. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6915. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6916. 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);
  6917. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6918. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6919. var a1 = this.startAngle.degrees();
  6920. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6921. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6922. // angles correction
  6923. if (a2 - a1 > +180.0)
  6924. a2 -= 360.0;
  6925. if (a2 - a1 < -180.0)
  6926. a2 += 360.0;
  6927. if (a3 - a2 > +180.0)
  6928. a3 -= 360.0;
  6929. if (a3 - a2 < -180.0)
  6930. a3 += 360.0;
  6931. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6932. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6933. }
  6934. return Arc2;
  6935. }());
  6936. BABYLON.Arc2 = Arc2;
  6937. var Path2 = /** @class */ (function () {
  6938. /**
  6939. * Creates a Path2 object from the starting 2D coordinates x and y.
  6940. */
  6941. function Path2(x, y) {
  6942. this._points = new Array();
  6943. this._length = 0.0;
  6944. this.closed = false;
  6945. this._points.push(new Vector2(x, y));
  6946. }
  6947. /**
  6948. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6949. * Returns the updated Path2.
  6950. */
  6951. Path2.prototype.addLineTo = function (x, y) {
  6952. if (this.closed) {
  6953. return this;
  6954. }
  6955. var newPoint = new Vector2(x, y);
  6956. var previousPoint = this._points[this._points.length - 1];
  6957. this._points.push(newPoint);
  6958. this._length += newPoint.subtract(previousPoint).length();
  6959. return this;
  6960. };
  6961. /**
  6962. * 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.
  6963. * Returns the updated Path2.
  6964. */
  6965. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6966. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6967. if (this.closed) {
  6968. return this;
  6969. }
  6970. var startPoint = this._points[this._points.length - 1];
  6971. var midPoint = new Vector2(midX, midY);
  6972. var endPoint = new Vector2(endX, endY);
  6973. var arc = new Arc2(startPoint, midPoint, endPoint);
  6974. var increment = arc.angle.radians() / numberOfSegments;
  6975. if (arc.orientation === Orientation.CW)
  6976. increment *= -1;
  6977. var currentAngle = arc.startAngle.radians() + increment;
  6978. for (var i = 0; i < numberOfSegments; i++) {
  6979. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6980. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6981. this.addLineTo(x, y);
  6982. currentAngle += increment;
  6983. }
  6984. return this;
  6985. };
  6986. /**
  6987. * Closes the Path2.
  6988. * Returns the Path2.
  6989. */
  6990. Path2.prototype.close = function () {
  6991. this.closed = true;
  6992. return this;
  6993. };
  6994. /**
  6995. * Returns the Path2 total length (float).
  6996. */
  6997. Path2.prototype.length = function () {
  6998. var result = this._length;
  6999. if (!this.closed) {
  7000. var lastPoint = this._points[this._points.length - 1];
  7001. var firstPoint = this._points[0];
  7002. result += (firstPoint.subtract(lastPoint).length());
  7003. }
  7004. return result;
  7005. };
  7006. /**
  7007. * Returns the Path2 internal array of points.
  7008. */
  7009. Path2.prototype.getPoints = function () {
  7010. return this._points;
  7011. };
  7012. /**
  7013. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7014. */
  7015. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7016. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7017. return Vector2.Zero();
  7018. }
  7019. var lengthPosition = normalizedLengthPosition * this.length();
  7020. var previousOffset = 0;
  7021. for (var i = 0; i < this._points.length; i++) {
  7022. var j = (i + 1) % this._points.length;
  7023. var a = this._points[i];
  7024. var b = this._points[j];
  7025. var bToA = b.subtract(a);
  7026. var nextOffset = (bToA.length() + previousOffset);
  7027. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7028. var dir = bToA.normalize();
  7029. var localOffset = lengthPosition - previousOffset;
  7030. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7031. }
  7032. previousOffset = nextOffset;
  7033. }
  7034. return Vector2.Zero();
  7035. };
  7036. /**
  7037. * Returns a new Path2 starting at the coordinates (x, y).
  7038. */
  7039. Path2.StartingAt = function (x, y) {
  7040. return new Path2(x, y);
  7041. };
  7042. return Path2;
  7043. }());
  7044. BABYLON.Path2 = Path2;
  7045. var Path3D = /** @class */ (function () {
  7046. /**
  7047. * new Path3D(path, normal, raw)
  7048. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7049. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7050. * path : an array of Vector3, the curve axis of the Path3D
  7051. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7052. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7053. */
  7054. function Path3D(path, firstNormal, raw) {
  7055. if (firstNormal === void 0) { firstNormal = null; }
  7056. this.path = path;
  7057. this._curve = new Array();
  7058. this._distances = new Array();
  7059. this._tangents = new Array();
  7060. this._normals = new Array();
  7061. this._binormals = new Array();
  7062. for (var p = 0; p < path.length; p++) {
  7063. this._curve[p] = path[p].clone(); // hard copy
  7064. }
  7065. this._raw = raw || false;
  7066. this._compute(firstNormal);
  7067. }
  7068. /**
  7069. * Returns the Path3D array of successive Vector3 designing its curve.
  7070. */
  7071. Path3D.prototype.getCurve = function () {
  7072. return this._curve;
  7073. };
  7074. /**
  7075. * Returns an array populated with tangent vectors on each Path3D curve point.
  7076. */
  7077. Path3D.prototype.getTangents = function () {
  7078. return this._tangents;
  7079. };
  7080. /**
  7081. * Returns an array populated with normal vectors on each Path3D curve point.
  7082. */
  7083. Path3D.prototype.getNormals = function () {
  7084. return this._normals;
  7085. };
  7086. /**
  7087. * Returns an array populated with binormal vectors on each Path3D curve point.
  7088. */
  7089. Path3D.prototype.getBinormals = function () {
  7090. return this._binormals;
  7091. };
  7092. /**
  7093. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7094. */
  7095. Path3D.prototype.getDistances = function () {
  7096. return this._distances;
  7097. };
  7098. /**
  7099. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7100. * Returns the same object updated.
  7101. */
  7102. Path3D.prototype.update = function (path, firstNormal) {
  7103. if (firstNormal === void 0) { firstNormal = null; }
  7104. for (var p = 0; p < path.length; p++) {
  7105. this._curve[p].x = path[p].x;
  7106. this._curve[p].y = path[p].y;
  7107. this._curve[p].z = path[p].z;
  7108. }
  7109. this._compute(firstNormal);
  7110. return this;
  7111. };
  7112. // private function compute() : computes tangents, normals and binormals
  7113. Path3D.prototype._compute = function (firstNormal) {
  7114. var l = this._curve.length;
  7115. // first and last tangents
  7116. this._tangents[0] = this._getFirstNonNullVector(0);
  7117. if (!this._raw) {
  7118. this._tangents[0].normalize();
  7119. }
  7120. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7121. if (!this._raw) {
  7122. this._tangents[l - 1].normalize();
  7123. }
  7124. // normals and binormals at first point : arbitrary vector with _normalVector()
  7125. var tg0 = this._tangents[0];
  7126. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7127. this._normals[0] = pp0;
  7128. if (!this._raw) {
  7129. this._normals[0].normalize();
  7130. }
  7131. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7132. if (!this._raw) {
  7133. this._binormals[0].normalize();
  7134. }
  7135. this._distances[0] = 0.0;
  7136. // normals and binormals : next points
  7137. var prev; // previous vector (segment)
  7138. var cur; // current vector (segment)
  7139. var curTang; // current tangent
  7140. // previous normal
  7141. var prevBinor; // previous binormal
  7142. for (var i = 1; i < l; i++) {
  7143. // tangents
  7144. prev = this._getLastNonNullVector(i);
  7145. if (i < l - 1) {
  7146. cur = this._getFirstNonNullVector(i);
  7147. this._tangents[i] = prev.add(cur);
  7148. this._tangents[i].normalize();
  7149. }
  7150. this._distances[i] = this._distances[i - 1] + prev.length();
  7151. // normals and binormals
  7152. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7153. curTang = this._tangents[i];
  7154. prevBinor = this._binormals[i - 1];
  7155. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7156. if (!this._raw) {
  7157. this._normals[i].normalize();
  7158. }
  7159. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7160. if (!this._raw) {
  7161. this._binormals[i].normalize();
  7162. }
  7163. }
  7164. };
  7165. // private function getFirstNonNullVector(index)
  7166. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7167. Path3D.prototype._getFirstNonNullVector = function (index) {
  7168. var i = 1;
  7169. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7170. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7171. i++;
  7172. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7173. }
  7174. return nNVector;
  7175. };
  7176. // private function getLastNonNullVector(index)
  7177. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7178. Path3D.prototype._getLastNonNullVector = function (index) {
  7179. var i = 1;
  7180. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7181. while (nLVector.length() === 0 && index > i + 1) {
  7182. i++;
  7183. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7184. }
  7185. return nLVector;
  7186. };
  7187. // private function normalVector(v0, vt, va) :
  7188. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7189. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7190. Path3D.prototype._normalVector = function (v0, vt, va) {
  7191. var normal0;
  7192. var tgl = vt.length();
  7193. if (tgl === 0.0) {
  7194. tgl = 1.0;
  7195. }
  7196. if (va === undefined || va === null) {
  7197. var point;
  7198. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7199. point = new Vector3(0.0, -1.0, 0.0);
  7200. }
  7201. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7202. point = new Vector3(1.0, 0.0, 0.0);
  7203. }
  7204. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7205. point = new Vector3(0.0, 0.0, 1.0);
  7206. }
  7207. else {
  7208. point = Vector3.Zero();
  7209. }
  7210. normal0 = Vector3.Cross(vt, point);
  7211. }
  7212. else {
  7213. normal0 = Vector3.Cross(vt, va);
  7214. Vector3.CrossToRef(normal0, vt, normal0);
  7215. }
  7216. normal0.normalize();
  7217. return normal0;
  7218. };
  7219. return Path3D;
  7220. }());
  7221. BABYLON.Path3D = Path3D;
  7222. var Curve3 = /** @class */ (function () {
  7223. /**
  7224. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7225. * A Curve3 is designed from a series of successive Vector3.
  7226. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7227. */
  7228. function Curve3(points) {
  7229. this._length = 0.0;
  7230. this._points = points;
  7231. this._length = this._computeLength(points);
  7232. }
  7233. /**
  7234. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7235. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7236. * @param v1 (Vector3) the control point
  7237. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7238. * @param nbPoints (integer) the wanted number of points in the curve
  7239. */
  7240. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7241. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7242. var bez = new Array();
  7243. var equation = function (t, val0, val1, val2) {
  7244. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7245. return res;
  7246. };
  7247. for (var i = 0; i <= nbPoints; i++) {
  7248. 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)));
  7249. }
  7250. return new Curve3(bez);
  7251. };
  7252. /**
  7253. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7254. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7255. * @param v1 (Vector3) the first control point
  7256. * @param v2 (Vector3) the second control point
  7257. * @param v3 (Vector3) the end point of the Cubic Bezier
  7258. * @param nbPoints (integer) the wanted number of points in the curve
  7259. */
  7260. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7261. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7262. var bez = new Array();
  7263. var equation = function (t, val0, val1, val2, val3) {
  7264. 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;
  7265. return res;
  7266. };
  7267. for (var i = 0; i <= nbPoints; i++) {
  7268. 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)));
  7269. }
  7270. return new Curve3(bez);
  7271. };
  7272. /**
  7273. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7274. * @param p1 (Vector3) the origin point of the Hermite Spline
  7275. * @param t1 (Vector3) the tangent vector at the origin point
  7276. * @param p2 (Vector3) the end point of the Hermite Spline
  7277. * @param t2 (Vector3) the tangent vector at the end point
  7278. * @param nbPoints (integer) the wanted number of points in the curve
  7279. */
  7280. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7281. var hermite = new Array();
  7282. var step = 1.0 / nbPoints;
  7283. for (var i = 0; i <= nbPoints; i++) {
  7284. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7285. }
  7286. return new Curve3(hermite);
  7287. };
  7288. /**
  7289. * Returns a Curve3 object along a CatmullRom Spline curve :
  7290. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  7291. * @param nbPoints (integer) the wanted number of points between each curve control points.
  7292. */
  7293. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  7294. var totalPoints = new Array();
  7295. totalPoints.push(points[0].clone());
  7296. Array.prototype.push.apply(totalPoints, points);
  7297. totalPoints.push(points[points.length - 1].clone());
  7298. var catmullRom = new Array();
  7299. var step = 1.0 / nbPoints;
  7300. var amount = 0.0;
  7301. for (var i = 0; i < totalPoints.length - 3; i++) {
  7302. amount = 0;
  7303. for (var c = 0; c < nbPoints; c++) {
  7304. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7305. amount += step;
  7306. }
  7307. }
  7308. i--;
  7309. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7310. return new Curve3(catmullRom);
  7311. };
  7312. /**
  7313. * Returns the Curve3 stored array of successive Vector3
  7314. */
  7315. Curve3.prototype.getPoints = function () {
  7316. return this._points;
  7317. };
  7318. /**
  7319. * Returns the computed length (float) of the curve.
  7320. */
  7321. Curve3.prototype.length = function () {
  7322. return this._length;
  7323. };
  7324. /**
  7325. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7326. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7327. * curveA and curveB keep unchanged.
  7328. */
  7329. Curve3.prototype.continue = function (curve) {
  7330. var lastPoint = this._points[this._points.length - 1];
  7331. var continuedPoints = this._points.slice();
  7332. var curvePoints = curve.getPoints();
  7333. for (var i = 1; i < curvePoints.length; i++) {
  7334. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7335. }
  7336. var continuedCurve = new Curve3(continuedPoints);
  7337. return continuedCurve;
  7338. };
  7339. Curve3.prototype._computeLength = function (path) {
  7340. var l = 0;
  7341. for (var i = 1; i < path.length; i++) {
  7342. l += (path[i].subtract(path[i - 1])).length();
  7343. }
  7344. return l;
  7345. };
  7346. return Curve3;
  7347. }());
  7348. BABYLON.Curve3 = Curve3;
  7349. // Vertex formats
  7350. var PositionNormalVertex = /** @class */ (function () {
  7351. function PositionNormalVertex(position, normal) {
  7352. if (position === void 0) { position = Vector3.Zero(); }
  7353. if (normal === void 0) { normal = Vector3.Up(); }
  7354. this.position = position;
  7355. this.normal = normal;
  7356. }
  7357. PositionNormalVertex.prototype.clone = function () {
  7358. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7359. };
  7360. return PositionNormalVertex;
  7361. }());
  7362. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7363. var PositionNormalTextureVertex = /** @class */ (function () {
  7364. function PositionNormalTextureVertex(position, normal, uv) {
  7365. if (position === void 0) { position = Vector3.Zero(); }
  7366. if (normal === void 0) { normal = Vector3.Up(); }
  7367. if (uv === void 0) { uv = Vector2.Zero(); }
  7368. this.position = position;
  7369. this.normal = normal;
  7370. this.uv = uv;
  7371. }
  7372. PositionNormalTextureVertex.prototype.clone = function () {
  7373. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7374. };
  7375. return PositionNormalTextureVertex;
  7376. }());
  7377. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7378. // Temporary pre-allocated objects for engine internal use
  7379. // usage in any internal function :
  7380. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7381. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7382. var Tmp = /** @class */ (function () {
  7383. function Tmp() {
  7384. }
  7385. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7386. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7387. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7388. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7389. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7390. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7391. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7392. Matrix.Zero(), Matrix.Zero(),
  7393. Matrix.Zero(), Matrix.Zero(),
  7394. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7395. return Tmp;
  7396. }());
  7397. BABYLON.Tmp = Tmp;
  7398. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7399. var MathTmp = /** @class */ (function () {
  7400. function MathTmp() {
  7401. }
  7402. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7403. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7404. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7405. return MathTmp;
  7406. }());
  7407. })(BABYLON || (BABYLON = {}));
  7408. //# sourceMappingURL=babylon.math.js.map
  7409. var BABYLON;
  7410. (function (BABYLON) {
  7411. var Scalar = /** @class */ (function () {
  7412. function Scalar() {
  7413. }
  7414. /**
  7415. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7416. */
  7417. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7418. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7419. var num = a - b;
  7420. return -epsilon <= num && num <= epsilon;
  7421. };
  7422. /**
  7423. * Returns a string : the upper case translation of the number i to hexadecimal.
  7424. */
  7425. Scalar.ToHex = function (i) {
  7426. var str = i.toString(16);
  7427. if (i <= 15) {
  7428. return ("0" + str).toUpperCase();
  7429. }
  7430. return str.toUpperCase();
  7431. };
  7432. /**
  7433. * Returns -1 if value is negative and +1 is value is positive.
  7434. * Returns the value itself if it's equal to zero.
  7435. */
  7436. Scalar.Sign = function (value) {
  7437. value = +value; // convert to a number
  7438. if (value === 0 || isNaN(value))
  7439. return value;
  7440. return value > 0 ? 1 : -1;
  7441. };
  7442. /**
  7443. * Returns the value itself if it's between min and max.
  7444. * Returns min if the value is lower than min.
  7445. * Returns max if the value is greater than max.
  7446. */
  7447. Scalar.Clamp = function (value, min, max) {
  7448. if (min === void 0) { min = 0; }
  7449. if (max === void 0) { max = 1; }
  7450. return Math.min(max, Math.max(min, value));
  7451. };
  7452. /**
  7453. * Returns the log2 of value.
  7454. */
  7455. Scalar.Log2 = function (value) {
  7456. return Math.log(value) * Math.LOG2E;
  7457. };
  7458. /**
  7459. * Loops the value, so that it is never larger than length and never smaller than 0.
  7460. *
  7461. * This is similar to the modulo operator but it works with floating point numbers.
  7462. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7463. * With t = 5 and length = 2.5, the result would be 0.0.
  7464. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7465. */
  7466. Scalar.Repeat = function (value, length) {
  7467. return value - Math.floor(value / length) * length;
  7468. };
  7469. /**
  7470. * Normalize the value between 0.0 and 1.0 using min and max values
  7471. */
  7472. Scalar.Normalize = function (value, min, max) {
  7473. return (value - min) / (max - min);
  7474. };
  7475. /**
  7476. * Denormalize the value from 0.0 and 1.0 using min and max values
  7477. */
  7478. Scalar.Denormalize = function (normalized, min, max) {
  7479. return (normalized * (max - min) + min);
  7480. };
  7481. /**
  7482. * Calculates the shortest difference between two given angles given in degrees.
  7483. */
  7484. Scalar.DeltaAngle = function (current, target) {
  7485. var num = Scalar.Repeat(target - current, 360.0);
  7486. if (num > 180.0) {
  7487. num -= 360.0;
  7488. }
  7489. return num;
  7490. };
  7491. /**
  7492. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7493. *
  7494. * The returned value will move back and forth between 0 and length
  7495. */
  7496. Scalar.PingPong = function (tx, length) {
  7497. var t = Scalar.Repeat(tx, length * 2.0);
  7498. return length - Math.abs(t - length);
  7499. };
  7500. /**
  7501. * Interpolates between min and max with smoothing at the limits.
  7502. *
  7503. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7504. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7505. */
  7506. Scalar.SmoothStep = function (from, to, tx) {
  7507. var t = Scalar.Clamp(tx);
  7508. t = -2.0 * t * t * t + 3.0 * t * t;
  7509. return to * t + from * (1.0 - t);
  7510. };
  7511. /**
  7512. * Moves a value current towards target.
  7513. *
  7514. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7515. * Negative values of maxDelta pushes the value away from target.
  7516. */
  7517. Scalar.MoveTowards = function (current, target, maxDelta) {
  7518. var result = 0;
  7519. if (Math.abs(target - current) <= maxDelta) {
  7520. result = target;
  7521. }
  7522. else {
  7523. result = current + Scalar.Sign(target - current) * maxDelta;
  7524. }
  7525. return result;
  7526. };
  7527. /**
  7528. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7529. *
  7530. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7531. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7532. */
  7533. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7534. var num = Scalar.DeltaAngle(current, target);
  7535. var result = 0;
  7536. if (-maxDelta < num && num < maxDelta) {
  7537. result = target;
  7538. }
  7539. else {
  7540. target = current + num;
  7541. result = Scalar.MoveTowards(current, target, maxDelta);
  7542. }
  7543. return result;
  7544. };
  7545. /**
  7546. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7547. */
  7548. Scalar.Lerp = function (start, end, amount) {
  7549. return start + ((end - start) * amount);
  7550. };
  7551. /**
  7552. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7553. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7554. */
  7555. Scalar.LerpAngle = function (start, end, amount) {
  7556. var num = Scalar.Repeat(end - start, 360.0);
  7557. if (num > 180.0) {
  7558. num -= 360.0;
  7559. }
  7560. return start + num * Scalar.Clamp(amount);
  7561. };
  7562. /**
  7563. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7564. */
  7565. Scalar.InverseLerp = function (a, b, value) {
  7566. var result = 0;
  7567. if (a != b) {
  7568. result = Scalar.Clamp((value - a) / (b - a));
  7569. }
  7570. else {
  7571. result = 0.0;
  7572. }
  7573. return result;
  7574. };
  7575. /**
  7576. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7577. */
  7578. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7579. var squared = amount * amount;
  7580. var cubed = amount * squared;
  7581. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7582. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7583. var part3 = (cubed - (2.0 * squared)) + amount;
  7584. var part4 = cubed - squared;
  7585. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7586. };
  7587. /**
  7588. * Returns a random float number between and min and max values
  7589. */
  7590. Scalar.RandomRange = function (min, max) {
  7591. if (min === max)
  7592. return min;
  7593. return ((Math.random() * (max - min)) + min);
  7594. };
  7595. /**
  7596. * This function returns percentage of a number in a given range.
  7597. *
  7598. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7599. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7600. */
  7601. Scalar.RangeToPercent = function (number, min, max) {
  7602. return ((number - min) / (max - min));
  7603. };
  7604. /**
  7605. * This function returns number that corresponds to the percentage in a given range.
  7606. *
  7607. * PercentToRange(0.34,0,100) will return 34.
  7608. */
  7609. Scalar.PercentToRange = function (percent, min, max) {
  7610. return ((max - min) * percent + min);
  7611. };
  7612. /**
  7613. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7614. * @param angle The angle to normalize in radian.
  7615. * @return The converted angle.
  7616. */
  7617. Scalar.NormalizeRadians = function (angle) {
  7618. // More precise but slower version kept for reference.
  7619. // angle = angle % Tools.TwoPi;
  7620. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7621. //if (angle > Math.PI) {
  7622. // angle -= Tools.TwoPi;
  7623. //}
  7624. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7625. return angle;
  7626. };
  7627. /**
  7628. * Two pi constants convenient for computation.
  7629. */
  7630. Scalar.TwoPi = Math.PI * 2;
  7631. return Scalar;
  7632. }());
  7633. BABYLON.Scalar = Scalar;
  7634. })(BABYLON || (BABYLON = {}));
  7635. //# sourceMappingURL=babylon.math.scalar.js.map
  7636. //# sourceMappingURL=babylon.mixins.js.map
  7637. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7638. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7639. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7640. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7641. //# sourceMappingURL=babylon.webgl2.js.map
  7642. var BABYLON;
  7643. (function (BABYLON) {
  7644. var __decoratorInitialStore = {};
  7645. var __mergedStore = {};
  7646. var _copySource = function (creationFunction, source, instanciate) {
  7647. var destination = creationFunction();
  7648. // Tags
  7649. if (BABYLON.Tags) {
  7650. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7651. }
  7652. var classStore = getMergedStore(destination);
  7653. // Properties
  7654. for (var property in classStore) {
  7655. var propertyDescriptor = classStore[property];
  7656. var sourceProperty = source[property];
  7657. var propertyType = propertyDescriptor.type;
  7658. if (sourceProperty !== undefined && sourceProperty !== null) {
  7659. switch (propertyType) {
  7660. case 0: // Value
  7661. case 6: // Mesh reference
  7662. case 11: // Camera reference
  7663. destination[property] = sourceProperty;
  7664. break;
  7665. case 1: // Texture
  7666. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7667. break;
  7668. case 2: // Color3
  7669. case 3: // FresnelParameters
  7670. case 4: // Vector2
  7671. case 5: // Vector3
  7672. case 7: // Color Curves
  7673. case 10: // Quaternion
  7674. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7675. break;
  7676. }
  7677. }
  7678. }
  7679. return destination;
  7680. };
  7681. function getDirectStore(target) {
  7682. var classKey = target.getClassName();
  7683. if (!__decoratorInitialStore[classKey]) {
  7684. __decoratorInitialStore[classKey] = {};
  7685. }
  7686. return __decoratorInitialStore[classKey];
  7687. }
  7688. /**
  7689. * Return the list of properties flagged as serializable
  7690. * @param target: host object
  7691. */
  7692. function getMergedStore(target) {
  7693. var classKey = target.getClassName();
  7694. if (__mergedStore[classKey]) {
  7695. return __mergedStore[classKey];
  7696. }
  7697. __mergedStore[classKey] = {};
  7698. var store = __mergedStore[classKey];
  7699. var currentTarget = target;
  7700. var currentKey = classKey;
  7701. while (currentKey) {
  7702. var initialStore = __decoratorInitialStore[currentKey];
  7703. for (var property in initialStore) {
  7704. store[property] = initialStore[property];
  7705. }
  7706. var parent_1 = void 0;
  7707. var done = false;
  7708. do {
  7709. parent_1 = Object.getPrototypeOf(currentTarget);
  7710. if (!parent_1.getClassName) {
  7711. done = true;
  7712. break;
  7713. }
  7714. if (parent_1.getClassName() !== currentKey) {
  7715. break;
  7716. }
  7717. currentTarget = parent_1;
  7718. } while (parent_1);
  7719. if (done) {
  7720. break;
  7721. }
  7722. currentKey = parent_1.getClassName();
  7723. currentTarget = parent_1;
  7724. }
  7725. return store;
  7726. }
  7727. function generateSerializableMember(type, sourceName) {
  7728. return function (target, propertyKey) {
  7729. var classStore = getDirectStore(target);
  7730. if (!classStore[propertyKey]) {
  7731. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7732. }
  7733. };
  7734. }
  7735. function generateExpandMember(setCallback, targetKey) {
  7736. if (targetKey === void 0) { targetKey = null; }
  7737. return function (target, propertyKey) {
  7738. var key = targetKey || ("_" + propertyKey);
  7739. Object.defineProperty(target, propertyKey, {
  7740. get: function () {
  7741. return this[key];
  7742. },
  7743. set: function (value) {
  7744. if (this[key] === value) {
  7745. return;
  7746. }
  7747. this[key] = value;
  7748. target[setCallback].apply(this);
  7749. },
  7750. enumerable: true,
  7751. configurable: true
  7752. });
  7753. };
  7754. }
  7755. function expandToProperty(callback, targetKey) {
  7756. if (targetKey === void 0) { targetKey = null; }
  7757. return generateExpandMember(callback, targetKey);
  7758. }
  7759. BABYLON.expandToProperty = expandToProperty;
  7760. function serialize(sourceName) {
  7761. return generateSerializableMember(0, sourceName); // value member
  7762. }
  7763. BABYLON.serialize = serialize;
  7764. function serializeAsTexture(sourceName) {
  7765. return generateSerializableMember(1, sourceName); // texture member
  7766. }
  7767. BABYLON.serializeAsTexture = serializeAsTexture;
  7768. function serializeAsColor3(sourceName) {
  7769. return generateSerializableMember(2, sourceName); // color3 member
  7770. }
  7771. BABYLON.serializeAsColor3 = serializeAsColor3;
  7772. function serializeAsFresnelParameters(sourceName) {
  7773. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7774. }
  7775. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7776. function serializeAsVector2(sourceName) {
  7777. return generateSerializableMember(4, sourceName); // vector2 member
  7778. }
  7779. BABYLON.serializeAsVector2 = serializeAsVector2;
  7780. function serializeAsVector3(sourceName) {
  7781. return generateSerializableMember(5, sourceName); // vector3 member
  7782. }
  7783. BABYLON.serializeAsVector3 = serializeAsVector3;
  7784. function serializeAsMeshReference(sourceName) {
  7785. return generateSerializableMember(6, sourceName); // mesh reference member
  7786. }
  7787. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7788. function serializeAsColorCurves(sourceName) {
  7789. return generateSerializableMember(7, sourceName); // color curves
  7790. }
  7791. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7792. function serializeAsColor4(sourceName) {
  7793. return generateSerializableMember(8, sourceName); // color 4
  7794. }
  7795. BABYLON.serializeAsColor4 = serializeAsColor4;
  7796. function serializeAsImageProcessingConfiguration(sourceName) {
  7797. return generateSerializableMember(9, sourceName); // image processing
  7798. }
  7799. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7800. function serializeAsQuaternion(sourceName) {
  7801. return generateSerializableMember(10, sourceName); // quaternion member
  7802. }
  7803. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7804. /**
  7805. * Decorator used to define property that can be serialized as reference to a camera
  7806. * @param sourceName defines the name of the property to decorate
  7807. */
  7808. function serializeAsCameraReference(sourceName) {
  7809. return generateSerializableMember(11, sourceName); // camera reference member
  7810. }
  7811. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7812. var SerializationHelper = /** @class */ (function () {
  7813. function SerializationHelper() {
  7814. }
  7815. SerializationHelper.Serialize = function (entity, serializationObject) {
  7816. if (!serializationObject) {
  7817. serializationObject = {};
  7818. }
  7819. // Tags
  7820. if (BABYLON.Tags) {
  7821. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7822. }
  7823. var serializedProperties = getMergedStore(entity);
  7824. // Properties
  7825. for (var property in serializedProperties) {
  7826. var propertyDescriptor = serializedProperties[property];
  7827. var targetPropertyName = propertyDescriptor.sourceName || property;
  7828. var propertyType = propertyDescriptor.type;
  7829. var sourceProperty = entity[property];
  7830. if (sourceProperty !== undefined && sourceProperty !== null) {
  7831. switch (propertyType) {
  7832. case 0: // Value
  7833. serializationObject[targetPropertyName] = sourceProperty;
  7834. break;
  7835. case 1: // Texture
  7836. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7837. break;
  7838. case 2: // Color3
  7839. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7840. break;
  7841. case 3: // FresnelParameters
  7842. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7843. break;
  7844. case 4: // Vector2
  7845. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7846. break;
  7847. case 5: // Vector3
  7848. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7849. break;
  7850. case 6: // Mesh reference
  7851. serializationObject[targetPropertyName] = sourceProperty.id;
  7852. break;
  7853. case 7: // Color Curves
  7854. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7855. break;
  7856. case 8: // Color 4
  7857. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7858. break;
  7859. case 9: // Image Processing
  7860. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7861. break;
  7862. case 10: // Quaternion
  7863. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7864. break;
  7865. case 11: // Camera reference
  7866. serializationObject[targetPropertyName] = sourceProperty.id;
  7867. break;
  7868. }
  7869. }
  7870. }
  7871. return serializationObject;
  7872. };
  7873. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7874. if (rootUrl === void 0) { rootUrl = null; }
  7875. var destination = creationFunction();
  7876. if (!rootUrl) {
  7877. rootUrl = "";
  7878. }
  7879. // Tags
  7880. if (BABYLON.Tags) {
  7881. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7882. }
  7883. var classStore = getMergedStore(destination);
  7884. // Properties
  7885. for (var property in classStore) {
  7886. var propertyDescriptor = classStore[property];
  7887. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7888. var propertyType = propertyDescriptor.type;
  7889. if (sourceProperty !== undefined && sourceProperty !== null) {
  7890. var dest = destination;
  7891. switch (propertyType) {
  7892. case 0: // Value
  7893. dest[property] = sourceProperty;
  7894. break;
  7895. case 1: // Texture
  7896. if (scene) {
  7897. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7898. }
  7899. break;
  7900. case 2: // Color3
  7901. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7902. break;
  7903. case 3: // FresnelParameters
  7904. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7905. break;
  7906. case 4: // Vector2
  7907. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7908. break;
  7909. case 5: // Vector3
  7910. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7911. break;
  7912. case 6: // Mesh reference
  7913. if (scene) {
  7914. dest[property] = scene.getLastMeshByID(sourceProperty);
  7915. }
  7916. break;
  7917. case 7: // Color Curves
  7918. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7919. break;
  7920. case 8: // Color 4
  7921. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7922. break;
  7923. case 9: // Image Processing
  7924. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7925. break;
  7926. case 10: // Quaternion
  7927. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7928. break;
  7929. case 11: // Camera reference
  7930. if (scene) {
  7931. dest[property] = scene.getCameraByID(sourceProperty);
  7932. }
  7933. break;
  7934. }
  7935. }
  7936. }
  7937. return destination;
  7938. };
  7939. SerializationHelper.Clone = function (creationFunction, source) {
  7940. return _copySource(creationFunction, source, false);
  7941. };
  7942. SerializationHelper.Instanciate = function (creationFunction, source) {
  7943. return _copySource(creationFunction, source, true);
  7944. };
  7945. return SerializationHelper;
  7946. }());
  7947. BABYLON.SerializationHelper = SerializationHelper;
  7948. })(BABYLON || (BABYLON = {}));
  7949. //# sourceMappingURL=babylon.decorators.js.map
  7950. var BABYLON;
  7951. (function (BABYLON) {
  7952. /**
  7953. * Wrapper class for promise with external resolve and reject.
  7954. */
  7955. var Deferred = /** @class */ (function () {
  7956. /**
  7957. * Constructor for this deferred object.
  7958. */
  7959. function Deferred() {
  7960. var _this = this;
  7961. this.promise = new Promise(function (resolve, reject) {
  7962. _this._resolve = resolve;
  7963. _this._reject = reject;
  7964. });
  7965. }
  7966. Object.defineProperty(Deferred.prototype, "resolve", {
  7967. /**
  7968. * The resolve method of the promise associated with this deferred object.
  7969. */
  7970. get: function () {
  7971. return this._resolve;
  7972. },
  7973. enumerable: true,
  7974. configurable: true
  7975. });
  7976. Object.defineProperty(Deferred.prototype, "reject", {
  7977. /**
  7978. * The reject method of the promise associated with this deferred object.
  7979. */
  7980. get: function () {
  7981. return this._reject;
  7982. },
  7983. enumerable: true,
  7984. configurable: true
  7985. });
  7986. return Deferred;
  7987. }());
  7988. BABYLON.Deferred = Deferred;
  7989. })(BABYLON || (BABYLON = {}));
  7990. //# sourceMappingURL=babylon.deferred.js.map
  7991. var BABYLON;
  7992. (function (BABYLON) {
  7993. /**
  7994. * A class serves as a medium between the observable and its observers
  7995. */
  7996. var EventState = /** @class */ (function () {
  7997. /**
  7998. * Create a new EventState
  7999. * @param mask defines the mask associated with this state
  8000. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8001. * @param target defines the original target of the state
  8002. * @param currentTarget defines the current target of the state
  8003. */
  8004. function EventState(mask, skipNextObservers, target, currentTarget) {
  8005. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8006. this.initalize(mask, skipNextObservers, target, currentTarget);
  8007. }
  8008. /**
  8009. * Initialize the current event state
  8010. * @param mask defines the mask associated with this state
  8011. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8012. * @param target defines the original target of the state
  8013. * @param currentTarget defines the current target of the state
  8014. * @returns the current event state
  8015. */
  8016. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8017. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8018. this.mask = mask;
  8019. this.skipNextObservers = skipNextObservers;
  8020. this.target = target;
  8021. this.currentTarget = currentTarget;
  8022. return this;
  8023. };
  8024. return EventState;
  8025. }());
  8026. BABYLON.EventState = EventState;
  8027. /**
  8028. * Represent an Observer registered to a given Observable object.
  8029. */
  8030. var Observer = /** @class */ (function () {
  8031. /**
  8032. * Creates a new observer
  8033. * @param callback defines the callback to call when the observer is notified
  8034. * @param mask defines the mask of the observer (used to filter notifications)
  8035. * @param scope defines the current scope used to restore the JS context
  8036. */
  8037. function Observer(
  8038. /**
  8039. * Defines the callback to call when the observer is notified
  8040. */
  8041. callback,
  8042. /**
  8043. * Defines the mask of the observer (used to filter notifications)
  8044. */
  8045. mask,
  8046. /**
  8047. * Defines the current scope used to restore the JS context
  8048. */
  8049. scope) {
  8050. if (scope === void 0) { scope = null; }
  8051. this.callback = callback;
  8052. this.mask = mask;
  8053. this.scope = scope;
  8054. /** @hidden */
  8055. this._willBeUnregistered = false;
  8056. /**
  8057. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8058. */
  8059. this.unregisterOnNextCall = false;
  8060. }
  8061. return Observer;
  8062. }());
  8063. BABYLON.Observer = Observer;
  8064. /**
  8065. * Represent a list of observers registered to multiple Observables object.
  8066. */
  8067. var MultiObserver = /** @class */ (function () {
  8068. function MultiObserver() {
  8069. }
  8070. /**
  8071. * Release associated resources
  8072. */
  8073. MultiObserver.prototype.dispose = function () {
  8074. if (this._observers && this._observables) {
  8075. for (var index = 0; index < this._observers.length; index++) {
  8076. this._observables[index].remove(this._observers[index]);
  8077. }
  8078. }
  8079. this._observers = null;
  8080. this._observables = null;
  8081. };
  8082. /**
  8083. * Raise a callback when one of the observable will notify
  8084. * @param observables defines a list of observables to watch
  8085. * @param callback defines the callback to call on notification
  8086. * @param mask defines the mask used to filter notifications
  8087. * @param scope defines the current scope used to restore the JS context
  8088. * @returns the new MultiObserver
  8089. */
  8090. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8091. if (mask === void 0) { mask = -1; }
  8092. if (scope === void 0) { scope = null; }
  8093. var result = new MultiObserver();
  8094. result._observers = new Array();
  8095. result._observables = observables;
  8096. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8097. var observable = observables_1[_i];
  8098. var observer = observable.add(callback, mask, false, scope);
  8099. if (observer) {
  8100. result._observers.push(observer);
  8101. }
  8102. }
  8103. return result;
  8104. };
  8105. return MultiObserver;
  8106. }());
  8107. BABYLON.MultiObserver = MultiObserver;
  8108. /**
  8109. * The Observable class is a simple implementation of the Observable pattern.
  8110. *
  8111. * 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.
  8112. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8113. * 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).
  8114. * 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.
  8115. */
  8116. var Observable = /** @class */ (function () {
  8117. /**
  8118. * Creates a new observable
  8119. * @param onObserverAdded defines a callback to call when a new observer is added
  8120. */
  8121. function Observable(onObserverAdded) {
  8122. this._observers = new Array();
  8123. this._eventState = new EventState(0);
  8124. if (onObserverAdded) {
  8125. this._onObserverAdded = onObserverAdded;
  8126. }
  8127. }
  8128. /**
  8129. * Create a new Observer with the specified callback
  8130. * @param callback the callback that will be executed for that Observer
  8131. * @param mask the mask used to filter observers
  8132. * @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.
  8133. * @param scope optional scope for the callback to be called from
  8134. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8135. * @returns the new observer created for the callback
  8136. */
  8137. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8138. if (mask === void 0) { mask = -1; }
  8139. if (insertFirst === void 0) { insertFirst = false; }
  8140. if (scope === void 0) { scope = null; }
  8141. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8142. if (!callback) {
  8143. return null;
  8144. }
  8145. var observer = new Observer(callback, mask, scope);
  8146. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8147. if (insertFirst) {
  8148. this._observers.unshift(observer);
  8149. }
  8150. else {
  8151. this._observers.push(observer);
  8152. }
  8153. if (this._onObserverAdded) {
  8154. this._onObserverAdded(observer);
  8155. }
  8156. return observer;
  8157. };
  8158. /**
  8159. * Remove an Observer from the Observable object
  8160. * @param observer the instance of the Observer to remove
  8161. * @returns false if it doesn't belong to this Observable
  8162. */
  8163. Observable.prototype.remove = function (observer) {
  8164. if (!observer) {
  8165. return false;
  8166. }
  8167. var index = this._observers.indexOf(observer);
  8168. if (index !== -1) {
  8169. this._observers.splice(index, 1);
  8170. return true;
  8171. }
  8172. return false;
  8173. };
  8174. /**
  8175. * Remove a callback from the Observable object
  8176. * @param callback the callback to remove
  8177. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8178. * @returns false if it doesn't belong to this Observable
  8179. */
  8180. Observable.prototype.removeCallback = function (callback, scope) {
  8181. for (var index = 0; index < this._observers.length; index++) {
  8182. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8183. this._observers.splice(index, 1);
  8184. return true;
  8185. }
  8186. }
  8187. return false;
  8188. };
  8189. Observable.prototype._deferUnregister = function (observer) {
  8190. var _this = this;
  8191. observer.unregisterOnNextCall = false;
  8192. observer._willBeUnregistered = true;
  8193. BABYLON.Tools.SetImmediate(function () {
  8194. _this.remove(observer);
  8195. });
  8196. };
  8197. /**
  8198. * Notify all Observers by calling their respective callback with the given data
  8199. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8200. * @param eventData defines the data to send to all observers
  8201. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8202. * @param target defines the original target of the state
  8203. * @param currentTarget defines the current target of the state
  8204. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8205. */
  8206. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8207. if (mask === void 0) { mask = -1; }
  8208. if (!this._observers.length) {
  8209. return true;
  8210. }
  8211. var state = this._eventState;
  8212. state.mask = mask;
  8213. state.target = target;
  8214. state.currentTarget = currentTarget;
  8215. state.skipNextObservers = false;
  8216. state.lastReturnValue = eventData;
  8217. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8218. var obs = _a[_i];
  8219. if (obs._willBeUnregistered) {
  8220. continue;
  8221. }
  8222. if (obs.mask & mask) {
  8223. if (obs.scope) {
  8224. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8225. }
  8226. else {
  8227. state.lastReturnValue = obs.callback(eventData, state);
  8228. }
  8229. if (obs.unregisterOnNextCall) {
  8230. this._deferUnregister(obs);
  8231. }
  8232. }
  8233. if (state.skipNextObservers) {
  8234. return false;
  8235. }
  8236. }
  8237. return true;
  8238. };
  8239. /**
  8240. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8241. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8242. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8243. * and it is crucial that all callbacks will be executed.
  8244. * The order of the callbacks is kept, callbacks are not executed parallel.
  8245. *
  8246. * @param eventData The data to be sent to each callback
  8247. * @param mask is used to filter observers defaults to -1
  8248. * @param target defines the callback target (see EventState)
  8249. * @param currentTarget defines he current object in the bubbling phase
  8250. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8251. */
  8252. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8253. var _this = this;
  8254. if (mask === void 0) { mask = -1; }
  8255. // create an empty promise
  8256. var p = Promise.resolve(eventData);
  8257. // no observers? return this promise.
  8258. if (!this._observers.length) {
  8259. return p;
  8260. }
  8261. var state = this._eventState;
  8262. state.mask = mask;
  8263. state.target = target;
  8264. state.currentTarget = currentTarget;
  8265. state.skipNextObservers = false;
  8266. // execute one callback after another (not using Promise.all, the order is important)
  8267. this._observers.forEach(function (obs) {
  8268. if (state.skipNextObservers) {
  8269. return;
  8270. }
  8271. if (obs._willBeUnregistered) {
  8272. return;
  8273. }
  8274. if (obs.mask & mask) {
  8275. if (obs.scope) {
  8276. p = p.then(function (lastReturnedValue) {
  8277. state.lastReturnValue = lastReturnedValue;
  8278. return obs.callback.apply(obs.scope, [eventData, state]);
  8279. });
  8280. }
  8281. else {
  8282. p = p.then(function (lastReturnedValue) {
  8283. state.lastReturnValue = lastReturnedValue;
  8284. return obs.callback(eventData, state);
  8285. });
  8286. }
  8287. if (obs.unregisterOnNextCall) {
  8288. _this._deferUnregister(obs);
  8289. }
  8290. }
  8291. });
  8292. // return the eventData
  8293. return p.then(function () { return eventData; });
  8294. };
  8295. /**
  8296. * Notify a specific observer
  8297. * @param observer defines the observer to notify
  8298. * @param eventData defines the data to be sent to each callback
  8299. * @param mask is used to filter observers defaults to -1
  8300. */
  8301. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8302. if (mask === void 0) { mask = -1; }
  8303. var state = this._eventState;
  8304. state.mask = mask;
  8305. state.skipNextObservers = false;
  8306. observer.callback(eventData, state);
  8307. };
  8308. /**
  8309. * Gets a boolean indicating if the observable has at least one observer
  8310. * @returns true is the Observable has at least one Observer registered
  8311. */
  8312. Observable.prototype.hasObservers = function () {
  8313. return this._observers.length > 0;
  8314. };
  8315. /**
  8316. * Clear the list of observers
  8317. */
  8318. Observable.prototype.clear = function () {
  8319. this._observers = new Array();
  8320. this._onObserverAdded = null;
  8321. };
  8322. /**
  8323. * Clone the current observable
  8324. * @returns a new observable
  8325. */
  8326. Observable.prototype.clone = function () {
  8327. var result = new Observable();
  8328. result._observers = this._observers.slice(0);
  8329. return result;
  8330. };
  8331. /**
  8332. * Does this observable handles observer registered with a given mask
  8333. * @param mask defines the mask to be tested
  8334. * @return whether or not one observer registered with the given mask is handeled
  8335. **/
  8336. Observable.prototype.hasSpecificMask = function (mask) {
  8337. if (mask === void 0) { mask = -1; }
  8338. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8339. var obs = _a[_i];
  8340. if (obs.mask & mask || obs.mask === mask) {
  8341. return true;
  8342. }
  8343. }
  8344. return false;
  8345. };
  8346. return Observable;
  8347. }());
  8348. BABYLON.Observable = Observable;
  8349. })(BABYLON || (BABYLON = {}));
  8350. //# sourceMappingURL=babylon.observable.js.map
  8351. var BABYLON;
  8352. (function (BABYLON) {
  8353. var SmartArray = /** @class */ (function () {
  8354. function SmartArray(capacity) {
  8355. this.length = 0;
  8356. this.data = new Array(capacity);
  8357. this._id = SmartArray._GlobalId++;
  8358. }
  8359. SmartArray.prototype.push = function (value) {
  8360. this.data[this.length++] = value;
  8361. if (this.length > this.data.length) {
  8362. this.data.length *= 2;
  8363. }
  8364. };
  8365. SmartArray.prototype.forEach = function (func) {
  8366. for (var index = 0; index < this.length; index++) {
  8367. func(this.data[index]);
  8368. }
  8369. };
  8370. SmartArray.prototype.sort = function (compareFn) {
  8371. this.data.sort(compareFn);
  8372. };
  8373. SmartArray.prototype.reset = function () {
  8374. this.length = 0;
  8375. };
  8376. SmartArray.prototype.dispose = function () {
  8377. this.reset();
  8378. if (this.data) {
  8379. this.data.length = 0;
  8380. this.data = [];
  8381. }
  8382. };
  8383. SmartArray.prototype.concat = function (array) {
  8384. if (array.length === 0) {
  8385. return;
  8386. }
  8387. if (this.length + array.length > this.data.length) {
  8388. this.data.length = (this.length + array.length) * 2;
  8389. }
  8390. for (var index = 0; index < array.length; index++) {
  8391. this.data[this.length++] = (array.data || array)[index];
  8392. }
  8393. };
  8394. SmartArray.prototype.indexOf = function (value) {
  8395. var position = this.data.indexOf(value);
  8396. if (position >= this.length) {
  8397. return -1;
  8398. }
  8399. return position;
  8400. };
  8401. SmartArray.prototype.contains = function (value) {
  8402. return this.data.indexOf(value) !== -1;
  8403. };
  8404. // Statics
  8405. SmartArray._GlobalId = 0;
  8406. return SmartArray;
  8407. }());
  8408. BABYLON.SmartArray = SmartArray;
  8409. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8410. __extends(SmartArrayNoDuplicate, _super);
  8411. function SmartArrayNoDuplicate() {
  8412. var _this = _super !== null && _super.apply(this, arguments) || this;
  8413. _this._duplicateId = 0;
  8414. return _this;
  8415. }
  8416. SmartArrayNoDuplicate.prototype.push = function (value) {
  8417. _super.prototype.push.call(this, value);
  8418. if (!value.__smartArrayFlags) {
  8419. value.__smartArrayFlags = {};
  8420. }
  8421. value.__smartArrayFlags[this._id] = this._duplicateId;
  8422. };
  8423. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8424. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8425. return false;
  8426. }
  8427. this.push(value);
  8428. return true;
  8429. };
  8430. SmartArrayNoDuplicate.prototype.reset = function () {
  8431. _super.prototype.reset.call(this);
  8432. this._duplicateId++;
  8433. };
  8434. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8435. if (array.length === 0) {
  8436. return;
  8437. }
  8438. if (this.length + array.length > this.data.length) {
  8439. this.data.length = (this.length + array.length) * 2;
  8440. }
  8441. for (var index = 0; index < array.length; index++) {
  8442. var item = (array.data || array)[index];
  8443. this.pushNoDuplicate(item);
  8444. }
  8445. };
  8446. return SmartArrayNoDuplicate;
  8447. }(SmartArray));
  8448. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8449. })(BABYLON || (BABYLON = {}));
  8450. //# sourceMappingURL=babylon.smartArray.js.map
  8451. var BABYLON;
  8452. (function (BABYLON) {
  8453. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8454. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8455. var LoadFileError = /** @class */ (function (_super) {
  8456. __extends(LoadFileError, _super);
  8457. function LoadFileError(message, request) {
  8458. var _this = _super.call(this, message) || this;
  8459. _this.request = request;
  8460. _this.name = "LoadFileError";
  8461. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8462. return _this;
  8463. }
  8464. // Polyfill for Object.setPrototypeOf if necessary.
  8465. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8466. return LoadFileError;
  8467. }(Error));
  8468. BABYLON.LoadFileError = LoadFileError;
  8469. var RetryStrategy = /** @class */ (function () {
  8470. function RetryStrategy() {
  8471. }
  8472. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8473. if (maxRetries === void 0) { maxRetries = 3; }
  8474. if (baseInterval === void 0) { baseInterval = 500; }
  8475. return function (url, request, retryIndex) {
  8476. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8477. return -1;
  8478. }
  8479. return Math.pow(2, retryIndex) * baseInterval;
  8480. };
  8481. };
  8482. return RetryStrategy;
  8483. }());
  8484. BABYLON.RetryStrategy = RetryStrategy;
  8485. // Screenshots
  8486. var screenshotCanvas;
  8487. var cloneValue = function (source, destinationObject) {
  8488. if (!source)
  8489. return null;
  8490. if (source instanceof BABYLON.Mesh) {
  8491. return null;
  8492. }
  8493. if (source instanceof BABYLON.SubMesh) {
  8494. return source.clone(destinationObject);
  8495. }
  8496. else if (source.clone) {
  8497. return source.clone();
  8498. }
  8499. return null;
  8500. };
  8501. var Tools = /** @class */ (function () {
  8502. function Tools() {
  8503. }
  8504. /**
  8505. * Interpolates between a and b via alpha
  8506. * @param a The lower value (returned when alpha = 0)
  8507. * @param b The upper value (returned when alpha = 1)
  8508. * @param alpha The interpolation-factor
  8509. * @return The mixed value
  8510. */
  8511. Tools.Mix = function (a, b, alpha) {
  8512. return a * (1 - alpha) + b * alpha;
  8513. };
  8514. Tools.Instantiate = function (className) {
  8515. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8516. return Tools.RegisteredExternalClasses[className];
  8517. }
  8518. var arr = className.split(".");
  8519. var fn = (window || this);
  8520. for (var i = 0, len = arr.length; i < len; i++) {
  8521. fn = fn[arr[i]];
  8522. }
  8523. if (typeof fn !== "function") {
  8524. return null;
  8525. }
  8526. return fn;
  8527. };
  8528. /**
  8529. * Provides a slice function that will work even on IE
  8530. * @param data defines the array to slice
  8531. * @param start defines the start of the data (optional)
  8532. * @param end defines the end of the data (optional)
  8533. * @returns the new sliced array
  8534. */
  8535. Tools.Slice = function (data, start, end) {
  8536. if (data.slice) {
  8537. return data.slice(start, end);
  8538. }
  8539. return Array.prototype.slice.call(data, start, end);
  8540. };
  8541. Tools.SetImmediate = function (action) {
  8542. if (window.setImmediate) {
  8543. window.setImmediate(action);
  8544. }
  8545. else {
  8546. setTimeout(action, 1);
  8547. }
  8548. };
  8549. Tools.IsExponentOfTwo = function (value) {
  8550. var count = 1;
  8551. do {
  8552. count *= 2;
  8553. } while (count < value);
  8554. return count === value;
  8555. };
  8556. /**
  8557. * Returns the nearest 32-bit single precision float representation of a Number
  8558. * @param value A Number. If the parameter is of a different type, it will get converted
  8559. * to a number or to NaN if it cannot be converted
  8560. * @returns number
  8561. */
  8562. Tools.FloatRound = function (value) {
  8563. if (Math.fround) {
  8564. return Math.fround(value);
  8565. }
  8566. return (Tools._tmpFloatArray[0] = value);
  8567. };
  8568. /**
  8569. * Find the next highest power of two.
  8570. * @param x Number to start search from.
  8571. * @return Next highest power of two.
  8572. */
  8573. Tools.CeilingPOT = function (x) {
  8574. x--;
  8575. x |= x >> 1;
  8576. x |= x >> 2;
  8577. x |= x >> 4;
  8578. x |= x >> 8;
  8579. x |= x >> 16;
  8580. x++;
  8581. return x;
  8582. };
  8583. /**
  8584. * Find the next lowest power of two.
  8585. * @param x Number to start search from.
  8586. * @return Next lowest power of two.
  8587. */
  8588. Tools.FloorPOT = function (x) {
  8589. x = x | (x >> 1);
  8590. x = x | (x >> 2);
  8591. x = x | (x >> 4);
  8592. x = x | (x >> 8);
  8593. x = x | (x >> 16);
  8594. return x - (x >> 1);
  8595. };
  8596. /**
  8597. * Find the nearest power of two.
  8598. * @param x Number to start search from.
  8599. * @return Next nearest power of two.
  8600. */
  8601. Tools.NearestPOT = function (x) {
  8602. var c = Tools.CeilingPOT(x);
  8603. var f = Tools.FloorPOT(x);
  8604. return (c - x) > (x - f) ? f : c;
  8605. };
  8606. Tools.GetExponentOfTwo = function (value, max, mode) {
  8607. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8608. var pot;
  8609. switch (mode) {
  8610. case BABYLON.Engine.SCALEMODE_FLOOR:
  8611. pot = Tools.FloorPOT(value);
  8612. break;
  8613. case BABYLON.Engine.SCALEMODE_NEAREST:
  8614. pot = Tools.NearestPOT(value);
  8615. break;
  8616. case BABYLON.Engine.SCALEMODE_CEILING:
  8617. default:
  8618. pot = Tools.CeilingPOT(value);
  8619. break;
  8620. }
  8621. return Math.min(pot, max);
  8622. };
  8623. Tools.GetFilename = function (path) {
  8624. var index = path.lastIndexOf("/");
  8625. if (index < 0)
  8626. return path;
  8627. return path.substring(index + 1);
  8628. };
  8629. /**
  8630. * Extracts the "folder" part of a path (everything before the filename).
  8631. * @param uri The URI to extract the info from
  8632. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8633. * @returns The "folder" part of the path
  8634. */
  8635. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8636. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8637. var index = uri.lastIndexOf("/");
  8638. if (index < 0) {
  8639. if (returnUnchangedIfNoSlash) {
  8640. return uri;
  8641. }
  8642. return "";
  8643. }
  8644. return uri.substring(0, index + 1);
  8645. };
  8646. Tools.GetDOMTextContent = function (element) {
  8647. var result = "";
  8648. var child = element.firstChild;
  8649. while (child) {
  8650. if (child.nodeType === 3) {
  8651. result += child.textContent;
  8652. }
  8653. child = child.nextSibling;
  8654. }
  8655. return result;
  8656. };
  8657. Tools.ToDegrees = function (angle) {
  8658. return angle * 180 / Math.PI;
  8659. };
  8660. Tools.ToRadians = function (angle) {
  8661. return angle * Math.PI / 180;
  8662. };
  8663. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8664. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8665. var output = "";
  8666. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8667. var i = 0;
  8668. var bytes = new Uint8Array(buffer);
  8669. while (i < bytes.length) {
  8670. chr1 = bytes[i++];
  8671. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8672. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8673. enc1 = chr1 >> 2;
  8674. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8675. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8676. enc4 = chr3 & 63;
  8677. if (isNaN(chr2)) {
  8678. enc3 = enc4 = 64;
  8679. }
  8680. else if (isNaN(chr3)) {
  8681. enc4 = 64;
  8682. }
  8683. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8684. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8685. }
  8686. return "data:image/png;base64," + output;
  8687. };
  8688. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8689. if (bias === void 0) { bias = null; }
  8690. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8691. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8692. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8693. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8694. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8695. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8696. }
  8697. if (bias) {
  8698. minimum.x -= minimum.x * bias.x + bias.y;
  8699. minimum.y -= minimum.y * bias.x + bias.y;
  8700. minimum.z -= minimum.z * bias.x + bias.y;
  8701. maximum.x += maximum.x * bias.x + bias.y;
  8702. maximum.y += maximum.y * bias.x + bias.y;
  8703. maximum.z += maximum.z * bias.x + bias.y;
  8704. }
  8705. return {
  8706. minimum: minimum,
  8707. maximum: maximum
  8708. };
  8709. };
  8710. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8711. if (bias === void 0) { bias = null; }
  8712. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8713. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8714. if (!stride) {
  8715. stride = 3;
  8716. }
  8717. for (var index = start; index < start + count; index++) {
  8718. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8719. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8720. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8721. }
  8722. if (bias) {
  8723. minimum.x -= minimum.x * bias.x + bias.y;
  8724. minimum.y -= minimum.y * bias.x + bias.y;
  8725. minimum.z -= minimum.z * bias.x + bias.y;
  8726. maximum.x += maximum.x * bias.x + bias.y;
  8727. maximum.y += maximum.y * bias.x + bias.y;
  8728. maximum.z += maximum.z * bias.x + bias.y;
  8729. }
  8730. return {
  8731. minimum: minimum,
  8732. maximum: maximum
  8733. };
  8734. };
  8735. Tools.Vector2ArrayFeeder = function (array) {
  8736. return function (index) {
  8737. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8738. var length = isFloatArray ? array.length / 2 : array.length;
  8739. if (index >= length) {
  8740. return null;
  8741. }
  8742. if (isFloatArray) {
  8743. var fa = array;
  8744. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8745. }
  8746. var a = array;
  8747. return a[index];
  8748. };
  8749. };
  8750. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8751. if (bias === void 0) { bias = null; }
  8752. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8753. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8754. var i = 0;
  8755. var cur = feeder(i++);
  8756. while (cur) {
  8757. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8758. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8759. cur = feeder(i++);
  8760. }
  8761. if (bias) {
  8762. minimum.x -= minimum.x * bias.x + bias.y;
  8763. minimum.y -= minimum.y * bias.x + bias.y;
  8764. maximum.x += maximum.x * bias.x + bias.y;
  8765. maximum.y += maximum.y * bias.x + bias.y;
  8766. }
  8767. return {
  8768. minimum: minimum,
  8769. maximum: maximum
  8770. };
  8771. };
  8772. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8773. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8774. return null;
  8775. return Array.isArray(obj) ? obj : [obj];
  8776. };
  8777. // Misc.
  8778. Tools.GetPointerPrefix = function () {
  8779. var eventPrefix = "pointer";
  8780. // Check if pointer events are supported
  8781. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8782. eventPrefix = "mouse";
  8783. }
  8784. return eventPrefix;
  8785. };
  8786. /**
  8787. * @param func - the function to be called
  8788. * @param requester - the object that will request the next frame. Falls back to window.
  8789. */
  8790. Tools.QueueNewFrame = function (func, requester) {
  8791. if (!Tools.IsWindowObjectExist()) {
  8792. return setTimeout(func, 16);
  8793. }
  8794. if (!requester) {
  8795. requester = window;
  8796. }
  8797. if (requester.requestAnimationFrame) {
  8798. return requester.requestAnimationFrame(func);
  8799. }
  8800. else if (requester.msRequestAnimationFrame) {
  8801. return requester.msRequestAnimationFrame(func);
  8802. }
  8803. else if (requester.webkitRequestAnimationFrame) {
  8804. return requester.webkitRequestAnimationFrame(func);
  8805. }
  8806. else if (requester.mozRequestAnimationFrame) {
  8807. return requester.mozRequestAnimationFrame(func);
  8808. }
  8809. else if (requester.oRequestAnimationFrame) {
  8810. return requester.oRequestAnimationFrame(func);
  8811. }
  8812. else {
  8813. return window.setTimeout(func, 16);
  8814. }
  8815. };
  8816. Tools.RequestFullscreen = function (element) {
  8817. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8818. if (!requestFunction)
  8819. return;
  8820. requestFunction.call(element);
  8821. };
  8822. Tools.ExitFullscreen = function () {
  8823. if (document.exitFullscreen) {
  8824. document.exitFullscreen();
  8825. }
  8826. else if (document.mozCancelFullScreen) {
  8827. document.mozCancelFullScreen();
  8828. }
  8829. else if (document.webkitCancelFullScreen) {
  8830. document.webkitCancelFullScreen();
  8831. }
  8832. else if (document.msCancelFullScreen) {
  8833. document.msCancelFullScreen();
  8834. }
  8835. };
  8836. Tools.SetCorsBehavior = function (url, element) {
  8837. if (url && url.indexOf("data:") === 0) {
  8838. return;
  8839. }
  8840. if (Tools.CorsBehavior) {
  8841. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8842. element.crossOrigin = Tools.CorsBehavior;
  8843. }
  8844. else {
  8845. var result = Tools.CorsBehavior(url);
  8846. if (result) {
  8847. element.crossOrigin = result;
  8848. }
  8849. }
  8850. }
  8851. };
  8852. // External files
  8853. Tools.CleanUrl = function (url) {
  8854. url = url.replace(/#/mg, "%23");
  8855. return url;
  8856. };
  8857. Tools.LoadImage = function (url, onLoad, onError, database) {
  8858. if (url instanceof ArrayBuffer) {
  8859. url = Tools.EncodeArrayBufferTobase64(url);
  8860. }
  8861. url = Tools.CleanUrl(url);
  8862. url = Tools.PreprocessUrl(url);
  8863. var img = new Image();
  8864. Tools.SetCorsBehavior(url, img);
  8865. var loadHandler = function () {
  8866. img.removeEventListener("load", loadHandler);
  8867. img.removeEventListener("error", errorHandler);
  8868. onLoad(img);
  8869. };
  8870. var errorHandler = function (err) {
  8871. img.removeEventListener("load", loadHandler);
  8872. img.removeEventListener("error", errorHandler);
  8873. Tools.Error("Error while trying to load image: " + url);
  8874. if (onError) {
  8875. onError("Error while trying to load image: " + url, err);
  8876. }
  8877. };
  8878. img.addEventListener("load", loadHandler);
  8879. img.addEventListener("error", errorHandler);
  8880. var noIndexedDB = function () {
  8881. img.src = url;
  8882. };
  8883. var loadFromIndexedDB = function () {
  8884. if (database) {
  8885. database.loadImageFromDB(url, img);
  8886. }
  8887. };
  8888. //ANY database to do!
  8889. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8890. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8891. }
  8892. else {
  8893. if (url.indexOf("file:") !== -1) {
  8894. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8895. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8896. try {
  8897. var blobURL;
  8898. try {
  8899. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8900. }
  8901. catch (ex) {
  8902. // Chrome doesn't support oneTimeOnly parameter
  8903. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8904. }
  8905. img.src = blobURL;
  8906. }
  8907. catch (e) {
  8908. img.src = "";
  8909. }
  8910. return img;
  8911. }
  8912. }
  8913. noIndexedDB();
  8914. }
  8915. return img;
  8916. };
  8917. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8918. url = Tools.CleanUrl(url);
  8919. url = Tools.PreprocessUrl(url);
  8920. // If file and file input are set
  8921. if (url.indexOf("file:") !== -1) {
  8922. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8923. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8924. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8925. }
  8926. }
  8927. var loadUrl = Tools.BaseUrl + url;
  8928. var aborted = false;
  8929. var fileRequest = {
  8930. onCompleteObservable: new BABYLON.Observable(),
  8931. abort: function () { return aborted = true; },
  8932. };
  8933. var requestFile = function () {
  8934. var request = new XMLHttpRequest();
  8935. var retryHandle = null;
  8936. fileRequest.abort = function () {
  8937. aborted = true;
  8938. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8939. request.abort();
  8940. }
  8941. if (retryHandle !== null) {
  8942. clearTimeout(retryHandle);
  8943. retryHandle = null;
  8944. }
  8945. };
  8946. var retryLoop = function (retryIndex) {
  8947. request.open('GET', loadUrl, true);
  8948. if (useArrayBuffer) {
  8949. request.responseType = "arraybuffer";
  8950. }
  8951. if (onProgress) {
  8952. request.addEventListener("progress", onProgress);
  8953. }
  8954. var onLoadEnd = function () {
  8955. request.removeEventListener("loadend", onLoadEnd);
  8956. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8957. fileRequest.onCompleteObservable.clear();
  8958. };
  8959. request.addEventListener("loadend", onLoadEnd);
  8960. var onReadyStateChange = function () {
  8961. if (aborted) {
  8962. return;
  8963. }
  8964. // In case of undefined state in some browsers.
  8965. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8966. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8967. request.removeEventListener("readystatechange", onReadyStateChange);
  8968. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8969. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8970. return;
  8971. }
  8972. var retryStrategy = Tools.DefaultRetryStrategy;
  8973. if (retryStrategy) {
  8974. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8975. if (waitTime !== -1) {
  8976. // Prevent the request from completing for retry.
  8977. request.removeEventListener("loadend", onLoadEnd);
  8978. request = new XMLHttpRequest();
  8979. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8980. return;
  8981. }
  8982. }
  8983. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8984. if (onError) {
  8985. onError(request, e);
  8986. }
  8987. else {
  8988. throw e;
  8989. }
  8990. }
  8991. };
  8992. request.addEventListener("readystatechange", onReadyStateChange);
  8993. request.send();
  8994. };
  8995. retryLoop(0);
  8996. };
  8997. // Caching all files
  8998. if (database && database.enableSceneOffline) {
  8999. var noIndexedDB_1 = function () {
  9000. if (!aborted) {
  9001. requestFile();
  9002. }
  9003. };
  9004. var loadFromIndexedDB = function () {
  9005. // TODO: database needs to support aborting and should return a IFileRequest
  9006. if (aborted) {
  9007. return;
  9008. }
  9009. if (database) {
  9010. database.loadFileFromDB(url, function (data) {
  9011. if (!aborted) {
  9012. onSuccess(data);
  9013. }
  9014. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9015. }, onProgress ? function (event) {
  9016. if (!aborted) {
  9017. onProgress(event);
  9018. }
  9019. } : undefined, noIndexedDB_1, useArrayBuffer);
  9020. }
  9021. };
  9022. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9023. }
  9024. else {
  9025. requestFile();
  9026. }
  9027. return fileRequest;
  9028. };
  9029. /**
  9030. * Load a script (identified by an url). When the url returns, the
  9031. * content of this file is added into a new script element, attached to the DOM (body element)
  9032. */
  9033. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9034. var head = document.getElementsByTagName('head')[0];
  9035. var script = document.createElement('script');
  9036. script.type = 'text/javascript';
  9037. script.src = scriptUrl;
  9038. script.onload = function () {
  9039. if (onSuccess) {
  9040. onSuccess();
  9041. }
  9042. };
  9043. script.onerror = function (e) {
  9044. if (onError) {
  9045. onError("Unable to load script '" + scriptUrl + "'", e);
  9046. }
  9047. };
  9048. head.appendChild(script);
  9049. };
  9050. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9051. var reader = new FileReader();
  9052. var request = {
  9053. onCompleteObservable: new BABYLON.Observable(),
  9054. abort: function () { return reader.abort(); },
  9055. };
  9056. reader.onloadend = function (e) {
  9057. request.onCompleteObservable.notifyObservers(request);
  9058. };
  9059. reader.onload = function (e) {
  9060. //target doesn't have result from ts 1.3
  9061. callback(e.target['result']);
  9062. };
  9063. reader.onprogress = progressCallback;
  9064. reader.readAsDataURL(fileToLoad);
  9065. return request;
  9066. };
  9067. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9068. var reader = new FileReader();
  9069. var request = {
  9070. onCompleteObservable: new BABYLON.Observable(),
  9071. abort: function () { return reader.abort(); },
  9072. };
  9073. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9074. reader.onerror = function (e) {
  9075. Tools.Log("Error while reading file: " + fileToLoad.name);
  9076. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9077. };
  9078. reader.onload = function (e) {
  9079. //target doesn't have result from ts 1.3
  9080. callback(e.target['result']);
  9081. };
  9082. if (progressCallBack) {
  9083. reader.onprogress = progressCallBack;
  9084. }
  9085. if (!useArrayBuffer) {
  9086. // Asynchronous read
  9087. reader.readAsText(fileToLoad);
  9088. }
  9089. else {
  9090. reader.readAsArrayBuffer(fileToLoad);
  9091. }
  9092. return request;
  9093. };
  9094. //returns a downloadable url to a file content.
  9095. Tools.FileAsURL = function (content) {
  9096. var fileBlob = new Blob([content]);
  9097. var url = window.URL || window.webkitURL;
  9098. var link = url.createObjectURL(fileBlob);
  9099. return link;
  9100. };
  9101. // Misc.
  9102. Tools.Format = function (value, decimals) {
  9103. if (decimals === void 0) { decimals = 2; }
  9104. return value.toFixed(decimals);
  9105. };
  9106. Tools.CheckExtends = function (v, min, max) {
  9107. if (v.x < min.x)
  9108. min.x = v.x;
  9109. if (v.y < min.y)
  9110. min.y = v.y;
  9111. if (v.z < min.z)
  9112. min.z = v.z;
  9113. if (v.x > max.x)
  9114. max.x = v.x;
  9115. if (v.y > max.y)
  9116. max.y = v.y;
  9117. if (v.z > max.z)
  9118. max.z = v.z;
  9119. };
  9120. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9121. for (var prop in source) {
  9122. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9123. continue;
  9124. }
  9125. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9126. continue;
  9127. }
  9128. var sourceValue = source[prop];
  9129. var typeOfSourceValue = typeof sourceValue;
  9130. if (typeOfSourceValue === "function") {
  9131. continue;
  9132. }
  9133. try {
  9134. if (typeOfSourceValue === "object") {
  9135. if (sourceValue instanceof Array) {
  9136. destination[prop] = [];
  9137. if (sourceValue.length > 0) {
  9138. if (typeof sourceValue[0] == "object") {
  9139. for (var index = 0; index < sourceValue.length; index++) {
  9140. var clonedValue = cloneValue(sourceValue[index], destination);
  9141. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9142. destination[prop].push(clonedValue);
  9143. }
  9144. }
  9145. }
  9146. else {
  9147. destination[prop] = sourceValue.slice(0);
  9148. }
  9149. }
  9150. }
  9151. else {
  9152. destination[prop] = cloneValue(sourceValue, destination);
  9153. }
  9154. }
  9155. else {
  9156. destination[prop] = sourceValue;
  9157. }
  9158. }
  9159. catch (e) {
  9160. // Just ignore error (it could be because of a read-only property)
  9161. }
  9162. }
  9163. };
  9164. Tools.IsEmpty = function (obj) {
  9165. for (var i in obj) {
  9166. if (obj.hasOwnProperty(i)) {
  9167. return false;
  9168. }
  9169. }
  9170. return true;
  9171. };
  9172. Tools.RegisterTopRootEvents = function (events) {
  9173. for (var index = 0; index < events.length; index++) {
  9174. var event = events[index];
  9175. window.addEventListener(event.name, event.handler, false);
  9176. try {
  9177. if (window.parent) {
  9178. window.parent.addEventListener(event.name, event.handler, false);
  9179. }
  9180. }
  9181. catch (e) {
  9182. // Silently fails...
  9183. }
  9184. }
  9185. };
  9186. Tools.UnregisterTopRootEvents = function (events) {
  9187. for (var index = 0; index < events.length; index++) {
  9188. var event = events[index];
  9189. window.removeEventListener(event.name, event.handler);
  9190. try {
  9191. if (window.parent) {
  9192. window.parent.removeEventListener(event.name, event.handler);
  9193. }
  9194. }
  9195. catch (e) {
  9196. // Silently fails...
  9197. }
  9198. }
  9199. };
  9200. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9201. if (mimeType === void 0) { mimeType = "image/png"; }
  9202. // Read the contents of the framebuffer
  9203. var numberOfChannelsByLine = width * 4;
  9204. var halfHeight = height / 2;
  9205. //Reading datas from WebGL
  9206. var data = engine.readPixels(0, 0, width, height);
  9207. //To flip image on Y axis.
  9208. for (var i = 0; i < halfHeight; i++) {
  9209. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9210. var currentCell = j + i * numberOfChannelsByLine;
  9211. var targetLine = height - i - 1;
  9212. var targetCell = j + targetLine * numberOfChannelsByLine;
  9213. var temp = data[currentCell];
  9214. data[currentCell] = data[targetCell];
  9215. data[targetCell] = temp;
  9216. }
  9217. }
  9218. // Create a 2D canvas to store the result
  9219. if (!screenshotCanvas) {
  9220. screenshotCanvas = document.createElement('canvas');
  9221. }
  9222. screenshotCanvas.width = width;
  9223. screenshotCanvas.height = height;
  9224. var context = screenshotCanvas.getContext('2d');
  9225. if (context) {
  9226. // Copy the pixels to a 2D canvas
  9227. var imageData = context.createImageData(width, height);
  9228. var castData = (imageData.data);
  9229. castData.set(data);
  9230. context.putImageData(imageData, 0, 0);
  9231. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9232. }
  9233. };
  9234. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9235. if (mimeType === void 0) { mimeType = "image/png"; }
  9236. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9237. if (successCallback) {
  9238. successCallback(base64Image);
  9239. }
  9240. else {
  9241. // We need HTMLCanvasElement.toBlob for HD screenshots
  9242. if (!screenshotCanvas.toBlob) {
  9243. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9244. screenshotCanvas.toBlob = function (callback, type, quality) {
  9245. var _this = this;
  9246. setTimeout(function () {
  9247. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9248. for (var i = 0; i < len; i++) {
  9249. arr[i] = binStr.charCodeAt(i);
  9250. }
  9251. callback(new Blob([arr], { type: type || 'image/png' }));
  9252. });
  9253. };
  9254. }
  9255. screenshotCanvas.toBlob(function (blob) {
  9256. var url = URL.createObjectURL(blob);
  9257. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9258. if (("download" in document.createElement("a"))) {
  9259. var a = window.document.createElement("a");
  9260. a.href = url;
  9261. if (fileName) {
  9262. a.setAttribute("download", fileName);
  9263. }
  9264. else {
  9265. var date = new Date();
  9266. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9267. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9268. }
  9269. window.document.body.appendChild(a);
  9270. a.addEventListener("click", function () {
  9271. if (a.parentElement) {
  9272. a.parentElement.removeChild(a);
  9273. }
  9274. });
  9275. a.click();
  9276. }
  9277. else {
  9278. var newWindow = window.open("");
  9279. if (!newWindow)
  9280. return;
  9281. var img = newWindow.document.createElement("img");
  9282. img.onload = function () {
  9283. // no longer need to read the blob so it's revoked
  9284. URL.revokeObjectURL(url);
  9285. };
  9286. img.src = url;
  9287. newWindow.document.body.appendChild(img);
  9288. }
  9289. });
  9290. }
  9291. };
  9292. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9293. if (mimeType === void 0) { mimeType = "image/png"; }
  9294. var width;
  9295. var height;
  9296. // If a precision value is specified
  9297. if (size.precision) {
  9298. width = Math.round(engine.getRenderWidth() * size.precision);
  9299. height = Math.round(width / engine.getAspectRatio(camera));
  9300. }
  9301. else if (size.width && size.height) {
  9302. width = size.width;
  9303. height = size.height;
  9304. }
  9305. //If passing only width, computing height to keep display canvas ratio.
  9306. else if (size.width && !size.height) {
  9307. width = size.width;
  9308. height = Math.round(width / engine.getAspectRatio(camera));
  9309. }
  9310. //If passing only height, computing width to keep display canvas ratio.
  9311. else if (size.height && !size.width) {
  9312. height = size.height;
  9313. width = Math.round(height * engine.getAspectRatio(camera));
  9314. }
  9315. //Assuming here that "size" parameter is a number
  9316. else if (!isNaN(size)) {
  9317. height = size;
  9318. width = size;
  9319. }
  9320. else {
  9321. Tools.Error("Invalid 'size' parameter !");
  9322. return;
  9323. }
  9324. if (!screenshotCanvas) {
  9325. screenshotCanvas = document.createElement('canvas');
  9326. }
  9327. screenshotCanvas.width = width;
  9328. screenshotCanvas.height = height;
  9329. var renderContext = screenshotCanvas.getContext("2d");
  9330. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9331. var newWidth = width;
  9332. var newHeight = newWidth / ratio;
  9333. if (newHeight > height) {
  9334. newHeight = height;
  9335. newWidth = newHeight * ratio;
  9336. }
  9337. var offsetX = Math.max(0, width - newWidth) / 2;
  9338. var offsetY = Math.max(0, height - newHeight) / 2;
  9339. var renderingCanvas = engine.getRenderingCanvas();
  9340. if (renderContext && renderingCanvas) {
  9341. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9342. }
  9343. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9344. };
  9345. /**
  9346. * Generates an image screenshot from the specified camera.
  9347. *
  9348. * @param engine The engine to use for rendering
  9349. * @param camera The camera to use for rendering
  9350. * @param size This parameter can be set to a single number or to an object with the
  9351. * following (optional) properties: precision, width, height. If a single number is passed,
  9352. * it will be used for both width and height. If an object is passed, the screenshot size
  9353. * will be derived from the parameters. The precision property is a multiplier allowing
  9354. * rendering at a higher or lower resolution.
  9355. * @param successCallback The callback receives a single parameter which contains the
  9356. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9357. * src parameter of an <img> to display it.
  9358. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9359. * Check your browser for supported MIME types.
  9360. * @param samples Texture samples (default: 1)
  9361. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9362. * @param fileName A name for for the downloaded file.
  9363. * @constructor
  9364. */
  9365. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9366. if (mimeType === void 0) { mimeType = "image/png"; }
  9367. if (samples === void 0) { samples = 1; }
  9368. if (antialiasing === void 0) { antialiasing = false; }
  9369. var width;
  9370. var height;
  9371. //If a precision value is specified
  9372. if (size.precision) {
  9373. width = Math.round(engine.getRenderWidth() * size.precision);
  9374. height = Math.round(width / engine.getAspectRatio(camera));
  9375. size = { width: width, height: height };
  9376. }
  9377. else if (size.width && size.height) {
  9378. width = size.width;
  9379. height = size.height;
  9380. }
  9381. //If passing only width, computing height to keep display canvas ratio.
  9382. else if (size.width && !size.height) {
  9383. width = size.width;
  9384. height = Math.round(width / engine.getAspectRatio(camera));
  9385. size = { width: width, height: height };
  9386. }
  9387. //If passing only height, computing width to keep display canvas ratio.
  9388. else if (size.height && !size.width) {
  9389. height = size.height;
  9390. width = Math.round(height * engine.getAspectRatio(camera));
  9391. size = { width: width, height: height };
  9392. }
  9393. //Assuming here that "size" parameter is a number
  9394. else if (!isNaN(size)) {
  9395. height = size;
  9396. width = size;
  9397. }
  9398. else {
  9399. Tools.Error("Invalid 'size' parameter !");
  9400. return;
  9401. }
  9402. var scene = camera.getScene();
  9403. var previousCamera = null;
  9404. if (scene.activeCamera !== camera) {
  9405. previousCamera = scene.activeCamera;
  9406. scene.activeCamera = camera;
  9407. }
  9408. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9409. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9410. texture.renderList = null;
  9411. texture.samples = samples;
  9412. if (antialiasing) {
  9413. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9414. }
  9415. texture.onAfterRenderObservable.add(function () {
  9416. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9417. });
  9418. scene.incrementRenderId();
  9419. scene.resetCachedMaterial();
  9420. texture.render(true);
  9421. texture.dispose();
  9422. if (previousCamera) {
  9423. scene.activeCamera = previousCamera;
  9424. }
  9425. camera.getProjectionMatrix(true); // Force cache refresh;
  9426. };
  9427. // XHR response validator for local file scenario
  9428. Tools.ValidateXHRData = function (xhr, dataType) {
  9429. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9430. if (dataType === void 0) { dataType = 7; }
  9431. try {
  9432. if (dataType & 1) {
  9433. if (xhr.responseText && xhr.responseText.length > 0) {
  9434. return true;
  9435. }
  9436. else if (dataType === 1) {
  9437. return false;
  9438. }
  9439. }
  9440. if (dataType & 2) {
  9441. // Check header width and height since there is no "TGA" magic number
  9442. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9443. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9444. return true;
  9445. }
  9446. else if (dataType === 2) {
  9447. return false;
  9448. }
  9449. }
  9450. if (dataType & 4) {
  9451. // Check for the "DDS" magic number
  9452. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9453. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9454. return true;
  9455. }
  9456. else {
  9457. return false;
  9458. }
  9459. }
  9460. }
  9461. catch (e) {
  9462. // Global protection
  9463. }
  9464. return false;
  9465. };
  9466. /**
  9467. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9468. * Be aware Math.random() could cause collisions, but:
  9469. * "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"
  9470. */
  9471. Tools.RandomId = function () {
  9472. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9473. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9474. return v.toString(16);
  9475. });
  9476. };
  9477. /**
  9478. * Test if the given uri is a base64 string.
  9479. * @param uri The uri to test
  9480. * @return True if the uri is a base64 string or false otherwise.
  9481. */
  9482. Tools.IsBase64 = function (uri) {
  9483. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9484. };
  9485. /**
  9486. * Decode the given base64 uri.
  9487. * @param uri The uri to decode
  9488. * @return The decoded base64 data.
  9489. */
  9490. Tools.DecodeBase64 = function (uri) {
  9491. var decodedString = atob(uri.split(",")[1]);
  9492. var bufferLength = decodedString.length;
  9493. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9494. for (var i = 0; i < bufferLength; i++) {
  9495. bufferView[i] = decodedString.charCodeAt(i);
  9496. }
  9497. return bufferView.buffer;
  9498. };
  9499. Object.defineProperty(Tools, "NoneLogLevel", {
  9500. get: function () {
  9501. return Tools._NoneLogLevel;
  9502. },
  9503. enumerable: true,
  9504. configurable: true
  9505. });
  9506. Object.defineProperty(Tools, "MessageLogLevel", {
  9507. get: function () {
  9508. return Tools._MessageLogLevel;
  9509. },
  9510. enumerable: true,
  9511. configurable: true
  9512. });
  9513. Object.defineProperty(Tools, "WarningLogLevel", {
  9514. get: function () {
  9515. return Tools._WarningLogLevel;
  9516. },
  9517. enumerable: true,
  9518. configurable: true
  9519. });
  9520. Object.defineProperty(Tools, "ErrorLogLevel", {
  9521. get: function () {
  9522. return Tools._ErrorLogLevel;
  9523. },
  9524. enumerable: true,
  9525. configurable: true
  9526. });
  9527. Object.defineProperty(Tools, "AllLogLevel", {
  9528. get: function () {
  9529. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9530. },
  9531. enumerable: true,
  9532. configurable: true
  9533. });
  9534. Tools._AddLogEntry = function (entry) {
  9535. Tools._LogCache = entry + Tools._LogCache;
  9536. if (Tools.OnNewCacheEntry) {
  9537. Tools.OnNewCacheEntry(entry);
  9538. }
  9539. };
  9540. Tools._FormatMessage = function (message) {
  9541. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9542. var date = new Date();
  9543. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9544. };
  9545. Tools._LogDisabled = function (message) {
  9546. // nothing to do
  9547. };
  9548. Tools._LogEnabled = function (message) {
  9549. var formattedMessage = Tools._FormatMessage(message);
  9550. console.log("BJS - " + formattedMessage);
  9551. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9552. Tools._AddLogEntry(entry);
  9553. };
  9554. Tools._WarnDisabled = function (message) {
  9555. // nothing to do
  9556. };
  9557. Tools._WarnEnabled = function (message) {
  9558. var formattedMessage = Tools._FormatMessage(message);
  9559. console.warn("BJS - " + formattedMessage);
  9560. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9561. Tools._AddLogEntry(entry);
  9562. };
  9563. Tools._ErrorDisabled = function (message) {
  9564. // nothing to do
  9565. };
  9566. Tools._ErrorEnabled = function (message) {
  9567. Tools.errorsCount++;
  9568. var formattedMessage = Tools._FormatMessage(message);
  9569. console.error("BJS - " + formattedMessage);
  9570. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9571. Tools._AddLogEntry(entry);
  9572. };
  9573. Object.defineProperty(Tools, "LogCache", {
  9574. get: function () {
  9575. return Tools._LogCache;
  9576. },
  9577. enumerable: true,
  9578. configurable: true
  9579. });
  9580. Tools.ClearLogCache = function () {
  9581. Tools._LogCache = "";
  9582. Tools.errorsCount = 0;
  9583. };
  9584. Object.defineProperty(Tools, "LogLevels", {
  9585. set: function (level) {
  9586. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9587. Tools.Log = Tools._LogEnabled;
  9588. }
  9589. else {
  9590. Tools.Log = Tools._LogDisabled;
  9591. }
  9592. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9593. Tools.Warn = Tools._WarnEnabled;
  9594. }
  9595. else {
  9596. Tools.Warn = Tools._WarnDisabled;
  9597. }
  9598. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9599. Tools.Error = Tools._ErrorEnabled;
  9600. }
  9601. else {
  9602. Tools.Error = Tools._ErrorDisabled;
  9603. }
  9604. },
  9605. enumerable: true,
  9606. configurable: true
  9607. });
  9608. Tools.IsWindowObjectExist = function () {
  9609. return (typeof window) !== "undefined";
  9610. };
  9611. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9612. get: function () {
  9613. return Tools._PerformanceNoneLogLevel;
  9614. },
  9615. enumerable: true,
  9616. configurable: true
  9617. });
  9618. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9619. get: function () {
  9620. return Tools._PerformanceUserMarkLogLevel;
  9621. },
  9622. enumerable: true,
  9623. configurable: true
  9624. });
  9625. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9626. get: function () {
  9627. return Tools._PerformanceConsoleLogLevel;
  9628. },
  9629. enumerable: true,
  9630. configurable: true
  9631. });
  9632. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9633. set: function (level) {
  9634. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9635. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9636. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9637. return;
  9638. }
  9639. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9640. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9641. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9642. return;
  9643. }
  9644. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9645. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9646. },
  9647. enumerable: true,
  9648. configurable: true
  9649. });
  9650. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9651. };
  9652. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9653. };
  9654. Tools._StartUserMark = function (counterName, condition) {
  9655. if (condition === void 0) { condition = true; }
  9656. if (!Tools._performance) {
  9657. if (!Tools.IsWindowObjectExist()) {
  9658. return;
  9659. }
  9660. Tools._performance = window.performance;
  9661. }
  9662. if (!condition || !Tools._performance.mark) {
  9663. return;
  9664. }
  9665. Tools._performance.mark(counterName + "-Begin");
  9666. };
  9667. Tools._EndUserMark = function (counterName, condition) {
  9668. if (condition === void 0) { condition = true; }
  9669. if (!condition || !Tools._performance.mark) {
  9670. return;
  9671. }
  9672. Tools._performance.mark(counterName + "-End");
  9673. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9674. };
  9675. Tools._StartPerformanceConsole = function (counterName, condition) {
  9676. if (condition === void 0) { condition = true; }
  9677. if (!condition) {
  9678. return;
  9679. }
  9680. Tools._StartUserMark(counterName, condition);
  9681. if (console.time) {
  9682. console.time(counterName);
  9683. }
  9684. };
  9685. Tools._EndPerformanceConsole = function (counterName, condition) {
  9686. if (condition === void 0) { condition = true; }
  9687. if (!condition) {
  9688. return;
  9689. }
  9690. Tools._EndUserMark(counterName, condition);
  9691. if (console.time) {
  9692. console.timeEnd(counterName);
  9693. }
  9694. };
  9695. Object.defineProperty(Tools, "Now", {
  9696. get: function () {
  9697. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9698. return window.performance.now();
  9699. }
  9700. return Date.now();
  9701. },
  9702. enumerable: true,
  9703. configurable: true
  9704. });
  9705. /**
  9706. * This method will return the name of the class used to create the instance of the given object.
  9707. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9708. * @param object the object to get the class name from
  9709. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9710. */
  9711. Tools.GetClassName = function (object, isType) {
  9712. if (isType === void 0) { isType = false; }
  9713. var name = null;
  9714. if (!isType && object.getClassName) {
  9715. name = object.getClassName();
  9716. }
  9717. else {
  9718. if (object instanceof Object) {
  9719. var classObj = isType ? object : Object.getPrototypeOf(object);
  9720. name = classObj.constructor["__bjsclassName__"];
  9721. }
  9722. if (!name) {
  9723. name = typeof object;
  9724. }
  9725. }
  9726. return name;
  9727. };
  9728. Tools.First = function (array, predicate) {
  9729. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9730. var el = array_1[_i];
  9731. if (predicate(el)) {
  9732. return el;
  9733. }
  9734. }
  9735. return null;
  9736. };
  9737. /**
  9738. * This method will return the name of the full name of the class, including its owning module (if any).
  9739. * 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).
  9740. * @param object the object to get the class name from
  9741. * @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.
  9742. */
  9743. Tools.getFullClassName = function (object, isType) {
  9744. if (isType === void 0) { isType = false; }
  9745. var className = null;
  9746. var moduleName = null;
  9747. if (!isType && object.getClassName) {
  9748. className = object.getClassName();
  9749. }
  9750. else {
  9751. if (object instanceof Object) {
  9752. var classObj = isType ? object : Object.getPrototypeOf(object);
  9753. className = classObj.constructor["__bjsclassName__"];
  9754. moduleName = classObj.constructor["__bjsmoduleName__"];
  9755. }
  9756. if (!className) {
  9757. className = typeof object;
  9758. }
  9759. }
  9760. if (!className) {
  9761. return null;
  9762. }
  9763. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9764. };
  9765. /**
  9766. * 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.
  9767. * @param array
  9768. */
  9769. Tools.arrayOrStringFeeder = function (array) {
  9770. return function (index) {
  9771. if (index >= array.length) {
  9772. return null;
  9773. }
  9774. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9775. if (val && val.getHashCode) {
  9776. val = val.getHashCode();
  9777. }
  9778. if (typeof val === "string") {
  9779. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9780. }
  9781. return val;
  9782. };
  9783. };
  9784. /**
  9785. * Compute the hashCode of a stream of number
  9786. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9787. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9788. * @return the hash code computed
  9789. */
  9790. Tools.hashCodeFromStream = function (feeder) {
  9791. // Based from here: http://stackoverflow.com/a/7616484/802124
  9792. var hash = 0;
  9793. var index = 0;
  9794. var chr = feeder(index++);
  9795. while (chr != null) {
  9796. hash = ((hash << 5) - hash) + chr;
  9797. hash |= 0; // Convert to 32bit integer
  9798. chr = feeder(index++);
  9799. }
  9800. return hash;
  9801. };
  9802. /**
  9803. * Returns a promise that resolves after the given amount of time.
  9804. * @param delay Number of milliseconds to delay
  9805. * @returns Promise that resolves after the given amount of time
  9806. */
  9807. Tools.DelayAsync = function (delay) {
  9808. return new Promise(function (resolve) {
  9809. setTimeout(function () {
  9810. resolve();
  9811. }, delay);
  9812. });
  9813. };
  9814. Tools.BaseUrl = "";
  9815. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9816. /**
  9817. * Default behaviour for cors in the application.
  9818. * It can be a string if the expected behavior is identical in the entire app.
  9819. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9820. */
  9821. Tools.CorsBehavior = "anonymous";
  9822. Tools.UseFallbackTexture = true;
  9823. /**
  9824. * Use this object to register external classes like custom textures or material
  9825. * to allow the laoders to instantiate them
  9826. */
  9827. Tools.RegisteredExternalClasses = {};
  9828. // Used in case of a texture loading problem
  9829. 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";
  9830. Tools._tmpFloatArray = new Float32Array(1);
  9831. Tools.PreprocessUrl = function (url) {
  9832. return url;
  9833. };
  9834. // Logs
  9835. Tools._NoneLogLevel = 0;
  9836. Tools._MessageLogLevel = 1;
  9837. Tools._WarningLogLevel = 2;
  9838. Tools._ErrorLogLevel = 4;
  9839. Tools._LogCache = "";
  9840. Tools.errorsCount = 0;
  9841. Tools.Log = Tools._LogEnabled;
  9842. Tools.Warn = Tools._WarnEnabled;
  9843. Tools.Error = Tools._ErrorEnabled;
  9844. // Performances
  9845. Tools._PerformanceNoneLogLevel = 0;
  9846. Tools._PerformanceUserMarkLogLevel = 1;
  9847. Tools._PerformanceConsoleLogLevel = 2;
  9848. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9849. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9850. return Tools;
  9851. }());
  9852. BABYLON.Tools = Tools;
  9853. /**
  9854. * This class is used to track a performance counter which is number based.
  9855. * The user has access to many properties which give statistics of different nature
  9856. *
  9857. * The implementer can track two kinds of Performance Counter: time and count
  9858. * 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.
  9859. * 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.
  9860. */
  9861. var PerfCounter = /** @class */ (function () {
  9862. function PerfCounter() {
  9863. this._startMonitoringTime = 0;
  9864. this._min = 0;
  9865. this._max = 0;
  9866. this._average = 0;
  9867. this._lastSecAverage = 0;
  9868. this._current = 0;
  9869. this._totalValueCount = 0;
  9870. this._totalAccumulated = 0;
  9871. this._lastSecAccumulated = 0;
  9872. this._lastSecTime = 0;
  9873. this._lastSecValueCount = 0;
  9874. }
  9875. Object.defineProperty(PerfCounter.prototype, "min", {
  9876. /**
  9877. * Returns the smallest value ever
  9878. */
  9879. get: function () {
  9880. return this._min;
  9881. },
  9882. enumerable: true,
  9883. configurable: true
  9884. });
  9885. Object.defineProperty(PerfCounter.prototype, "max", {
  9886. /**
  9887. * Returns the biggest value ever
  9888. */
  9889. get: function () {
  9890. return this._max;
  9891. },
  9892. enumerable: true,
  9893. configurable: true
  9894. });
  9895. Object.defineProperty(PerfCounter.prototype, "average", {
  9896. /**
  9897. * Returns the average value since the performance counter is running
  9898. */
  9899. get: function () {
  9900. return this._average;
  9901. },
  9902. enumerable: true,
  9903. configurable: true
  9904. });
  9905. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9906. /**
  9907. * Returns the average value of the last second the counter was monitored
  9908. */
  9909. get: function () {
  9910. return this._lastSecAverage;
  9911. },
  9912. enumerable: true,
  9913. configurable: true
  9914. });
  9915. Object.defineProperty(PerfCounter.prototype, "current", {
  9916. /**
  9917. * Returns the current value
  9918. */
  9919. get: function () {
  9920. return this._current;
  9921. },
  9922. enumerable: true,
  9923. configurable: true
  9924. });
  9925. Object.defineProperty(PerfCounter.prototype, "total", {
  9926. get: function () {
  9927. return this._totalAccumulated;
  9928. },
  9929. enumerable: true,
  9930. configurable: true
  9931. });
  9932. Object.defineProperty(PerfCounter.prototype, "count", {
  9933. get: function () {
  9934. return this._totalValueCount;
  9935. },
  9936. enumerable: true,
  9937. configurable: true
  9938. });
  9939. /**
  9940. * Call this method to start monitoring a new frame.
  9941. * 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.
  9942. */
  9943. PerfCounter.prototype.fetchNewFrame = function () {
  9944. this._totalValueCount++;
  9945. this._current = 0;
  9946. this._lastSecValueCount++;
  9947. };
  9948. /**
  9949. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9950. * @param newCount the count value to add to the monitored count
  9951. * @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.
  9952. */
  9953. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9954. if (!PerfCounter.Enabled) {
  9955. return;
  9956. }
  9957. this._current += newCount;
  9958. if (fetchResult) {
  9959. this._fetchResult();
  9960. }
  9961. };
  9962. /**
  9963. * Start monitoring this performance counter
  9964. */
  9965. PerfCounter.prototype.beginMonitoring = function () {
  9966. if (!PerfCounter.Enabled) {
  9967. return;
  9968. }
  9969. this._startMonitoringTime = Tools.Now;
  9970. };
  9971. /**
  9972. * Compute the time lapsed since the previous beginMonitoring() call.
  9973. * @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
  9974. */
  9975. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9976. if (newFrame === void 0) { newFrame = true; }
  9977. if (!PerfCounter.Enabled) {
  9978. return;
  9979. }
  9980. if (newFrame) {
  9981. this.fetchNewFrame();
  9982. }
  9983. var currentTime = Tools.Now;
  9984. this._current = currentTime - this._startMonitoringTime;
  9985. if (newFrame) {
  9986. this._fetchResult();
  9987. }
  9988. };
  9989. PerfCounter.prototype._fetchResult = function () {
  9990. this._totalAccumulated += this._current;
  9991. this._lastSecAccumulated += this._current;
  9992. // Min/Max update
  9993. this._min = Math.min(this._min, this._current);
  9994. this._max = Math.max(this._max, this._current);
  9995. this._average = this._totalAccumulated / this._totalValueCount;
  9996. // Reset last sec?
  9997. var now = Tools.Now;
  9998. if ((now - this._lastSecTime) > 1000) {
  9999. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10000. this._lastSecTime = now;
  10001. this._lastSecAccumulated = 0;
  10002. this._lastSecValueCount = 0;
  10003. }
  10004. };
  10005. PerfCounter.Enabled = true;
  10006. return PerfCounter;
  10007. }());
  10008. BABYLON.PerfCounter = PerfCounter;
  10009. /**
  10010. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10011. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10012. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10013. * @param name The name of the class, case should be preserved
  10014. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10015. */
  10016. function className(name, module) {
  10017. return function (target) {
  10018. target["__bjsclassName__"] = name;
  10019. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10020. };
  10021. }
  10022. BABYLON.className = className;
  10023. /**
  10024. * An implementation of a loop for asynchronous functions.
  10025. */
  10026. var AsyncLoop = /** @class */ (function () {
  10027. /**
  10028. * Constroctor.
  10029. * @param iterations the number of iterations.
  10030. * @param _fn the function to run each iteration
  10031. * @param _successCallback the callback that will be called upon succesful execution
  10032. * @param offset starting offset.
  10033. */
  10034. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10035. if (offset === void 0) { offset = 0; }
  10036. this.iterations = iterations;
  10037. this._fn = _fn;
  10038. this._successCallback = _successCallback;
  10039. this.index = offset - 1;
  10040. this._done = false;
  10041. }
  10042. /**
  10043. * Execute the next iteration. Must be called after the last iteration was finished.
  10044. */
  10045. AsyncLoop.prototype.executeNext = function () {
  10046. if (!this._done) {
  10047. if (this.index + 1 < this.iterations) {
  10048. ++this.index;
  10049. this._fn(this);
  10050. }
  10051. else {
  10052. this.breakLoop();
  10053. }
  10054. }
  10055. };
  10056. /**
  10057. * Break the loop and run the success callback.
  10058. */
  10059. AsyncLoop.prototype.breakLoop = function () {
  10060. this._done = true;
  10061. this._successCallback();
  10062. };
  10063. /**
  10064. * Helper function
  10065. */
  10066. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10067. if (offset === void 0) { offset = 0; }
  10068. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10069. loop.executeNext();
  10070. return loop;
  10071. };
  10072. /**
  10073. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10074. * @param iterations total number of iterations
  10075. * @param syncedIterations number of synchronous iterations in each async iteration.
  10076. * @param fn the function to call each iteration.
  10077. * @param callback a success call back that will be called when iterating stops.
  10078. * @param breakFunction a break condition (optional)
  10079. * @param timeout timeout settings for the setTimeout function. default - 0.
  10080. * @constructor
  10081. */
  10082. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10083. if (timeout === void 0) { timeout = 0; }
  10084. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10085. if (breakFunction && breakFunction())
  10086. loop.breakLoop();
  10087. else {
  10088. setTimeout(function () {
  10089. for (var i = 0; i < syncedIterations; ++i) {
  10090. var iteration = (loop.index * syncedIterations) + i;
  10091. if (iteration >= iterations)
  10092. break;
  10093. fn(iteration);
  10094. if (breakFunction && breakFunction()) {
  10095. loop.breakLoop();
  10096. break;
  10097. }
  10098. }
  10099. loop.executeNext();
  10100. }, timeout);
  10101. }
  10102. }, callback);
  10103. };
  10104. return AsyncLoop;
  10105. }());
  10106. BABYLON.AsyncLoop = AsyncLoop;
  10107. })(BABYLON || (BABYLON = {}));
  10108. //# sourceMappingURL=babylon.tools.js.map
  10109. var BABYLON;
  10110. (function (BABYLON) {
  10111. var PromiseStates;
  10112. (function (PromiseStates) {
  10113. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10114. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10115. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10116. })(PromiseStates || (PromiseStates = {}));
  10117. var FulFillmentAgregator = /** @class */ (function () {
  10118. function FulFillmentAgregator() {
  10119. this.count = 0;
  10120. this.target = 0;
  10121. this.results = [];
  10122. }
  10123. return FulFillmentAgregator;
  10124. }());
  10125. var InternalPromise = /** @class */ (function () {
  10126. function InternalPromise(resolver) {
  10127. var _this = this;
  10128. this._state = PromiseStates.Pending;
  10129. this._children = new Array();
  10130. this._rejectWasConsumed = false;
  10131. if (!resolver) {
  10132. return;
  10133. }
  10134. try {
  10135. resolver(function (value) {
  10136. _this._resolve(value);
  10137. }, function (reason) {
  10138. _this._reject(reason);
  10139. });
  10140. }
  10141. catch (e) {
  10142. this._reject(e);
  10143. }
  10144. }
  10145. Object.defineProperty(InternalPromise.prototype, "_result", {
  10146. get: function () {
  10147. return this._resultValue;
  10148. },
  10149. set: function (value) {
  10150. this._resultValue = value;
  10151. if (this._parent && this._parent._result === undefined) {
  10152. this._parent._result = value;
  10153. }
  10154. },
  10155. enumerable: true,
  10156. configurable: true
  10157. });
  10158. InternalPromise.prototype.catch = function (onRejected) {
  10159. return this.then(undefined, onRejected);
  10160. };
  10161. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10162. var _this = this;
  10163. var newPromise = new InternalPromise();
  10164. newPromise._onFulfilled = onFulfilled;
  10165. newPromise._onRejected = onRejected;
  10166. // Composition
  10167. this._children.push(newPromise);
  10168. newPromise._parent = this;
  10169. if (this._state !== PromiseStates.Pending) {
  10170. BABYLON.Tools.SetImmediate(function () {
  10171. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10172. var returnedValue = newPromise._resolve(_this._result);
  10173. if (returnedValue !== undefined && returnedValue !== null) {
  10174. if (returnedValue._state !== undefined) {
  10175. var returnedPromise = returnedValue;
  10176. newPromise._children.push(returnedPromise);
  10177. returnedPromise._parent = newPromise;
  10178. newPromise = returnedPromise;
  10179. }
  10180. else {
  10181. newPromise._result = returnedValue;
  10182. }
  10183. }
  10184. }
  10185. else {
  10186. newPromise._reject(_this._reason);
  10187. }
  10188. });
  10189. }
  10190. return newPromise;
  10191. };
  10192. InternalPromise.prototype._moveChildren = function (children) {
  10193. var _this = this;
  10194. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10195. this._children.forEach(function (child) {
  10196. child._parent = _this;
  10197. });
  10198. if (this._state === PromiseStates.Fulfilled) {
  10199. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10200. var child = _b[_i];
  10201. child._resolve(this._result);
  10202. }
  10203. }
  10204. else if (this._state === PromiseStates.Rejected) {
  10205. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10206. var child = _d[_c];
  10207. child._reject(this._reason);
  10208. }
  10209. }
  10210. var _a;
  10211. };
  10212. InternalPromise.prototype._resolve = function (value) {
  10213. try {
  10214. this._state = PromiseStates.Fulfilled;
  10215. var returnedValue = null;
  10216. if (this._onFulfilled) {
  10217. returnedValue = this._onFulfilled(value);
  10218. }
  10219. if (returnedValue !== undefined && returnedValue !== null) {
  10220. if (returnedValue._state !== undefined) {
  10221. // Transmit children
  10222. var returnedPromise = returnedValue;
  10223. returnedPromise._parent = this;
  10224. returnedPromise._moveChildren(this._children);
  10225. value = returnedPromise._result;
  10226. }
  10227. else {
  10228. value = returnedValue;
  10229. }
  10230. }
  10231. this._result = value;
  10232. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10233. var child = _a[_i];
  10234. child._resolve(value);
  10235. }
  10236. this._children.length = 0;
  10237. delete this._onFulfilled;
  10238. delete this._onRejected;
  10239. }
  10240. catch (e) {
  10241. this._reject(e, true);
  10242. }
  10243. };
  10244. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10245. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10246. this._state = PromiseStates.Rejected;
  10247. this._reason = reason;
  10248. if (this._onRejected && !onLocalThrow) {
  10249. try {
  10250. this._onRejected(reason);
  10251. this._rejectWasConsumed = true;
  10252. }
  10253. catch (e) {
  10254. reason = e;
  10255. }
  10256. }
  10257. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10258. var child = _a[_i];
  10259. if (this._rejectWasConsumed) {
  10260. child._resolve(null);
  10261. }
  10262. else {
  10263. child._reject(reason);
  10264. }
  10265. }
  10266. this._children.length = 0;
  10267. delete this._onFulfilled;
  10268. delete this._onRejected;
  10269. };
  10270. InternalPromise.resolve = function (value) {
  10271. var newPromise = new InternalPromise();
  10272. newPromise._resolve(value);
  10273. return newPromise;
  10274. };
  10275. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10276. promise.then(function (value) {
  10277. agregator.results[index] = value;
  10278. agregator.count++;
  10279. if (agregator.count === agregator.target) {
  10280. agregator.rootPromise._resolve(agregator.results);
  10281. }
  10282. return null;
  10283. }, function (reason) {
  10284. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10285. agregator.rootPromise._reject(reason);
  10286. }
  10287. });
  10288. };
  10289. InternalPromise.all = function (promises) {
  10290. var newPromise = new InternalPromise();
  10291. var agregator = new FulFillmentAgregator();
  10292. agregator.target = promises.length;
  10293. agregator.rootPromise = newPromise;
  10294. if (promises.length) {
  10295. for (var index = 0; index < promises.length; index++) {
  10296. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10297. }
  10298. }
  10299. else {
  10300. newPromise._resolve([]);
  10301. }
  10302. return newPromise;
  10303. };
  10304. InternalPromise.race = function (promises) {
  10305. var newPromise = new InternalPromise();
  10306. if (promises.length) {
  10307. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10308. var promise = promises_1[_i];
  10309. promise.then(function (value) {
  10310. if (newPromise) {
  10311. newPromise._resolve(value);
  10312. newPromise = null;
  10313. }
  10314. return null;
  10315. }, function (reason) {
  10316. if (newPromise) {
  10317. newPromise._reject(reason);
  10318. newPromise = null;
  10319. }
  10320. });
  10321. }
  10322. }
  10323. return newPromise;
  10324. };
  10325. return InternalPromise;
  10326. }());
  10327. /**
  10328. * Helper class that provides a small promise polyfill
  10329. */
  10330. var PromisePolyfill = /** @class */ (function () {
  10331. function PromisePolyfill() {
  10332. }
  10333. /**
  10334. * Static function used to check if the polyfill is required
  10335. * If this is the case then the function will inject the polyfill to window.Promise
  10336. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10337. */
  10338. PromisePolyfill.Apply = function (force) {
  10339. if (force === void 0) { force = false; }
  10340. if (force || typeof Promise === 'undefined') {
  10341. var root = window;
  10342. root.Promise = InternalPromise;
  10343. }
  10344. };
  10345. return PromisePolyfill;
  10346. }());
  10347. BABYLON.PromisePolyfill = PromisePolyfill;
  10348. })(BABYLON || (BABYLON = {}));
  10349. //# sourceMappingURL=babylon.promise.js.map
  10350. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10351. var BABYLON;
  10352. (function (BABYLON) {
  10353. /**
  10354. * Helper class to push actions to a pool of workers.
  10355. */
  10356. var WorkerPool = /** @class */ (function () {
  10357. /**
  10358. * Constructor
  10359. * @param workers Array of workers to use for actions
  10360. */
  10361. function WorkerPool(workers) {
  10362. this._pendingActions = new Array();
  10363. this._workerInfos = workers.map(function (worker) { return ({
  10364. worker: worker,
  10365. active: false
  10366. }); });
  10367. }
  10368. /**
  10369. * Terminates all workers and clears any pending actions.
  10370. */
  10371. WorkerPool.prototype.dispose = function () {
  10372. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10373. var workerInfo = _a[_i];
  10374. workerInfo.worker.terminate();
  10375. }
  10376. delete this._workerInfos;
  10377. delete this._pendingActions;
  10378. };
  10379. /**
  10380. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10381. * pended until a worker has completed its action.
  10382. * @param action The action to perform. Call onComplete when the action is complete.
  10383. */
  10384. WorkerPool.prototype.push = function (action) {
  10385. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10386. var workerInfo = _a[_i];
  10387. if (!workerInfo.active) {
  10388. this._execute(workerInfo, action);
  10389. return;
  10390. }
  10391. }
  10392. this._pendingActions.push(action);
  10393. };
  10394. WorkerPool.prototype._execute = function (workerInfo, action) {
  10395. var _this = this;
  10396. workerInfo.active = true;
  10397. action(workerInfo.worker, function () {
  10398. workerInfo.active = false;
  10399. var nextAction = _this._pendingActions.shift();
  10400. if (nextAction) {
  10401. _this._execute(workerInfo, nextAction);
  10402. }
  10403. });
  10404. };
  10405. return WorkerPool;
  10406. }());
  10407. BABYLON.WorkerPool = WorkerPool;
  10408. })(BABYLON || (BABYLON = {}));
  10409. //# sourceMappingURL=babylon.workerPool.js.map
  10410. var BABYLON;
  10411. (function (BABYLON) {
  10412. /**
  10413. * @hidden
  10414. **/
  10415. var _AlphaState = /** @class */ (function () {
  10416. /**
  10417. * Initializes the state.
  10418. */
  10419. function _AlphaState() {
  10420. this._isAlphaBlendDirty = false;
  10421. this._isBlendFunctionParametersDirty = false;
  10422. this._isBlendEquationParametersDirty = false;
  10423. this._isBlendConstantsDirty = false;
  10424. this._alphaBlend = false;
  10425. this._blendFunctionParameters = new Array(4);
  10426. this._blendEquationParameters = new Array(2);
  10427. this._blendConstants = new Array(4);
  10428. this.reset();
  10429. }
  10430. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10431. get: function () {
  10432. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10433. },
  10434. enumerable: true,
  10435. configurable: true
  10436. });
  10437. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10438. get: function () {
  10439. return this._alphaBlend;
  10440. },
  10441. set: function (value) {
  10442. if (this._alphaBlend === value) {
  10443. return;
  10444. }
  10445. this._alphaBlend = value;
  10446. this._isAlphaBlendDirty = true;
  10447. },
  10448. enumerable: true,
  10449. configurable: true
  10450. });
  10451. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10452. if (this._blendConstants[0] === r &&
  10453. this._blendConstants[1] === g &&
  10454. this._blendConstants[2] === b &&
  10455. this._blendConstants[3] === a) {
  10456. return;
  10457. }
  10458. this._blendConstants[0] = r;
  10459. this._blendConstants[1] = g;
  10460. this._blendConstants[2] = b;
  10461. this._blendConstants[3] = a;
  10462. this._isBlendConstantsDirty = true;
  10463. };
  10464. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10465. if (this._blendFunctionParameters[0] === value0 &&
  10466. this._blendFunctionParameters[1] === value1 &&
  10467. this._blendFunctionParameters[2] === value2 &&
  10468. this._blendFunctionParameters[3] === value3) {
  10469. return;
  10470. }
  10471. this._blendFunctionParameters[0] = value0;
  10472. this._blendFunctionParameters[1] = value1;
  10473. this._blendFunctionParameters[2] = value2;
  10474. this._blendFunctionParameters[3] = value3;
  10475. this._isBlendFunctionParametersDirty = true;
  10476. };
  10477. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10478. if (this._blendEquationParameters[0] === rgb &&
  10479. this._blendEquationParameters[1] === alpha) {
  10480. return;
  10481. }
  10482. this._blendEquationParameters[0] = rgb;
  10483. this._blendEquationParameters[1] = alpha;
  10484. this._isBlendEquationParametersDirty = true;
  10485. };
  10486. _AlphaState.prototype.reset = function () {
  10487. this._alphaBlend = false;
  10488. this._blendFunctionParameters[0] = null;
  10489. this._blendFunctionParameters[1] = null;
  10490. this._blendFunctionParameters[2] = null;
  10491. this._blendFunctionParameters[3] = null;
  10492. this._blendEquationParameters[0] = null;
  10493. this._blendEquationParameters[1] = null;
  10494. this._blendConstants[0] = null;
  10495. this._blendConstants[1] = null;
  10496. this._blendConstants[2] = null;
  10497. this._blendConstants[3] = null;
  10498. this._isAlphaBlendDirty = true;
  10499. this._isBlendFunctionParametersDirty = false;
  10500. this._isBlendEquationParametersDirty = false;
  10501. this._isBlendConstantsDirty = false;
  10502. };
  10503. _AlphaState.prototype.apply = function (gl) {
  10504. if (!this.isDirty) {
  10505. return;
  10506. }
  10507. // Alpha blend
  10508. if (this._isAlphaBlendDirty) {
  10509. if (this._alphaBlend) {
  10510. gl.enable(gl.BLEND);
  10511. }
  10512. else {
  10513. gl.disable(gl.BLEND);
  10514. }
  10515. this._isAlphaBlendDirty = false;
  10516. }
  10517. // Alpha function
  10518. if (this._isBlendFunctionParametersDirty) {
  10519. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10520. this._isBlendFunctionParametersDirty = false;
  10521. }
  10522. // Alpha equation
  10523. if (this._isBlendEquationParametersDirty) {
  10524. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10525. this._isBlendEquationParametersDirty = false;
  10526. }
  10527. // Constants
  10528. if (this._isBlendConstantsDirty) {
  10529. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10530. this._isBlendConstantsDirty = false;
  10531. }
  10532. };
  10533. return _AlphaState;
  10534. }());
  10535. BABYLON._AlphaState = _AlphaState;
  10536. })(BABYLON || (BABYLON = {}));
  10537. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10538. var BABYLON;
  10539. (function (BABYLON) {
  10540. /**
  10541. * @hidden
  10542. **/
  10543. var _DepthCullingState = /** @class */ (function () {
  10544. /**
  10545. * Initializes the state.
  10546. */
  10547. function _DepthCullingState() {
  10548. this._isDepthTestDirty = false;
  10549. this._isDepthMaskDirty = false;
  10550. this._isDepthFuncDirty = false;
  10551. this._isCullFaceDirty = false;
  10552. this._isCullDirty = false;
  10553. this._isZOffsetDirty = false;
  10554. this._isFrontFaceDirty = false;
  10555. this.reset();
  10556. }
  10557. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10558. get: function () {
  10559. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10560. },
  10561. enumerable: true,
  10562. configurable: true
  10563. });
  10564. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10565. get: function () {
  10566. return this._zOffset;
  10567. },
  10568. set: function (value) {
  10569. if (this._zOffset === value) {
  10570. return;
  10571. }
  10572. this._zOffset = value;
  10573. this._isZOffsetDirty = true;
  10574. },
  10575. enumerable: true,
  10576. configurable: true
  10577. });
  10578. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10579. get: function () {
  10580. return this._cullFace;
  10581. },
  10582. set: function (value) {
  10583. if (this._cullFace === value) {
  10584. return;
  10585. }
  10586. this._cullFace = value;
  10587. this._isCullFaceDirty = true;
  10588. },
  10589. enumerable: true,
  10590. configurable: true
  10591. });
  10592. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10593. get: function () {
  10594. return this._cull;
  10595. },
  10596. set: function (value) {
  10597. if (this._cull === value) {
  10598. return;
  10599. }
  10600. this._cull = value;
  10601. this._isCullDirty = true;
  10602. },
  10603. enumerable: true,
  10604. configurable: true
  10605. });
  10606. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10607. get: function () {
  10608. return this._depthFunc;
  10609. },
  10610. set: function (value) {
  10611. if (this._depthFunc === value) {
  10612. return;
  10613. }
  10614. this._depthFunc = value;
  10615. this._isDepthFuncDirty = true;
  10616. },
  10617. enumerable: true,
  10618. configurable: true
  10619. });
  10620. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10621. get: function () {
  10622. return this._depthMask;
  10623. },
  10624. set: function (value) {
  10625. if (this._depthMask === value) {
  10626. return;
  10627. }
  10628. this._depthMask = value;
  10629. this._isDepthMaskDirty = true;
  10630. },
  10631. enumerable: true,
  10632. configurable: true
  10633. });
  10634. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10635. get: function () {
  10636. return this._depthTest;
  10637. },
  10638. set: function (value) {
  10639. if (this._depthTest === value) {
  10640. return;
  10641. }
  10642. this._depthTest = value;
  10643. this._isDepthTestDirty = true;
  10644. },
  10645. enumerable: true,
  10646. configurable: true
  10647. });
  10648. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10649. get: function () {
  10650. return this._frontFace;
  10651. },
  10652. set: function (value) {
  10653. if (this._frontFace === value) {
  10654. return;
  10655. }
  10656. this._frontFace = value;
  10657. this._isFrontFaceDirty = true;
  10658. },
  10659. enumerable: true,
  10660. configurable: true
  10661. });
  10662. _DepthCullingState.prototype.reset = function () {
  10663. this._depthMask = true;
  10664. this._depthTest = true;
  10665. this._depthFunc = null;
  10666. this._cullFace = null;
  10667. this._cull = null;
  10668. this._zOffset = 0;
  10669. this._frontFace = null;
  10670. this._isDepthTestDirty = true;
  10671. this._isDepthMaskDirty = true;
  10672. this._isDepthFuncDirty = false;
  10673. this._isCullFaceDirty = false;
  10674. this._isCullDirty = false;
  10675. this._isZOffsetDirty = false;
  10676. this._isFrontFaceDirty = false;
  10677. };
  10678. _DepthCullingState.prototype.apply = function (gl) {
  10679. if (!this.isDirty) {
  10680. return;
  10681. }
  10682. // Cull
  10683. if (this._isCullDirty) {
  10684. if (this.cull) {
  10685. gl.enable(gl.CULL_FACE);
  10686. }
  10687. else {
  10688. gl.disable(gl.CULL_FACE);
  10689. }
  10690. this._isCullDirty = false;
  10691. }
  10692. // Cull face
  10693. if (this._isCullFaceDirty) {
  10694. gl.cullFace(this.cullFace);
  10695. this._isCullFaceDirty = false;
  10696. }
  10697. // Depth mask
  10698. if (this._isDepthMaskDirty) {
  10699. gl.depthMask(this.depthMask);
  10700. this._isDepthMaskDirty = false;
  10701. }
  10702. // Depth test
  10703. if (this._isDepthTestDirty) {
  10704. if (this.depthTest) {
  10705. gl.enable(gl.DEPTH_TEST);
  10706. }
  10707. else {
  10708. gl.disable(gl.DEPTH_TEST);
  10709. }
  10710. this._isDepthTestDirty = false;
  10711. }
  10712. // Depth func
  10713. if (this._isDepthFuncDirty) {
  10714. gl.depthFunc(this.depthFunc);
  10715. this._isDepthFuncDirty = false;
  10716. }
  10717. // zOffset
  10718. if (this._isZOffsetDirty) {
  10719. if (this.zOffset) {
  10720. gl.enable(gl.POLYGON_OFFSET_FILL);
  10721. gl.polygonOffset(this.zOffset, 0);
  10722. }
  10723. else {
  10724. gl.disable(gl.POLYGON_OFFSET_FILL);
  10725. }
  10726. this._isZOffsetDirty = false;
  10727. }
  10728. // Front face
  10729. if (this._isFrontFaceDirty) {
  10730. gl.frontFace(this.frontFace);
  10731. this._isFrontFaceDirty = false;
  10732. }
  10733. };
  10734. return _DepthCullingState;
  10735. }());
  10736. BABYLON._DepthCullingState = _DepthCullingState;
  10737. })(BABYLON || (BABYLON = {}));
  10738. //# sourceMappingURL=babylon.depthCullingState.js.map
  10739. var BABYLON;
  10740. (function (BABYLON) {
  10741. /**
  10742. * @hidden
  10743. **/
  10744. var _StencilState = /** @class */ (function () {
  10745. function _StencilState() {
  10746. this._isStencilTestDirty = false;
  10747. this._isStencilMaskDirty = false;
  10748. this._isStencilFuncDirty = false;
  10749. this._isStencilOpDirty = false;
  10750. this.reset();
  10751. }
  10752. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10753. get: function () {
  10754. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10755. },
  10756. enumerable: true,
  10757. configurable: true
  10758. });
  10759. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10760. get: function () {
  10761. return this._stencilFunc;
  10762. },
  10763. set: function (value) {
  10764. if (this._stencilFunc === value) {
  10765. return;
  10766. }
  10767. this._stencilFunc = value;
  10768. this._isStencilFuncDirty = true;
  10769. },
  10770. enumerable: true,
  10771. configurable: true
  10772. });
  10773. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10774. get: function () {
  10775. return this._stencilFuncRef;
  10776. },
  10777. set: function (value) {
  10778. if (this._stencilFuncRef === value) {
  10779. return;
  10780. }
  10781. this._stencilFuncRef = value;
  10782. this._isStencilFuncDirty = true;
  10783. },
  10784. enumerable: true,
  10785. configurable: true
  10786. });
  10787. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10788. get: function () {
  10789. return this._stencilFuncMask;
  10790. },
  10791. set: function (value) {
  10792. if (this._stencilFuncMask === value) {
  10793. return;
  10794. }
  10795. this._stencilFuncMask = value;
  10796. this._isStencilFuncDirty = true;
  10797. },
  10798. enumerable: true,
  10799. configurable: true
  10800. });
  10801. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10802. get: function () {
  10803. return this._stencilOpStencilFail;
  10804. },
  10805. set: function (value) {
  10806. if (this._stencilOpStencilFail === value) {
  10807. return;
  10808. }
  10809. this._stencilOpStencilFail = value;
  10810. this._isStencilOpDirty = true;
  10811. },
  10812. enumerable: true,
  10813. configurable: true
  10814. });
  10815. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10816. get: function () {
  10817. return this._stencilOpDepthFail;
  10818. },
  10819. set: function (value) {
  10820. if (this._stencilOpDepthFail === value) {
  10821. return;
  10822. }
  10823. this._stencilOpDepthFail = value;
  10824. this._isStencilOpDirty = true;
  10825. },
  10826. enumerable: true,
  10827. configurable: true
  10828. });
  10829. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10830. get: function () {
  10831. return this._stencilOpStencilDepthPass;
  10832. },
  10833. set: function (value) {
  10834. if (this._stencilOpStencilDepthPass === value) {
  10835. return;
  10836. }
  10837. this._stencilOpStencilDepthPass = value;
  10838. this._isStencilOpDirty = true;
  10839. },
  10840. enumerable: true,
  10841. configurable: true
  10842. });
  10843. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10844. get: function () {
  10845. return this._stencilMask;
  10846. },
  10847. set: function (value) {
  10848. if (this._stencilMask === value) {
  10849. return;
  10850. }
  10851. this._stencilMask = value;
  10852. this._isStencilMaskDirty = true;
  10853. },
  10854. enumerable: true,
  10855. configurable: true
  10856. });
  10857. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10858. get: function () {
  10859. return this._stencilTest;
  10860. },
  10861. set: function (value) {
  10862. if (this._stencilTest === value) {
  10863. return;
  10864. }
  10865. this._stencilTest = value;
  10866. this._isStencilTestDirty = true;
  10867. },
  10868. enumerable: true,
  10869. configurable: true
  10870. });
  10871. _StencilState.prototype.reset = function () {
  10872. this._stencilTest = false;
  10873. this._stencilMask = 0xFF;
  10874. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10875. this._stencilFuncRef = 1;
  10876. this._stencilFuncMask = 0xFF;
  10877. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10878. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10879. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10880. this._isStencilTestDirty = true;
  10881. this._isStencilMaskDirty = true;
  10882. this._isStencilFuncDirty = true;
  10883. this._isStencilOpDirty = true;
  10884. };
  10885. _StencilState.prototype.apply = function (gl) {
  10886. if (!this.isDirty) {
  10887. return;
  10888. }
  10889. // Stencil test
  10890. if (this._isStencilTestDirty) {
  10891. if (this.stencilTest) {
  10892. gl.enable(gl.STENCIL_TEST);
  10893. }
  10894. else {
  10895. gl.disable(gl.STENCIL_TEST);
  10896. }
  10897. this._isStencilTestDirty = false;
  10898. }
  10899. // Stencil mask
  10900. if (this._isStencilMaskDirty) {
  10901. gl.stencilMask(this.stencilMask);
  10902. this._isStencilMaskDirty = false;
  10903. }
  10904. // Stencil func
  10905. if (this._isStencilFuncDirty) {
  10906. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10907. this._isStencilFuncDirty = false;
  10908. }
  10909. // Stencil op
  10910. if (this._isStencilOpDirty) {
  10911. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10912. this._isStencilOpDirty = false;
  10913. }
  10914. };
  10915. return _StencilState;
  10916. }());
  10917. BABYLON._StencilState = _StencilState;
  10918. })(BABYLON || (BABYLON = {}));
  10919. //# sourceMappingURL=babylon.stencilState.js.map
  10920. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10921. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10922. s = arguments[i];
  10923. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10924. t[p] = s[p];
  10925. }
  10926. return t;
  10927. };
  10928. var BABYLON;
  10929. (function (BABYLON) {
  10930. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10931. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10932. };
  10933. var compileRawShader = function (gl, source, type) {
  10934. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10935. gl.shaderSource(shader, source);
  10936. gl.compileShader(shader);
  10937. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10938. var log = gl.getShaderInfoLog(shader);
  10939. if (log) {
  10940. throw new Error(log);
  10941. }
  10942. }
  10943. if (!shader) {
  10944. throw new Error("Something went wrong while compile the shader.");
  10945. }
  10946. return shader;
  10947. };
  10948. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10949. var magFilter = gl.NEAREST;
  10950. var minFilter = gl.NEAREST;
  10951. switch (samplingMode) {
  10952. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10953. magFilter = gl.LINEAR;
  10954. if (generateMipMaps) {
  10955. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10956. }
  10957. else {
  10958. minFilter = gl.LINEAR;
  10959. }
  10960. break;
  10961. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10962. magFilter = gl.LINEAR;
  10963. if (generateMipMaps) {
  10964. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10965. }
  10966. else {
  10967. minFilter = gl.LINEAR;
  10968. }
  10969. break;
  10970. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10971. magFilter = gl.NEAREST;
  10972. if (generateMipMaps) {
  10973. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10974. }
  10975. else {
  10976. minFilter = gl.NEAREST;
  10977. }
  10978. break;
  10979. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10980. magFilter = gl.NEAREST;
  10981. if (generateMipMaps) {
  10982. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10983. }
  10984. else {
  10985. minFilter = gl.NEAREST;
  10986. }
  10987. break;
  10988. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10989. magFilter = gl.NEAREST;
  10990. if (generateMipMaps) {
  10991. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10992. }
  10993. else {
  10994. minFilter = gl.LINEAR;
  10995. }
  10996. break;
  10997. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10998. magFilter = gl.NEAREST;
  10999. if (generateMipMaps) {
  11000. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11001. }
  11002. else {
  11003. minFilter = gl.LINEAR;
  11004. }
  11005. break;
  11006. case BABYLON.Texture.NEAREST_LINEAR:
  11007. magFilter = gl.NEAREST;
  11008. minFilter = gl.LINEAR;
  11009. break;
  11010. case BABYLON.Texture.NEAREST_NEAREST:
  11011. magFilter = gl.NEAREST;
  11012. minFilter = gl.NEAREST;
  11013. break;
  11014. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11015. magFilter = gl.LINEAR;
  11016. if (generateMipMaps) {
  11017. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11018. }
  11019. else {
  11020. minFilter = gl.NEAREST;
  11021. }
  11022. break;
  11023. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11024. magFilter = gl.LINEAR;
  11025. if (generateMipMaps) {
  11026. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11027. }
  11028. else {
  11029. minFilter = gl.NEAREST;
  11030. }
  11031. break;
  11032. case BABYLON.Texture.LINEAR_LINEAR:
  11033. magFilter = gl.LINEAR;
  11034. minFilter = gl.LINEAR;
  11035. break;
  11036. case BABYLON.Texture.LINEAR_NEAREST:
  11037. magFilter = gl.LINEAR;
  11038. minFilter = gl.NEAREST;
  11039. break;
  11040. }
  11041. return {
  11042. min: minFilter,
  11043. mag: magFilter
  11044. };
  11045. };
  11046. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11047. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11048. var img;
  11049. var onload = function () {
  11050. loadedImages[index] = img;
  11051. loadedImages._internalCount++;
  11052. if (scene) {
  11053. scene._removePendingData(img);
  11054. }
  11055. if (loadedImages._internalCount === 6) {
  11056. onfinish(loadedImages);
  11057. }
  11058. };
  11059. var onerror = function (message, exception) {
  11060. if (scene) {
  11061. scene._removePendingData(img);
  11062. }
  11063. if (onErrorCallBack) {
  11064. onErrorCallBack(message, exception);
  11065. }
  11066. };
  11067. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11068. if (scene) {
  11069. scene._addPendingData(img);
  11070. }
  11071. };
  11072. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11073. if (onError === void 0) { onError = null; }
  11074. var loadedImages = [];
  11075. loadedImages._internalCount = 0;
  11076. for (var index = 0; index < 6; index++) {
  11077. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11078. }
  11079. };
  11080. var BufferPointer = /** @class */ (function () {
  11081. function BufferPointer() {
  11082. }
  11083. return BufferPointer;
  11084. }());
  11085. /**
  11086. * Interface for attribute information associated with buffer instanciation
  11087. */
  11088. var InstancingAttributeInfo = /** @class */ (function () {
  11089. function InstancingAttributeInfo() {
  11090. }
  11091. return InstancingAttributeInfo;
  11092. }());
  11093. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11094. /**
  11095. * Define options used to create a render target texture
  11096. */
  11097. var RenderTargetCreationOptions = /** @class */ (function () {
  11098. function RenderTargetCreationOptions() {
  11099. }
  11100. return RenderTargetCreationOptions;
  11101. }());
  11102. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11103. /**
  11104. * Define options used to create a depth texture
  11105. */
  11106. var DepthTextureCreationOptions = /** @class */ (function () {
  11107. function DepthTextureCreationOptions() {
  11108. }
  11109. return DepthTextureCreationOptions;
  11110. }());
  11111. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11112. /**
  11113. * Class used to describe the capabilities of the engine relatively to the current browser
  11114. */
  11115. var EngineCapabilities = /** @class */ (function () {
  11116. function EngineCapabilities() {
  11117. }
  11118. return EngineCapabilities;
  11119. }());
  11120. BABYLON.EngineCapabilities = EngineCapabilities;
  11121. /**
  11122. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11123. */
  11124. var Engine = /** @class */ (function () {
  11125. /**
  11126. * Creates a new engine
  11127. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11128. * @param antialias defines enable antialiasing (default: false)
  11129. * @param options defines further options to be sent to the getContext() function
  11130. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11131. */
  11132. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11133. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11134. var _this = this;
  11135. // Public members
  11136. /**
  11137. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11138. */
  11139. this.forcePOTTextures = false;
  11140. /**
  11141. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11142. */
  11143. this.isFullscreen = false;
  11144. /**
  11145. * Gets a boolean indicating if the pointer is currently locked
  11146. */
  11147. this.isPointerLock = false;
  11148. /**
  11149. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11150. */
  11151. this.cullBackFaces = true;
  11152. /**
  11153. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11154. */
  11155. this.renderEvenInBackground = true;
  11156. /**
  11157. * Gets or sets a boolean indicating that cache can be kept between frames
  11158. */
  11159. this.preventCacheWipeBetweenFrames = false;
  11160. /**
  11161. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11162. **/
  11163. this.enableOfflineSupport = false;
  11164. /**
  11165. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11166. **/
  11167. this.disableManifestCheck = false;
  11168. /**
  11169. * Gets the list of created scenes
  11170. */
  11171. this.scenes = new Array();
  11172. /**
  11173. * Gets the list of created postprocesses
  11174. */
  11175. this.postProcesses = new Array();
  11176. // Observables
  11177. /**
  11178. * Observable event triggered each time the rendering canvas is resized
  11179. */
  11180. this.onResizeObservable = new BABYLON.Observable();
  11181. /**
  11182. * Observable event triggered each time the canvas loses focus
  11183. */
  11184. this.onCanvasBlurObservable = new BABYLON.Observable();
  11185. /**
  11186. * Observable event triggered each time the canvas gains focus
  11187. */
  11188. this.onCanvasFocusObservable = new BABYLON.Observable();
  11189. /**
  11190. * Observable event triggered each time the canvas receives pointerout event
  11191. */
  11192. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11193. /**
  11194. * Observable event triggered before each texture is initialized
  11195. */
  11196. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11197. //WebVR
  11198. this._vrDisplay = undefined;
  11199. this._vrSupported = false;
  11200. this._vrExclusivePointerMode = false;
  11201. // Uniform buffers list
  11202. /**
  11203. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11204. */
  11205. this.disableUniformBuffers = false;
  11206. /** @hidden */
  11207. this._uniformBuffers = new Array();
  11208. // Observables
  11209. /**
  11210. * Observable raised when the engine begins a new frame
  11211. */
  11212. this.onBeginFrameObservable = new BABYLON.Observable();
  11213. /**
  11214. * Observable raised when the engine ends the current frame
  11215. */
  11216. this.onEndFrameObservable = new BABYLON.Observable();
  11217. /**
  11218. * Observable raised when the engine is about to compile a shader
  11219. */
  11220. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11221. /**
  11222. * Observable raised when the engine has jsut compiled a shader
  11223. */
  11224. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11225. this._windowIsBackground = false;
  11226. this._webGLVersion = 1.0;
  11227. /** @hidden */
  11228. this._badOS = false;
  11229. /** @hidden */
  11230. this._badDesktopOS = false;
  11231. /**
  11232. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11233. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11234. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11235. */
  11236. this.disableTextureBindingOptimization = false;
  11237. /**
  11238. * Observable signaled when VR display mode changes
  11239. */
  11240. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11241. /**
  11242. * Observable signaled when VR request present is complete
  11243. */
  11244. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11245. /**
  11246. * Observable signaled when VR request present starts
  11247. */
  11248. this.onVRRequestPresentStart = new BABYLON.Observable();
  11249. this._colorWrite = true;
  11250. /** @hidden */
  11251. this._drawCalls = new BABYLON.PerfCounter();
  11252. /** @hidden */
  11253. this._textureCollisions = new BABYLON.PerfCounter();
  11254. this._renderingQueueLaunched = false;
  11255. this._activeRenderLoops = new Array();
  11256. // Deterministic lockstepMaxSteps
  11257. this._deterministicLockstep = false;
  11258. this._lockstepMaxSteps = 4;
  11259. // Lost context
  11260. /**
  11261. * Observable signaled when a context lost event is raised
  11262. */
  11263. this.onContextLostObservable = new BABYLON.Observable();
  11264. /**
  11265. * Observable signaled when a context restored event is raised
  11266. */
  11267. this.onContextRestoredObservable = new BABYLON.Observable();
  11268. this._contextWasLost = false;
  11269. this._doNotHandleContextLost = false;
  11270. // FPS
  11271. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11272. this._fps = 60;
  11273. this._deltaTime = 0;
  11274. /**
  11275. * Turn this value on if you want to pause FPS computation when in background
  11276. */
  11277. this.disablePerformanceMonitorInBackground = false;
  11278. // States
  11279. /** @hidden */
  11280. this._depthCullingState = new BABYLON._DepthCullingState();
  11281. /** @hidden */
  11282. this._stencilState = new BABYLON._StencilState();
  11283. /** @hidden */
  11284. this._alphaState = new BABYLON._AlphaState();
  11285. /** @hidden */
  11286. this._alphaMode = Engine.ALPHA_DISABLE;
  11287. // Cache
  11288. this._internalTexturesCache = new Array();
  11289. /** @hidden */
  11290. this._activeChannel = 0;
  11291. this._currentTextureChannel = -1;
  11292. /** @hidden */
  11293. this._boundTexturesCache = {};
  11294. this._compiledEffects = {};
  11295. this._vertexAttribArraysEnabled = [];
  11296. this._uintIndicesCurrentlySet = false;
  11297. this._currentBoundBuffer = new Array();
  11298. this._currentBufferPointers = new Array();
  11299. this._currentInstanceLocations = new Array();
  11300. this._currentInstanceBuffers = new Array();
  11301. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11302. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11303. this._vaoRecordInProgress = false;
  11304. this._mustWipeVertexAttributes = false;
  11305. this._nextFreeTextureSlots = new Array();
  11306. this._maxSimultaneousTextures = 0;
  11307. this._activeRequests = new Array();
  11308. // Hardware supported Compressed Textures
  11309. this._texturesSupported = new Array();
  11310. this._onVRFullScreenTriggered = function () {
  11311. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11312. //get the old size before we change
  11313. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11314. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11315. //get the width and height, change the render size
  11316. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11317. _this.setHardwareScalingLevel(1);
  11318. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11319. }
  11320. else {
  11321. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11322. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11323. }
  11324. };
  11325. this._boundUniforms = {};
  11326. // Register promises
  11327. BABYLON.PromisePolyfill.Apply();
  11328. var canvas = null;
  11329. Engine.Instances.push(this);
  11330. if (!canvasOrContext) {
  11331. return;
  11332. }
  11333. options = options || {};
  11334. if (canvasOrContext.getContext) {
  11335. canvas = canvasOrContext;
  11336. this._renderingCanvas = canvas;
  11337. if (antialias != null) {
  11338. options.antialias = antialias;
  11339. }
  11340. if (options.deterministicLockstep === undefined) {
  11341. options.deterministicLockstep = false;
  11342. }
  11343. if (options.lockstepMaxSteps === undefined) {
  11344. options.lockstepMaxSteps = 4;
  11345. }
  11346. if (options.preserveDrawingBuffer === undefined) {
  11347. options.preserveDrawingBuffer = false;
  11348. }
  11349. if (options.audioEngine === undefined) {
  11350. options.audioEngine = true;
  11351. }
  11352. if (options.stencil === undefined) {
  11353. options.stencil = true;
  11354. }
  11355. this._deterministicLockstep = options.deterministicLockstep;
  11356. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11357. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11358. // Exceptions
  11359. if (navigator && navigator.userAgent) {
  11360. var ua = navigator.userAgent;
  11361. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11362. var exception = _a[_i];
  11363. var key = exception.key;
  11364. var targets = exception.targets;
  11365. if (ua.indexOf(key) > -1) {
  11366. if (exception.capture && exception.captureConstraint) {
  11367. var capture = exception.capture;
  11368. var constraint = exception.captureConstraint;
  11369. var regex = new RegExp(capture);
  11370. var matches = regex.exec(ua);
  11371. if (matches && matches.length > 0) {
  11372. var capturedValue = parseInt(matches[matches.length - 1]);
  11373. if (capturedValue >= constraint) {
  11374. continue;
  11375. }
  11376. }
  11377. }
  11378. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11379. var target = targets_1[_b];
  11380. switch (target) {
  11381. case "uniformBuffer":
  11382. this.disableUniformBuffers = true;
  11383. break;
  11384. case "textureBindingOptimization":
  11385. this.disableTextureBindingOptimization = true;
  11386. break;
  11387. }
  11388. }
  11389. }
  11390. }
  11391. }
  11392. // GL
  11393. if (!options.disableWebGL2Support) {
  11394. try {
  11395. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11396. if (this._gl) {
  11397. this._webGLVersion = 2.0;
  11398. }
  11399. }
  11400. catch (e) {
  11401. // Do nothing
  11402. }
  11403. }
  11404. if (!this._gl) {
  11405. if (!canvas) {
  11406. throw new Error("The provided canvas is null or undefined.");
  11407. }
  11408. try {
  11409. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11410. }
  11411. catch (e) {
  11412. throw new Error("WebGL not supported");
  11413. }
  11414. }
  11415. if (!this._gl) {
  11416. throw new Error("WebGL not supported");
  11417. }
  11418. this._onCanvasFocus = function () {
  11419. _this.onCanvasFocusObservable.notifyObservers(_this);
  11420. };
  11421. this._onCanvasBlur = function () {
  11422. _this.onCanvasBlurObservable.notifyObservers(_this);
  11423. };
  11424. canvas.addEventListener("focus", this._onCanvasFocus);
  11425. canvas.addEventListener("blur", this._onCanvasBlur);
  11426. this._onBlur = function () {
  11427. if (_this.disablePerformanceMonitorInBackground) {
  11428. _this._performanceMonitor.disable();
  11429. }
  11430. _this._windowIsBackground = true;
  11431. };
  11432. this._onFocus = function () {
  11433. if (_this.disablePerformanceMonitorInBackground) {
  11434. _this._performanceMonitor.enable();
  11435. }
  11436. _this._windowIsBackground = false;
  11437. };
  11438. this._onCanvasPointerOut = function (ev) {
  11439. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11440. };
  11441. window.addEventListener("blur", this._onBlur);
  11442. window.addEventListener("focus", this._onFocus);
  11443. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11444. // Context lost
  11445. if (!this._doNotHandleContextLost) {
  11446. this._onContextLost = function (evt) {
  11447. evt.preventDefault();
  11448. _this._contextWasLost = true;
  11449. BABYLON.Tools.Warn("WebGL context lost.");
  11450. _this.onContextLostObservable.notifyObservers(_this);
  11451. };
  11452. this._onContextRestored = function (evt) {
  11453. // Adding a timeout to avoid race condition at browser level
  11454. setTimeout(function () {
  11455. // Rebuild gl context
  11456. _this._initGLContext();
  11457. // Rebuild effects
  11458. _this._rebuildEffects();
  11459. // Rebuild textures
  11460. _this._rebuildInternalTextures();
  11461. // Rebuild buffers
  11462. _this._rebuildBuffers();
  11463. // Cache
  11464. _this.wipeCaches(true);
  11465. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11466. _this.onContextRestoredObservable.notifyObservers(_this);
  11467. _this._contextWasLost = false;
  11468. }, 0);
  11469. };
  11470. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11471. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11472. }
  11473. }
  11474. else {
  11475. this._gl = canvasOrContext;
  11476. this._renderingCanvas = this._gl.canvas;
  11477. if (this._gl.renderbufferStorageMultisample) {
  11478. this._webGLVersion = 2.0;
  11479. }
  11480. options.stencil = this._gl.getContextAttributes().stencil;
  11481. }
  11482. // Viewport
  11483. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11484. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11485. this.resize();
  11486. this._isStencilEnable = options.stencil ? true : false;
  11487. this._initGLContext();
  11488. if (canvas) {
  11489. // Fullscreen
  11490. this._onFullscreenChange = function () {
  11491. if (document.fullscreen !== undefined) {
  11492. _this.isFullscreen = document.fullscreen;
  11493. }
  11494. else if (document.mozFullScreen !== undefined) {
  11495. _this.isFullscreen = document.mozFullScreen;
  11496. }
  11497. else if (document.webkitIsFullScreen !== undefined) {
  11498. _this.isFullscreen = document.webkitIsFullScreen;
  11499. }
  11500. else if (document.msIsFullScreen !== undefined) {
  11501. _this.isFullscreen = document.msIsFullScreen;
  11502. }
  11503. // Pointer lock
  11504. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11505. canvas.requestPointerLock = canvas.requestPointerLock ||
  11506. canvas.msRequestPointerLock ||
  11507. canvas.mozRequestPointerLock ||
  11508. canvas.webkitRequestPointerLock;
  11509. if (canvas.requestPointerLock) {
  11510. canvas.requestPointerLock();
  11511. }
  11512. }
  11513. };
  11514. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11515. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11516. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11517. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11518. // Pointer lock
  11519. this._onPointerLockChange = function () {
  11520. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11521. document.webkitPointerLockElement === canvas ||
  11522. document.msPointerLockElement === canvas ||
  11523. document.pointerLockElement === canvas);
  11524. };
  11525. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11526. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11527. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11528. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11529. this._onVRDisplayPointerRestricted = function () {
  11530. if (canvas) {
  11531. canvas.requestPointerLock();
  11532. }
  11533. };
  11534. this._onVRDisplayPointerUnrestricted = function () {
  11535. document.exitPointerLock();
  11536. };
  11537. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11538. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11539. }
  11540. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11541. Engine.audioEngine = new BABYLON.AudioEngine();
  11542. }
  11543. // Prepare buffer pointers
  11544. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11545. this._currentBufferPointers[i] = new BufferPointer();
  11546. }
  11547. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11548. // Load WebVR Devices
  11549. if (options.autoEnableWebVR) {
  11550. this.initWebVR();
  11551. }
  11552. // Detect if we are running on a faulty buggy OS.
  11553. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11554. // Detect if we are running on a faulty buggy desktop OS.
  11555. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11556. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11557. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11558. }
  11559. Object.defineProperty(Engine, "LastCreatedEngine", {
  11560. /**
  11561. * Gets the latest created engine
  11562. */
  11563. get: function () {
  11564. if (Engine.Instances.length === 0) {
  11565. return null;
  11566. }
  11567. return Engine.Instances[Engine.Instances.length - 1];
  11568. },
  11569. enumerable: true,
  11570. configurable: true
  11571. });
  11572. Object.defineProperty(Engine, "LastCreatedScene", {
  11573. /**
  11574. * Gets the latest created scene
  11575. */
  11576. get: function () {
  11577. var lastCreatedEngine = Engine.LastCreatedEngine;
  11578. if (!lastCreatedEngine) {
  11579. return null;
  11580. }
  11581. if (lastCreatedEngine.scenes.length === 0) {
  11582. return null;
  11583. }
  11584. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11585. },
  11586. enumerable: true,
  11587. configurable: true
  11588. });
  11589. /**
  11590. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11591. * @param flag defines which part of the materials must be marked as dirty
  11592. * @param predicate defines a predicate used to filter which materials should be affected
  11593. */
  11594. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11595. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11596. var engine = Engine.Instances[engineIndex];
  11597. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11598. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11599. }
  11600. }
  11601. };
  11602. Object.defineProperty(Engine, "NEVER", {
  11603. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11604. get: function () {
  11605. return Engine._NEVER;
  11606. },
  11607. enumerable: true,
  11608. configurable: true
  11609. });
  11610. Object.defineProperty(Engine, "ALWAYS", {
  11611. /** 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 */
  11612. get: function () {
  11613. return Engine._ALWAYS;
  11614. },
  11615. enumerable: true,
  11616. configurable: true
  11617. });
  11618. Object.defineProperty(Engine, "LESS", {
  11619. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11620. get: function () {
  11621. return Engine._LESS;
  11622. },
  11623. enumerable: true,
  11624. configurable: true
  11625. });
  11626. Object.defineProperty(Engine, "EQUAL", {
  11627. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11628. get: function () {
  11629. return Engine._EQUAL;
  11630. },
  11631. enumerable: true,
  11632. configurable: true
  11633. });
  11634. Object.defineProperty(Engine, "LEQUAL", {
  11635. /** 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 */
  11636. get: function () {
  11637. return Engine._LEQUAL;
  11638. },
  11639. enumerable: true,
  11640. configurable: true
  11641. });
  11642. Object.defineProperty(Engine, "GREATER", {
  11643. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11644. get: function () {
  11645. return Engine._GREATER;
  11646. },
  11647. enumerable: true,
  11648. configurable: true
  11649. });
  11650. Object.defineProperty(Engine, "GEQUAL", {
  11651. /** 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 */
  11652. get: function () {
  11653. return Engine._GEQUAL;
  11654. },
  11655. enumerable: true,
  11656. configurable: true
  11657. });
  11658. Object.defineProperty(Engine, "NOTEQUAL", {
  11659. /** 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 */
  11660. get: function () {
  11661. return Engine._NOTEQUAL;
  11662. },
  11663. enumerable: true,
  11664. configurable: true
  11665. });
  11666. Object.defineProperty(Engine, "KEEP", {
  11667. /** Passed to stencilOperation to specify that stencil value must be kept */
  11668. get: function () {
  11669. return Engine._KEEP;
  11670. },
  11671. enumerable: true,
  11672. configurable: true
  11673. });
  11674. Object.defineProperty(Engine, "REPLACE", {
  11675. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11676. get: function () {
  11677. return Engine._REPLACE;
  11678. },
  11679. enumerable: true,
  11680. configurable: true
  11681. });
  11682. Object.defineProperty(Engine, "INCR", {
  11683. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11684. get: function () {
  11685. return Engine._INCR;
  11686. },
  11687. enumerable: true,
  11688. configurable: true
  11689. });
  11690. Object.defineProperty(Engine, "DECR", {
  11691. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11692. get: function () {
  11693. return Engine._DECR;
  11694. },
  11695. enumerable: true,
  11696. configurable: true
  11697. });
  11698. Object.defineProperty(Engine, "INVERT", {
  11699. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11700. get: function () {
  11701. return Engine._INVERT;
  11702. },
  11703. enumerable: true,
  11704. configurable: true
  11705. });
  11706. Object.defineProperty(Engine, "INCR_WRAP", {
  11707. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11708. get: function () {
  11709. return Engine._INCR_WRAP;
  11710. },
  11711. enumerable: true,
  11712. configurable: true
  11713. });
  11714. Object.defineProperty(Engine, "DECR_WRAP", {
  11715. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11716. get: function () {
  11717. return Engine._DECR_WRAP;
  11718. },
  11719. enumerable: true,
  11720. configurable: true
  11721. });
  11722. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11723. // Alpha
  11724. /** Defines that alpha blending is disabled */
  11725. get: function () {
  11726. return Engine._ALPHA_DISABLE;
  11727. },
  11728. enumerable: true,
  11729. configurable: true
  11730. });
  11731. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11732. /** Defines that alpha blending to SRC + DEST */
  11733. get: function () {
  11734. return Engine._ALPHA_ONEONE;
  11735. },
  11736. enumerable: true,
  11737. configurable: true
  11738. });
  11739. Object.defineProperty(Engine, "ALPHA_ADD", {
  11740. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11741. get: function () {
  11742. return Engine._ALPHA_ADD;
  11743. },
  11744. enumerable: true,
  11745. configurable: true
  11746. });
  11747. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11748. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11749. get: function () {
  11750. return Engine._ALPHA_COMBINE;
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11756. /** Defines that alpha blending to DEST - SRC * DEST */
  11757. get: function () {
  11758. return Engine._ALPHA_SUBTRACT;
  11759. },
  11760. enumerable: true,
  11761. configurable: true
  11762. });
  11763. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11764. /** Defines that alpha blending to SRC * DEST */
  11765. get: function () {
  11766. return Engine._ALPHA_MULTIPLY;
  11767. },
  11768. enumerable: true,
  11769. configurable: true
  11770. });
  11771. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11772. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11773. get: function () {
  11774. return Engine._ALPHA_MAXIMIZED;
  11775. },
  11776. enumerable: true,
  11777. configurable: true
  11778. });
  11779. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11780. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11781. get: function () {
  11782. return Engine._ALPHA_PREMULTIPLIED;
  11783. },
  11784. enumerable: true,
  11785. configurable: true
  11786. });
  11787. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11788. /**
  11789. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11790. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11791. */
  11792. get: function () {
  11793. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11794. },
  11795. enumerable: true,
  11796. configurable: true
  11797. });
  11798. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11799. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11800. get: function () {
  11801. return Engine._ALPHA_INTERPOLATE;
  11802. },
  11803. enumerable: true,
  11804. configurable: true
  11805. });
  11806. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11807. /**
  11808. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11809. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11810. */
  11811. get: function () {
  11812. return Engine._ALPHA_SCREENMODE;
  11813. },
  11814. enumerable: true,
  11815. configurable: true
  11816. });
  11817. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11818. // Delays
  11819. /** Defines that the ressource is not delayed*/
  11820. get: function () {
  11821. return Engine._DELAYLOADSTATE_NONE;
  11822. },
  11823. enumerable: true,
  11824. configurable: true
  11825. });
  11826. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11827. /** Defines that the ressource was successfully delay loaded */
  11828. get: function () {
  11829. return Engine._DELAYLOADSTATE_LOADED;
  11830. },
  11831. enumerable: true,
  11832. configurable: true
  11833. });
  11834. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11835. /** Defines that the ressource is currently delay loading */
  11836. get: function () {
  11837. return Engine._DELAYLOADSTATE_LOADING;
  11838. },
  11839. enumerable: true,
  11840. configurable: true
  11841. });
  11842. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11843. /** Defines that the ressource is delayed and has not started loading */
  11844. get: function () {
  11845. return Engine._DELAYLOADSTATE_NOTLOADED;
  11846. },
  11847. enumerable: true,
  11848. configurable: true
  11849. });
  11850. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11851. /** ALPHA */
  11852. get: function () {
  11853. return Engine._TEXTUREFORMAT_ALPHA;
  11854. },
  11855. enumerable: true,
  11856. configurable: true
  11857. });
  11858. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11859. /** LUMINANCE */
  11860. get: function () {
  11861. return Engine._TEXTUREFORMAT_LUMINANCE;
  11862. },
  11863. enumerable: true,
  11864. configurable: true
  11865. });
  11866. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11867. /**
  11868. * R32F
  11869. */
  11870. get: function () {
  11871. return Engine._TEXTUREFORMAT_R32F;
  11872. },
  11873. enumerable: true,
  11874. configurable: true
  11875. });
  11876. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11877. /**
  11878. * RG32F
  11879. */
  11880. get: function () {
  11881. return Engine._TEXTUREFORMAT_RG32F;
  11882. },
  11883. enumerable: true,
  11884. configurable: true
  11885. });
  11886. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11887. /**
  11888. * RGB32F
  11889. */
  11890. get: function () {
  11891. return Engine._TEXTUREFORMAT_RGB32F;
  11892. },
  11893. enumerable: true,
  11894. configurable: true
  11895. });
  11896. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11897. /**
  11898. * RGBA32F
  11899. */
  11900. get: function () {
  11901. return Engine._TEXTUREFORMAT_RGBA32F;
  11902. },
  11903. enumerable: true,
  11904. configurable: true
  11905. });
  11906. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11907. /** LUMINANCE_ALPHA */
  11908. get: function () {
  11909. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11910. },
  11911. enumerable: true,
  11912. configurable: true
  11913. });
  11914. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11915. /** RGB */
  11916. get: function () {
  11917. return Engine._TEXTUREFORMAT_RGB;
  11918. },
  11919. enumerable: true,
  11920. configurable: true
  11921. });
  11922. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11923. /** RGBA */
  11924. get: function () {
  11925. return Engine._TEXTUREFORMAT_RGBA;
  11926. },
  11927. enumerable: true,
  11928. configurable: true
  11929. });
  11930. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11931. /** UNSIGNED_INT */
  11932. get: function () {
  11933. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11934. },
  11935. enumerable: true,
  11936. configurable: true
  11937. });
  11938. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11939. /** FLOAT */
  11940. get: function () {
  11941. return Engine._TEXTURETYPE_FLOAT;
  11942. },
  11943. enumerable: true,
  11944. configurable: true
  11945. });
  11946. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11947. /** HALF_FLOAT */
  11948. get: function () {
  11949. return Engine._TEXTURETYPE_HALF_FLOAT;
  11950. },
  11951. enumerable: true,
  11952. configurable: true
  11953. });
  11954. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11955. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11956. get: function () {
  11957. return Engine._SCALEMODE_FLOOR;
  11958. },
  11959. enumerable: true,
  11960. configurable: true
  11961. });
  11962. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11963. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11964. get: function () {
  11965. return Engine._SCALEMODE_NEAREST;
  11966. },
  11967. enumerable: true,
  11968. configurable: true
  11969. });
  11970. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11971. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11972. get: function () {
  11973. return Engine._SCALEMODE_CEILING;
  11974. },
  11975. enumerable: true,
  11976. configurable: true
  11977. });
  11978. Object.defineProperty(Engine, "Version", {
  11979. /**
  11980. * Returns the current version of the framework
  11981. */
  11982. get: function () {
  11983. return "3.2.0-rc.1";
  11984. },
  11985. enumerable: true,
  11986. configurable: true
  11987. });
  11988. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11989. /**
  11990. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11991. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11992. */
  11993. get: function () {
  11994. return this._vrExclusivePointerMode;
  11995. },
  11996. enumerable: true,
  11997. configurable: true
  11998. });
  11999. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12000. /**
  12001. * Gets a boolean indicating that the engine supports uniform buffers
  12002. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12003. */
  12004. get: function () {
  12005. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12006. },
  12007. enumerable: true,
  12008. configurable: true
  12009. });
  12010. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12011. /**
  12012. * Gets a boolean indicating that only power of 2 textures are supported
  12013. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12014. */
  12015. get: function () {
  12016. return this._webGLVersion < 2 || this.forcePOTTextures;
  12017. },
  12018. enumerable: true,
  12019. configurable: true
  12020. });
  12021. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12022. /**
  12023. * Gets the performance monitor attached to this engine
  12024. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12025. */
  12026. get: function () {
  12027. return this._performanceMonitor;
  12028. },
  12029. enumerable: true,
  12030. configurable: true
  12031. });
  12032. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12033. /**
  12034. * Gets the list of texture formats supported
  12035. */
  12036. get: function () {
  12037. return this._texturesSupported;
  12038. },
  12039. enumerable: true,
  12040. configurable: true
  12041. });
  12042. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12043. /**
  12044. * Gets the list of texture formats in use
  12045. */
  12046. get: function () {
  12047. return this._textureFormatInUse;
  12048. },
  12049. enumerable: true,
  12050. configurable: true
  12051. });
  12052. Object.defineProperty(Engine.prototype, "currentViewport", {
  12053. /**
  12054. * Gets the current viewport
  12055. */
  12056. get: function () {
  12057. return this._cachedViewport;
  12058. },
  12059. enumerable: true,
  12060. configurable: true
  12061. });
  12062. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12063. /**
  12064. * Gets the default empty texture
  12065. */
  12066. get: function () {
  12067. if (!this._emptyTexture) {
  12068. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12069. }
  12070. return this._emptyTexture;
  12071. },
  12072. enumerable: true,
  12073. configurable: true
  12074. });
  12075. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12076. /**
  12077. * Gets the default empty 3D texture
  12078. */
  12079. get: function () {
  12080. if (!this._emptyTexture3D) {
  12081. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12082. }
  12083. return this._emptyTexture3D;
  12084. },
  12085. enumerable: true,
  12086. configurable: true
  12087. });
  12088. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12089. /**
  12090. * Gets the default empty cube texture
  12091. */
  12092. get: function () {
  12093. if (!this._emptyCubeTexture) {
  12094. var faceData = new Uint8Array(4);
  12095. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12096. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12097. }
  12098. return this._emptyCubeTexture;
  12099. },
  12100. enumerable: true,
  12101. configurable: true
  12102. });
  12103. Engine.prototype._rebuildInternalTextures = function () {
  12104. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12105. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12106. var internalTexture = currentState_1[_i];
  12107. internalTexture._rebuild();
  12108. }
  12109. };
  12110. Engine.prototype._rebuildEffects = function () {
  12111. for (var key in this._compiledEffects) {
  12112. var effect = this._compiledEffects[key];
  12113. effect._prepareEffect();
  12114. }
  12115. BABYLON.Effect.ResetCache();
  12116. };
  12117. Engine.prototype._rebuildBuffers = function () {
  12118. // Index / Vertex
  12119. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12120. var scene = _a[_i];
  12121. scene.resetCachedMaterial();
  12122. scene._rebuildGeometries();
  12123. scene._rebuildTextures();
  12124. }
  12125. // Uniforms
  12126. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12127. var uniformBuffer = _c[_b];
  12128. uniformBuffer._rebuild();
  12129. }
  12130. };
  12131. Engine.prototype._initGLContext = function () {
  12132. // Caps
  12133. this._caps = new EngineCapabilities();
  12134. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12135. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12136. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12137. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12138. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12139. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12140. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12141. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12142. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12143. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12144. // Infos
  12145. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12146. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12147. if (rendererInfo != null) {
  12148. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12149. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12150. }
  12151. if (!this._glVendor) {
  12152. this._glVendor = "Unknown vendor";
  12153. }
  12154. if (!this._glRenderer) {
  12155. this._glRenderer = "Unknown renderer";
  12156. }
  12157. // Constants
  12158. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12159. if (this._gl.RGBA16F !== 0x881A) {
  12160. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12161. }
  12162. if (this._gl.RGBA32F !== 0x8814) {
  12163. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12164. }
  12165. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12166. this._gl.DEPTH24_STENCIL8 = 35056;
  12167. }
  12168. // Extensions
  12169. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12170. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12171. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12172. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12173. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12174. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12175. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12176. 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');
  12177. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12178. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12179. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12180. this._caps.highPrecisionShaderSupported = true;
  12181. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12182. if (this._caps.timerQuery) {
  12183. if (this._webGLVersion === 1) {
  12184. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12185. }
  12186. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12187. }
  12188. // Checks if some of the format renders first to allow the use of webgl inspector.
  12189. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12190. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12191. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12192. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12193. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12194. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12195. if (this._webGLVersion > 1) {
  12196. this._gl.HALF_FLOAT_OES = 0x140B;
  12197. }
  12198. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12199. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12200. // Draw buffers
  12201. if (this._webGLVersion > 1) {
  12202. this._caps.drawBuffersExtension = true;
  12203. }
  12204. else {
  12205. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12206. if (drawBuffersExtension !== null) {
  12207. this._caps.drawBuffersExtension = true;
  12208. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12209. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12210. for (var i = 0; i < 16; i++) {
  12211. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12212. }
  12213. }
  12214. else {
  12215. this._caps.drawBuffersExtension = false;
  12216. }
  12217. }
  12218. // Depth Texture
  12219. if (this._webGLVersion > 1) {
  12220. this._caps.depthTextureExtension = true;
  12221. }
  12222. else {
  12223. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12224. if (depthTextureExtension != null) {
  12225. this._caps.depthTextureExtension = true;
  12226. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12227. }
  12228. }
  12229. // Vertex array object
  12230. if (this._webGLVersion > 1) {
  12231. this._caps.vertexArrayObject = true;
  12232. }
  12233. else {
  12234. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12235. if (vertexArrayObjectExtension != null) {
  12236. this._caps.vertexArrayObject = true;
  12237. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12238. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12239. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12240. }
  12241. else {
  12242. this._caps.vertexArrayObject = false;
  12243. }
  12244. }
  12245. // Instances count
  12246. if (this._webGLVersion > 1) {
  12247. this._caps.instancedArrays = true;
  12248. }
  12249. else {
  12250. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12251. if (instanceExtension != null) {
  12252. this._caps.instancedArrays = true;
  12253. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12254. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12255. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12256. }
  12257. else {
  12258. this._caps.instancedArrays = false;
  12259. }
  12260. }
  12261. // Intelligently add supported compressed formats in order to check for.
  12262. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12263. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12264. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12265. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12266. if (this._caps.astc)
  12267. this.texturesSupported.push('-astc.ktx');
  12268. if (this._caps.s3tc)
  12269. this.texturesSupported.push('-dxt.ktx');
  12270. if (this._caps.pvrtc)
  12271. this.texturesSupported.push('-pvrtc.ktx');
  12272. if (this._caps.etc2)
  12273. this.texturesSupported.push('-etc2.ktx');
  12274. if (this._caps.etc1)
  12275. this.texturesSupported.push('-etc1.ktx');
  12276. if (this._gl.getShaderPrecisionFormat) {
  12277. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12278. if (highp) {
  12279. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12280. }
  12281. }
  12282. // Depth buffer
  12283. this.setDepthBuffer(true);
  12284. this.setDepthFunctionToLessOrEqual();
  12285. this.setDepthWrite(true);
  12286. // Texture maps
  12287. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12288. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12289. this._nextFreeTextureSlots.push(slot);
  12290. }
  12291. };
  12292. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12293. /**
  12294. * Gets version of the current webGL context
  12295. */
  12296. get: function () {
  12297. return this._webGLVersion;
  12298. },
  12299. enumerable: true,
  12300. configurable: true
  12301. });
  12302. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12303. /**
  12304. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12305. */
  12306. get: function () {
  12307. return this._isStencilEnable;
  12308. },
  12309. enumerable: true,
  12310. configurable: true
  12311. });
  12312. Engine.prototype._prepareWorkingCanvas = function () {
  12313. if (this._workingCanvas) {
  12314. return;
  12315. }
  12316. this._workingCanvas = document.createElement("canvas");
  12317. var context = this._workingCanvas.getContext("2d");
  12318. if (context) {
  12319. this._workingContext = context;
  12320. }
  12321. };
  12322. /**
  12323. * Reset the texture cache to empty state
  12324. */
  12325. Engine.prototype.resetTextureCache = function () {
  12326. for (var key in this._boundTexturesCache) {
  12327. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12328. continue;
  12329. }
  12330. var boundTexture = this._boundTexturesCache[key];
  12331. if (boundTexture) {
  12332. this._removeDesignatedSlot(boundTexture);
  12333. }
  12334. this._boundTexturesCache[key] = null;
  12335. }
  12336. if (!this.disableTextureBindingOptimization) {
  12337. this._nextFreeTextureSlots = [];
  12338. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12339. this._nextFreeTextureSlots.push(slot);
  12340. }
  12341. }
  12342. this._currentTextureChannel = -1;
  12343. };
  12344. /**
  12345. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12346. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12347. * @returns true if engine is in deterministic lock step mode
  12348. */
  12349. Engine.prototype.isDeterministicLockStep = function () {
  12350. return this._deterministicLockstep;
  12351. };
  12352. /**
  12353. * Gets the max steps when engine is running in deterministic lock step
  12354. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12355. * @returns the max steps
  12356. */
  12357. Engine.prototype.getLockstepMaxSteps = function () {
  12358. return this._lockstepMaxSteps;
  12359. };
  12360. /**
  12361. * Gets an object containing information about the current webGL context
  12362. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12363. */
  12364. Engine.prototype.getGlInfo = function () {
  12365. return {
  12366. vendor: this._glVendor,
  12367. renderer: this._glRenderer,
  12368. version: this._glVersion
  12369. };
  12370. };
  12371. /**
  12372. * Gets current aspect ratio
  12373. * @param camera defines the camera to use to get the aspect ratio
  12374. * @param useScreen defines if screen size must be used (or the current render target if any)
  12375. * @returns a number defining the aspect ratio
  12376. */
  12377. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12378. if (useScreen === void 0) { useScreen = false; }
  12379. var viewport = camera.viewport;
  12380. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12381. };
  12382. /**
  12383. * Gets the current render width
  12384. * @param useScreen defines if screen size must be used (or the current render target if any)
  12385. * @returns a number defining the current render width
  12386. */
  12387. Engine.prototype.getRenderWidth = function (useScreen) {
  12388. if (useScreen === void 0) { useScreen = false; }
  12389. if (!useScreen && this._currentRenderTarget) {
  12390. return this._currentRenderTarget.width;
  12391. }
  12392. return this._gl.drawingBufferWidth;
  12393. };
  12394. /**
  12395. * Gets the current render height
  12396. * @param useScreen defines if screen size must be used (or the current render target if any)
  12397. * @returns a number defining the current render height
  12398. */
  12399. Engine.prototype.getRenderHeight = function (useScreen) {
  12400. if (useScreen === void 0) { useScreen = false; }
  12401. if (!useScreen && this._currentRenderTarget) {
  12402. return this._currentRenderTarget.height;
  12403. }
  12404. return this._gl.drawingBufferHeight;
  12405. };
  12406. /**
  12407. * Gets the HTML canvas attached with the current webGL context
  12408. * @returns a HTML canvas
  12409. */
  12410. Engine.prototype.getRenderingCanvas = function () {
  12411. return this._renderingCanvas;
  12412. };
  12413. /**
  12414. * Gets the client rect of the HTML canvas attached with the current webGL context
  12415. * @returns a client rectanglee
  12416. */
  12417. Engine.prototype.getRenderingCanvasClientRect = function () {
  12418. if (!this._renderingCanvas) {
  12419. return null;
  12420. }
  12421. return this._renderingCanvas.getBoundingClientRect();
  12422. };
  12423. /**
  12424. * Defines the hardware scaling level.
  12425. * By default the hardware scaling level is computed from the window device ratio.
  12426. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12427. * @param level defines the level to use
  12428. */
  12429. Engine.prototype.setHardwareScalingLevel = function (level) {
  12430. this._hardwareScalingLevel = level;
  12431. this.resize();
  12432. };
  12433. /**
  12434. * Gets the current hardware scaling level.
  12435. * By default the hardware scaling level is computed from the window device ratio.
  12436. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  12437. * @returns a number indicating the current hardware scaling level
  12438. */
  12439. Engine.prototype.getHardwareScalingLevel = function () {
  12440. return this._hardwareScalingLevel;
  12441. };
  12442. /**
  12443. * Gets the list of loaded textures
  12444. * @returns an array containing all loaded textures
  12445. */
  12446. Engine.prototype.getLoadedTexturesCache = function () {
  12447. return this._internalTexturesCache;
  12448. };
  12449. /**
  12450. * Gets the object containing all engine capabilities
  12451. * @returns the EngineCapabilities object
  12452. */
  12453. Engine.prototype.getCaps = function () {
  12454. return this._caps;
  12455. };
  12456. Object.defineProperty(Engine.prototype, "drawCalls", {
  12457. /** @hidden */
  12458. get: function () {
  12459. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12460. return 0;
  12461. },
  12462. enumerable: true,
  12463. configurable: true
  12464. });
  12465. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12466. /** @hidden */
  12467. get: function () {
  12468. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12469. return null;
  12470. },
  12471. enumerable: true,
  12472. configurable: true
  12473. });
  12474. /**
  12475. * Gets the current depth function
  12476. * @returns a number defining the depth function
  12477. */
  12478. Engine.prototype.getDepthFunction = function () {
  12479. return this._depthCullingState.depthFunc;
  12480. };
  12481. /**
  12482. * Sets the current depth function
  12483. * @param depthFunc defines the function to use
  12484. */
  12485. Engine.prototype.setDepthFunction = function (depthFunc) {
  12486. this._depthCullingState.depthFunc = depthFunc;
  12487. };
  12488. /**
  12489. * Sets the current depth function to GREATER
  12490. */
  12491. Engine.prototype.setDepthFunctionToGreater = function () {
  12492. this._depthCullingState.depthFunc = this._gl.GREATER;
  12493. };
  12494. /**
  12495. * Sets the current depth function to GEQUAL
  12496. */
  12497. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12498. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12499. };
  12500. /**
  12501. * Sets the current depth function to LESS
  12502. */
  12503. Engine.prototype.setDepthFunctionToLess = function () {
  12504. this._depthCullingState.depthFunc = this._gl.LESS;
  12505. };
  12506. /**
  12507. * Sets the current depth function to LEQUAL
  12508. */
  12509. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12510. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12511. };
  12512. /**
  12513. * Gets a boolean indicating if stencil buffer is enabled
  12514. * @returns the current stencil buffer state
  12515. */
  12516. Engine.prototype.getStencilBuffer = function () {
  12517. return this._stencilState.stencilTest;
  12518. };
  12519. /**
  12520. * Enable or disable the stencil buffer
  12521. * @param enable defines if the stencil buffer must be enabled or disabled
  12522. */
  12523. Engine.prototype.setStencilBuffer = function (enable) {
  12524. this._stencilState.stencilTest = enable;
  12525. };
  12526. /**
  12527. * Gets the current stencil mask
  12528. * @returns a number defining the new stencil mask to use
  12529. */
  12530. Engine.prototype.getStencilMask = function () {
  12531. return this._stencilState.stencilMask;
  12532. };
  12533. /**
  12534. * Sets the current stencil mask
  12535. * @param mask defines the new stencil mask to use
  12536. */
  12537. Engine.prototype.setStencilMask = function (mask) {
  12538. this._stencilState.stencilMask = mask;
  12539. };
  12540. /**
  12541. * Gets the current stencil function
  12542. * @returns a number defining the stencil function to use
  12543. */
  12544. Engine.prototype.getStencilFunction = function () {
  12545. return this._stencilState.stencilFunc;
  12546. };
  12547. /**
  12548. * Gets the current stencil reference value
  12549. * @returns a number defining the stencil reference value to use
  12550. */
  12551. Engine.prototype.getStencilFunctionReference = function () {
  12552. return this._stencilState.stencilFuncRef;
  12553. };
  12554. /**
  12555. * Gets the current stencil mask
  12556. * @returns a number defining the stencil mask to use
  12557. */
  12558. Engine.prototype.getStencilFunctionMask = function () {
  12559. return this._stencilState.stencilFuncMask;
  12560. };
  12561. /**
  12562. * Sets the current stencil function
  12563. * @param stencilFunc defines the new stencil function to use
  12564. */
  12565. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12566. this._stencilState.stencilFunc = stencilFunc;
  12567. };
  12568. /**
  12569. * Sets the current stencil reference
  12570. * @param reference defines the new stencil reference to use
  12571. */
  12572. Engine.prototype.setStencilFunctionReference = function (reference) {
  12573. this._stencilState.stencilFuncRef = reference;
  12574. };
  12575. /**
  12576. * Sets the current stencil mask
  12577. * @param mask defines the new stencil mask to use
  12578. */
  12579. Engine.prototype.setStencilFunctionMask = function (mask) {
  12580. this._stencilState.stencilFuncMask = mask;
  12581. };
  12582. /**
  12583. * Gets the current stencil operation when stencil fails
  12584. * @returns a number defining stencil operation to use when stencil fails
  12585. */
  12586. Engine.prototype.getStencilOperationFail = function () {
  12587. return this._stencilState.stencilOpStencilFail;
  12588. };
  12589. /**
  12590. * Gets the current stencil operation when depth fails
  12591. * @returns a number defining stencil operation to use when depth fails
  12592. */
  12593. Engine.prototype.getStencilOperationDepthFail = function () {
  12594. return this._stencilState.stencilOpDepthFail;
  12595. };
  12596. /**
  12597. * Gets the current stencil operation when stencil passes
  12598. * @returns a number defining stencil operation to use when stencil passes
  12599. */
  12600. Engine.prototype.getStencilOperationPass = function () {
  12601. return this._stencilState.stencilOpStencilDepthPass;
  12602. };
  12603. /**
  12604. * Sets the stencil operation to use when stencil fails
  12605. * @param operation defines the stencil operation to use when stencil fails
  12606. */
  12607. Engine.prototype.setStencilOperationFail = function (operation) {
  12608. this._stencilState.stencilOpStencilFail = operation;
  12609. };
  12610. /**
  12611. * Sets the stencil operation to use when depth fails
  12612. * @param operation defines the stencil operation to use when depth fails
  12613. */
  12614. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12615. this._stencilState.stencilOpDepthFail = operation;
  12616. };
  12617. /**
  12618. * Sets the stencil operation to use when stencil passes
  12619. * @param operation defines the stencil operation to use when stencil passes
  12620. */
  12621. Engine.prototype.setStencilOperationPass = function (operation) {
  12622. this._stencilState.stencilOpStencilDepthPass = operation;
  12623. };
  12624. /**
  12625. * Sets a boolean indicating if the dithering state is enabled or disabled
  12626. * @param value defines the dithering state
  12627. */
  12628. Engine.prototype.setDitheringState = function (value) {
  12629. if (value) {
  12630. this._gl.enable(this._gl.DITHER);
  12631. }
  12632. else {
  12633. this._gl.disable(this._gl.DITHER);
  12634. }
  12635. };
  12636. /**
  12637. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12638. * @param value defines the rasterizer state
  12639. */
  12640. Engine.prototype.setRasterizerState = function (value) {
  12641. if (value) {
  12642. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12643. }
  12644. else {
  12645. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12646. }
  12647. };
  12648. /**
  12649. * stop executing a render loop function and remove it from the execution array
  12650. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12651. */
  12652. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12653. if (!renderFunction) {
  12654. this._activeRenderLoops = [];
  12655. return;
  12656. }
  12657. var index = this._activeRenderLoops.indexOf(renderFunction);
  12658. if (index >= 0) {
  12659. this._activeRenderLoops.splice(index, 1);
  12660. }
  12661. };
  12662. /** @hidden */
  12663. Engine.prototype._renderLoop = function () {
  12664. if (!this._contextWasLost) {
  12665. var shouldRender = true;
  12666. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12667. shouldRender = false;
  12668. }
  12669. if (shouldRender) {
  12670. // Start new frame
  12671. this.beginFrame();
  12672. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12673. var renderFunction = this._activeRenderLoops[index];
  12674. renderFunction();
  12675. }
  12676. // Present
  12677. this.endFrame();
  12678. }
  12679. }
  12680. if (this._activeRenderLoops.length > 0) {
  12681. // Register new frame
  12682. var requester = null;
  12683. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12684. requester = this._vrDisplay;
  12685. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12686. }
  12687. else {
  12688. this._renderingQueueLaunched = false;
  12689. }
  12690. };
  12691. /**
  12692. * Register and execute a render loop. The engine can have more than one render function
  12693. * @param renderFunction defines the function to continuously execute
  12694. */
  12695. Engine.prototype.runRenderLoop = function (renderFunction) {
  12696. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12697. return;
  12698. }
  12699. this._activeRenderLoops.push(renderFunction);
  12700. if (!this._renderingQueueLaunched) {
  12701. this._renderingQueueLaunched = true;
  12702. this._bindedRenderFunction = this._renderLoop.bind(this);
  12703. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12704. }
  12705. };
  12706. /**
  12707. * Toggle full screen mode
  12708. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12709. * @param options defines an option object to be sent to the requestFullscreen function
  12710. */
  12711. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12712. if (this.isFullscreen) {
  12713. BABYLON.Tools.ExitFullscreen();
  12714. }
  12715. else {
  12716. this._pointerLockRequested = requestPointerLock;
  12717. if (this._renderingCanvas) {
  12718. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12719. }
  12720. }
  12721. };
  12722. /**
  12723. * Clear the current render buffer or the current render target (if any is set up)
  12724. * @param color defines the color to use
  12725. * @param backBuffer defines if the back buffer must be cleared
  12726. * @param depth defines if the depth buffer must be cleared
  12727. * @param stencil defines if the stencil buffer must be cleared
  12728. */
  12729. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12730. if (stencil === void 0) { stencil = false; }
  12731. this.applyStates();
  12732. var mode = 0;
  12733. if (backBuffer && color) {
  12734. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12735. mode |= this._gl.COLOR_BUFFER_BIT;
  12736. }
  12737. if (depth) {
  12738. this._gl.clearDepth(1.0);
  12739. mode |= this._gl.DEPTH_BUFFER_BIT;
  12740. }
  12741. if (stencil) {
  12742. this._gl.clearStencil(0);
  12743. mode |= this._gl.STENCIL_BUFFER_BIT;
  12744. }
  12745. this._gl.clear(mode);
  12746. };
  12747. /**
  12748. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12749. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12750. * @param y defines the y-coordinate of the corner of the clear rectangle
  12751. * @param width defines the width of the clear rectangle
  12752. * @param height defines the height of the clear rectangle
  12753. * @param clearColor defines the clear color
  12754. */
  12755. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12756. var gl = this._gl;
  12757. // Save state
  12758. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12759. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12760. // Change state
  12761. gl.enable(gl.SCISSOR_TEST);
  12762. gl.scissor(x, y, width, height);
  12763. // Clear
  12764. this.clear(clearColor, true, true, true);
  12765. // Restore state
  12766. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12767. if (curScissor === true) {
  12768. gl.enable(gl.SCISSOR_TEST);
  12769. }
  12770. else {
  12771. gl.disable(gl.SCISSOR_TEST);
  12772. }
  12773. };
  12774. /**
  12775. * Set the WebGL's viewport
  12776. * @param viewport defines the viewport element to be used
  12777. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12778. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12779. */
  12780. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12781. var width = requiredWidth || this.getRenderWidth();
  12782. var height = requiredHeight || this.getRenderHeight();
  12783. var x = viewport.x || 0;
  12784. var y = viewport.y || 0;
  12785. this._cachedViewport = viewport;
  12786. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12787. };
  12788. /**
  12789. * Directly set the WebGL Viewport
  12790. * @param x defines the x coordinate of the viewport (in screen space)
  12791. * @param y defines the y coordinate of the viewport (in screen space)
  12792. * @param width defines the width of the viewport (in screen space)
  12793. * @param height defines the height of the viewport (in screen space)
  12794. * @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
  12795. */
  12796. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12797. var currentViewport = this._cachedViewport;
  12798. this._cachedViewport = null;
  12799. this._gl.viewport(x, y, width, height);
  12800. return currentViewport;
  12801. };
  12802. /**
  12803. * Begin a new frame
  12804. */
  12805. Engine.prototype.beginFrame = function () {
  12806. this.onBeginFrameObservable.notifyObservers(this);
  12807. this._measureFps();
  12808. };
  12809. /**
  12810. * Enf the current frame
  12811. */
  12812. Engine.prototype.endFrame = function () {
  12813. // Force a flush in case we are using a bad OS.
  12814. if (this._badOS) {
  12815. this.flushFramebuffer();
  12816. }
  12817. // Submit frame to the vr device, if enabled
  12818. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12819. // TODO: We should only submit the frame if we read frameData successfully.
  12820. this._vrDisplay.submitFrame();
  12821. }
  12822. this.onEndFrameObservable.notifyObservers(this);
  12823. };
  12824. /**
  12825. * Resize the view according to the canvas' size
  12826. */
  12827. Engine.prototype.resize = function () {
  12828. // We're not resizing the size of the canvas while in VR mode & presenting
  12829. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12830. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12831. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12832. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12833. }
  12834. };
  12835. /**
  12836. * Force a specific size of the canvas
  12837. * @param width defines the new canvas' width
  12838. * @param height defines the new canvas' height
  12839. */
  12840. Engine.prototype.setSize = function (width, height) {
  12841. if (!this._renderingCanvas) {
  12842. return;
  12843. }
  12844. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12845. return;
  12846. }
  12847. this._renderingCanvas.width = width;
  12848. this._renderingCanvas.height = height;
  12849. for (var index = 0; index < this.scenes.length; index++) {
  12850. var scene = this.scenes[index];
  12851. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12852. var cam = scene.cameras[camIndex];
  12853. cam._currentRenderId = 0;
  12854. }
  12855. }
  12856. if (this.onResizeObservable.hasObservers) {
  12857. this.onResizeObservable.notifyObservers(this);
  12858. }
  12859. };
  12860. // WebVR functions
  12861. /**
  12862. * Gets a boolean indicating if a webVR device was detected
  12863. * @returns true if a webVR device was detected
  12864. */
  12865. Engine.prototype.isVRDevicePresent = function () {
  12866. return !!this._vrDisplay;
  12867. };
  12868. /**
  12869. * Gets the current webVR device
  12870. * @returns the current webVR device (or null)
  12871. */
  12872. Engine.prototype.getVRDevice = function () {
  12873. return this._vrDisplay;
  12874. };
  12875. /**
  12876. * Initializes a webVR display and starts listening to display change events
  12877. * The onVRDisplayChangedObservable will be notified upon these changes
  12878. * @returns The onVRDisplayChangedObservable
  12879. */
  12880. Engine.prototype.initWebVR = function () {
  12881. this.initWebVRAsync();
  12882. return this.onVRDisplayChangedObservable;
  12883. };
  12884. /**
  12885. * Initializes a webVR display and starts listening to display change events
  12886. * The onVRDisplayChangedObservable will be notified upon these changes
  12887. * @returns A promise containing a VRDisplay and if vr is supported
  12888. */
  12889. Engine.prototype.initWebVRAsync = function () {
  12890. var _this = this;
  12891. var notifyObservers = function () {
  12892. var eventArgs = {
  12893. vrDisplay: _this._vrDisplay,
  12894. vrSupported: _this._vrSupported
  12895. };
  12896. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12897. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12898. };
  12899. if (!this._onVrDisplayConnect) {
  12900. this._onVrDisplayConnect = function (event) {
  12901. _this._vrDisplay = event.display;
  12902. notifyObservers();
  12903. };
  12904. this._onVrDisplayDisconnect = function () {
  12905. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12906. _this._vrDisplay = undefined;
  12907. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12908. notifyObservers();
  12909. };
  12910. this._onVrDisplayPresentChange = function () {
  12911. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12912. };
  12913. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12914. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12915. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12916. }
  12917. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12918. this._webVRInitPromise.then(notifyObservers);
  12919. return this._webVRInitPromise;
  12920. };
  12921. /**
  12922. * Call this function to switch to webVR mode
  12923. * Will do nothing if webVR is not supported or if there is no webVR device
  12924. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12925. */
  12926. Engine.prototype.enableVR = function () {
  12927. var _this = this;
  12928. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12929. var onResolved = function () {
  12930. _this.onVRRequestPresentComplete.notifyObservers(true);
  12931. _this._onVRFullScreenTriggered();
  12932. };
  12933. var onRejected = function () {
  12934. _this.onVRRequestPresentComplete.notifyObservers(false);
  12935. };
  12936. this.onVRRequestPresentStart.notifyObservers(this);
  12937. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12938. }
  12939. };
  12940. /**
  12941. * Call this function to leave webVR mode
  12942. * Will do nothing if webVR is not supported or if there is no webVR device
  12943. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12944. */
  12945. Engine.prototype.disableVR = function () {
  12946. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12947. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12948. }
  12949. };
  12950. Engine.prototype._getVRDisplaysAsync = function () {
  12951. var _this = this;
  12952. return new Promise(function (res, rej) {
  12953. if (navigator.getVRDisplays) {
  12954. navigator.getVRDisplays().then(function (devices) {
  12955. _this._vrSupported = true;
  12956. // note that devices may actually be an empty array. This is fine;
  12957. // we expect this._vrDisplay to be undefined in this case.
  12958. _this._vrDisplay = devices[0];
  12959. res({
  12960. vrDisplay: _this._vrDisplay,
  12961. vrSupported: _this._vrSupported
  12962. });
  12963. });
  12964. }
  12965. else {
  12966. _this._vrDisplay = undefined;
  12967. _this._vrSupported = false;
  12968. res({
  12969. vrDisplay: _this._vrDisplay,
  12970. vrSupported: _this._vrSupported
  12971. });
  12972. }
  12973. });
  12974. };
  12975. /**
  12976. * Binds the frame buffer to the specified texture.
  12977. * @param texture The texture to render to or null for the default canvas
  12978. * @param faceIndex The face of the texture to render to in case of cube texture
  12979. * @param requiredWidth The width of the target to render to
  12980. * @param requiredHeight The height of the target to render to
  12981. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12982. * @param depthStencilTexture The depth stencil texture to use to render
  12983. */
  12984. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12985. if (this._currentRenderTarget) {
  12986. this.unBindFramebuffer(this._currentRenderTarget);
  12987. }
  12988. this._currentRenderTarget = texture;
  12989. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12990. var gl = this._gl;
  12991. if (texture.isCube) {
  12992. if (faceIndex === undefined) {
  12993. faceIndex = 0;
  12994. }
  12995. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12996. if (depthStencilTexture) {
  12997. if (depthStencilTexture._generateStencilBuffer) {
  12998. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12999. }
  13000. else {
  13001. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13002. }
  13003. }
  13004. }
  13005. if (this._cachedViewport && !forceFullscreenViewport) {
  13006. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13007. }
  13008. else {
  13009. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  13010. }
  13011. this.wipeCaches();
  13012. };
  13013. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13014. if (this._currentFramebuffer !== framebuffer) {
  13015. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13016. this._currentFramebuffer = framebuffer;
  13017. }
  13018. };
  13019. /**
  13020. * Unbind the current render target texture from the webGL context
  13021. * @param texture defines the render target texture to unbind
  13022. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13023. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13024. */
  13025. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13026. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13027. this._currentRenderTarget = null;
  13028. // If MSAA, we need to bitblt back to main texture
  13029. var gl = this._gl;
  13030. if (texture._MSAAFramebuffer) {
  13031. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13032. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13033. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13034. }
  13035. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13036. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13037. gl.generateMipmap(gl.TEXTURE_2D);
  13038. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13039. }
  13040. if (onBeforeUnbind) {
  13041. if (texture._MSAAFramebuffer) {
  13042. // Bind the correct framebuffer
  13043. this.bindUnboundFramebuffer(texture._framebuffer);
  13044. }
  13045. onBeforeUnbind();
  13046. }
  13047. this.bindUnboundFramebuffer(null);
  13048. };
  13049. /**
  13050. * Unbind a list of render target textures from the webGL context
  13051. * This is used only when drawBuffer extension or webGL2 are active
  13052. * @param textures defines the render target textures to unbind
  13053. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13054. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13055. */
  13056. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13057. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13058. this._currentRenderTarget = null;
  13059. // If MSAA, we need to bitblt back to main texture
  13060. var gl = this._gl;
  13061. if (textures[0]._MSAAFramebuffer) {
  13062. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13063. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13064. var attachments = textures[0]._attachments;
  13065. if (!attachments) {
  13066. attachments = new Array(textures.length);
  13067. textures[0]._attachments = attachments;
  13068. }
  13069. for (var i = 0; i < textures.length; i++) {
  13070. var texture = textures[i];
  13071. for (var j = 0; j < attachments.length; j++) {
  13072. attachments[j] = gl.NONE;
  13073. }
  13074. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13075. gl.readBuffer(attachments[i]);
  13076. gl.drawBuffers(attachments);
  13077. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13078. }
  13079. for (var i = 0; i < attachments.length; i++) {
  13080. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13081. }
  13082. gl.drawBuffers(attachments);
  13083. }
  13084. for (var i = 0; i < textures.length; i++) {
  13085. var texture = textures[i];
  13086. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13087. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13088. gl.generateMipmap(gl.TEXTURE_2D);
  13089. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13090. }
  13091. }
  13092. if (onBeforeUnbind) {
  13093. if (textures[0]._MSAAFramebuffer) {
  13094. // Bind the correct framebuffer
  13095. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13096. }
  13097. onBeforeUnbind();
  13098. }
  13099. this.bindUnboundFramebuffer(null);
  13100. };
  13101. /**
  13102. * Force the mipmap generation for the given render target texture
  13103. * @param texture defines the render target texture to use
  13104. */
  13105. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13106. if (texture.generateMipMaps) {
  13107. var gl = this._gl;
  13108. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13109. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13110. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13111. }
  13112. };
  13113. /**
  13114. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13115. */
  13116. Engine.prototype.flushFramebuffer = function () {
  13117. this._gl.flush();
  13118. };
  13119. /**
  13120. * Unbind the current render target and bind the default framebuffer
  13121. */
  13122. Engine.prototype.restoreDefaultFramebuffer = function () {
  13123. if (this._currentRenderTarget) {
  13124. this.unBindFramebuffer(this._currentRenderTarget);
  13125. }
  13126. else {
  13127. this.bindUnboundFramebuffer(null);
  13128. }
  13129. if (this._cachedViewport) {
  13130. this.setViewport(this._cachedViewport);
  13131. }
  13132. this.wipeCaches();
  13133. };
  13134. // UBOs
  13135. /**
  13136. * Create an uniform buffer
  13137. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13138. * @param elements defines the content of the uniform buffer
  13139. * @returns the webGL uniform buffer
  13140. */
  13141. Engine.prototype.createUniformBuffer = function (elements) {
  13142. var ubo = this._gl.createBuffer();
  13143. if (!ubo) {
  13144. throw new Error("Unable to create uniform buffer");
  13145. }
  13146. this.bindUniformBuffer(ubo);
  13147. if (elements instanceof Float32Array) {
  13148. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13149. }
  13150. else {
  13151. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13152. }
  13153. this.bindUniformBuffer(null);
  13154. ubo.references = 1;
  13155. return ubo;
  13156. };
  13157. /**
  13158. * Create a dynamic uniform buffer
  13159. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13160. * @param elements defines the content of the uniform buffer
  13161. * @returns the webGL uniform buffer
  13162. */
  13163. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13164. var ubo = this._gl.createBuffer();
  13165. if (!ubo) {
  13166. throw new Error("Unable to create dynamic uniform buffer");
  13167. }
  13168. this.bindUniformBuffer(ubo);
  13169. if (elements instanceof Float32Array) {
  13170. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13171. }
  13172. else {
  13173. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13174. }
  13175. this.bindUniformBuffer(null);
  13176. ubo.references = 1;
  13177. return ubo;
  13178. };
  13179. /**
  13180. * Update an existing uniform buffer
  13181. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13182. * @param uniformBuffer defines the target uniform buffer
  13183. * @param elements defines the content to update
  13184. * @param offset defines the offset in the uniform buffer where update should start
  13185. * @param count defines the size of the data to update
  13186. */
  13187. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13188. this.bindUniformBuffer(uniformBuffer);
  13189. if (offset === undefined) {
  13190. offset = 0;
  13191. }
  13192. if (count === undefined) {
  13193. if (elements instanceof Float32Array) {
  13194. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13195. }
  13196. else {
  13197. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13198. }
  13199. }
  13200. else {
  13201. if (elements instanceof Float32Array) {
  13202. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13203. }
  13204. else {
  13205. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13206. }
  13207. }
  13208. this.bindUniformBuffer(null);
  13209. };
  13210. // VBOs
  13211. Engine.prototype._resetVertexBufferBinding = function () {
  13212. this.bindArrayBuffer(null);
  13213. this._cachedVertexBuffers = null;
  13214. };
  13215. /**
  13216. * Creates a vertex buffer
  13217. * @param data the data for the vertex buffer
  13218. * @returns the new WebGL static buffer
  13219. */
  13220. Engine.prototype.createVertexBuffer = function (data) {
  13221. var vbo = this._gl.createBuffer();
  13222. if (!vbo) {
  13223. throw new Error("Unable to create vertex buffer");
  13224. }
  13225. this.bindArrayBuffer(vbo);
  13226. if (data instanceof Array) {
  13227. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13228. }
  13229. else {
  13230. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13231. }
  13232. this._resetVertexBufferBinding();
  13233. vbo.references = 1;
  13234. return vbo;
  13235. };
  13236. /**
  13237. * Creates a dynamic vertex buffer
  13238. * @param data the data for the dynamic vertex buffer
  13239. * @returns the new WebGL dynamic buffer
  13240. */
  13241. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13242. var vbo = this._gl.createBuffer();
  13243. if (!vbo) {
  13244. throw new Error("Unable to create dynamic vertex buffer");
  13245. }
  13246. this.bindArrayBuffer(vbo);
  13247. if (data instanceof Array) {
  13248. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13249. }
  13250. else {
  13251. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13252. }
  13253. this._resetVertexBufferBinding();
  13254. vbo.references = 1;
  13255. return vbo;
  13256. };
  13257. /**
  13258. * Update a dynamic index buffer
  13259. * @param indexBuffer defines the target index buffer
  13260. * @param indices defines the data to update
  13261. * @param offset defines the offset in the target index buffer where update should start
  13262. */
  13263. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13264. if (offset === void 0) { offset = 0; }
  13265. // Force cache update
  13266. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13267. this.bindIndexBuffer(indexBuffer);
  13268. var arrayBuffer;
  13269. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13270. arrayBuffer = indices;
  13271. }
  13272. else {
  13273. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13274. }
  13275. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13276. this._resetIndexBufferBinding();
  13277. };
  13278. /**
  13279. * Updates a dynamic vertex buffer.
  13280. * @param vertexBuffer the vertex buffer to update
  13281. * @param data the data used to update the vertex buffer
  13282. * @param byteOffset the byte offset of the data
  13283. * @param byteLength the byte length of the data
  13284. */
  13285. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13286. this.bindArrayBuffer(vertexBuffer);
  13287. if (byteOffset === undefined) {
  13288. byteOffset = 0;
  13289. }
  13290. if (byteLength === undefined) {
  13291. if (data instanceof Array) {
  13292. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13293. }
  13294. else {
  13295. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13296. }
  13297. }
  13298. else {
  13299. if (data instanceof Array) {
  13300. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13301. }
  13302. else {
  13303. if (data instanceof ArrayBuffer) {
  13304. data = new Uint8Array(data, byteOffset, byteLength);
  13305. }
  13306. else {
  13307. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13308. }
  13309. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13310. }
  13311. }
  13312. this._resetVertexBufferBinding();
  13313. };
  13314. Engine.prototype._resetIndexBufferBinding = function () {
  13315. this.bindIndexBuffer(null);
  13316. this._cachedIndexBuffer = null;
  13317. };
  13318. /**
  13319. * Creates a new index buffer
  13320. * @param indices defines the content of the index buffer
  13321. * @param updatable defines if the index buffer must be updatable
  13322. * @returns a new webGL buffer
  13323. */
  13324. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13325. var vbo = this._gl.createBuffer();
  13326. if (!vbo) {
  13327. throw new Error("Unable to create index buffer");
  13328. }
  13329. this.bindIndexBuffer(vbo);
  13330. // Check for 32 bits indices
  13331. var arrayBuffer;
  13332. var need32Bits = false;
  13333. if (indices instanceof Uint16Array) {
  13334. arrayBuffer = indices;
  13335. }
  13336. else {
  13337. //check 32 bit support
  13338. if (this._caps.uintIndices) {
  13339. if (indices instanceof Uint32Array) {
  13340. arrayBuffer = indices;
  13341. need32Bits = true;
  13342. }
  13343. else {
  13344. //number[] or Int32Array, check if 32 bit is necessary
  13345. for (var index = 0; index < indices.length; index++) {
  13346. if (indices[index] > 65535) {
  13347. need32Bits = true;
  13348. break;
  13349. }
  13350. }
  13351. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13352. }
  13353. }
  13354. else {
  13355. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13356. arrayBuffer = new Uint16Array(indices);
  13357. }
  13358. }
  13359. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13360. this._resetIndexBufferBinding();
  13361. vbo.references = 1;
  13362. vbo.is32Bits = need32Bits;
  13363. return vbo;
  13364. };
  13365. /**
  13366. * Bind a webGL buffer to the webGL context
  13367. * @param buffer defines the buffer to bind
  13368. */
  13369. Engine.prototype.bindArrayBuffer = function (buffer) {
  13370. if (!this._vaoRecordInProgress) {
  13371. this._unbindVertexArrayObject();
  13372. }
  13373. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13374. };
  13375. /**
  13376. * Bind an uniform buffer to the current webGL context
  13377. * @param buffer defines the buffer to bind
  13378. */
  13379. Engine.prototype.bindUniformBuffer = function (buffer) {
  13380. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13381. };
  13382. /**
  13383. * Bind a buffer to the current webGL context at a given location
  13384. * @param buffer defines the buffer to bind
  13385. * @param location defines the index where to bind the buffer
  13386. */
  13387. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13388. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13389. };
  13390. /**
  13391. * Bind a specific block at a given index in a specific shader program
  13392. * @param shaderProgram defines the shader program
  13393. * @param blockName defines the block name
  13394. * @param index defines the index where to bind the block
  13395. */
  13396. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13397. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13398. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13399. };
  13400. ;
  13401. Engine.prototype.bindIndexBuffer = function (buffer) {
  13402. if (!this._vaoRecordInProgress) {
  13403. this._unbindVertexArrayObject();
  13404. }
  13405. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13406. };
  13407. Engine.prototype.bindBuffer = function (buffer, target) {
  13408. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13409. this._gl.bindBuffer(target, buffer);
  13410. this._currentBoundBuffer[target] = buffer;
  13411. }
  13412. };
  13413. /**
  13414. * update the bound buffer with the given data
  13415. * @param data defines the data to update
  13416. */
  13417. Engine.prototype.updateArrayBuffer = function (data) {
  13418. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13419. };
  13420. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13421. var pointer = this._currentBufferPointers[indx];
  13422. var changed = false;
  13423. if (!pointer.active) {
  13424. changed = true;
  13425. pointer.active = true;
  13426. pointer.index = indx;
  13427. pointer.size = size;
  13428. pointer.type = type;
  13429. pointer.normalized = normalized;
  13430. pointer.stride = stride;
  13431. pointer.offset = offset;
  13432. pointer.buffer = buffer;
  13433. }
  13434. else {
  13435. if (pointer.buffer !== buffer) {
  13436. pointer.buffer = buffer;
  13437. changed = true;
  13438. }
  13439. if (pointer.size !== size) {
  13440. pointer.size = size;
  13441. changed = true;
  13442. }
  13443. if (pointer.type !== type) {
  13444. pointer.type = type;
  13445. changed = true;
  13446. }
  13447. if (pointer.normalized !== normalized) {
  13448. pointer.normalized = normalized;
  13449. changed = true;
  13450. }
  13451. if (pointer.stride !== stride) {
  13452. pointer.stride = stride;
  13453. changed = true;
  13454. }
  13455. if (pointer.offset !== offset) {
  13456. pointer.offset = offset;
  13457. changed = true;
  13458. }
  13459. }
  13460. if (changed || this._vaoRecordInProgress) {
  13461. this.bindArrayBuffer(buffer);
  13462. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13463. }
  13464. };
  13465. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13466. if (indexBuffer == null) {
  13467. return;
  13468. }
  13469. if (this._cachedIndexBuffer !== indexBuffer) {
  13470. this._cachedIndexBuffer = indexBuffer;
  13471. this.bindIndexBuffer(indexBuffer);
  13472. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13473. }
  13474. };
  13475. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13476. var attributes = effect.getAttributesNames();
  13477. if (!this._vaoRecordInProgress) {
  13478. this._unbindVertexArrayObject();
  13479. }
  13480. this.unbindAllAttributes();
  13481. for (var index = 0; index < attributes.length; index++) {
  13482. var order = effect.getAttributeLocation(index);
  13483. if (order >= 0) {
  13484. var vertexBuffer = vertexBuffers[attributes[index]];
  13485. if (!vertexBuffer) {
  13486. continue;
  13487. }
  13488. this._gl.enableVertexAttribArray(order);
  13489. if (!this._vaoRecordInProgress) {
  13490. this._vertexAttribArraysEnabled[order] = true;
  13491. }
  13492. var buffer = vertexBuffer.getBuffer();
  13493. if (buffer) {
  13494. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13495. if (vertexBuffer.getIsInstanced()) {
  13496. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13497. if (!this._vaoRecordInProgress) {
  13498. this._currentInstanceLocations.push(order);
  13499. this._currentInstanceBuffers.push(buffer);
  13500. }
  13501. }
  13502. }
  13503. }
  13504. }
  13505. };
  13506. /**
  13507. * Records a vertex array object
  13508. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13509. * @param vertexBuffers defines the list of vertex buffers to store
  13510. * @param indexBuffer defines the index buffer to store
  13511. * @param effect defines the effect to store
  13512. * @returns the new vertex array object
  13513. */
  13514. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13515. var vao = this._gl.createVertexArray();
  13516. this._vaoRecordInProgress = true;
  13517. this._gl.bindVertexArray(vao);
  13518. this._mustWipeVertexAttributes = true;
  13519. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13520. this.bindIndexBuffer(indexBuffer);
  13521. this._vaoRecordInProgress = false;
  13522. this._gl.bindVertexArray(null);
  13523. return vao;
  13524. };
  13525. /**
  13526. * Bind a specific vertex array object
  13527. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13528. * @param vertexArrayObject defines the vertex array object to bind
  13529. * @param indexBuffer defines the index buffer to bind
  13530. */
  13531. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13532. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13533. this._cachedVertexArrayObject = vertexArrayObject;
  13534. this._gl.bindVertexArray(vertexArrayObject);
  13535. this._cachedVertexBuffers = null;
  13536. this._cachedIndexBuffer = null;
  13537. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13538. this._mustWipeVertexAttributes = true;
  13539. }
  13540. };
  13541. /**
  13542. * Bind webGl buffers directly to the webGL context
  13543. * @param vertexBuffer defines the vertex buffer to bind
  13544. * @param indexBuffer defines the index buffer to bind
  13545. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13546. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13547. * @param effect defines the effect associated with the vertex buffer
  13548. */
  13549. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13550. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13551. this._cachedVertexBuffers = vertexBuffer;
  13552. this._cachedEffectForVertexBuffers = effect;
  13553. var attributesCount = effect.getAttributesCount();
  13554. this._unbindVertexArrayObject();
  13555. this.unbindAllAttributes();
  13556. var offset = 0;
  13557. for (var index = 0; index < attributesCount; index++) {
  13558. if (index < vertexDeclaration.length) {
  13559. var order = effect.getAttributeLocation(index);
  13560. if (order >= 0) {
  13561. this._gl.enableVertexAttribArray(order);
  13562. this._vertexAttribArraysEnabled[order] = true;
  13563. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13564. }
  13565. offset += vertexDeclaration[index] * 4;
  13566. }
  13567. }
  13568. }
  13569. this._bindIndexBufferWithCache(indexBuffer);
  13570. };
  13571. Engine.prototype._unbindVertexArrayObject = function () {
  13572. if (!this._cachedVertexArrayObject) {
  13573. return;
  13574. }
  13575. this._cachedVertexArrayObject = null;
  13576. this._gl.bindVertexArray(null);
  13577. };
  13578. /**
  13579. * Bind a list of vertex buffers to the webGL context
  13580. * @param vertexBuffers defines the list of vertex buffers to bind
  13581. * @param indexBuffer defines the index buffer to bind
  13582. * @param effect defines the effect associated with the vertex buffers
  13583. */
  13584. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13585. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13586. this._cachedVertexBuffers = vertexBuffers;
  13587. this._cachedEffectForVertexBuffers = effect;
  13588. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13589. }
  13590. this._bindIndexBufferWithCache(indexBuffer);
  13591. };
  13592. /**
  13593. * Unbind all instance attributes
  13594. */
  13595. Engine.prototype.unbindInstanceAttributes = function () {
  13596. var boundBuffer;
  13597. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13598. var instancesBuffer = this._currentInstanceBuffers[i];
  13599. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13600. boundBuffer = instancesBuffer;
  13601. this.bindArrayBuffer(instancesBuffer);
  13602. }
  13603. var offsetLocation = this._currentInstanceLocations[i];
  13604. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13605. }
  13606. this._currentInstanceBuffers.length = 0;
  13607. this._currentInstanceLocations.length = 0;
  13608. };
  13609. /**
  13610. * Release and free the memory of a vertex array object
  13611. * @param vao defines the vertex array object to delete
  13612. */
  13613. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13614. this._gl.deleteVertexArray(vao);
  13615. };
  13616. /** @hidden */
  13617. Engine.prototype._releaseBuffer = function (buffer) {
  13618. buffer.references--;
  13619. if (buffer.references === 0) {
  13620. this._gl.deleteBuffer(buffer);
  13621. return true;
  13622. }
  13623. return false;
  13624. };
  13625. /**
  13626. * Creates a webGL buffer to use with instanciation
  13627. * @param capacity defines the size of the buffer
  13628. * @returns the webGL buffer
  13629. */
  13630. Engine.prototype.createInstancesBuffer = function (capacity) {
  13631. var buffer = this._gl.createBuffer();
  13632. if (!buffer) {
  13633. throw new Error("Unable to create instance buffer");
  13634. }
  13635. buffer.capacity = capacity;
  13636. this.bindArrayBuffer(buffer);
  13637. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13638. return buffer;
  13639. };
  13640. /**
  13641. * Delete a webGL buffer used with instanciation
  13642. * @param buffer defines the webGL buffer to delete
  13643. */
  13644. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13645. this._gl.deleteBuffer(buffer);
  13646. };
  13647. /**
  13648. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13649. * @param instancesBuffer defines the webGL buffer to update and bind
  13650. * @param data defines the data to store in the buffer
  13651. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13652. */
  13653. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13654. this.bindArrayBuffer(instancesBuffer);
  13655. if (data) {
  13656. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13657. }
  13658. if (offsetLocations[0].index !== undefined) {
  13659. var stride = 0;
  13660. for (var i = 0; i < offsetLocations.length; i++) {
  13661. var ai = offsetLocations[i];
  13662. stride += ai.attributeSize * 4;
  13663. }
  13664. for (var i = 0; i < offsetLocations.length; i++) {
  13665. var ai = offsetLocations[i];
  13666. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13667. this._gl.enableVertexAttribArray(ai.index);
  13668. this._vertexAttribArraysEnabled[ai.index] = true;
  13669. }
  13670. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13671. this._gl.vertexAttribDivisor(ai.index, 1);
  13672. this._currentInstanceLocations.push(ai.index);
  13673. this._currentInstanceBuffers.push(instancesBuffer);
  13674. }
  13675. }
  13676. else {
  13677. for (var index = 0; index < 4; index++) {
  13678. var offsetLocation = offsetLocations[index];
  13679. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13680. this._gl.enableVertexAttribArray(offsetLocation);
  13681. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13682. }
  13683. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13684. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13685. this._currentInstanceLocations.push(offsetLocation);
  13686. this._currentInstanceBuffers.push(instancesBuffer);
  13687. }
  13688. }
  13689. };
  13690. /**
  13691. * Apply all cached states (depth, culling, stencil and alpha)
  13692. */
  13693. Engine.prototype.applyStates = function () {
  13694. this._depthCullingState.apply(this._gl);
  13695. this._stencilState.apply(this._gl);
  13696. this._alphaState.apply(this._gl);
  13697. };
  13698. /**
  13699. * Send a draw order
  13700. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13701. * @param indexStart defines the starting index
  13702. * @param indexCount defines the number of index to draw
  13703. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13704. */
  13705. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13706. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13707. };
  13708. /**
  13709. * Draw a list of points
  13710. * @param verticesStart defines the index of first vertex to draw
  13711. * @param verticesCount defines the count of vertices to draw
  13712. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13713. */
  13714. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13715. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13716. };
  13717. /**
  13718. * Draw a list of unindexed primitives
  13719. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13720. * @param verticesStart defines the index of first vertex to draw
  13721. * @param verticesCount defines the count of vertices to draw
  13722. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13723. */
  13724. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13725. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13726. };
  13727. /**
  13728. * Draw a list of indexed primitives
  13729. * @param fillMode defines the primitive to use
  13730. * @param indexStart defines the starting index
  13731. * @param indexCount defines the number of index to draw
  13732. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13733. */
  13734. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13735. // Apply states
  13736. this.applyStates();
  13737. this._drawCalls.addCount(1, false);
  13738. // Render
  13739. var drawMode = this._drawMode(fillMode);
  13740. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13741. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13742. if (instancesCount) {
  13743. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13744. }
  13745. else {
  13746. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13747. }
  13748. };
  13749. /**
  13750. * Draw a list of unindexed primitives
  13751. * @param fillMode defines the primitive to use
  13752. * @param verticesStart defines the index of first vertex to draw
  13753. * @param verticesCount defines the count of vertices to draw
  13754. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13755. */
  13756. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13757. // Apply states
  13758. this.applyStates();
  13759. this._drawCalls.addCount(1, false);
  13760. var drawMode = this._drawMode(fillMode);
  13761. if (instancesCount) {
  13762. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13763. }
  13764. else {
  13765. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13766. }
  13767. };
  13768. Engine.prototype._drawMode = function (fillMode) {
  13769. switch (fillMode) {
  13770. // Triangle views
  13771. case BABYLON.Material.TriangleFillMode:
  13772. return this._gl.TRIANGLES;
  13773. case BABYLON.Material.PointFillMode:
  13774. return this._gl.POINTS;
  13775. case BABYLON.Material.WireFrameFillMode:
  13776. return this._gl.LINES;
  13777. // Draw modes
  13778. case BABYLON.Material.PointListDrawMode:
  13779. return this._gl.POINTS;
  13780. case BABYLON.Material.LineListDrawMode:
  13781. return this._gl.LINES;
  13782. case BABYLON.Material.LineLoopDrawMode:
  13783. return this._gl.LINE_LOOP;
  13784. case BABYLON.Material.LineStripDrawMode:
  13785. return this._gl.LINE_STRIP;
  13786. case BABYLON.Material.TriangleStripDrawMode:
  13787. return this._gl.TRIANGLE_STRIP;
  13788. case BABYLON.Material.TriangleFanDrawMode:
  13789. return this._gl.TRIANGLE_FAN;
  13790. default:
  13791. return this._gl.TRIANGLES;
  13792. }
  13793. };
  13794. // Shaders
  13795. /** @hidden */
  13796. Engine.prototype._releaseEffect = function (effect) {
  13797. if (this._compiledEffects[effect._key]) {
  13798. delete this._compiledEffects[effect._key];
  13799. this._deleteProgram(effect.getProgram());
  13800. }
  13801. };
  13802. /** @hidden */
  13803. Engine.prototype._deleteProgram = function (program) {
  13804. if (program) {
  13805. program.__SPECTOR_rebuildProgram = null;
  13806. if (program.transformFeedback) {
  13807. this.deleteTransformFeedback(program.transformFeedback);
  13808. program.transformFeedback = null;
  13809. }
  13810. this._gl.deleteProgram(program);
  13811. }
  13812. };
  13813. /**
  13814. * Create a new effect (used to store vertex/fragment shaders)
  13815. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13816. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13817. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13818. * @param samplers defines an array of string used to represent textures
  13819. * @param defines defines the string containing the defines to use to compile the shaders
  13820. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13821. * @param onCompiled defines a function to call when the effect creation is successful
  13822. * @param onError defines a function to call when the effect creation has failed
  13823. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13824. * @returns the new Effect
  13825. */
  13826. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13827. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13828. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13829. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13830. if (this._compiledEffects[name]) {
  13831. var compiledEffect = this._compiledEffects[name];
  13832. if (onCompiled && compiledEffect.isReady()) {
  13833. onCompiled(compiledEffect);
  13834. }
  13835. return compiledEffect;
  13836. }
  13837. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13838. effect._key = name;
  13839. this._compiledEffects[name] = effect;
  13840. return effect;
  13841. };
  13842. /**
  13843. * Create an effect to use with particle systems
  13844. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13845. * @param uniformsNames defines a list of attribute names
  13846. * @param samplers defines an array of string used to represent textures
  13847. * @param defines defines the string containing the defines to use to compile the shaders
  13848. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13849. * @param onCompiled defines a function to call when the effect creation is successful
  13850. * @param onError defines a function to call when the effect creation has failed
  13851. * @returns the new Effect
  13852. */
  13853. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13854. if (uniformsNames === void 0) { uniformsNames = []; }
  13855. if (samplers === void 0) { samplers = []; }
  13856. if (defines === void 0) { defines = ""; }
  13857. return this.createEffect({
  13858. vertex: "particles",
  13859. fragmentElement: fragmentName
  13860. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13861. };
  13862. /**
  13863. * Directly creates a webGL program
  13864. * @param vertexCode defines the vertex shader code to use
  13865. * @param fragmentCode defines the fragment shader code to use
  13866. * @param context defines the webGL context to use (if not set, the current one will be used)
  13867. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13868. * @returns the new webGL program
  13869. */
  13870. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13871. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13872. context = context || this._gl;
  13873. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13874. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13875. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13876. };
  13877. /**
  13878. * Creates a webGL program
  13879. * @param vertexCode defines the vertex shader code to use
  13880. * @param fragmentCode defines the fragment shader code to use
  13881. * @param defines defines the string containing the defines to use to compile the shaders
  13882. * @param context defines the webGL context to use (if not set, the current one will be used)
  13883. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13884. * @returns the new webGL program
  13885. */
  13886. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13887. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13888. context = context || this._gl;
  13889. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13890. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13891. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13892. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13893. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13894. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13895. return program;
  13896. };
  13897. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13898. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13899. var shaderProgram = context.createProgram();
  13900. if (!shaderProgram) {
  13901. throw new Error("Unable to create program");
  13902. }
  13903. context.attachShader(shaderProgram, vertexShader);
  13904. context.attachShader(shaderProgram, fragmentShader);
  13905. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13906. var transformFeedback = this.createTransformFeedback();
  13907. this.bindTransformFeedback(transformFeedback);
  13908. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13909. shaderProgram.transformFeedback = transformFeedback;
  13910. }
  13911. context.linkProgram(shaderProgram);
  13912. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13913. this.bindTransformFeedback(null);
  13914. }
  13915. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13916. if (!linked) {
  13917. context.validateProgram(shaderProgram);
  13918. var error = context.getProgramInfoLog(shaderProgram);
  13919. if (error) {
  13920. throw new Error(error);
  13921. }
  13922. }
  13923. context.deleteShader(vertexShader);
  13924. context.deleteShader(fragmentShader);
  13925. return shaderProgram;
  13926. };
  13927. /**
  13928. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13929. * @param shaderProgram defines the webGL program to use
  13930. * @param uniformsNames defines the list of uniform names
  13931. * @returns an array of webGL uniform locations
  13932. */
  13933. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13934. var results = new Array();
  13935. for (var index = 0; index < uniformsNames.length; index++) {
  13936. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13937. }
  13938. return results;
  13939. };
  13940. /**
  13941. * Gets the lsit of active attributes for a given webGL program
  13942. * @param shaderProgram defines the webGL program to use
  13943. * @param attributesNames defines the list of attribute names to get
  13944. * @returns an array of indices indicating the offset of each attribute
  13945. */
  13946. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13947. var results = [];
  13948. for (var index = 0; index < attributesNames.length; index++) {
  13949. try {
  13950. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13951. }
  13952. catch (e) {
  13953. results.push(-1);
  13954. }
  13955. }
  13956. return results;
  13957. };
  13958. /**
  13959. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13960. * @param effect defines the effect to activate
  13961. */
  13962. Engine.prototype.enableEffect = function (effect) {
  13963. if (!effect) {
  13964. return;
  13965. }
  13966. // Use program
  13967. this.bindSamplers(effect);
  13968. this._currentEffect = effect;
  13969. if (effect.onBind) {
  13970. effect.onBind(effect);
  13971. }
  13972. effect.onBindObservable.notifyObservers(effect);
  13973. };
  13974. /**
  13975. * Set the value of an uniform to an array of int32
  13976. * @param uniform defines the webGL uniform location where to store the value
  13977. * @param array defines the array of int32 to store
  13978. */
  13979. Engine.prototype.setIntArray = function (uniform, array) {
  13980. if (!uniform)
  13981. return;
  13982. this._gl.uniform1iv(uniform, array);
  13983. };
  13984. /**
  13985. * Set the value of an uniform to an array of int32 (stored as vec2)
  13986. * @param uniform defines the webGL uniform location where to store the value
  13987. * @param array defines the array of int32 to store
  13988. */
  13989. Engine.prototype.setIntArray2 = function (uniform, array) {
  13990. if (!uniform || array.length % 2 !== 0)
  13991. return;
  13992. this._gl.uniform2iv(uniform, array);
  13993. };
  13994. /**
  13995. * Set the value of an uniform to an array of int32 (stored as vec3)
  13996. * @param uniform defines the webGL uniform location where to store the value
  13997. * @param array defines the array of int32 to store
  13998. */
  13999. Engine.prototype.setIntArray3 = function (uniform, array) {
  14000. if (!uniform || array.length % 3 !== 0)
  14001. return;
  14002. this._gl.uniform3iv(uniform, array);
  14003. };
  14004. /**
  14005. * Set the value of an uniform to an array of int32 (stored as vec4)
  14006. * @param uniform defines the webGL uniform location where to store the value
  14007. * @param array defines the array of int32 to store
  14008. */
  14009. Engine.prototype.setIntArray4 = function (uniform, array) {
  14010. if (!uniform || array.length % 4 !== 0)
  14011. return;
  14012. this._gl.uniform4iv(uniform, array);
  14013. };
  14014. /**
  14015. * Set the value of an uniform to an array of float32
  14016. * @param uniform defines the webGL uniform location where to store the value
  14017. * @param array defines the array of float32 to store
  14018. */
  14019. Engine.prototype.setFloatArray = function (uniform, array) {
  14020. if (!uniform)
  14021. return;
  14022. this._gl.uniform1fv(uniform, array);
  14023. };
  14024. /**
  14025. * Set the value of an uniform to an array of float32 (stored as vec2)
  14026. * @param uniform defines the webGL uniform location where to store the value
  14027. * @param array defines the array of float32 to store
  14028. */
  14029. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14030. if (!uniform || array.length % 2 !== 0)
  14031. return;
  14032. this._gl.uniform2fv(uniform, array);
  14033. };
  14034. /**
  14035. * Set the value of an uniform to an array of float32 (stored as vec3)
  14036. * @param uniform defines the webGL uniform location where to store the value
  14037. * @param array defines the array of float32 to store
  14038. */
  14039. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14040. if (!uniform || array.length % 3 !== 0)
  14041. return;
  14042. this._gl.uniform3fv(uniform, array);
  14043. };
  14044. /**
  14045. * Set the value of an uniform to an array of float32 (stored as vec4)
  14046. * @param uniform defines the webGL uniform location where to store the value
  14047. * @param array defines the array of float32 to store
  14048. */
  14049. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14050. if (!uniform || array.length % 4 !== 0)
  14051. return;
  14052. this._gl.uniform4fv(uniform, array);
  14053. };
  14054. /**
  14055. * Set the value of an uniform to an array of number
  14056. * @param uniform defines the webGL uniform location where to store the value
  14057. * @param array defines the array of number to store
  14058. */
  14059. Engine.prototype.setArray = function (uniform, array) {
  14060. if (!uniform)
  14061. return;
  14062. this._gl.uniform1fv(uniform, array);
  14063. };
  14064. /**
  14065. * Set the value of an uniform to an array of number (stored as vec2)
  14066. * @param uniform defines the webGL uniform location where to store the value
  14067. * @param array defines the array of number to store
  14068. */
  14069. Engine.prototype.setArray2 = function (uniform, array) {
  14070. if (!uniform || array.length % 2 !== 0)
  14071. return;
  14072. this._gl.uniform2fv(uniform, array);
  14073. };
  14074. /**
  14075. * Set the value of an uniform to an array of number (stored as vec3)
  14076. * @param uniform defines the webGL uniform location where to store the value
  14077. * @param array defines the array of number to store
  14078. */
  14079. Engine.prototype.setArray3 = function (uniform, array) {
  14080. if (!uniform || array.length % 3 !== 0)
  14081. return;
  14082. this._gl.uniform3fv(uniform, array);
  14083. };
  14084. /**
  14085. * Set the value of an uniform to an array of number (stored as vec4)
  14086. * @param uniform defines the webGL uniform location where to store the value
  14087. * @param array defines the array of number to store
  14088. */
  14089. Engine.prototype.setArray4 = function (uniform, array) {
  14090. if (!uniform || array.length % 4 !== 0)
  14091. return;
  14092. this._gl.uniform4fv(uniform, array);
  14093. };
  14094. /**
  14095. * Set the value of an uniform to an array of float32 (stored as matrices)
  14096. * @param uniform defines the webGL uniform location where to store the value
  14097. * @param matrices defines the array of float32 to store
  14098. */
  14099. Engine.prototype.setMatrices = function (uniform, matrices) {
  14100. if (!uniform)
  14101. return;
  14102. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14103. };
  14104. /**
  14105. * Set the value of an uniform to a matrix
  14106. * @param uniform defines the webGL uniform location where to store the value
  14107. * @param matrix defines the matrix to store
  14108. */
  14109. Engine.prototype.setMatrix = function (uniform, matrix) {
  14110. if (!uniform)
  14111. return;
  14112. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14113. };
  14114. /**
  14115. * Set the value of an uniform to a matrix (3x3)
  14116. * @param uniform defines the webGL uniform location where to store the value
  14117. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14118. */
  14119. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14120. if (!uniform)
  14121. return;
  14122. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14123. };
  14124. /**
  14125. * Set the value of an uniform to a matrix (2x2)
  14126. * @param uniform defines the webGL uniform location where to store the value
  14127. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14128. */
  14129. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14130. if (!uniform)
  14131. return;
  14132. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14133. };
  14134. /**
  14135. * Set the value of an uniform to a number (int)
  14136. * @param uniform defines the webGL uniform location where to store the value
  14137. * @param value defines the int number to store
  14138. */
  14139. Engine.prototype.setInt = function (uniform, value) {
  14140. if (!uniform)
  14141. return;
  14142. this._gl.uniform1i(uniform, value);
  14143. };
  14144. /**
  14145. * Set the value of an uniform to a number (float)
  14146. * @param uniform defines the webGL uniform location where to store the value
  14147. * @param value defines the float number to store
  14148. */
  14149. Engine.prototype.setFloat = function (uniform, value) {
  14150. if (!uniform)
  14151. return;
  14152. this._gl.uniform1f(uniform, value);
  14153. };
  14154. /**
  14155. * Set the value of an uniform to a vec2
  14156. * @param uniform defines the webGL uniform location where to store the value
  14157. * @param x defines the 1st component of the value
  14158. * @param y defines the 2nd component of the value
  14159. */
  14160. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14161. if (!uniform)
  14162. return;
  14163. this._gl.uniform2f(uniform, x, y);
  14164. };
  14165. /**
  14166. * Set the value of an uniform to a vec3
  14167. * @param uniform defines the webGL uniform location where to store the value
  14168. * @param x defines the 1st component of the value
  14169. * @param y defines the 2nd component of the value
  14170. * @param z defines the 3rd component of the value
  14171. */
  14172. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14173. if (!uniform)
  14174. return;
  14175. this._gl.uniform3f(uniform, x, y, z);
  14176. };
  14177. /**
  14178. * Set the value of an uniform to a boolean
  14179. * @param uniform defines the webGL uniform location where to store the value
  14180. * @param bool defines the boolean to store
  14181. */
  14182. Engine.prototype.setBool = function (uniform, bool) {
  14183. if (!uniform)
  14184. return;
  14185. this._gl.uniform1i(uniform, bool);
  14186. };
  14187. /**
  14188. * Set the value of an uniform to a vec4
  14189. * @param uniform defines the webGL uniform location where to store the value
  14190. * @param x defines the 1st component of the value
  14191. * @param y defines the 2nd component of the value
  14192. * @param z defines the 3rd component of the value
  14193. * @param w defines the 4th component of the value
  14194. */
  14195. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14196. if (!uniform)
  14197. return;
  14198. this._gl.uniform4f(uniform, x, y, z, w);
  14199. };
  14200. /**
  14201. * Set the value of an uniform to a Color3
  14202. * @param uniform defines the webGL uniform location where to store the value
  14203. * @param color3 defines the color to store
  14204. */
  14205. Engine.prototype.setColor3 = function (uniform, color3) {
  14206. if (!uniform)
  14207. return;
  14208. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14209. };
  14210. /**
  14211. * Set the value of an uniform to a Color3 and an alpha value
  14212. * @param uniform defines the webGL uniform location where to store the value
  14213. * @param color3 defines the color to store
  14214. * @param alpha defines the alpha component to store
  14215. */
  14216. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14217. if (!uniform)
  14218. return;
  14219. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14220. };
  14221. /**
  14222. * Sets a Color4 on a uniform variable
  14223. * @param uniform defines the uniform location
  14224. * @param color4 defines the value to be set
  14225. */
  14226. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14227. if (!uniform)
  14228. return;
  14229. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14230. };
  14231. // States
  14232. /**
  14233. * Set various states to the webGL context
  14234. * @param culling defines backface culling state
  14235. * @param zOffset defines the value to apply to zOffset (0 by default)
  14236. * @param force defines if states must be applied even if cache is up to date
  14237. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14238. */
  14239. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14240. if (zOffset === void 0) { zOffset = 0; }
  14241. if (reverseSide === void 0) { reverseSide = false; }
  14242. // Culling
  14243. if (this._depthCullingState.cull !== culling || force) {
  14244. this._depthCullingState.cull = culling;
  14245. }
  14246. // Cull face
  14247. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14248. if (this._depthCullingState.cullFace !== cullFace || force) {
  14249. this._depthCullingState.cullFace = cullFace;
  14250. }
  14251. // Z offset
  14252. this.setZOffset(zOffset);
  14253. // Front face
  14254. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14255. if (this._depthCullingState.frontFace !== frontFace || force) {
  14256. this._depthCullingState.frontFace = frontFace;
  14257. }
  14258. };
  14259. /**
  14260. * Set the z offset to apply to current rendering
  14261. * @param value defines the offset to apply
  14262. */
  14263. Engine.prototype.setZOffset = function (value) {
  14264. this._depthCullingState.zOffset = value;
  14265. };
  14266. /**
  14267. * Gets the current value of the zOffset
  14268. * @returns the current zOffset state
  14269. */
  14270. Engine.prototype.getZOffset = function () {
  14271. return this._depthCullingState.zOffset;
  14272. };
  14273. /**
  14274. * Enable or disable depth buffering
  14275. * @param enable defines the state to set
  14276. */
  14277. Engine.prototype.setDepthBuffer = function (enable) {
  14278. this._depthCullingState.depthTest = enable;
  14279. };
  14280. /**
  14281. * Gets a boolean indicating if depth writing is enabled
  14282. * @returns the current depth writing state
  14283. */
  14284. Engine.prototype.getDepthWrite = function () {
  14285. return this._depthCullingState.depthMask;
  14286. };
  14287. /**
  14288. * Enable or disable depth writing
  14289. * @param enable defines the state to set
  14290. */
  14291. Engine.prototype.setDepthWrite = function (enable) {
  14292. this._depthCullingState.depthMask = enable;
  14293. };
  14294. /**
  14295. * Enable or disable color writing
  14296. * @param enable defines the state to set
  14297. */
  14298. Engine.prototype.setColorWrite = function (enable) {
  14299. this._gl.colorMask(enable, enable, enable, enable);
  14300. this._colorWrite = enable;
  14301. };
  14302. /**
  14303. * Gets a boolean indicating if color writing is enabled
  14304. * @returns the current color writing state
  14305. */
  14306. Engine.prototype.getColorWrite = function () {
  14307. return this._colorWrite;
  14308. };
  14309. /**
  14310. * Sets alpha constants used by some alpha blending modes
  14311. * @param r defines the red component
  14312. * @param g defines the green component
  14313. * @param b defines the blue component
  14314. * @param a defines the alpha component
  14315. */
  14316. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14317. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14318. };
  14319. /**
  14320. * Sets the current alpha mode
  14321. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14322. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14323. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14324. */
  14325. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14326. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14327. if (this._alphaMode === mode) {
  14328. return;
  14329. }
  14330. switch (mode) {
  14331. case Engine.ALPHA_DISABLE:
  14332. this._alphaState.alphaBlend = false;
  14333. break;
  14334. case Engine.ALPHA_PREMULTIPLIED:
  14335. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14336. this._alphaState.alphaBlend = true;
  14337. break;
  14338. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14339. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14340. this._alphaState.alphaBlend = true;
  14341. break;
  14342. case Engine.ALPHA_COMBINE:
  14343. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14344. this._alphaState.alphaBlend = true;
  14345. break;
  14346. case Engine.ALPHA_ONEONE:
  14347. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14348. this._alphaState.alphaBlend = true;
  14349. break;
  14350. case Engine.ALPHA_ADD:
  14351. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14352. this._alphaState.alphaBlend = true;
  14353. break;
  14354. case Engine.ALPHA_SUBTRACT:
  14355. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14356. this._alphaState.alphaBlend = true;
  14357. break;
  14358. case Engine.ALPHA_MULTIPLY:
  14359. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14360. this._alphaState.alphaBlend = true;
  14361. break;
  14362. case Engine.ALPHA_MAXIMIZED:
  14363. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14364. this._alphaState.alphaBlend = true;
  14365. break;
  14366. case Engine.ALPHA_INTERPOLATE:
  14367. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14368. this._alphaState.alphaBlend = true;
  14369. break;
  14370. case Engine.ALPHA_SCREENMODE:
  14371. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14372. this._alphaState.alphaBlend = true;
  14373. break;
  14374. }
  14375. if (!noDepthWriteChange) {
  14376. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14377. }
  14378. this._alphaMode = mode;
  14379. };
  14380. /**
  14381. * Gets the current alpha mode
  14382. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14383. * @returns the current alpha mode
  14384. */
  14385. Engine.prototype.getAlphaMode = function () {
  14386. return this._alphaMode;
  14387. };
  14388. // Textures
  14389. /**
  14390. * Force the entire cache to be cleared
  14391. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14392. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14393. */
  14394. Engine.prototype.wipeCaches = function (bruteForce) {
  14395. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14396. return;
  14397. }
  14398. this._currentEffect = null;
  14399. if (bruteForce) {
  14400. this.resetTextureCache();
  14401. this._currentProgram = null;
  14402. this._stencilState.reset();
  14403. this._depthCullingState.reset();
  14404. this.setDepthFunctionToLessOrEqual();
  14405. this._alphaState.reset();
  14406. }
  14407. this._resetVertexBufferBinding();
  14408. this._cachedIndexBuffer = null;
  14409. this._cachedEffectForVertexBuffers = null;
  14410. this._unbindVertexArrayObject();
  14411. this.bindIndexBuffer(null);
  14412. };
  14413. /**
  14414. * Set the compressed texture format to use, based on the formats you have, and the formats
  14415. * supported by the hardware / browser.
  14416. *
  14417. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14418. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14419. * to API arguments needed to compressed textures. This puts the burden on the container
  14420. * generator to house the arcane code for determining these for current & future formats.
  14421. *
  14422. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14423. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14424. *
  14425. * Note: The result of this call is not taken into account when a texture is base64.
  14426. *
  14427. * @param formatsAvailable defines the list of those format families you have created
  14428. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14429. *
  14430. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14431. * @returns The extension selected.
  14432. */
  14433. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14434. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14435. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14436. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14437. return this._textureFormatInUse = this._texturesSupported[i];
  14438. }
  14439. }
  14440. }
  14441. // actively set format to nothing, to allow this to be called more than once
  14442. // and possibly fail the 2nd time
  14443. this._textureFormatInUse = null;
  14444. return null;
  14445. };
  14446. /** @hidden */
  14447. Engine.prototype._createTexture = function () {
  14448. var texture = this._gl.createTexture();
  14449. if (!texture) {
  14450. throw new Error("Unable to create texture");
  14451. }
  14452. return texture;
  14453. };
  14454. /**
  14455. * Usually called from BABYLON.Texture.ts.
  14456. * Passed information to create a WebGLTexture
  14457. * @param urlArg defines a value which contains one of the following:
  14458. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14459. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14460. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14461. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14462. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14463. * @param scene needed for loading to the correct scene
  14464. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14465. * @param onLoad optional callback to be called upon successful completion
  14466. * @param onError optional callback to be called upon failure
  14467. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14468. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14469. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14470. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14471. */
  14472. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14473. var _this = this;
  14474. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14475. if (onLoad === void 0) { onLoad = null; }
  14476. if (onError === void 0) { onError = null; }
  14477. if (buffer === void 0) { buffer = null; }
  14478. if (fallback === void 0) { fallback = null; }
  14479. if (format === void 0) { format = null; }
  14480. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14481. var fromData = url.substr(0, 5) === "data:";
  14482. var fromBlob = url.substr(0, 5) === "blob:";
  14483. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14484. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14485. // establish the file extension, if possible
  14486. var lastDot = url.lastIndexOf('.');
  14487. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14488. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14489. var isTGA = (extension.indexOf(".tga") === 0);
  14490. // determine if a ktx file should be substituted
  14491. var isKTX = false;
  14492. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14493. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14494. isKTX = true;
  14495. }
  14496. if (scene) {
  14497. scene._addPendingData(texture);
  14498. }
  14499. texture.url = url;
  14500. texture.generateMipMaps = !noMipmap;
  14501. texture.samplingMode = samplingMode;
  14502. texture.invertY = invertY;
  14503. if (!this._doNotHandleContextLost) {
  14504. // Keep a link to the buffer only if we plan to handle context lost
  14505. texture._buffer = buffer;
  14506. }
  14507. var onLoadObserver = null;
  14508. if (onLoad && !fallback) {
  14509. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14510. }
  14511. if (!fallback)
  14512. this._internalTexturesCache.push(texture);
  14513. var onerror = function (message, exception) {
  14514. if (scene) {
  14515. scene._removePendingData(texture);
  14516. }
  14517. if (onLoadObserver) {
  14518. texture.onLoadedObservable.remove(onLoadObserver);
  14519. }
  14520. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14521. if (isKTX) {
  14522. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14523. }
  14524. else if (BABYLON.Tools.UseFallbackTexture) {
  14525. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14526. }
  14527. if (onError) {
  14528. onError(message || "Unknown error", exception);
  14529. }
  14530. };
  14531. var callback = null;
  14532. // processing for non-image formats
  14533. if (isKTX || isTGA || isDDS) {
  14534. if (isKTX) {
  14535. callback = function (data) {
  14536. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14537. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14538. ktx.uploadLevels(_this._gl, !noMipmap);
  14539. return false;
  14540. }, samplingMode);
  14541. };
  14542. }
  14543. else if (isTGA) {
  14544. callback = function (arrayBuffer) {
  14545. var data = new Uint8Array(arrayBuffer);
  14546. var header = BABYLON.TGATools.GetTGAHeader(data);
  14547. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14548. BABYLON.TGATools.UploadContent(_this._gl, data);
  14549. return false;
  14550. }, samplingMode);
  14551. };
  14552. }
  14553. else if (isDDS) {
  14554. callback = function (data) {
  14555. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14556. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14557. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14558. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14559. return false;
  14560. }, samplingMode);
  14561. };
  14562. }
  14563. if (!buffer) {
  14564. this._loadFile(url, function (data) {
  14565. if (callback) {
  14566. callback(data);
  14567. }
  14568. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14569. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14570. });
  14571. }
  14572. else {
  14573. if (callback) {
  14574. callback(buffer);
  14575. }
  14576. }
  14577. // image format processing
  14578. }
  14579. else {
  14580. var onload = function (img) {
  14581. if (fromBlob && !_this._doNotHandleContextLost) {
  14582. // We need to store the image if we need to rebuild the texture
  14583. // in case of a webgl context lost
  14584. texture._buffer = img;
  14585. }
  14586. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14587. var gl = _this._gl;
  14588. var isPot = (img.width === potWidth && img.height === potHeight);
  14589. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14590. if (isPot) {
  14591. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14592. return false;
  14593. }
  14594. // Using shaders to rescale because canvas.drawImage is lossy
  14595. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14596. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14597. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14598. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14599. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14600. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14601. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14602. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14603. _this._releaseTexture(source);
  14604. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14605. continuationCallback();
  14606. });
  14607. return true;
  14608. }, samplingMode);
  14609. };
  14610. if (!fromData || isBase64)
  14611. if (buffer instanceof HTMLImageElement) {
  14612. onload(buffer);
  14613. }
  14614. else {
  14615. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14616. }
  14617. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14618. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14619. else
  14620. onload(buffer);
  14621. }
  14622. return texture;
  14623. };
  14624. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14625. var _this = this;
  14626. var rtt = this.createRenderTargetTexture({
  14627. width: destination.width,
  14628. height: destination.height,
  14629. }, {
  14630. generateMipMaps: false,
  14631. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14632. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14633. generateDepthBuffer: false,
  14634. generateStencilBuffer: false
  14635. });
  14636. if (!this._rescalePostProcess) {
  14637. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14638. }
  14639. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14640. _this._rescalePostProcess.onApply = function (effect) {
  14641. effect._bindTexture("textureSampler", source);
  14642. };
  14643. var hostingScene = scene;
  14644. if (!hostingScene) {
  14645. hostingScene = _this.scenes[_this.scenes.length - 1];
  14646. }
  14647. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14648. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14649. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14650. _this.unBindFramebuffer(rtt);
  14651. _this._releaseTexture(rtt);
  14652. if (onComplete) {
  14653. onComplete();
  14654. }
  14655. });
  14656. };
  14657. /**
  14658. * Update a raw texture
  14659. * @param texture defines the texture to update
  14660. * @param data defines the data to store in the texture
  14661. * @param format defines the format of the data
  14662. * @param invertY defines if data must be stored with Y axis inverted
  14663. * @param compression defines the compression used (null by default)
  14664. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14665. */
  14666. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14667. if (compression === void 0) { compression = null; }
  14668. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14669. if (!texture) {
  14670. return;
  14671. }
  14672. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14673. var internalFormat = this._getInternalFormat(format);
  14674. var textureType = this._getWebGLTextureType(type);
  14675. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14676. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14677. if (!this._doNotHandleContextLost) {
  14678. texture._bufferView = data;
  14679. texture.format = format;
  14680. texture.type = type;
  14681. texture.invertY = invertY;
  14682. texture._compression = compression;
  14683. }
  14684. if (texture.width % 4 !== 0) {
  14685. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14686. }
  14687. if (compression && data) {
  14688. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14689. }
  14690. else {
  14691. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14692. }
  14693. if (texture.generateMipMaps) {
  14694. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14695. }
  14696. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14697. // this.resetTextureCache();
  14698. texture.isReady = true;
  14699. };
  14700. /**
  14701. * Creates a raw texture
  14702. * @param data defines the data to store in the texture
  14703. * @param width defines the width of the texture
  14704. * @param height defines the height of the texture
  14705. * @param format defines the format of the data
  14706. * @param generateMipMaps defines if the engine should generate the mip levels
  14707. * @param invertY defines if data must be stored with Y axis inverted
  14708. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14709. * @param compression defines the compression used (null by default)
  14710. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14711. * @returns the raw texture inside an InternalTexture
  14712. */
  14713. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14714. if (compression === void 0) { compression = null; }
  14715. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14716. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14717. texture.baseWidth = width;
  14718. texture.baseHeight = height;
  14719. texture.width = width;
  14720. texture.height = height;
  14721. texture.format = format;
  14722. texture.generateMipMaps = generateMipMaps;
  14723. texture.samplingMode = samplingMode;
  14724. texture.invertY = invertY;
  14725. texture._compression = compression;
  14726. texture.type = type;
  14727. if (!this._doNotHandleContextLost) {
  14728. texture._bufferView = data;
  14729. }
  14730. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14731. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14732. // Filters
  14733. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14734. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14735. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14736. if (generateMipMaps) {
  14737. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14738. }
  14739. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14740. this._internalTexturesCache.push(texture);
  14741. return texture;
  14742. };
  14743. /**
  14744. * Creates a dynamic texture
  14745. * @param width defines the width of the texture
  14746. * @param height defines the height of the texture
  14747. * @param generateMipMaps defines if the engine should generate the mip levels
  14748. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14749. * @returns the dynamic texture inside an InternalTexture
  14750. */
  14751. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14752. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14753. texture.baseWidth = width;
  14754. texture.baseHeight = height;
  14755. if (generateMipMaps) {
  14756. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14757. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14758. }
  14759. // this.resetTextureCache();
  14760. texture.width = width;
  14761. texture.height = height;
  14762. texture.isReady = false;
  14763. texture.generateMipMaps = generateMipMaps;
  14764. texture.samplingMode = samplingMode;
  14765. this.updateTextureSamplingMode(samplingMode, texture);
  14766. this._internalTexturesCache.push(texture);
  14767. return texture;
  14768. };
  14769. /**
  14770. * Update the sampling mode of a given texture
  14771. * @param samplingMode defines the required sampling mode
  14772. * @param texture defines the texture to update
  14773. */
  14774. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14775. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14776. if (texture.isCube) {
  14777. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14778. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14779. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14780. }
  14781. else if (texture.is3D) {
  14782. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14783. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14784. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14785. }
  14786. else {
  14787. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14788. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14789. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14790. }
  14791. texture.samplingMode = samplingMode;
  14792. };
  14793. /**
  14794. * Update the content of a dynamic texture
  14795. * @param texture defines the texture to update
  14796. * @param canvas defines the canvas containing the source
  14797. * @param invertY defines if data must be stored with Y axis inverted
  14798. * @param premulAlpha defines if alpha is stored as premultiplied
  14799. * @param format defines the format of the data
  14800. */
  14801. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14802. if (premulAlpha === void 0) { premulAlpha = false; }
  14803. if (!texture) {
  14804. return;
  14805. }
  14806. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14807. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14808. if (premulAlpha) {
  14809. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14810. }
  14811. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14812. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14813. if (texture.generateMipMaps) {
  14814. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14815. }
  14816. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14817. if (premulAlpha) {
  14818. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14819. }
  14820. texture.isReady = true;
  14821. };
  14822. /**
  14823. * Update a video texture
  14824. * @param texture defines the texture to update
  14825. * @param video defines the video element to use
  14826. * @param invertY defines if data must be stored with Y axis inverted
  14827. */
  14828. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14829. if (!texture || texture._isDisabled) {
  14830. return;
  14831. }
  14832. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14833. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14834. try {
  14835. // Testing video texture support
  14836. if (this._videoTextureSupported === undefined) {
  14837. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14838. if (this._gl.getError() !== 0) {
  14839. this._videoTextureSupported = false;
  14840. }
  14841. else {
  14842. this._videoTextureSupported = true;
  14843. }
  14844. }
  14845. // Copy video through the current working canvas if video texture is not supported
  14846. if (!this._videoTextureSupported) {
  14847. if (!texture._workingCanvas) {
  14848. texture._workingCanvas = document.createElement("canvas");
  14849. var context = texture._workingCanvas.getContext("2d");
  14850. if (!context) {
  14851. throw new Error("Unable to get 2d context");
  14852. }
  14853. texture._workingContext = context;
  14854. texture._workingCanvas.width = texture.width;
  14855. texture._workingCanvas.height = texture.height;
  14856. }
  14857. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14858. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14859. }
  14860. else {
  14861. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14862. }
  14863. if (texture.generateMipMaps) {
  14864. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14865. }
  14866. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14867. // this.resetTextureCache();
  14868. texture.isReady = true;
  14869. }
  14870. catch (ex) {
  14871. // Something unexpected
  14872. // Let's disable the texture
  14873. texture._isDisabled = true;
  14874. }
  14875. };
  14876. /**
  14877. * Updates a depth texture Comparison Mode and Function.
  14878. * If the comparison Function is equal to 0, the mode will be set to none.
  14879. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14880. * @param texture The texture to set the comparison function for
  14881. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14882. */
  14883. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14884. if (this.webGLVersion === 1) {
  14885. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14886. return;
  14887. }
  14888. var gl = this._gl;
  14889. if (texture.isCube) {
  14890. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14891. if (comparisonFunction === 0) {
  14892. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14893. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14894. }
  14895. else {
  14896. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14897. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14898. }
  14899. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14900. }
  14901. else {
  14902. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14903. if (comparisonFunction === 0) {
  14904. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14905. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14906. }
  14907. else {
  14908. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14909. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14910. }
  14911. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14912. }
  14913. texture._comparisonFunction = comparisonFunction;
  14914. };
  14915. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14916. var width = size.width || size;
  14917. var height = size.height || size;
  14918. internalTexture.baseWidth = width;
  14919. internalTexture.baseHeight = height;
  14920. internalTexture.width = width;
  14921. internalTexture.height = height;
  14922. internalTexture.isReady = true;
  14923. internalTexture.samples = 1;
  14924. internalTexture.generateMipMaps = false;
  14925. internalTexture._generateDepthBuffer = true;
  14926. internalTexture._generateStencilBuffer = generateStencil;
  14927. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14928. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14929. internalTexture._comparisonFunction = comparisonFunction;
  14930. var gl = this._gl;
  14931. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14932. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14933. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14934. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14935. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14936. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14937. if (comparisonFunction === 0) {
  14938. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14939. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14940. }
  14941. else {
  14942. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14943. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14944. }
  14945. };
  14946. /**
  14947. * Creates a depth stencil texture.
  14948. * This is only available in WebGL 2 or with the depth texture extension available.
  14949. * @param size The size of face edge in the texture.
  14950. * @param options The options defining the texture.
  14951. * @returns The texture
  14952. */
  14953. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14954. if (options.isCube) {
  14955. var width = size.width || size;
  14956. return this._createDepthStencilCubeTexture(width, options);
  14957. }
  14958. else {
  14959. return this._createDepthStencilTexture(size, options);
  14960. }
  14961. };
  14962. /**
  14963. * Creates a depth stencil texture.
  14964. * This is only available in WebGL 2 or with the depth texture extension available.
  14965. * @param size The size of face edge in the texture.
  14966. * @param options The options defining the texture.
  14967. * @returns The texture
  14968. */
  14969. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14970. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14971. if (!this._caps.depthTextureExtension) {
  14972. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14973. return internalTexture;
  14974. }
  14975. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14976. var gl = this._gl;
  14977. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14978. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14979. if (this.webGLVersion > 1) {
  14980. if (internalOptions.generateStencil) {
  14981. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14982. }
  14983. else {
  14984. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14985. }
  14986. }
  14987. else {
  14988. if (internalOptions.generateStencil) {
  14989. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14990. }
  14991. else {
  14992. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14993. }
  14994. }
  14995. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14996. return internalTexture;
  14997. };
  14998. /**
  14999. * Creates a depth stencil cube texture.
  15000. * This is only available in WebGL 2.
  15001. * @param size The size of face edge in the cube texture.
  15002. * @param options The options defining the cube texture.
  15003. * @returns The cube texture
  15004. */
  15005. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15006. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15007. internalTexture.isCube = true;
  15008. if (this.webGLVersion === 1) {
  15009. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15010. return internalTexture;
  15011. }
  15012. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15013. var gl = this._gl;
  15014. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15015. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15016. // Create the depth/stencil buffer
  15017. for (var face = 0; face < 6; face++) {
  15018. if (internalOptions.generateStencil) {
  15019. 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);
  15020. }
  15021. else {
  15022. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15023. }
  15024. }
  15025. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15026. return internalTexture;
  15027. };
  15028. /**
  15029. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15030. * @param renderTarget The render target to set the frame buffer for
  15031. */
  15032. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15033. // Create the framebuffer
  15034. var internalTexture = renderTarget.getInternalTexture();
  15035. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15036. return;
  15037. }
  15038. var gl = this._gl;
  15039. var depthStencilTexture = renderTarget.depthStencilTexture;
  15040. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15041. if (depthStencilTexture.isCube) {
  15042. if (depthStencilTexture._generateStencilBuffer) {
  15043. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15044. }
  15045. else {
  15046. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15047. }
  15048. }
  15049. else {
  15050. if (depthStencilTexture._generateStencilBuffer) {
  15051. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15052. }
  15053. else {
  15054. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15055. }
  15056. }
  15057. this.bindUnboundFramebuffer(null);
  15058. };
  15059. /**
  15060. * Creates a new render target texture
  15061. * @param size defines the size of the texture
  15062. * @param options defines the options used to create the texture
  15063. * @returns a new render target texture stored in an InternalTexture
  15064. */
  15065. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15066. var fullOptions = new RenderTargetCreationOptions();
  15067. if (options !== undefined && typeof options === "object") {
  15068. fullOptions.generateMipMaps = options.generateMipMaps;
  15069. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15070. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15071. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15072. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15073. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15074. }
  15075. else {
  15076. fullOptions.generateMipMaps = options;
  15077. fullOptions.generateDepthBuffer = true;
  15078. fullOptions.generateStencilBuffer = false;
  15079. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15080. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15081. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15082. }
  15083. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15084. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15085. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15086. }
  15087. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15088. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15089. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15090. }
  15091. var gl = this._gl;
  15092. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15093. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15094. var width = size.width || size;
  15095. var height = size.height || size;
  15096. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15097. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15098. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15099. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15100. }
  15101. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15102. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15103. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15104. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15105. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15106. // Create the framebuffer
  15107. var framebuffer = gl.createFramebuffer();
  15108. this.bindUnboundFramebuffer(framebuffer);
  15109. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15110. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15111. if (fullOptions.generateMipMaps) {
  15112. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15113. }
  15114. // Unbind
  15115. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15116. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15117. this.bindUnboundFramebuffer(null);
  15118. texture._framebuffer = framebuffer;
  15119. texture.baseWidth = width;
  15120. texture.baseHeight = height;
  15121. texture.width = width;
  15122. texture.height = height;
  15123. texture.isReady = true;
  15124. texture.samples = 1;
  15125. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15126. texture.samplingMode = fullOptions.samplingMode;
  15127. texture.type = fullOptions.type;
  15128. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15129. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15130. // this.resetTextureCache();
  15131. this._internalTexturesCache.push(texture);
  15132. return texture;
  15133. };
  15134. /**
  15135. * Create a multi render target texture
  15136. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15137. * @param size defines the size of the texture
  15138. * @param options defines the creation options
  15139. * @returns the cube texture as an InternalTexture
  15140. */
  15141. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15142. var generateMipMaps = false;
  15143. var generateDepthBuffer = true;
  15144. var generateStencilBuffer = false;
  15145. var generateDepthTexture = false;
  15146. var textureCount = 1;
  15147. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15148. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15149. var types = new Array();
  15150. var samplingModes = new Array();
  15151. if (options !== undefined) {
  15152. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15153. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15154. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15155. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15156. textureCount = options.textureCount || 1;
  15157. if (options.types) {
  15158. types = options.types;
  15159. }
  15160. if (options.samplingModes) {
  15161. samplingModes = options.samplingModes;
  15162. }
  15163. }
  15164. var gl = this._gl;
  15165. // Create the framebuffer
  15166. var framebuffer = gl.createFramebuffer();
  15167. this.bindUnboundFramebuffer(framebuffer);
  15168. var width = size.width || size;
  15169. var height = size.height || size;
  15170. var textures = [];
  15171. var attachments = [];
  15172. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15173. for (var i = 0; i < textureCount; i++) {
  15174. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15175. var type = types[i] || defaultType;
  15176. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15177. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15178. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15179. }
  15180. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15181. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15182. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15183. }
  15184. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15185. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15186. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15187. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15188. }
  15189. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15190. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15191. textures.push(texture);
  15192. attachments.push(attachment);
  15193. gl.activeTexture(gl["TEXTURE" + i]);
  15194. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15195. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15196. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15197. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15198. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15199. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15200. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15201. if (generateMipMaps) {
  15202. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15203. }
  15204. // Unbind
  15205. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15206. texture._framebuffer = framebuffer;
  15207. texture._depthStencilBuffer = depthStencilBuffer;
  15208. texture.baseWidth = width;
  15209. texture.baseHeight = height;
  15210. texture.width = width;
  15211. texture.height = height;
  15212. texture.isReady = true;
  15213. texture.samples = 1;
  15214. texture.generateMipMaps = generateMipMaps;
  15215. texture.samplingMode = samplingMode;
  15216. texture.type = type;
  15217. texture._generateDepthBuffer = generateDepthBuffer;
  15218. texture._generateStencilBuffer = generateStencilBuffer;
  15219. texture._attachments = attachments;
  15220. this._internalTexturesCache.push(texture);
  15221. }
  15222. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15223. // Depth texture
  15224. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15225. gl.activeTexture(gl.TEXTURE0);
  15226. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15227. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15228. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15229. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15230. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15231. 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);
  15232. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15233. depthTexture._framebuffer = framebuffer;
  15234. depthTexture.baseWidth = width;
  15235. depthTexture.baseHeight = height;
  15236. depthTexture.width = width;
  15237. depthTexture.height = height;
  15238. depthTexture.isReady = true;
  15239. depthTexture.samples = 1;
  15240. depthTexture.generateMipMaps = generateMipMaps;
  15241. depthTexture.samplingMode = gl.NEAREST;
  15242. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15243. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15244. textures.push(depthTexture);
  15245. this._internalTexturesCache.push(depthTexture);
  15246. }
  15247. gl.drawBuffers(attachments);
  15248. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15249. this.bindUnboundFramebuffer(null);
  15250. this.resetTextureCache();
  15251. return textures;
  15252. };
  15253. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15254. if (samples === void 0) { samples = 1; }
  15255. var depthStencilBuffer = null;
  15256. var gl = this._gl;
  15257. // Create the depth/stencil buffer
  15258. if (generateStencilBuffer) {
  15259. depthStencilBuffer = gl.createRenderbuffer();
  15260. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15261. if (samples > 1) {
  15262. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15263. }
  15264. else {
  15265. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15266. }
  15267. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15268. }
  15269. else if (generateDepthBuffer) {
  15270. depthStencilBuffer = gl.createRenderbuffer();
  15271. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15272. if (samples > 1) {
  15273. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15274. }
  15275. else {
  15276. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15277. }
  15278. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15279. }
  15280. return depthStencilBuffer;
  15281. };
  15282. /**
  15283. * Updates the sample count of a render target texture
  15284. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15285. * @param texture defines the texture to update
  15286. * @param samples defines the sample count to set
  15287. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15288. */
  15289. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15290. if (this.webGLVersion < 2 || !texture) {
  15291. return 1;
  15292. }
  15293. if (texture.samples === samples) {
  15294. return samples;
  15295. }
  15296. var gl = this._gl;
  15297. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15298. // Dispose previous render buffers
  15299. if (texture._depthStencilBuffer) {
  15300. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15301. texture._depthStencilBuffer = null;
  15302. }
  15303. if (texture._MSAAFramebuffer) {
  15304. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15305. texture._MSAAFramebuffer = null;
  15306. }
  15307. if (texture._MSAARenderBuffer) {
  15308. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15309. texture._MSAARenderBuffer = null;
  15310. }
  15311. if (samples > 1) {
  15312. var framebuffer = gl.createFramebuffer();
  15313. if (!framebuffer) {
  15314. throw new Error("Unable to create multi sampled framebuffer");
  15315. }
  15316. texture._MSAAFramebuffer = framebuffer;
  15317. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15318. var colorRenderbuffer = gl.createRenderbuffer();
  15319. if (!colorRenderbuffer) {
  15320. throw new Error("Unable to create multi sampled framebuffer");
  15321. }
  15322. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15323. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15324. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15325. texture._MSAARenderBuffer = colorRenderbuffer;
  15326. }
  15327. else {
  15328. this.bindUnboundFramebuffer(texture._framebuffer);
  15329. }
  15330. texture.samples = samples;
  15331. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15332. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15333. this.bindUnboundFramebuffer(null);
  15334. return samples;
  15335. };
  15336. /**
  15337. * Update the sample count for a given multiple render target texture
  15338. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15339. * @param textures defines the textures to update
  15340. * @param samples defines the sample count to set
  15341. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15342. */
  15343. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15344. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15345. return 1;
  15346. }
  15347. if (textures[0].samples === samples) {
  15348. return samples;
  15349. }
  15350. var gl = this._gl;
  15351. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15352. // Dispose previous render buffers
  15353. if (textures[0]._depthStencilBuffer) {
  15354. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15355. textures[0]._depthStencilBuffer = null;
  15356. }
  15357. if (textures[0]._MSAAFramebuffer) {
  15358. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15359. textures[0]._MSAAFramebuffer = null;
  15360. }
  15361. for (var i = 0; i < textures.length; i++) {
  15362. if (textures[i]._MSAARenderBuffer) {
  15363. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15364. textures[i]._MSAARenderBuffer = null;
  15365. }
  15366. }
  15367. if (samples > 1) {
  15368. var framebuffer = gl.createFramebuffer();
  15369. if (!framebuffer) {
  15370. throw new Error("Unable to create multi sampled framebuffer");
  15371. }
  15372. this.bindUnboundFramebuffer(framebuffer);
  15373. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15374. var attachments = [];
  15375. for (var i = 0; i < textures.length; i++) {
  15376. var texture = textures[i];
  15377. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15378. var colorRenderbuffer = gl.createRenderbuffer();
  15379. if (!colorRenderbuffer) {
  15380. throw new Error("Unable to create multi sampled framebuffer");
  15381. }
  15382. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15383. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15384. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15385. texture._MSAAFramebuffer = framebuffer;
  15386. texture._MSAARenderBuffer = colorRenderbuffer;
  15387. texture.samples = samples;
  15388. texture._depthStencilBuffer = depthStencilBuffer;
  15389. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15390. attachments.push(attachment);
  15391. }
  15392. gl.drawBuffers(attachments);
  15393. }
  15394. else {
  15395. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15396. }
  15397. this.bindUnboundFramebuffer(null);
  15398. return samples;
  15399. };
  15400. /** @hidden */
  15401. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15402. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15403. };
  15404. /** @hidden */
  15405. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15406. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15407. };
  15408. /**
  15409. * Creates a new render target cube texture
  15410. * @param size defines the size of the texture
  15411. * @param options defines the options used to create the texture
  15412. * @returns a new render target cube texture stored in an InternalTexture
  15413. */
  15414. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15415. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15416. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15417. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15418. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15419. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15420. }
  15421. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15422. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15423. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15424. }
  15425. var gl = this._gl;
  15426. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15427. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15428. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15429. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15430. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15431. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15432. }
  15433. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15434. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15435. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15436. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15437. for (var face = 0; face < 6; face++) {
  15438. 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);
  15439. }
  15440. // Create the framebuffer
  15441. var framebuffer = gl.createFramebuffer();
  15442. this.bindUnboundFramebuffer(framebuffer);
  15443. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15444. // MipMaps
  15445. if (fullOptions.generateMipMaps) {
  15446. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15447. }
  15448. // Unbind
  15449. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15450. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15451. this.bindUnboundFramebuffer(null);
  15452. texture._framebuffer = framebuffer;
  15453. texture.width = size;
  15454. texture.height = size;
  15455. texture.isReady = true;
  15456. texture.isCube = true;
  15457. texture.samples = 1;
  15458. texture.generateMipMaps = fullOptions.generateMipMaps;
  15459. texture.samplingMode = fullOptions.samplingMode;
  15460. texture.type = fullOptions.type;
  15461. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15462. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15463. this._internalTexturesCache.push(texture);
  15464. return texture;
  15465. };
  15466. /**
  15467. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15468. * @param rootUrl defines the url where the file to load is located
  15469. * @param scene defines the current scene
  15470. * @param scale defines scale to apply to the mip map selection
  15471. * @param offset defines offset to apply to the mip map selection
  15472. * @param onLoad defines an optional callback raised when the texture is loaded
  15473. * @param onError defines an optional callback raised if there is an issue to load the texture
  15474. * @param format defines the format of the data
  15475. * @param forcedExtension defines the extension to use to pick the right loader
  15476. * @returns the cube texture as an InternalTexture
  15477. */
  15478. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15479. var _this = this;
  15480. if (onLoad === void 0) { onLoad = null; }
  15481. if (onError === void 0) { onError = null; }
  15482. if (forcedExtension === void 0) { forcedExtension = null; }
  15483. var callback = function (loadData) {
  15484. if (!loadData) {
  15485. if (onLoad) {
  15486. onLoad(null);
  15487. }
  15488. return;
  15489. }
  15490. var texture = loadData.texture;
  15491. if (loadData.info.sphericalPolynomial) {
  15492. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15493. }
  15494. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15495. texture._lodGenerationScale = scale;
  15496. texture._lodGenerationOffset = offset;
  15497. if (_this._caps.textureLOD) {
  15498. // Do not add extra process if texture lod is supported.
  15499. if (onLoad) {
  15500. onLoad(texture);
  15501. }
  15502. return;
  15503. }
  15504. var mipSlices = 3;
  15505. var gl = _this._gl;
  15506. var width = loadData.width;
  15507. if (!width) {
  15508. return;
  15509. }
  15510. var textures = [];
  15511. for (var i = 0; i < mipSlices; i++) {
  15512. //compute LOD from even spacing in smoothness (matching shader calculation)
  15513. var smoothness = i / (mipSlices - 1);
  15514. var roughness = 1 - smoothness;
  15515. var minLODIndex = offset; // roughness = 0
  15516. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15517. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15518. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15519. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15520. glTextureFromLod.isCube = true;
  15521. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15522. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15523. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15524. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15525. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15526. if (loadData.isDDS) {
  15527. var info = loadData.info;
  15528. var data = loadData.data;
  15529. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15530. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15531. }
  15532. else {
  15533. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15534. }
  15535. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15536. // Wrap in a base texture for easy binding.
  15537. var lodTexture = new BABYLON.BaseTexture(scene);
  15538. lodTexture.isCube = true;
  15539. lodTexture._texture = glTextureFromLod;
  15540. glTextureFromLod.isReady = true;
  15541. textures.push(lodTexture);
  15542. }
  15543. texture._lodTextureHigh = textures[2];
  15544. texture._lodTextureMid = textures[1];
  15545. texture._lodTextureLow = textures[0];
  15546. if (onLoad) {
  15547. onLoad(texture);
  15548. }
  15549. };
  15550. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, true);
  15551. };
  15552. /**
  15553. * Creates a cube texture
  15554. * @param rootUrl defines the url where the files to load is located
  15555. * @param scene defines the current scene
  15556. * @param files defines the list of files to load (1 per face)
  15557. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15558. * @param onLoad defines an optional callback raised when the texture is loaded
  15559. * @param onError defines an optional callback raised if there is an issue to load the texture
  15560. * @param format defines the format of the data
  15561. * @param forcedExtension defines the extension to use to pick the right loader
  15562. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15563. * @returns the cube texture as an InternalTexture
  15564. */
  15565. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15566. var _this = this;
  15567. if (onLoad === void 0) { onLoad = null; }
  15568. if (onError === void 0) { onError = null; }
  15569. if (forcedExtension === void 0) { forcedExtension = null; }
  15570. if (createPolynomials === void 0) { createPolynomials = false; }
  15571. var gl = this._gl;
  15572. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15573. texture.isCube = true;
  15574. texture.url = rootUrl;
  15575. texture.generateMipMaps = !noMipmap;
  15576. if (!this._doNotHandleContextLost) {
  15577. texture._extension = forcedExtension;
  15578. texture._files = files;
  15579. }
  15580. var isKTX = false;
  15581. var isDDS = false;
  15582. var lastDot = rootUrl.lastIndexOf('.');
  15583. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15584. if (this._textureFormatInUse) {
  15585. extension = this._textureFormatInUse;
  15586. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15587. isKTX = true;
  15588. }
  15589. else {
  15590. isDDS = (extension === ".dds");
  15591. }
  15592. var onerror = function (request, exception) {
  15593. if (onError && request) {
  15594. onError(request.status + " " + request.statusText, exception);
  15595. }
  15596. };
  15597. if (isKTX) {
  15598. this._loadFile(rootUrl, function (data) {
  15599. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15600. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15601. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15602. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15603. ktx.uploadLevels(_this._gl, !noMipmap);
  15604. _this.setCubeMapTextureParams(gl, loadMipmap);
  15605. texture.width = ktx.pixelWidth;
  15606. texture.height = ktx.pixelHeight;
  15607. texture.isReady = true;
  15608. }, undefined, undefined, true, onerror);
  15609. }
  15610. else if (isDDS) {
  15611. if (files && files.length === 6) {
  15612. this._cascadeLoadFiles(scene, function (imgs) {
  15613. var info;
  15614. var loadMipmap = false;
  15615. var width = 0;
  15616. for (var index = 0; index < imgs.length; index++) {
  15617. var data = imgs[index];
  15618. info = BABYLON.DDSTools.GetDDSInfo(data);
  15619. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15620. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15621. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15622. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15623. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15624. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15625. }
  15626. texture.width = info.width;
  15627. texture.height = info.height;
  15628. texture.type = info.textureType;
  15629. width = info.width;
  15630. }
  15631. _this.setCubeMapTextureParams(gl, loadMipmap);
  15632. texture.isReady = true;
  15633. if (onLoad) {
  15634. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15635. }
  15636. }, files, onError);
  15637. }
  15638. else {
  15639. this._loadFile(rootUrl, function (data) {
  15640. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15641. if (createPolynomials) {
  15642. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15643. }
  15644. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15645. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15646. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15647. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15648. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15649. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15650. }
  15651. _this.setCubeMapTextureParams(gl, loadMipmap);
  15652. texture.width = info.width;
  15653. texture.height = info.height;
  15654. texture.isReady = true;
  15655. texture.type = info.textureType;
  15656. if (onLoad) {
  15657. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15658. }
  15659. }, undefined, undefined, true, onerror);
  15660. }
  15661. }
  15662. else {
  15663. if (!files) {
  15664. throw new Error("Cannot load cubemap because files were not defined");
  15665. }
  15666. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15667. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15668. var height = width;
  15669. _this._prepareWorkingCanvas();
  15670. if (!_this._workingCanvas || !_this._workingContext) {
  15671. return;
  15672. }
  15673. _this._workingCanvas.width = width;
  15674. _this._workingCanvas.height = height;
  15675. var faces = [
  15676. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15677. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15678. ];
  15679. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15680. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15681. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15682. for (var index = 0; index < faces.length; index++) {
  15683. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15684. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15685. }
  15686. if (!noMipmap) {
  15687. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15688. }
  15689. _this.setCubeMapTextureParams(gl, !noMipmap);
  15690. texture.width = width;
  15691. texture.height = height;
  15692. texture.isReady = true;
  15693. if (format) {
  15694. texture.format = format;
  15695. }
  15696. texture.onLoadedObservable.notifyObservers(texture);
  15697. texture.onLoadedObservable.clear();
  15698. if (onLoad) {
  15699. onLoad();
  15700. }
  15701. }, files, onError);
  15702. }
  15703. this._internalTexturesCache.push(texture);
  15704. return texture;
  15705. };
  15706. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15707. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15708. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15709. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15710. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15711. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15712. // this.resetTextureCache();
  15713. };
  15714. /**
  15715. * Update a raw cube texture
  15716. * @param texture defines the texture to udpdate
  15717. * @param data defines the data to store
  15718. * @param format defines the data format
  15719. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15720. * @param invertY defines if data must be stored with Y axis inverted
  15721. * @param compression defines the compression used (null by default)
  15722. * @param level defines which level of the texture to update
  15723. */
  15724. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15725. if (compression === void 0) { compression = null; }
  15726. if (level === void 0) { level = 0; }
  15727. texture._bufferViewArray = data;
  15728. texture.format = format;
  15729. texture.type = type;
  15730. texture.invertY = invertY;
  15731. texture._compression = compression;
  15732. var gl = this._gl;
  15733. var textureType = this._getWebGLTextureType(type);
  15734. var internalFormat = this._getInternalFormat(format);
  15735. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15736. var needConversion = false;
  15737. if (internalFormat === gl.RGB) {
  15738. internalFormat = gl.RGBA;
  15739. needConversion = true;
  15740. }
  15741. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15742. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15743. if (texture.width % 4 !== 0) {
  15744. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15745. }
  15746. // Data are known to be in +X +Y +Z -X -Y -Z
  15747. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15748. var faceData = data[faceIndex];
  15749. if (compression) {
  15750. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15751. }
  15752. else {
  15753. if (needConversion) {
  15754. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15755. }
  15756. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15757. }
  15758. }
  15759. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15760. if (isPot && texture.generateMipMaps && level === 0) {
  15761. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15762. }
  15763. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15764. // this.resetTextureCache();
  15765. texture.isReady = true;
  15766. };
  15767. /**
  15768. * Creates a new raw cube texture
  15769. * @param data defines the array of data to use to create each face
  15770. * @param size defines the size of the textures
  15771. * @param format defines the format of the data
  15772. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15773. * @param generateMipMaps defines if the engine should generate the mip levels
  15774. * @param invertY defines if data must be stored with Y axis inverted
  15775. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15776. * @param compression defines the compression used (null by default)
  15777. * @returns the cube texture as an InternalTexture
  15778. */
  15779. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15780. if (compression === void 0) { compression = null; }
  15781. var gl = this._gl;
  15782. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15783. texture.isCube = true;
  15784. texture.generateMipMaps = generateMipMaps;
  15785. texture.format = format;
  15786. texture.type = type;
  15787. if (!this._doNotHandleContextLost) {
  15788. texture._bufferViewArray = data;
  15789. }
  15790. var textureType = this._getWebGLTextureType(type);
  15791. var internalFormat = this._getInternalFormat(format);
  15792. if (internalFormat === gl.RGB) {
  15793. internalFormat = gl.RGBA;
  15794. }
  15795. var width = size;
  15796. var height = width;
  15797. texture.width = width;
  15798. texture.height = height;
  15799. // Double check on POT to generate Mips.
  15800. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15801. if (!isPot) {
  15802. generateMipMaps = false;
  15803. }
  15804. // Upload data if needed. The texture won't be ready until then.
  15805. if (data) {
  15806. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15807. }
  15808. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15809. // Filters
  15810. if (data && generateMipMaps) {
  15811. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15812. }
  15813. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15814. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15815. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15816. }
  15817. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15819. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15820. }
  15821. else {
  15822. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15823. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15824. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15825. }
  15826. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15827. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15828. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15829. return texture;
  15830. };
  15831. /**
  15832. * Creates a new raw cube texture from a specified url
  15833. * @param url defines the url where the data is located
  15834. * @param scene defines the current scene
  15835. * @param size defines the size of the textures
  15836. * @param format defines the format of the data
  15837. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15838. * @param noMipmap defines if the engine should avoid generating the mip levels
  15839. * @param callback defines a callback used to extract texture data from loaded data
  15840. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15841. * @param onLoad defines a callback called when texture is loaded
  15842. * @param onError defines a callback called if there is an error
  15843. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15844. * @param invertY defines if data must be stored with Y axis inverted
  15845. * @returns the cube texture as an InternalTexture
  15846. */
  15847. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15848. var _this = this;
  15849. if (onLoad === void 0) { onLoad = null; }
  15850. if (onError === void 0) { onError = null; }
  15851. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15852. if (invertY === void 0) { invertY = false; }
  15853. var gl = this._gl;
  15854. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15855. scene._addPendingData(texture);
  15856. texture.url = url;
  15857. this._internalTexturesCache.push(texture);
  15858. var onerror = function (request, exception) {
  15859. scene._removePendingData(texture);
  15860. if (onError && request) {
  15861. onError(request.status + " " + request.statusText, exception);
  15862. }
  15863. };
  15864. var internalCallback = function (data) {
  15865. var width = texture.width;
  15866. var faceDataArrays = callback(data);
  15867. if (!faceDataArrays) {
  15868. return;
  15869. }
  15870. if (mipmapGenerator) {
  15871. var textureType = _this._getWebGLTextureType(type);
  15872. var internalFormat = _this._getInternalFormat(format);
  15873. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15874. var needConversion = false;
  15875. if (internalFormat === gl.RGB) {
  15876. internalFormat = gl.RGBA;
  15877. needConversion = true;
  15878. }
  15879. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15880. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15881. var mipData = mipmapGenerator(faceDataArrays);
  15882. for (var level = 0; level < mipData.length; level++) {
  15883. var mipSize = width >> level;
  15884. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15885. var mipFaceData = mipData[level][faceIndex];
  15886. if (needConversion) {
  15887. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15888. }
  15889. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15890. }
  15891. }
  15892. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15893. }
  15894. else {
  15895. texture.generateMipMaps = !noMipmap;
  15896. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15897. }
  15898. texture.isReady = true;
  15899. // this.resetTextureCache();
  15900. scene._removePendingData(texture);
  15901. if (onLoad) {
  15902. onLoad();
  15903. }
  15904. };
  15905. this._loadFile(url, function (data) {
  15906. internalCallback(data);
  15907. }, undefined, scene.database, true, onerror);
  15908. return texture;
  15909. };
  15910. ;
  15911. /**
  15912. * Update a raw 3D texture
  15913. * @param texture defines the texture to update
  15914. * @param data defines the data to store
  15915. * @param format defines the data format
  15916. * @param invertY defines if data must be stored with Y axis inverted
  15917. * @param compression defines the used compression (can be null)
  15918. */
  15919. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15920. if (compression === void 0) { compression = null; }
  15921. var internalFormat = this._getInternalFormat(format);
  15922. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15923. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15924. if (!this._doNotHandleContextLost) {
  15925. texture._bufferView = data;
  15926. texture.format = format;
  15927. texture.invertY = invertY;
  15928. texture._compression = compression;
  15929. }
  15930. if (texture.width % 4 !== 0) {
  15931. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15932. }
  15933. if (compression && data) {
  15934. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15935. }
  15936. else {
  15937. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15938. }
  15939. if (texture.generateMipMaps) {
  15940. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15941. }
  15942. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15943. // this.resetTextureCache();
  15944. texture.isReady = true;
  15945. };
  15946. /**
  15947. * Creates a new raw 3D texture
  15948. * @param data defines the data used to create the texture
  15949. * @param width defines the width of the texture
  15950. * @param height defines the height of the texture
  15951. * @param depth defines the depth of the texture
  15952. * @param format defines the format of the texture
  15953. * @param generateMipMaps defines if the engine must generate mip levels
  15954. * @param invertY defines if data must be stored with Y axis inverted
  15955. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15956. * @param compression defines the compressed used (can be null)
  15957. * @returns a new raw 3D texture (stored in an InternalTexture)
  15958. */
  15959. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15960. if (compression === void 0) { compression = null; }
  15961. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15962. texture.baseWidth = width;
  15963. texture.baseHeight = height;
  15964. texture.baseDepth = depth;
  15965. texture.width = width;
  15966. texture.height = height;
  15967. texture.depth = depth;
  15968. texture.format = format;
  15969. texture.generateMipMaps = generateMipMaps;
  15970. texture.samplingMode = samplingMode;
  15971. texture.is3D = true;
  15972. if (!this._doNotHandleContextLost) {
  15973. texture._bufferView = data;
  15974. }
  15975. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15976. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15977. // Filters
  15978. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15979. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15980. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15981. if (generateMipMaps) {
  15982. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15983. }
  15984. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15985. this._internalTexturesCache.push(texture);
  15986. return texture;
  15987. };
  15988. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15989. var gl = this._gl;
  15990. if (!gl) {
  15991. return;
  15992. }
  15993. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  15994. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15995. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15996. if (!noMipmap && !isCompressed) {
  15997. gl.generateMipmap(gl.TEXTURE_2D);
  15998. }
  15999. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16000. // this.resetTextureCache();
  16001. if (scene) {
  16002. scene._removePendingData(texture);
  16003. }
  16004. texture.onLoadedObservable.notifyObservers(texture);
  16005. texture.onLoadedObservable.clear();
  16006. };
  16007. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16008. var _this = this;
  16009. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16010. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16011. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16012. var gl = this._gl;
  16013. if (!gl) {
  16014. return;
  16015. }
  16016. if (!texture._webGLTexture) {
  16017. // this.resetTextureCache();
  16018. if (scene) {
  16019. scene._removePendingData(texture);
  16020. }
  16021. return;
  16022. }
  16023. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16024. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16025. texture.baseWidth = width;
  16026. texture.baseHeight = height;
  16027. texture.width = potWidth;
  16028. texture.height = potHeight;
  16029. texture.isReady = true;
  16030. if (processFunction(potWidth, potHeight, function () {
  16031. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16032. })) {
  16033. // Returning as texture needs extra async steps
  16034. return;
  16035. }
  16036. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16037. };
  16038. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16039. // Create new RGBA data container.
  16040. var rgbaData;
  16041. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16042. rgbaData = new Float32Array(width * height * 4);
  16043. }
  16044. else {
  16045. rgbaData = new Uint32Array(width * height * 4);
  16046. }
  16047. // Convert each pixel.
  16048. for (var x = 0; x < width; x++) {
  16049. for (var y = 0; y < height; y++) {
  16050. var index = (y * width + x) * 3;
  16051. var newIndex = (y * width + x) * 4;
  16052. // Map Old Value to new value.
  16053. rgbaData[newIndex + 0] = rgbData[index + 0];
  16054. rgbaData[newIndex + 1] = rgbData[index + 1];
  16055. rgbaData[newIndex + 2] = rgbData[index + 2];
  16056. // Add fully opaque alpha channel.
  16057. rgbaData[newIndex + 3] = 1;
  16058. }
  16059. }
  16060. return rgbaData;
  16061. };
  16062. /** @hidden */
  16063. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16064. var gl = this._gl;
  16065. if (texture._framebuffer) {
  16066. gl.deleteFramebuffer(texture._framebuffer);
  16067. texture._framebuffer = null;
  16068. }
  16069. if (texture._depthStencilBuffer) {
  16070. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16071. texture._depthStencilBuffer = null;
  16072. }
  16073. if (texture._MSAAFramebuffer) {
  16074. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16075. texture._MSAAFramebuffer = null;
  16076. }
  16077. if (texture._MSAARenderBuffer) {
  16078. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16079. texture._MSAARenderBuffer = null;
  16080. }
  16081. };
  16082. /** @hidden */
  16083. Engine.prototype._releaseTexture = function (texture) {
  16084. var gl = this._gl;
  16085. this._releaseFramebufferObjects(texture);
  16086. gl.deleteTexture(texture._webGLTexture);
  16087. // Unbind channels
  16088. this.unbindAllTextures();
  16089. var index = this._internalTexturesCache.indexOf(texture);
  16090. if (index !== -1) {
  16091. this._internalTexturesCache.splice(index, 1);
  16092. }
  16093. // Integrated fixed lod samplers.
  16094. if (texture._lodTextureHigh) {
  16095. texture._lodTextureHigh.dispose();
  16096. }
  16097. if (texture._lodTextureMid) {
  16098. texture._lodTextureMid.dispose();
  16099. }
  16100. if (texture._lodTextureLow) {
  16101. texture._lodTextureLow.dispose();
  16102. }
  16103. // Set output texture of post process to null if the texture has been released/disposed
  16104. this.scenes.forEach(function (scene) {
  16105. scene.postProcesses.forEach(function (postProcess) {
  16106. if (postProcess._outputTexture == texture) {
  16107. postProcess._outputTexture = null;
  16108. }
  16109. });
  16110. scene.cameras.forEach(function (camera) {
  16111. camera._postProcesses.forEach(function (postProcess) {
  16112. if (postProcess) {
  16113. if (postProcess._outputTexture == texture) {
  16114. postProcess._outputTexture = null;
  16115. }
  16116. }
  16117. });
  16118. });
  16119. });
  16120. };
  16121. Engine.prototype.setProgram = function (program) {
  16122. if (this._currentProgram !== program) {
  16123. this._gl.useProgram(program);
  16124. this._currentProgram = program;
  16125. }
  16126. };
  16127. /**
  16128. * Binds an effect to the webGL context
  16129. * @param effect defines the effect to bind
  16130. */
  16131. Engine.prototype.bindSamplers = function (effect) {
  16132. this.setProgram(effect.getProgram());
  16133. var samplers = effect.getSamplers();
  16134. for (var index = 0; index < samplers.length; index++) {
  16135. var uniform = effect.getUniform(samplers[index]);
  16136. if (uniform) {
  16137. this._boundUniforms[index] = uniform;
  16138. }
  16139. }
  16140. this._currentEffect = null;
  16141. };
  16142. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16143. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16144. return;
  16145. }
  16146. // Remove
  16147. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16148. // Bind last to it
  16149. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16150. // Bind to dummy
  16151. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16152. };
  16153. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16154. if (!internalTexture) {
  16155. return -1;
  16156. }
  16157. internalTexture._initialSlot = channel;
  16158. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16159. if (channel !== internalTexture._designatedSlot) {
  16160. this._textureCollisions.addCount(1, false);
  16161. }
  16162. }
  16163. else {
  16164. if (channel !== internalTexture._designatedSlot) {
  16165. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16166. return internalTexture._designatedSlot;
  16167. }
  16168. else {
  16169. // No slot for this texture, let's pick a new one (if we find a free slot)
  16170. if (this._nextFreeTextureSlots.length) {
  16171. return this._nextFreeTextureSlots[0];
  16172. }
  16173. // We need to recycle the oldest bound texture, sorry.
  16174. this._textureCollisions.addCount(1, false);
  16175. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16176. }
  16177. }
  16178. }
  16179. return channel;
  16180. };
  16181. Engine.prototype._linkTrackers = function (previous, next) {
  16182. previous.next = next;
  16183. next.previous = previous;
  16184. };
  16185. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16186. var currentSlot = internalTexture._designatedSlot;
  16187. if (currentSlot === -1) {
  16188. return -1;
  16189. }
  16190. internalTexture._designatedSlot = -1;
  16191. if (this.disableTextureBindingOptimization) {
  16192. return -1;
  16193. }
  16194. // Remove from bound list
  16195. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16196. // Free the slot
  16197. this._boundTexturesCache[currentSlot] = null;
  16198. this._nextFreeTextureSlots.push(currentSlot);
  16199. return currentSlot;
  16200. };
  16201. Engine.prototype._activateCurrentTexture = function () {
  16202. if (this._currentTextureChannel !== this._activeChannel) {
  16203. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16204. this._currentTextureChannel = this._activeChannel;
  16205. }
  16206. };
  16207. /** @hidden */
  16208. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16209. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16210. if (force === void 0) { force = false; }
  16211. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16212. this._activeChannel = texture._designatedSlot;
  16213. }
  16214. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16215. var isTextureForRendering = texture && texture._initialSlot > -1;
  16216. if (currentTextureBound !== texture || force) {
  16217. if (currentTextureBound) {
  16218. this._removeDesignatedSlot(currentTextureBound);
  16219. }
  16220. this._activateCurrentTexture();
  16221. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16222. this._boundTexturesCache[this._activeChannel] = texture;
  16223. if (texture) {
  16224. if (!this.disableTextureBindingOptimization) {
  16225. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16226. if (slotIndex > -1) {
  16227. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16228. }
  16229. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16230. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16231. }
  16232. texture._designatedSlot = this._activeChannel;
  16233. }
  16234. }
  16235. else if (forTextureDataUpdate) {
  16236. this._activateCurrentTexture();
  16237. }
  16238. if (isTextureForRendering && !forTextureDataUpdate) {
  16239. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16240. }
  16241. };
  16242. /** @hidden */
  16243. Engine.prototype._bindTexture = function (channel, texture) {
  16244. if (channel < 0) {
  16245. return;
  16246. }
  16247. if (texture) {
  16248. channel = this._getCorrectTextureChannel(channel, texture);
  16249. }
  16250. this._activeChannel = channel;
  16251. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16252. };
  16253. /**
  16254. * Sets a texture to the webGL context from a postprocess
  16255. * @param channel defines the channel to use
  16256. * @param postProcess defines the source postprocess
  16257. */
  16258. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16259. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16260. };
  16261. /**
  16262. * Binds the output of the passed in post process to the texture channel specified
  16263. * @param channel The channel the texture should be bound to
  16264. * @param postProcess The post process which's output should be bound
  16265. */
  16266. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16267. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16268. };
  16269. /**
  16270. * Unbind all textures from the webGL context
  16271. */
  16272. Engine.prototype.unbindAllTextures = function () {
  16273. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16274. this._activeChannel = channel;
  16275. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16276. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16277. if (this.webGLVersion > 1) {
  16278. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16279. }
  16280. }
  16281. };
  16282. /**
  16283. * Sets a texture to the according uniform.
  16284. * @param channel The texture channel
  16285. * @param uniform The uniform to set
  16286. * @param texture The texture to apply
  16287. */
  16288. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16289. if (channel < 0) {
  16290. return;
  16291. }
  16292. if (uniform) {
  16293. this._boundUniforms[channel] = uniform;
  16294. }
  16295. this._setTexture(channel, texture);
  16296. };
  16297. /**
  16298. * Sets a depth stencil texture from a render target to the according uniform.
  16299. * @param channel The texture channel
  16300. * @param uniform The uniform to set
  16301. * @param texture The render target texture containing the depth stencil texture to apply
  16302. */
  16303. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16304. if (channel < 0) {
  16305. return;
  16306. }
  16307. if (uniform) {
  16308. this._boundUniforms[channel] = uniform;
  16309. }
  16310. if (!texture || !texture.depthStencilTexture) {
  16311. this._setTexture(channel, null);
  16312. }
  16313. else {
  16314. this._setTexture(channel, texture, false, true);
  16315. }
  16316. };
  16317. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16318. var uniform = this._boundUniforms[sourceSlot];
  16319. if (uniform._currentState === destination) {
  16320. return;
  16321. }
  16322. this._gl.uniform1i(uniform, destination);
  16323. uniform._currentState = destination;
  16324. };
  16325. Engine.prototype._getTextureWrapMode = function (mode) {
  16326. switch (mode) {
  16327. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16328. return this._gl.REPEAT;
  16329. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16330. return this._gl.CLAMP_TO_EDGE;
  16331. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16332. return this._gl.MIRRORED_REPEAT;
  16333. }
  16334. return this._gl.REPEAT;
  16335. };
  16336. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16337. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16338. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16339. // Not ready?
  16340. if (!texture) {
  16341. if (this._boundTexturesCache[channel] != null) {
  16342. this._activeChannel = channel;
  16343. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16344. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16345. if (this.webGLVersion > 1) {
  16346. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16347. }
  16348. }
  16349. return false;
  16350. }
  16351. // Video
  16352. if (texture.video) {
  16353. this._activeChannel = channel;
  16354. texture.update();
  16355. }
  16356. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16357. texture.delayLoad();
  16358. return false;
  16359. }
  16360. var internalTexture;
  16361. if (depthStencilTexture) {
  16362. internalTexture = texture.depthStencilTexture;
  16363. }
  16364. else if (texture.isReady()) {
  16365. internalTexture = texture.getInternalTexture();
  16366. }
  16367. else if (texture.isCube) {
  16368. internalTexture = this.emptyCubeTexture;
  16369. }
  16370. else if (texture.is3D) {
  16371. internalTexture = this.emptyTexture3D;
  16372. }
  16373. else {
  16374. internalTexture = this.emptyTexture;
  16375. }
  16376. if (!isPartOfTextureArray) {
  16377. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16378. }
  16379. var needToBind = true;
  16380. if (this._boundTexturesCache[channel] === internalTexture) {
  16381. this._moveBoundTextureOnTop(internalTexture);
  16382. if (!isPartOfTextureArray) {
  16383. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16384. }
  16385. needToBind = false;
  16386. }
  16387. this._activeChannel = channel;
  16388. if (internalTexture && internalTexture.is3D) {
  16389. if (needToBind) {
  16390. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16391. }
  16392. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16393. internalTexture._cachedWrapU = texture.wrapU;
  16394. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16395. }
  16396. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16397. internalTexture._cachedWrapV = texture.wrapV;
  16398. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16399. }
  16400. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16401. internalTexture._cachedWrapR = texture.wrapR;
  16402. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16403. }
  16404. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16405. }
  16406. else if (internalTexture && internalTexture.isCube) {
  16407. if (needToBind) {
  16408. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16409. }
  16410. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16411. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16412. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16413. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16414. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16415. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16416. }
  16417. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16418. }
  16419. else {
  16420. if (needToBind) {
  16421. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16422. }
  16423. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16424. internalTexture._cachedWrapU = texture.wrapU;
  16425. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16426. }
  16427. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16428. internalTexture._cachedWrapV = texture.wrapV;
  16429. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16430. }
  16431. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16432. }
  16433. return true;
  16434. };
  16435. /**
  16436. * Sets an array of texture to the webGL context
  16437. * @param channel defines the channel where the texture array must be set
  16438. * @param uniform defines the associated uniform location
  16439. * @param textures defines the array of textures to bind
  16440. */
  16441. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16442. if (channel < 0 || !uniform) {
  16443. return;
  16444. }
  16445. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16446. this._textureUnits = new Int32Array(textures.length);
  16447. }
  16448. for (var i = 0; i < textures.length; i++) {
  16449. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16450. }
  16451. this._gl.uniform1iv(uniform, this._textureUnits);
  16452. for (var index = 0; index < textures.length; index++) {
  16453. this._setTexture(this._textureUnits[index], textures[index], true);
  16454. }
  16455. };
  16456. /** @hidden */
  16457. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16458. var internalTexture = texture.getInternalTexture();
  16459. if (!internalTexture) {
  16460. return;
  16461. }
  16462. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16463. var value = texture.anisotropicFilteringLevel;
  16464. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16465. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16466. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16467. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16468. }
  16469. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16470. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16471. internalTexture._cachedAnisotropicFilteringLevel = value;
  16472. }
  16473. };
  16474. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16475. this._bindTextureDirectly(target, texture, true, true);
  16476. this._gl.texParameterf(target, parameter, value);
  16477. };
  16478. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16479. if (texture) {
  16480. this._bindTextureDirectly(target, texture, true, true);
  16481. }
  16482. this._gl.texParameteri(target, parameter, value);
  16483. };
  16484. /**
  16485. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16486. * @param x defines the x coordinate of the rectangle where pixels must be read
  16487. * @param y defines the y coordinate of the rectangle where pixels must be read
  16488. * @param width defines the width of the rectangle where pixels must be read
  16489. * @param height defines the height of the rectangle where pixels must be read
  16490. * @returns a Uint8Array containing RGBA colors
  16491. */
  16492. Engine.prototype.readPixels = function (x, y, width, height) {
  16493. var data = new Uint8Array(height * width * 4);
  16494. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16495. return data;
  16496. };
  16497. /**
  16498. * Add an externaly attached data from its key.
  16499. * This method call will fail and return false, if such key already exists.
  16500. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16501. * @param key the unique key that identifies the data
  16502. * @param data the data object to associate to the key for this Engine instance
  16503. * @return true if no such key were already present and the data was added successfully, false otherwise
  16504. */
  16505. Engine.prototype.addExternalData = function (key, data) {
  16506. if (!this._externalData) {
  16507. this._externalData = new BABYLON.StringDictionary();
  16508. }
  16509. return this._externalData.add(key, data);
  16510. };
  16511. /**
  16512. * Get an externaly attached data from its key
  16513. * @param key the unique key that identifies the data
  16514. * @return the associated data, if present (can be null), or undefined if not present
  16515. */
  16516. Engine.prototype.getExternalData = function (key) {
  16517. if (!this._externalData) {
  16518. this._externalData = new BABYLON.StringDictionary();
  16519. }
  16520. return this._externalData.get(key);
  16521. };
  16522. /**
  16523. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16524. * @param key the unique key that identifies the data
  16525. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16526. * @return the associated data, can be null if the factory returned null.
  16527. */
  16528. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16529. if (!this._externalData) {
  16530. this._externalData = new BABYLON.StringDictionary();
  16531. }
  16532. return this._externalData.getOrAddWithFactory(key, factory);
  16533. };
  16534. /**
  16535. * Remove an externaly attached data from the Engine instance
  16536. * @param key the unique key that identifies the data
  16537. * @return true if the data was successfully removed, false if it doesn't exist
  16538. */
  16539. Engine.prototype.removeExternalData = function (key) {
  16540. if (!this._externalData) {
  16541. this._externalData = new BABYLON.StringDictionary();
  16542. }
  16543. return this._externalData.remove(key);
  16544. };
  16545. /**
  16546. * Unbind all vertex attributes from the webGL context
  16547. */
  16548. Engine.prototype.unbindAllAttributes = function () {
  16549. if (this._mustWipeVertexAttributes) {
  16550. this._mustWipeVertexAttributes = false;
  16551. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16552. this._gl.disableVertexAttribArray(i);
  16553. this._vertexAttribArraysEnabled[i] = false;
  16554. this._currentBufferPointers[i].active = false;
  16555. }
  16556. return;
  16557. }
  16558. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16559. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16560. continue;
  16561. }
  16562. this._gl.disableVertexAttribArray(i);
  16563. this._vertexAttribArraysEnabled[i] = false;
  16564. this._currentBufferPointers[i].active = false;
  16565. }
  16566. };
  16567. /**
  16568. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  16569. */
  16570. Engine.prototype.releaseEffects = function () {
  16571. for (var name in this._compiledEffects) {
  16572. this._deleteProgram(this._compiledEffects[name]._program);
  16573. }
  16574. this._compiledEffects = {};
  16575. };
  16576. /**
  16577. * Dispose and release all associated resources
  16578. */
  16579. Engine.prototype.dispose = function () {
  16580. this.hideLoadingUI();
  16581. this.stopRenderLoop();
  16582. // Release postProcesses
  16583. while (this.postProcesses.length) {
  16584. this.postProcesses[0].dispose();
  16585. }
  16586. // Empty texture
  16587. if (this._emptyTexture) {
  16588. this._releaseTexture(this._emptyTexture);
  16589. this._emptyTexture = null;
  16590. }
  16591. if (this._emptyCubeTexture) {
  16592. this._releaseTexture(this._emptyCubeTexture);
  16593. this._emptyCubeTexture = null;
  16594. }
  16595. // Rescale PP
  16596. if (this._rescalePostProcess) {
  16597. this._rescalePostProcess.dispose();
  16598. }
  16599. // Release scenes
  16600. while (this.scenes.length) {
  16601. this.scenes[0].dispose();
  16602. }
  16603. // Release audio engine
  16604. if (Engine.audioEngine) {
  16605. Engine.audioEngine.dispose();
  16606. }
  16607. // Release effects
  16608. this.releaseEffects();
  16609. // Unbind
  16610. this.unbindAllAttributes();
  16611. this._boundUniforms = [];
  16612. if (this._dummyFramebuffer) {
  16613. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16614. }
  16615. //WebVR
  16616. this.disableVR();
  16617. // Events
  16618. if (BABYLON.Tools.IsWindowObjectExist()) {
  16619. window.removeEventListener("blur", this._onBlur);
  16620. window.removeEventListener("focus", this._onFocus);
  16621. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16622. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16623. if (this._renderingCanvas) {
  16624. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16625. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16626. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16627. if (!this._doNotHandleContextLost) {
  16628. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16629. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16630. }
  16631. }
  16632. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16633. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16634. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16635. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16636. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16637. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16638. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16639. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16640. if (this._onVrDisplayConnect) {
  16641. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16642. if (this._onVrDisplayDisconnect) {
  16643. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16644. }
  16645. if (this._onVrDisplayPresentChange) {
  16646. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16647. }
  16648. this._onVrDisplayConnect = null;
  16649. this._onVrDisplayDisconnect = null;
  16650. }
  16651. }
  16652. // Remove from Instances
  16653. var index = Engine.Instances.indexOf(this);
  16654. if (index >= 0) {
  16655. Engine.Instances.splice(index, 1);
  16656. }
  16657. this._workingCanvas = null;
  16658. this._workingContext = null;
  16659. this._currentBufferPointers = [];
  16660. this._renderingCanvas = null;
  16661. this._currentProgram = null;
  16662. this._bindedRenderFunction = null;
  16663. this.onResizeObservable.clear();
  16664. this.onCanvasBlurObservable.clear();
  16665. this.onCanvasFocusObservable.clear();
  16666. this.onCanvasPointerOutObservable.clear();
  16667. this.onBeginFrameObservable.clear();
  16668. this.onEndFrameObservable.clear();
  16669. BABYLON.Effect.ResetCache();
  16670. // Abort active requests
  16671. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16672. var request = _a[_i];
  16673. request.abort();
  16674. }
  16675. };
  16676. // Loading screen
  16677. /**
  16678. * Display the loading screen
  16679. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16680. */
  16681. Engine.prototype.displayLoadingUI = function () {
  16682. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16683. return;
  16684. }
  16685. var loadingScreen = this.loadingScreen;
  16686. if (loadingScreen) {
  16687. loadingScreen.displayLoadingUI();
  16688. }
  16689. };
  16690. /**
  16691. * Hide the loading screen
  16692. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16693. */
  16694. Engine.prototype.hideLoadingUI = function () {
  16695. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16696. return;
  16697. }
  16698. var loadingScreen = this.loadingScreen;
  16699. if (loadingScreen) {
  16700. loadingScreen.hideLoadingUI();
  16701. }
  16702. };
  16703. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16704. /**
  16705. * Gets the current loading screen object
  16706. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16707. */
  16708. get: function () {
  16709. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16710. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16711. return this._loadingScreen;
  16712. },
  16713. /**
  16714. * Sets the current loading screen object
  16715. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16716. */
  16717. set: function (loadingScreen) {
  16718. this._loadingScreen = loadingScreen;
  16719. },
  16720. enumerable: true,
  16721. configurable: true
  16722. });
  16723. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16724. /**
  16725. * Sets the current loading screen text
  16726. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16727. */
  16728. set: function (text) {
  16729. this.loadingScreen.loadingUIText = text;
  16730. },
  16731. enumerable: true,
  16732. configurable: true
  16733. });
  16734. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16735. /**
  16736. * Sets the current loading screen background color
  16737. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16738. */
  16739. set: function (color) {
  16740. this.loadingScreen.loadingUIBackgroundColor = color;
  16741. },
  16742. enumerable: true,
  16743. configurable: true
  16744. });
  16745. /**
  16746. * Attach a new callback raised when context lost event is fired
  16747. * @param callback defines the callback to call
  16748. */
  16749. Engine.prototype.attachContextLostEvent = function (callback) {
  16750. if (this._renderingCanvas) {
  16751. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16752. }
  16753. };
  16754. /**
  16755. * Attach a new callback raised when context restored event is fired
  16756. * @param callback defines the callback to call
  16757. */
  16758. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16759. if (this._renderingCanvas) {
  16760. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16761. }
  16762. };
  16763. /**
  16764. * Gets the source code of the vertex shader associated with a specific webGL program
  16765. * @param program defines the program to use
  16766. * @returns a string containing the source code of the vertex shader associated with the program
  16767. */
  16768. Engine.prototype.getVertexShaderSource = function (program) {
  16769. var shaders = this._gl.getAttachedShaders(program);
  16770. if (!shaders) {
  16771. return null;
  16772. }
  16773. return this._gl.getShaderSource(shaders[0]);
  16774. };
  16775. /**
  16776. * Gets the source code of the fragment shader associated with a specific webGL program
  16777. * @param program defines the program to use
  16778. * @returns a string containing the source code of the fragment shader associated with the program
  16779. */
  16780. Engine.prototype.getFragmentShaderSource = function (program) {
  16781. var shaders = this._gl.getAttachedShaders(program);
  16782. if (!shaders) {
  16783. return null;
  16784. }
  16785. return this._gl.getShaderSource(shaders[1]);
  16786. };
  16787. /**
  16788. * Get the current error code of the webGL context
  16789. * @returns the error code
  16790. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16791. */
  16792. Engine.prototype.getError = function () {
  16793. return this._gl.getError();
  16794. };
  16795. // FPS
  16796. /**
  16797. * Gets the current framerate
  16798. * @returns a number representing the framerate
  16799. */
  16800. Engine.prototype.getFps = function () {
  16801. return this._fps;
  16802. };
  16803. /**
  16804. * Gets the time spent between current and previous frame
  16805. * @returns a number representing the delta time in ms
  16806. */
  16807. Engine.prototype.getDeltaTime = function () {
  16808. return this._deltaTime;
  16809. };
  16810. Engine.prototype._measureFps = function () {
  16811. this._performanceMonitor.sampleFrame();
  16812. this._fps = this._performanceMonitor.averageFPS;
  16813. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16814. };
  16815. /** @hidden */
  16816. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16817. if (faceIndex === void 0) { faceIndex = -1; }
  16818. var gl = this._gl;
  16819. if (!this._dummyFramebuffer) {
  16820. var dummy = gl.createFramebuffer();
  16821. if (!dummy) {
  16822. throw new Error("Unable to create dummy framebuffer");
  16823. }
  16824. this._dummyFramebuffer = dummy;
  16825. }
  16826. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16827. if (faceIndex > -1) {
  16828. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16829. }
  16830. else {
  16831. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16832. }
  16833. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16834. var buffer;
  16835. switch (readType) {
  16836. case gl.UNSIGNED_BYTE:
  16837. buffer = new Uint8Array(4 * width * height);
  16838. readType = gl.UNSIGNED_BYTE;
  16839. break;
  16840. default:
  16841. buffer = new Float32Array(4 * width * height);
  16842. readType = gl.FLOAT;
  16843. break;
  16844. }
  16845. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16846. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16847. return buffer;
  16848. };
  16849. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16850. if (this._webGLVersion > 1) {
  16851. return this._caps.colorBufferFloat;
  16852. }
  16853. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16854. };
  16855. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16856. if (this._webGLVersion > 1) {
  16857. return this._caps.colorBufferFloat;
  16858. }
  16859. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16860. };
  16861. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16862. Engine.prototype._canRenderToFramebuffer = function (type) {
  16863. var gl = this._gl;
  16864. //clear existing errors
  16865. while (gl.getError() !== gl.NO_ERROR) { }
  16866. var successful = true;
  16867. var texture = gl.createTexture();
  16868. gl.bindTexture(gl.TEXTURE_2D, texture);
  16869. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16870. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16871. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16872. var fb = gl.createFramebuffer();
  16873. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16874. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16875. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16876. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16877. successful = successful && (gl.getError() === gl.NO_ERROR);
  16878. //try render by clearing frame buffer's color buffer
  16879. if (successful) {
  16880. gl.clear(gl.COLOR_BUFFER_BIT);
  16881. successful = successful && (gl.getError() === gl.NO_ERROR);
  16882. }
  16883. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16884. if (successful) {
  16885. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16886. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16887. var readFormat = gl.RGBA;
  16888. var readType = gl.UNSIGNED_BYTE;
  16889. var buffer = new Uint8Array(4);
  16890. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16891. successful = successful && (gl.getError() === gl.NO_ERROR);
  16892. }
  16893. //clean up
  16894. gl.deleteTexture(texture);
  16895. gl.deleteFramebuffer(fb);
  16896. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16897. //clear accumulated errors
  16898. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16899. return successful;
  16900. };
  16901. /** @hidden */
  16902. Engine.prototype._getWebGLTextureType = function (type) {
  16903. if (type === Engine.TEXTURETYPE_FLOAT) {
  16904. return this._gl.FLOAT;
  16905. }
  16906. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16907. // Add Half Float Constant.
  16908. return this._gl.HALF_FLOAT_OES;
  16909. }
  16910. return this._gl.UNSIGNED_BYTE;
  16911. };
  16912. ;
  16913. Engine.prototype._getInternalFormat = function (format) {
  16914. var internalFormat = this._gl.RGBA;
  16915. switch (format) {
  16916. case Engine.TEXTUREFORMAT_ALPHA:
  16917. internalFormat = this._gl.ALPHA;
  16918. break;
  16919. case Engine.TEXTUREFORMAT_LUMINANCE:
  16920. internalFormat = this._gl.LUMINANCE;
  16921. break;
  16922. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16923. internalFormat = this._gl.LUMINANCE_ALPHA;
  16924. break;
  16925. case Engine.TEXTUREFORMAT_RGB:
  16926. case Engine.TEXTUREFORMAT_RGB32F:
  16927. internalFormat = this._gl.RGB;
  16928. break;
  16929. case Engine.TEXTUREFORMAT_RGBA:
  16930. case Engine.TEXTUREFORMAT_RGBA32F:
  16931. internalFormat = this._gl.RGBA;
  16932. break;
  16933. case Engine.TEXTUREFORMAT_R32F:
  16934. internalFormat = this._gl.RED;
  16935. break;
  16936. case Engine.TEXTUREFORMAT_RG32F:
  16937. internalFormat = this._gl.RG;
  16938. break;
  16939. }
  16940. return internalFormat;
  16941. };
  16942. /** @hidden */
  16943. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16944. if (this._webGLVersion === 1) {
  16945. if (format) {
  16946. switch (format) {
  16947. case Engine.TEXTUREFORMAT_LUMINANCE:
  16948. return this._gl.LUMINANCE;
  16949. }
  16950. }
  16951. return this._gl.RGBA;
  16952. }
  16953. if (type === Engine.TEXTURETYPE_FLOAT) {
  16954. if (format) {
  16955. switch (format) {
  16956. case Engine.TEXTUREFORMAT_R32F:
  16957. return this._gl.R32F;
  16958. case Engine.TEXTUREFORMAT_RG32F:
  16959. return this._gl.RG32F;
  16960. case Engine.TEXTUREFORMAT_RGB32F:
  16961. return this._gl.RGB32F;
  16962. }
  16963. }
  16964. return this._gl.RGBA32F;
  16965. }
  16966. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16967. return this._gl.RGBA16F;
  16968. }
  16969. if (format) {
  16970. switch (format) {
  16971. case Engine.TEXTUREFORMAT_LUMINANCE:
  16972. return this._gl.LUMINANCE;
  16973. }
  16974. }
  16975. return this._gl.RGBA;
  16976. };
  16977. ;
  16978. /** @hidden */
  16979. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16980. if (type === Engine.TEXTURETYPE_FLOAT) {
  16981. return this._gl.RGBA32F;
  16982. }
  16983. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16984. return this._gl.RGBA16F;
  16985. }
  16986. return this._gl.RGBA8;
  16987. };
  16988. ;
  16989. /**
  16990. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  16991. * @return the new query
  16992. */
  16993. Engine.prototype.createQuery = function () {
  16994. return this._gl.createQuery();
  16995. };
  16996. /**
  16997. * Delete and release a webGL query
  16998. * @param query defines the query to delete
  16999. * @return the current engine
  17000. */
  17001. Engine.prototype.deleteQuery = function (query) {
  17002. this._gl.deleteQuery(query);
  17003. return this;
  17004. };
  17005. /**
  17006. * Check if a given query has resolved and got its value
  17007. * @param query defines the query to check
  17008. * @returns true if the query got its value
  17009. */
  17010. Engine.prototype.isQueryResultAvailable = function (query) {
  17011. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17012. };
  17013. /**
  17014. * Gets the value of a given query
  17015. * @param query defines the query to check
  17016. * @returns the value of the query
  17017. */
  17018. Engine.prototype.getQueryResult = function (query) {
  17019. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17020. };
  17021. /**
  17022. * Initiates an occlusion query
  17023. * @param algorithmType defines the algorithm to use
  17024. * @param query defines the query to use
  17025. * @returns the current engine
  17026. * @see http://doc.babylonjs.com/features/occlusionquery
  17027. */
  17028. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17029. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17030. this._gl.beginQuery(glAlgorithm, query);
  17031. return this;
  17032. };
  17033. /**
  17034. * Ends an occlusion query
  17035. * @see http://doc.babylonjs.com/features/occlusionquery
  17036. * @param algorithmType defines the algorithm to use
  17037. * @returns the current engine
  17038. */
  17039. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17040. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17041. this._gl.endQuery(glAlgorithm);
  17042. return this;
  17043. };
  17044. /* Time queries */
  17045. Engine.prototype._createTimeQuery = function () {
  17046. var timerQuery = this._caps.timerQuery;
  17047. if (timerQuery.createQueryEXT) {
  17048. return timerQuery.createQueryEXT();
  17049. }
  17050. return this.createQuery();
  17051. };
  17052. Engine.prototype._deleteTimeQuery = function (query) {
  17053. var timerQuery = this._caps.timerQuery;
  17054. if (timerQuery.deleteQueryEXT) {
  17055. timerQuery.deleteQueryEXT(query);
  17056. return;
  17057. }
  17058. this.deleteQuery(query);
  17059. };
  17060. Engine.prototype._getTimeQueryResult = function (query) {
  17061. var timerQuery = this._caps.timerQuery;
  17062. if (timerQuery.getQueryObjectEXT) {
  17063. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17064. }
  17065. return this.getQueryResult(query);
  17066. };
  17067. Engine.prototype._getTimeQueryAvailability = function (query) {
  17068. var timerQuery = this._caps.timerQuery;
  17069. if (timerQuery.getQueryObjectEXT) {
  17070. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17071. }
  17072. return this.isQueryResultAvailable(query);
  17073. };
  17074. /**
  17075. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17076. * Please note that only one query can be issued at a time
  17077. * @returns a time token used to track the time span
  17078. */
  17079. Engine.prototype.startTimeQuery = function () {
  17080. var timerQuery = this._caps.timerQuery;
  17081. if (!timerQuery) {
  17082. return null;
  17083. }
  17084. var token = new BABYLON._TimeToken();
  17085. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17086. if (this._caps.canUseTimestampForTimerQuery) {
  17087. token._startTimeQuery = this._createTimeQuery();
  17088. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17089. }
  17090. else {
  17091. if (this._currentNonTimestampToken) {
  17092. return this._currentNonTimestampToken;
  17093. }
  17094. token._timeElapsedQuery = this._createTimeQuery();
  17095. if (timerQuery.beginQueryEXT) {
  17096. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17097. }
  17098. else {
  17099. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17100. }
  17101. this._currentNonTimestampToken = token;
  17102. }
  17103. return token;
  17104. };
  17105. /**
  17106. * Ends a time query
  17107. * @param token defines the token used to measure the time span
  17108. * @returns the time spent (in ns)
  17109. */
  17110. Engine.prototype.endTimeQuery = function (token) {
  17111. var timerQuery = this._caps.timerQuery;
  17112. if (!timerQuery || !token) {
  17113. return -1;
  17114. }
  17115. if (this._caps.canUseTimestampForTimerQuery) {
  17116. if (!token._startTimeQuery) {
  17117. return -1;
  17118. }
  17119. if (!token._endTimeQuery) {
  17120. token._endTimeQuery = this._createTimeQuery();
  17121. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17122. }
  17123. }
  17124. else if (!token._timeElapsedQueryEnded) {
  17125. if (!token._timeElapsedQuery) {
  17126. return -1;
  17127. }
  17128. if (timerQuery.endQueryEXT) {
  17129. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17130. }
  17131. else {
  17132. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17133. }
  17134. token._timeElapsedQueryEnded = true;
  17135. }
  17136. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17137. var available = false;
  17138. if (token._endTimeQuery) {
  17139. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17140. }
  17141. else if (token._timeElapsedQuery) {
  17142. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17143. }
  17144. if (available && !disjoint) {
  17145. var result = 0;
  17146. if (this._caps.canUseTimestampForTimerQuery) {
  17147. if (!token._startTimeQuery || !token._endTimeQuery) {
  17148. return -1;
  17149. }
  17150. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17151. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17152. result = timeEnd - timeStart;
  17153. this._deleteTimeQuery(token._startTimeQuery);
  17154. this._deleteTimeQuery(token._endTimeQuery);
  17155. token._startTimeQuery = null;
  17156. token._endTimeQuery = null;
  17157. }
  17158. else {
  17159. if (!token._timeElapsedQuery) {
  17160. return -1;
  17161. }
  17162. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17163. this._deleteTimeQuery(token._timeElapsedQuery);
  17164. token._timeElapsedQuery = null;
  17165. token._timeElapsedQueryEnded = false;
  17166. this._currentNonTimestampToken = null;
  17167. }
  17168. return result;
  17169. }
  17170. return -1;
  17171. };
  17172. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17173. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17174. };
  17175. // Transform feedback
  17176. /**
  17177. * Creates a webGL transform feedback object
  17178. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17179. * @returns the webGL transform feedback object
  17180. */
  17181. Engine.prototype.createTransformFeedback = function () {
  17182. return this._gl.createTransformFeedback();
  17183. };
  17184. /**
  17185. * Delete a webGL transform feedback object
  17186. * @param value defines the webGL transform feedback object to delete
  17187. */
  17188. Engine.prototype.deleteTransformFeedback = function (value) {
  17189. this._gl.deleteTransformFeedback(value);
  17190. };
  17191. /**
  17192. * Bind a webGL transform feedback object to the webgl context
  17193. * @param value defines the webGL transform feedback object to bind
  17194. */
  17195. Engine.prototype.bindTransformFeedback = function (value) {
  17196. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17197. };
  17198. /**
  17199. * Begins a transform feedback operation
  17200. * @param usePoints defines if points or triangles must be used
  17201. */
  17202. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17203. if (usePoints === void 0) { usePoints = true; }
  17204. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17205. };
  17206. /**
  17207. * Ends a transform feedback operation
  17208. */
  17209. Engine.prototype.endTransformFeedback = function () {
  17210. this._gl.endTransformFeedback();
  17211. };
  17212. /**
  17213. * Specify the varyings to use with transform feedback
  17214. * @param program defines the associated webGL program
  17215. * @param value defines the list of strings representing the varying names
  17216. */
  17217. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17218. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17219. };
  17220. /**
  17221. * Bind a webGL buffer for a transform feedback operation
  17222. * @param value defines the webGL buffer to bind
  17223. */
  17224. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17225. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17226. };
  17227. /** @hidden */
  17228. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17229. var _this = this;
  17230. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17231. this._activeRequests.push(request);
  17232. request.onCompleteObservable.add(function (request) {
  17233. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17234. });
  17235. return request;
  17236. };
  17237. /** @hidden */
  17238. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17239. var _this = this;
  17240. return new Promise(function (resolve, reject) {
  17241. _this._loadFile(url, function (data) {
  17242. resolve(data);
  17243. }, undefined, database, useArrayBuffer, function (request, exception) {
  17244. reject(exception);
  17245. });
  17246. });
  17247. };
  17248. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17249. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17250. var onload = function (data) {
  17251. loadedFiles[index] = data;
  17252. loadedFiles._internalCount++;
  17253. if (loadedFiles._internalCount === 6) {
  17254. onfinish(loadedFiles);
  17255. }
  17256. };
  17257. var onerror = function (request, exception) {
  17258. if (onErrorCallBack && request) {
  17259. onErrorCallBack(request.status + " " + request.statusText, exception);
  17260. }
  17261. };
  17262. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17263. };
  17264. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17265. if (onError === void 0) { onError = null; }
  17266. var loadedFiles = [];
  17267. loadedFiles._internalCount = 0;
  17268. for (var index = 0; index < 6; index++) {
  17269. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17270. }
  17271. };
  17272. // Statics
  17273. /**
  17274. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17275. * @returns true if the engine can be created
  17276. * @ignorenaming
  17277. */
  17278. Engine.isSupported = function () {
  17279. try {
  17280. var tempcanvas = document.createElement("canvas");
  17281. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17282. return gl != null && !!window.WebGLRenderingContext;
  17283. }
  17284. catch (e) {
  17285. return false;
  17286. }
  17287. };
  17288. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17289. Engine.ExceptionList = [
  17290. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17291. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17292. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17293. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17294. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17295. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17296. ];
  17297. /** Gets the list of created engines */
  17298. Engine.Instances = new Array();
  17299. // Const statics
  17300. Engine._ALPHA_DISABLE = 0;
  17301. Engine._ALPHA_ADD = 1;
  17302. Engine._ALPHA_COMBINE = 2;
  17303. Engine._ALPHA_SUBTRACT = 3;
  17304. Engine._ALPHA_MULTIPLY = 4;
  17305. Engine._ALPHA_MAXIMIZED = 5;
  17306. Engine._ALPHA_ONEONE = 6;
  17307. Engine._ALPHA_PREMULTIPLIED = 7;
  17308. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17309. Engine._ALPHA_INTERPOLATE = 9;
  17310. Engine._ALPHA_SCREENMODE = 10;
  17311. Engine._DELAYLOADSTATE_NONE = 0;
  17312. Engine._DELAYLOADSTATE_LOADED = 1;
  17313. Engine._DELAYLOADSTATE_LOADING = 2;
  17314. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17315. Engine._TEXTUREFORMAT_ALPHA = 0;
  17316. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17317. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17318. Engine._TEXTUREFORMAT_RGB = 4;
  17319. Engine._TEXTUREFORMAT_RGBA = 5;
  17320. Engine._TEXTUREFORMAT_R32F = 6;
  17321. Engine._TEXTUREFORMAT_RG32F = 7;
  17322. Engine._TEXTUREFORMAT_RGB32F = 8;
  17323. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17324. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17325. Engine._TEXTURETYPE_FLOAT = 1;
  17326. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17327. // Depht or Stencil test Constants.
  17328. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17329. 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.
  17330. 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.
  17331. 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.
  17332. 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.
  17333. 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.
  17334. 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.
  17335. 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.
  17336. // Stencil Actions Constants.
  17337. Engine._KEEP = 0x1E00;
  17338. Engine._REPLACE = 0x1E01;
  17339. Engine._INCR = 0x1E02;
  17340. Engine._DECR = 0x1E03;
  17341. Engine._INVERT = 0x150A;
  17342. Engine._INCR_WRAP = 0x8507;
  17343. Engine._DECR_WRAP = 0x8508;
  17344. // Texture rescaling mode
  17345. Engine._SCALEMODE_FLOOR = 1;
  17346. Engine._SCALEMODE_NEAREST = 2;
  17347. Engine._SCALEMODE_CEILING = 3;
  17348. // Updatable statics so stick with vars here
  17349. /**
  17350. * Gets or sets the epsilon value used by collision engine
  17351. */
  17352. Engine.CollisionsEpsilon = 0.001;
  17353. /**
  17354. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17355. */
  17356. Engine.CodeRepository = "src/";
  17357. /**
  17358. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17359. */
  17360. Engine.ShadersRepository = "src/Shaders/";
  17361. return Engine;
  17362. }());
  17363. BABYLON.Engine = Engine;
  17364. })(BABYLON || (BABYLON = {}));
  17365. //# sourceMappingURL=babylon.engine.js.map
  17366. var BABYLON;
  17367. (function (BABYLON) {
  17368. /**
  17369. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17370. */
  17371. var Node = /** @class */ (function () {
  17372. /**
  17373. * Creates a new Node
  17374. * @param {string} name - the name and id to be given to this node
  17375. * @param {BABYLON.Scene} the scene this node will be added to
  17376. */
  17377. function Node(name, scene) {
  17378. if (scene === void 0) { scene = null; }
  17379. /**
  17380. * Gets or sets a string used to store user defined state for the node
  17381. */
  17382. this.state = "";
  17383. /**
  17384. * Gets or sets an object used to store user defined information for the node
  17385. */
  17386. this.metadata = null;
  17387. /**
  17388. * Gets or sets a boolean used to define if the node must be serialized
  17389. */
  17390. this.doNotSerialize = false;
  17391. /** @hidden */
  17392. this._isDisposed = false;
  17393. /**
  17394. * Gets a list of Animations associated with the node
  17395. */
  17396. this.animations = new Array();
  17397. this._ranges = {};
  17398. this._isEnabled = true;
  17399. this._isReady = true;
  17400. /** @hidden */
  17401. this._currentRenderId = -1;
  17402. this._parentRenderId = -1;
  17403. this._childRenderId = -1;
  17404. this._animationPropertiesOverride = null;
  17405. /**
  17406. * An event triggered when the mesh is disposed
  17407. */
  17408. this.onDisposeObservable = new BABYLON.Observable();
  17409. // Behaviors
  17410. this._behaviors = new Array();
  17411. this.name = name;
  17412. this.id = name;
  17413. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17414. this.uniqueId = this._scene.getUniqueId();
  17415. this._initCache();
  17416. }
  17417. /**
  17418. * Gets a boolean indicating if the node has been disposed
  17419. * @returns true if the node was disposed
  17420. */
  17421. Node.prototype.isDisposed = function () {
  17422. return this._isDisposed;
  17423. };
  17424. Object.defineProperty(Node.prototype, "parent", {
  17425. get: function () {
  17426. return this._parentNode;
  17427. },
  17428. /**
  17429. * Gets or sets the parent of the node
  17430. */
  17431. set: function (parent) {
  17432. if (this._parentNode === parent) {
  17433. return;
  17434. }
  17435. // Remove self from list of children of parent
  17436. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17437. var index = this._parentNode._children.indexOf(this);
  17438. if (index !== -1) {
  17439. this._parentNode._children.splice(index, 1);
  17440. }
  17441. }
  17442. // Store new parent
  17443. this._parentNode = parent;
  17444. // Add as child to new parent
  17445. if (this._parentNode) {
  17446. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17447. this._parentNode._children = new Array();
  17448. }
  17449. this._parentNode._children.push(this);
  17450. }
  17451. },
  17452. enumerable: true,
  17453. configurable: true
  17454. });
  17455. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17456. /**
  17457. * Gets or sets the animation properties override
  17458. */
  17459. get: function () {
  17460. if (!this._animationPropertiesOverride) {
  17461. return this._scene.animationPropertiesOverride;
  17462. }
  17463. return this._animationPropertiesOverride;
  17464. },
  17465. set: function (value) {
  17466. this._animationPropertiesOverride = value;
  17467. },
  17468. enumerable: true,
  17469. configurable: true
  17470. });
  17471. /**
  17472. * Gets a string idenfifying the name of the class
  17473. * @returns "Node" string
  17474. */
  17475. Node.prototype.getClassName = function () {
  17476. return "Node";
  17477. };
  17478. Object.defineProperty(Node.prototype, "onDispose", {
  17479. /**
  17480. * Sets a callback that will be raised when the node will be disposed
  17481. */
  17482. set: function (callback) {
  17483. if (this._onDisposeObserver) {
  17484. this.onDisposeObservable.remove(this._onDisposeObserver);
  17485. }
  17486. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17487. },
  17488. enumerable: true,
  17489. configurable: true
  17490. });
  17491. /**
  17492. * Gets the scene of the node
  17493. * @returns a {BABYLON.Scene}
  17494. */
  17495. Node.prototype.getScene = function () {
  17496. return this._scene;
  17497. };
  17498. /**
  17499. * Gets the engine of the node
  17500. * @returns a {BABYLON.Engine}
  17501. */
  17502. Node.prototype.getEngine = function () {
  17503. return this._scene.getEngine();
  17504. };
  17505. /**
  17506. * Attach a behavior to the node
  17507. * @see http://doc.babylonjs.com/features/behaviour
  17508. * @param behavior defines the behavior to attach
  17509. * @returns the current Node
  17510. */
  17511. Node.prototype.addBehavior = function (behavior) {
  17512. var _this = this;
  17513. var index = this._behaviors.indexOf(behavior);
  17514. if (index !== -1) {
  17515. return this;
  17516. }
  17517. behavior.init();
  17518. if (this._scene.isLoading) {
  17519. // We defer the attach when the scene will be loaded
  17520. var observer = this._scene.onDataLoadedObservable.add(function () {
  17521. behavior.attach(_this);
  17522. setTimeout(function () {
  17523. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17524. _this._scene.onDataLoadedObservable.remove(observer);
  17525. }, 0);
  17526. });
  17527. }
  17528. else {
  17529. behavior.attach(this);
  17530. }
  17531. this._behaviors.push(behavior);
  17532. return this;
  17533. };
  17534. /**
  17535. * Remove an attached behavior
  17536. * @see http://doc.babylonjs.com/features/behaviour
  17537. * @param behavior defines the behavior to attach
  17538. * @returns the current Node
  17539. */
  17540. Node.prototype.removeBehavior = function (behavior) {
  17541. var index = this._behaviors.indexOf(behavior);
  17542. if (index === -1) {
  17543. return this;
  17544. }
  17545. this._behaviors[index].detach();
  17546. this._behaviors.splice(index, 1);
  17547. return this;
  17548. };
  17549. Object.defineProperty(Node.prototype, "behaviors", {
  17550. /**
  17551. * Gets the list of attached behaviors
  17552. * @see http://doc.babylonjs.com/features/behaviour
  17553. */
  17554. get: function () {
  17555. return this._behaviors;
  17556. },
  17557. enumerable: true,
  17558. configurable: true
  17559. });
  17560. /**
  17561. * Gets an attached behavior by name
  17562. * @param name defines the name of the behavior to look for
  17563. * @see http://doc.babylonjs.com/features/behaviour
  17564. * @returns null if behavior was not found else the requested behavior
  17565. */
  17566. Node.prototype.getBehaviorByName = function (name) {
  17567. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17568. var behavior = _a[_i];
  17569. if (behavior.name === name) {
  17570. return behavior;
  17571. }
  17572. }
  17573. return null;
  17574. };
  17575. /**
  17576. * Returns the world matrix of the node
  17577. * @returns a matrix containing the node's world matrix
  17578. */
  17579. Node.prototype.getWorldMatrix = function () {
  17580. return BABYLON.Matrix.Identity();
  17581. };
  17582. /** @hidden */
  17583. Node.prototype._getWorldMatrixDeterminant = function () {
  17584. return 1;
  17585. };
  17586. // override it in derived class if you add new variables to the cache
  17587. // and call the parent class method
  17588. /** @hidden */
  17589. Node.prototype._initCache = function () {
  17590. this._cache = {};
  17591. this._cache.parent = undefined;
  17592. };
  17593. /** @hidden */
  17594. Node.prototype.updateCache = function (force) {
  17595. if (!force && this.isSynchronized())
  17596. return;
  17597. this._cache.parent = this.parent;
  17598. this._updateCache();
  17599. };
  17600. // override it in derived class if you add new variables to the cache
  17601. // and call the parent class method if !ignoreParentClass
  17602. /** @hidden */
  17603. Node.prototype._updateCache = function (ignoreParentClass) {
  17604. };
  17605. // override it in derived class if you add new variables to the cache
  17606. /** @hidden */
  17607. Node.prototype._isSynchronized = function () {
  17608. return true;
  17609. };
  17610. /** @hidden */
  17611. Node.prototype._markSyncedWithParent = function () {
  17612. if (this.parent) {
  17613. this._parentRenderId = this.parent._childRenderId;
  17614. }
  17615. };
  17616. /** @hidden */
  17617. Node.prototype.isSynchronizedWithParent = function () {
  17618. if (!this.parent) {
  17619. return true;
  17620. }
  17621. if (this._parentRenderId !== this.parent._childRenderId) {
  17622. return false;
  17623. }
  17624. return this.parent.isSynchronized();
  17625. };
  17626. /** @hidden */
  17627. Node.prototype.isSynchronized = function (updateCache) {
  17628. var check = this.hasNewParent();
  17629. check = check || !this.isSynchronizedWithParent();
  17630. check = check || !this._isSynchronized();
  17631. if (updateCache)
  17632. this.updateCache(true);
  17633. return !check;
  17634. };
  17635. /** @hidden */
  17636. Node.prototype.hasNewParent = function (update) {
  17637. if (this._cache.parent === this.parent)
  17638. return false;
  17639. if (update)
  17640. this._cache.parent = this.parent;
  17641. return true;
  17642. };
  17643. /**
  17644. * Is this node ready to be used/rendered
  17645. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17646. * @return true if the node is ready
  17647. */
  17648. Node.prototype.isReady = function (completeCheck) {
  17649. if (completeCheck === void 0) { completeCheck = false; }
  17650. return this._isReady;
  17651. };
  17652. /**
  17653. * Is this node enabled?
  17654. * 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
  17655. * @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
  17656. * @return whether this node (and its parent) is enabled
  17657. */
  17658. Node.prototype.isEnabled = function (checkAncestors) {
  17659. if (checkAncestors === void 0) { checkAncestors = true; }
  17660. if (checkAncestors === false) {
  17661. return this._isEnabled;
  17662. }
  17663. if (this._isEnabled === false) {
  17664. return false;
  17665. }
  17666. if (this.parent !== undefined && this.parent !== null) {
  17667. return this.parent.isEnabled(checkAncestors);
  17668. }
  17669. return true;
  17670. };
  17671. /**
  17672. * Set the enabled state of this node
  17673. * @param value defines the new enabled state
  17674. */
  17675. Node.prototype.setEnabled = function (value) {
  17676. this._isEnabled = value;
  17677. };
  17678. /**
  17679. * Is this node a descendant of the given node?
  17680. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17681. * @param ancestor defines the parent node to inspect
  17682. * @returns a boolean indicating if this node is a descendant of the given node
  17683. */
  17684. Node.prototype.isDescendantOf = function (ancestor) {
  17685. if (this.parent) {
  17686. if (this.parent === ancestor) {
  17687. return true;
  17688. }
  17689. return this.parent.isDescendantOf(ancestor);
  17690. }
  17691. return false;
  17692. };
  17693. /** @hidden */
  17694. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17695. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17696. if (!this._children) {
  17697. return;
  17698. }
  17699. for (var index = 0; index < this._children.length; index++) {
  17700. var item = this._children[index];
  17701. if (!predicate || predicate(item)) {
  17702. results.push(item);
  17703. }
  17704. if (!directDescendantsOnly) {
  17705. item._getDescendants(results, false, predicate);
  17706. }
  17707. }
  17708. };
  17709. /**
  17710. * Will return all nodes that have this node as ascendant
  17711. * @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
  17712. * @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
  17713. * @return all children nodes of all types
  17714. */
  17715. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17716. var results = new Array();
  17717. this._getDescendants(results, directDescendantsOnly, predicate);
  17718. return results;
  17719. };
  17720. /**
  17721. * Get all child-meshes of this node
  17722. * @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
  17723. * @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
  17724. * @returns an array of {BABYLON.AbstractMesh}
  17725. */
  17726. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17727. var results = [];
  17728. this._getDescendants(results, directDescendantsOnly, function (node) {
  17729. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17730. });
  17731. return results;
  17732. };
  17733. /**
  17734. * Get all child-transformNodes of this node
  17735. * @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
  17736. * @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
  17737. * @returns an array of {BABYLON.TransformNode}
  17738. */
  17739. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17740. var results = [];
  17741. this._getDescendants(results, directDescendantsOnly, function (node) {
  17742. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17743. });
  17744. return results;
  17745. };
  17746. /**
  17747. * Get all direct children of this node
  17748. * @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
  17749. * @returns an array of {BABYLON.Node}
  17750. */
  17751. Node.prototype.getChildren = function (predicate) {
  17752. return this.getDescendants(true, predicate);
  17753. };
  17754. /** @hidden */
  17755. Node.prototype._setReady = function (state) {
  17756. if (state === this._isReady) {
  17757. return;
  17758. }
  17759. if (!state) {
  17760. this._isReady = false;
  17761. return;
  17762. }
  17763. if (this.onReady) {
  17764. this.onReady(this);
  17765. }
  17766. this._isReady = true;
  17767. };
  17768. /**
  17769. * Get an animation by name
  17770. * @param name defines the name of the animation to look for
  17771. * @returns null if not found else the requested animation
  17772. */
  17773. Node.prototype.getAnimationByName = function (name) {
  17774. for (var i = 0; i < this.animations.length; i++) {
  17775. var animation = this.animations[i];
  17776. if (animation.name === name) {
  17777. return animation;
  17778. }
  17779. }
  17780. return null;
  17781. };
  17782. /**
  17783. * Creates an animation range for this node
  17784. * @param name defines the name of the range
  17785. * @param from defines the starting key
  17786. * @param to defines the end key
  17787. */
  17788. Node.prototype.createAnimationRange = function (name, from, to) {
  17789. // check name not already in use
  17790. if (!this._ranges[name]) {
  17791. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17792. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17793. if (this.animations[i]) {
  17794. this.animations[i].createRange(name, from, to);
  17795. }
  17796. }
  17797. }
  17798. };
  17799. /**
  17800. * Delete a specific animation range
  17801. * @param name defines the name of the range to delete
  17802. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17803. */
  17804. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17805. if (deleteFrames === void 0) { deleteFrames = true; }
  17806. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17807. if (this.animations[i]) {
  17808. this.animations[i].deleteRange(name, deleteFrames);
  17809. }
  17810. }
  17811. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17812. };
  17813. /**
  17814. * Get an animation range by name
  17815. * @param name defines the name of the animation range to look for
  17816. * @returns null if not found else the requested animation range
  17817. */
  17818. Node.prototype.getAnimationRange = function (name) {
  17819. return this._ranges[name];
  17820. };
  17821. /**
  17822. * Will start the animation sequence
  17823. * @param name defines the range frames for animation sequence
  17824. * @param loop defines if the animation should loop (false by default)
  17825. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17826. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17827. * @returns the object created for this animation. If range does not exist, it will return null
  17828. */
  17829. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17830. var range = this.getAnimationRange(name);
  17831. if (!range) {
  17832. return null;
  17833. }
  17834. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17835. };
  17836. /**
  17837. * Serialize animation ranges into a JSON compatible object
  17838. * @returns serialization object
  17839. */
  17840. Node.prototype.serializeAnimationRanges = function () {
  17841. var serializationRanges = [];
  17842. for (var name in this._ranges) {
  17843. var localRange = this._ranges[name];
  17844. if (!localRange) {
  17845. continue;
  17846. }
  17847. var range = {};
  17848. range.name = name;
  17849. range.from = localRange.from;
  17850. range.to = localRange.to;
  17851. serializationRanges.push(range);
  17852. }
  17853. return serializationRanges;
  17854. };
  17855. /**
  17856. * Computes the world matrix of the node
  17857. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17858. * @returns the world matrix
  17859. */
  17860. Node.prototype.computeWorldMatrix = function (force) {
  17861. return BABYLON.Matrix.Identity();
  17862. };
  17863. /**
  17864. * Releases resources associated with this node.
  17865. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17866. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17867. */
  17868. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17869. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17870. if (!doNotRecurse) {
  17871. var nodes = this.getDescendants(true);
  17872. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17873. var node = nodes_1[_i];
  17874. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17875. }
  17876. }
  17877. else {
  17878. var transformNodes = this.getChildTransformNodes(true);
  17879. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17880. var transformNode = transformNodes_1[_a];
  17881. transformNode.parent = null;
  17882. transformNode.computeWorldMatrix(true);
  17883. }
  17884. }
  17885. this.parent = null;
  17886. // Callback
  17887. this.onDisposeObservable.notifyObservers(this);
  17888. this.onDisposeObservable.clear();
  17889. // Behaviors
  17890. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17891. var behavior = _c[_b];
  17892. behavior.detach();
  17893. }
  17894. this._behaviors = [];
  17895. this._isDisposed = true;
  17896. };
  17897. /**
  17898. * Parse animation range data from a serialization object and store them into a given node
  17899. * @param node defines where to store the animation ranges
  17900. * @param parsedNode defines the serialization object to read data from
  17901. * @param scene defines the hosting scene
  17902. */
  17903. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17904. if (parsedNode.ranges) {
  17905. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17906. var data = parsedNode.ranges[index];
  17907. node.createAnimationRange(data.name, data.from, data.to);
  17908. }
  17909. }
  17910. };
  17911. __decorate([
  17912. BABYLON.serialize()
  17913. ], Node.prototype, "name", void 0);
  17914. __decorate([
  17915. BABYLON.serialize()
  17916. ], Node.prototype, "id", void 0);
  17917. __decorate([
  17918. BABYLON.serialize()
  17919. ], Node.prototype, "uniqueId", void 0);
  17920. __decorate([
  17921. BABYLON.serialize()
  17922. ], Node.prototype, "state", void 0);
  17923. __decorate([
  17924. BABYLON.serialize()
  17925. ], Node.prototype, "metadata", void 0);
  17926. return Node;
  17927. }());
  17928. BABYLON.Node = Node;
  17929. })(BABYLON || (BABYLON = {}));
  17930. //# sourceMappingURL=babylon.node.js.map
  17931. var BABYLON;
  17932. (function (BABYLON) {
  17933. var BoundingSphere = /** @class */ (function () {
  17934. /**
  17935. * Creates a new bounding sphere
  17936. * @param min defines the minimum vector (in local space)
  17937. * @param max defines the maximum vector (in local space)
  17938. */
  17939. function BoundingSphere(min, max) {
  17940. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17941. this.reConstruct(min, max);
  17942. }
  17943. /**
  17944. * Recreates the entire bounding sphere from scratch
  17945. * @param min defines the new minimum vector (in local space)
  17946. * @param max defines the new maximum vector (in local space)
  17947. */
  17948. BoundingSphere.prototype.reConstruct = function (min, max) {
  17949. this.minimum = min.clone();
  17950. this.maximum = max.clone();
  17951. var distance = BABYLON.Vector3.Distance(min, max);
  17952. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17953. this.radius = distance * 0.5;
  17954. this.centerWorld = BABYLON.Vector3.Zero();
  17955. this._update(BABYLON.Matrix.Identity());
  17956. };
  17957. // Methods
  17958. BoundingSphere.prototype._update = function (world) {
  17959. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17960. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17961. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17962. };
  17963. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17964. for (var i = 0; i < 6; i++) {
  17965. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17966. return false;
  17967. }
  17968. return true;
  17969. };
  17970. BoundingSphere.prototype.intersectsPoint = function (point) {
  17971. var x = this.centerWorld.x - point.x;
  17972. var y = this.centerWorld.y - point.y;
  17973. var z = this.centerWorld.z - point.z;
  17974. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17975. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17976. return false;
  17977. return true;
  17978. };
  17979. // Statics
  17980. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17981. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17982. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17983. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17984. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17985. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17986. return false;
  17987. return true;
  17988. };
  17989. return BoundingSphere;
  17990. }());
  17991. BABYLON.BoundingSphere = BoundingSphere;
  17992. })(BABYLON || (BABYLON = {}));
  17993. //# sourceMappingURL=babylon.boundingSphere.js.map
  17994. var BABYLON;
  17995. (function (BABYLON) {
  17996. var BoundingBox = /** @class */ (function () {
  17997. /**
  17998. * Creates a new bounding box
  17999. * @param min defines the minimum vector (in local space)
  18000. * @param max defines the maximum vector (in local space)
  18001. */
  18002. function BoundingBox(min, max) {
  18003. this.vectorsWorld = new Array();
  18004. this.reConstruct(min, max);
  18005. }
  18006. // Methods
  18007. /**
  18008. * Recreates the entire bounding box from scratch
  18009. * @param min defines the new minimum vector (in local space)
  18010. * @param max defines the new maximum vector (in local space)
  18011. */
  18012. BoundingBox.prototype.reConstruct = function (min, max) {
  18013. this.minimum = min.clone();
  18014. this.maximum = max.clone();
  18015. // Bounding vectors
  18016. this.vectors = new Array();
  18017. this.vectors.push(this.minimum.clone());
  18018. this.vectors.push(this.maximum.clone());
  18019. this.vectors.push(this.minimum.clone());
  18020. this.vectors[2].x = this.maximum.x;
  18021. this.vectors.push(this.minimum.clone());
  18022. this.vectors[3].y = this.maximum.y;
  18023. this.vectors.push(this.minimum.clone());
  18024. this.vectors[4].z = this.maximum.z;
  18025. this.vectors.push(this.maximum.clone());
  18026. this.vectors[5].z = this.minimum.z;
  18027. this.vectors.push(this.maximum.clone());
  18028. this.vectors[6].x = this.minimum.x;
  18029. this.vectors.push(this.maximum.clone());
  18030. this.vectors[7].y = this.minimum.y;
  18031. // OBB
  18032. this.center = this.maximum.add(this.minimum).scale(0.5);
  18033. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18034. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18035. // World
  18036. for (var index = 0; index < this.vectors.length; index++) {
  18037. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18038. }
  18039. this.minimumWorld = BABYLON.Vector3.Zero();
  18040. this.maximumWorld = BABYLON.Vector3.Zero();
  18041. this.centerWorld = BABYLON.Vector3.Zero();
  18042. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18043. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18044. };
  18045. BoundingBox.prototype.getWorldMatrix = function () {
  18046. return this._worldMatrix;
  18047. };
  18048. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18049. this._worldMatrix.copyFrom(matrix);
  18050. return this;
  18051. };
  18052. BoundingBox.prototype._update = function (world) {
  18053. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18054. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18055. for (var index = 0; index < this.vectors.length; index++) {
  18056. var v = this.vectorsWorld[index];
  18057. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18058. if (v.x < this.minimumWorld.x)
  18059. this.minimumWorld.x = v.x;
  18060. if (v.y < this.minimumWorld.y)
  18061. this.minimumWorld.y = v.y;
  18062. if (v.z < this.minimumWorld.z)
  18063. this.minimumWorld.z = v.z;
  18064. if (v.x > this.maximumWorld.x)
  18065. this.maximumWorld.x = v.x;
  18066. if (v.y > this.maximumWorld.y)
  18067. this.maximumWorld.y = v.y;
  18068. if (v.z > this.maximumWorld.z)
  18069. this.maximumWorld.z = v.z;
  18070. }
  18071. // Extend
  18072. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18073. this.extendSizeWorld.scaleInPlace(0.5);
  18074. // OBB
  18075. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18076. this.centerWorld.scaleInPlace(0.5);
  18077. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18078. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18079. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18080. this._worldMatrix = world;
  18081. };
  18082. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18083. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18084. };
  18085. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18086. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18087. };
  18088. BoundingBox.prototype.intersectsPoint = function (point) {
  18089. var delta = -BABYLON.Epsilon;
  18090. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18091. return false;
  18092. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18093. return false;
  18094. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18095. return false;
  18096. return true;
  18097. };
  18098. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18099. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18100. };
  18101. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18102. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18103. return false;
  18104. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18105. return false;
  18106. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18107. return false;
  18108. return true;
  18109. };
  18110. // Statics
  18111. BoundingBox.Intersects = function (box0, box1) {
  18112. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18113. return false;
  18114. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18115. return false;
  18116. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18117. return false;
  18118. return true;
  18119. };
  18120. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18121. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18122. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18123. return (num <= (sphereRadius * sphereRadius));
  18124. };
  18125. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18126. for (var p = 0; p < 6; p++) {
  18127. for (var i = 0; i < 8; i++) {
  18128. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18129. return false;
  18130. }
  18131. }
  18132. }
  18133. return true;
  18134. };
  18135. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18136. for (var p = 0; p < 6; p++) {
  18137. var inCount = 8;
  18138. for (var i = 0; i < 8; i++) {
  18139. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18140. --inCount;
  18141. }
  18142. else {
  18143. break;
  18144. }
  18145. }
  18146. if (inCount === 0)
  18147. return false;
  18148. }
  18149. return true;
  18150. };
  18151. return BoundingBox;
  18152. }());
  18153. BABYLON.BoundingBox = BoundingBox;
  18154. })(BABYLON || (BABYLON = {}));
  18155. //# sourceMappingURL=babylon.boundingBox.js.map
  18156. var BABYLON;
  18157. (function (BABYLON) {
  18158. var computeBoxExtents = function (axis, box) {
  18159. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18160. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18161. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18162. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18163. var r = r0 + r1 + r2;
  18164. return {
  18165. min: p - r,
  18166. max: p + r
  18167. };
  18168. };
  18169. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18170. var axisOverlap = function (axis, box0, box1) {
  18171. var result0 = computeBoxExtents(axis, box0);
  18172. var result1 = computeBoxExtents(axis, box1);
  18173. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18174. };
  18175. var BoundingInfo = /** @class */ (function () {
  18176. function BoundingInfo(minimum, maximum) {
  18177. this.minimum = minimum;
  18178. this.maximum = maximum;
  18179. this._isLocked = false;
  18180. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18181. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18182. }
  18183. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18184. get: function () {
  18185. return this._isLocked;
  18186. },
  18187. set: function (value) {
  18188. this._isLocked = value;
  18189. },
  18190. enumerable: true,
  18191. configurable: true
  18192. });
  18193. // Methods
  18194. BoundingInfo.prototype.update = function (world) {
  18195. if (this._isLocked) {
  18196. return;
  18197. }
  18198. this.boundingBox._update(world);
  18199. this.boundingSphere._update(world);
  18200. };
  18201. /**
  18202. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18203. * @param center New center of the bounding info
  18204. * @param extend New extend of the bounding info
  18205. */
  18206. BoundingInfo.prototype.centerOn = function (center, extend) {
  18207. this.minimum = center.subtract(extend);
  18208. this.maximum = center.add(extend);
  18209. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18210. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18211. return this;
  18212. };
  18213. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18214. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18215. return false;
  18216. return this.boundingBox.isInFrustum(frustumPlanes);
  18217. };
  18218. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18219. /**
  18220. * Gets the world distance between the min and max points of the bounding box
  18221. */
  18222. get: function () {
  18223. var boundingBox = this.boundingBox;
  18224. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18225. return size.length();
  18226. },
  18227. enumerable: true,
  18228. configurable: true
  18229. });
  18230. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18231. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18232. };
  18233. BoundingInfo.prototype._checkCollision = function (collider) {
  18234. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18235. };
  18236. BoundingInfo.prototype.intersectsPoint = function (point) {
  18237. if (!this.boundingSphere.centerWorld) {
  18238. return false;
  18239. }
  18240. if (!this.boundingSphere.intersectsPoint(point)) {
  18241. return false;
  18242. }
  18243. if (!this.boundingBox.intersectsPoint(point)) {
  18244. return false;
  18245. }
  18246. return true;
  18247. };
  18248. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18249. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18250. return false;
  18251. }
  18252. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18253. return false;
  18254. }
  18255. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18256. return false;
  18257. }
  18258. if (!precise) {
  18259. return true;
  18260. }
  18261. var box0 = this.boundingBox;
  18262. var box1 = boundingInfo.boundingBox;
  18263. if (!axisOverlap(box0.directions[0], box0, box1))
  18264. return false;
  18265. if (!axisOverlap(box0.directions[1], box0, box1))
  18266. return false;
  18267. if (!axisOverlap(box0.directions[2], box0, box1))
  18268. return false;
  18269. if (!axisOverlap(box1.directions[0], box0, box1))
  18270. return false;
  18271. if (!axisOverlap(box1.directions[1], box0, box1))
  18272. return false;
  18273. if (!axisOverlap(box1.directions[2], box0, box1))
  18274. return false;
  18275. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18276. return false;
  18277. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18278. return false;
  18279. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18280. return false;
  18281. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18282. return false;
  18283. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18284. return false;
  18285. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18286. return false;
  18287. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18288. return false;
  18289. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18290. return false;
  18291. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18292. return false;
  18293. return true;
  18294. };
  18295. return BoundingInfo;
  18296. }());
  18297. BABYLON.BoundingInfo = BoundingInfo;
  18298. })(BABYLON || (BABYLON = {}));
  18299. //# sourceMappingURL=babylon.boundingInfo.js.map
  18300. var BABYLON;
  18301. (function (BABYLON) {
  18302. var TransformNode = /** @class */ (function (_super) {
  18303. __extends(TransformNode, _super);
  18304. function TransformNode(name, scene, isPure) {
  18305. if (scene === void 0) { scene = null; }
  18306. if (isPure === void 0) { isPure = true; }
  18307. var _this = _super.call(this, name, scene) || this;
  18308. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18309. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18310. _this._up = new BABYLON.Vector3(0, 1, 0);
  18311. _this._right = new BABYLON.Vector3(1, 0, 0);
  18312. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18313. // Properties
  18314. _this._rotation = BABYLON.Vector3.Zero();
  18315. _this._scaling = BABYLON.Vector3.One();
  18316. _this._isDirty = false;
  18317. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18318. _this.scalingDeterminant = 1;
  18319. _this.infiniteDistance = false;
  18320. _this.position = BABYLON.Vector3.Zero();
  18321. _this._localWorld = BABYLON.Matrix.Zero();
  18322. _this._worldMatrix = BABYLON.Matrix.Zero();
  18323. _this._worldMatrixDeterminant = 0;
  18324. _this._absolutePosition = BABYLON.Vector3.Zero();
  18325. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18326. _this._postMultiplyPivotMatrix = false;
  18327. _this._isWorldMatrixFrozen = false;
  18328. /**
  18329. * An event triggered after the world matrix is updated
  18330. */
  18331. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18332. _this._nonUniformScaling = false;
  18333. if (isPure) {
  18334. _this.getScene().addTransformNode(_this);
  18335. }
  18336. return _this;
  18337. }
  18338. /**
  18339. * Gets a string idenfifying the name of the class
  18340. * @returns "TransformNode" string
  18341. */
  18342. TransformNode.prototype.getClassName = function () {
  18343. return "TransformNode";
  18344. };
  18345. Object.defineProperty(TransformNode.prototype, "rotation", {
  18346. /**
  18347. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18348. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18349. * Default : (0.0, 0.0, 0.0)
  18350. */
  18351. get: function () {
  18352. return this._rotation;
  18353. },
  18354. set: function (newRotation) {
  18355. this._rotation = newRotation;
  18356. },
  18357. enumerable: true,
  18358. configurable: true
  18359. });
  18360. Object.defineProperty(TransformNode.prototype, "scaling", {
  18361. /**
  18362. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18363. * Default : (1.0, 1.0, 1.0)
  18364. */
  18365. get: function () {
  18366. return this._scaling;
  18367. },
  18368. /**
  18369. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18370. * Default : (1.0, 1.0, 1.0)
  18371. */
  18372. set: function (newScaling) {
  18373. this._scaling = newScaling;
  18374. },
  18375. enumerable: true,
  18376. configurable: true
  18377. });
  18378. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18379. /**
  18380. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18381. * It's null by default.
  18382. * 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)
  18383. */
  18384. get: function () {
  18385. return this._rotationQuaternion;
  18386. },
  18387. set: function (quaternion) {
  18388. this._rotationQuaternion = quaternion;
  18389. //reset the rotation vector.
  18390. if (quaternion && this.rotation.length()) {
  18391. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18392. }
  18393. },
  18394. enumerable: true,
  18395. configurable: true
  18396. });
  18397. Object.defineProperty(TransformNode.prototype, "forward", {
  18398. /**
  18399. * The forward direction of that transform in world space.
  18400. */
  18401. get: function () {
  18402. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18403. },
  18404. enumerable: true,
  18405. configurable: true
  18406. });
  18407. Object.defineProperty(TransformNode.prototype, "up", {
  18408. /**
  18409. * The up direction of that transform in world space.
  18410. */
  18411. get: function () {
  18412. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18413. },
  18414. enumerable: true,
  18415. configurable: true
  18416. });
  18417. Object.defineProperty(TransformNode.prototype, "right", {
  18418. /**
  18419. * The right direction of that transform in world space.
  18420. */
  18421. get: function () {
  18422. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18423. },
  18424. enumerable: true,
  18425. configurable: true
  18426. });
  18427. /**
  18428. * Returns the latest update of the World matrix
  18429. * Returns a Matrix.
  18430. */
  18431. TransformNode.prototype.getWorldMatrix = function () {
  18432. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18433. this.computeWorldMatrix();
  18434. }
  18435. return this._worldMatrix;
  18436. };
  18437. /** @hidden */
  18438. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18439. return this._worldMatrixDeterminant;
  18440. };
  18441. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18442. /**
  18443. * Returns directly the latest state of the mesh World matrix.
  18444. * A Matrix is returned.
  18445. */
  18446. get: function () {
  18447. return this._worldMatrix;
  18448. },
  18449. enumerable: true,
  18450. configurable: true
  18451. });
  18452. /**
  18453. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18454. * Returns the TransformNode.
  18455. */
  18456. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18457. this._poseMatrix.copyFrom(matrix);
  18458. return this;
  18459. };
  18460. /**
  18461. * Returns the mesh Pose matrix.
  18462. * Returned object : Matrix
  18463. */
  18464. TransformNode.prototype.getPoseMatrix = function () {
  18465. return this._poseMatrix;
  18466. };
  18467. TransformNode.prototype._isSynchronized = function () {
  18468. if (this._isDirty) {
  18469. return false;
  18470. }
  18471. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18472. return false;
  18473. if (this._cache.pivotMatrixUpdated) {
  18474. return false;
  18475. }
  18476. if (this.infiniteDistance) {
  18477. return false;
  18478. }
  18479. if (!this._cache.position.equals(this.position))
  18480. return false;
  18481. if (this.rotationQuaternion) {
  18482. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18483. return false;
  18484. }
  18485. if (!this._cache.rotation.equals(this.rotation))
  18486. return false;
  18487. if (!this._cache.scaling.equals(this.scaling))
  18488. return false;
  18489. return true;
  18490. };
  18491. TransformNode.prototype._initCache = function () {
  18492. _super.prototype._initCache.call(this);
  18493. this._cache.localMatrixUpdated = false;
  18494. this._cache.position = BABYLON.Vector3.Zero();
  18495. this._cache.scaling = BABYLON.Vector3.Zero();
  18496. this._cache.rotation = BABYLON.Vector3.Zero();
  18497. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18498. this._cache.billboardMode = -1;
  18499. };
  18500. TransformNode.prototype.markAsDirty = function (property) {
  18501. if (property === "rotation") {
  18502. this.rotationQuaternion = null;
  18503. }
  18504. this._currentRenderId = Number.MAX_VALUE;
  18505. this._isDirty = true;
  18506. return this;
  18507. };
  18508. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18509. /**
  18510. * Returns the current mesh absolute position.
  18511. * Retuns a Vector3.
  18512. */
  18513. get: function () {
  18514. return this._absolutePosition;
  18515. },
  18516. enumerable: true,
  18517. configurable: true
  18518. });
  18519. /**
  18520. * Sets a new matrix to apply before all other transformation
  18521. * @param matrix defines the transform matrix
  18522. * @returns the current TransformNode
  18523. */
  18524. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18525. return this.setPivotMatrix(matrix, false);
  18526. };
  18527. /**
  18528. * Sets a new pivot matrix to the current node
  18529. * @param matrix defines the new pivot matrix to use
  18530. * @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
  18531. * @returns the current TransformNode
  18532. */
  18533. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18534. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18535. this._pivotMatrix = matrix.clone();
  18536. this._cache.pivotMatrixUpdated = true;
  18537. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18538. if (this._postMultiplyPivotMatrix) {
  18539. if (!this._pivotMatrixInverse) {
  18540. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18541. }
  18542. else {
  18543. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18544. }
  18545. }
  18546. return this;
  18547. };
  18548. /**
  18549. * Returns the mesh pivot matrix.
  18550. * Default : Identity.
  18551. * A Matrix is returned.
  18552. */
  18553. TransformNode.prototype.getPivotMatrix = function () {
  18554. return this._pivotMatrix;
  18555. };
  18556. /**
  18557. * Prevents the World matrix to be computed any longer.
  18558. * Returns the TransformNode.
  18559. */
  18560. TransformNode.prototype.freezeWorldMatrix = function () {
  18561. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18562. this.computeWorldMatrix(true);
  18563. this._isWorldMatrixFrozen = true;
  18564. return this;
  18565. };
  18566. /**
  18567. * Allows back the World matrix computation.
  18568. * Returns the TransformNode.
  18569. */
  18570. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18571. this._isWorldMatrixFrozen = false;
  18572. this.computeWorldMatrix(true);
  18573. return this;
  18574. };
  18575. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18576. /**
  18577. * True if the World matrix has been frozen.
  18578. * Returns a boolean.
  18579. */
  18580. get: function () {
  18581. return this._isWorldMatrixFrozen;
  18582. },
  18583. enumerable: true,
  18584. configurable: true
  18585. });
  18586. /**
  18587. * Retuns the mesh absolute position in the World.
  18588. * Returns a Vector3.
  18589. */
  18590. TransformNode.prototype.getAbsolutePosition = function () {
  18591. this.computeWorldMatrix();
  18592. return this._absolutePosition;
  18593. };
  18594. /**
  18595. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18596. * Returns the TransformNode.
  18597. */
  18598. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18599. if (!absolutePosition) {
  18600. return this;
  18601. }
  18602. var absolutePositionX;
  18603. var absolutePositionY;
  18604. var absolutePositionZ;
  18605. if (absolutePosition.x === undefined) {
  18606. if (arguments.length < 3) {
  18607. return this;
  18608. }
  18609. absolutePositionX = arguments[0];
  18610. absolutePositionY = arguments[1];
  18611. absolutePositionZ = arguments[2];
  18612. }
  18613. else {
  18614. absolutePositionX = absolutePosition.x;
  18615. absolutePositionY = absolutePosition.y;
  18616. absolutePositionZ = absolutePosition.z;
  18617. }
  18618. if (this.parent) {
  18619. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18620. invertParentWorldMatrix.invert();
  18621. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18622. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18623. }
  18624. else {
  18625. this.position.x = absolutePositionX;
  18626. this.position.y = absolutePositionY;
  18627. this.position.z = absolutePositionZ;
  18628. }
  18629. return this;
  18630. };
  18631. /**
  18632. * Sets the mesh position in its local space.
  18633. * Returns the TransformNode.
  18634. */
  18635. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18636. this.computeWorldMatrix();
  18637. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18638. return this;
  18639. };
  18640. /**
  18641. * Returns the mesh position in the local space from the current World matrix values.
  18642. * Returns a new Vector3.
  18643. */
  18644. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18645. this.computeWorldMatrix();
  18646. var invLocalWorldMatrix = this._localWorld.clone();
  18647. invLocalWorldMatrix.invert();
  18648. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18649. };
  18650. /**
  18651. * Translates the mesh along the passed Vector3 in its local space.
  18652. * Returns the TransformNode.
  18653. */
  18654. TransformNode.prototype.locallyTranslate = function (vector3) {
  18655. this.computeWorldMatrix(true);
  18656. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18657. return this;
  18658. };
  18659. /**
  18660. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18661. * @param targetPoint the position (must be in same space as current mesh) to look at
  18662. * @param yawCor optional yaw (y-axis) correction in radians
  18663. * @param pitchCor optional pitch (x-axis) correction in radians
  18664. * @param rollCor optional roll (z-axis) correction in radians
  18665. * @param space the choosen space of the target
  18666. * @returns the TransformNode.
  18667. */
  18668. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18669. if (yawCor === void 0) { yawCor = 0; }
  18670. if (pitchCor === void 0) { pitchCor = 0; }
  18671. if (rollCor === void 0) { rollCor = 0; }
  18672. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18673. var dv = TransformNode._lookAtVectorCache;
  18674. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18675. targetPoint.subtractToRef(pos, dv);
  18676. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18677. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18678. var pitch = Math.atan2(dv.y, len);
  18679. if (this.rotationQuaternion) {
  18680. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18681. }
  18682. else {
  18683. this.rotation.x = pitch + pitchCor;
  18684. this.rotation.y = yaw + yawCor;
  18685. this.rotation.z = rollCor;
  18686. }
  18687. return this;
  18688. };
  18689. /**
  18690. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18691. * This Vector3 is expressed in the World space.
  18692. */
  18693. TransformNode.prototype.getDirection = function (localAxis) {
  18694. var result = BABYLON.Vector3.Zero();
  18695. this.getDirectionToRef(localAxis, result);
  18696. return result;
  18697. };
  18698. /**
  18699. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18700. * localAxis is expressed in the mesh local space.
  18701. * result is computed in the Wordl space from the mesh World matrix.
  18702. * Returns the TransformNode.
  18703. */
  18704. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18705. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18706. return this;
  18707. };
  18708. /**
  18709. * Sets a new pivot point to the current node
  18710. * @param point defines the new pivot point to use
  18711. * @param space defines if the point is in world or local space (local by default)
  18712. * @returns the current TransformNode
  18713. */
  18714. TransformNode.prototype.setPivotPoint = function (point, space) {
  18715. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18716. if (this.getScene().getRenderId() == 0) {
  18717. this.computeWorldMatrix(true);
  18718. }
  18719. var wm = this.getWorldMatrix();
  18720. if (space == BABYLON.Space.WORLD) {
  18721. var tmat = BABYLON.Tmp.Matrix[0];
  18722. wm.invertToRef(tmat);
  18723. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18724. }
  18725. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18726. };
  18727. /**
  18728. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18729. */
  18730. TransformNode.prototype.getPivotPoint = function () {
  18731. var point = BABYLON.Vector3.Zero();
  18732. this.getPivotPointToRef(point);
  18733. return point;
  18734. };
  18735. /**
  18736. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18737. * Returns the TransformNode.
  18738. */
  18739. TransformNode.prototype.getPivotPointToRef = function (result) {
  18740. result.x = -this._pivotMatrix.m[12];
  18741. result.y = -this._pivotMatrix.m[13];
  18742. result.z = -this._pivotMatrix.m[14];
  18743. return this;
  18744. };
  18745. /**
  18746. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18747. */
  18748. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18749. var point = BABYLON.Vector3.Zero();
  18750. this.getAbsolutePivotPointToRef(point);
  18751. return point;
  18752. };
  18753. /**
  18754. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18755. * Returns the TransformNode.
  18756. */
  18757. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18758. result.x = this._pivotMatrix.m[12];
  18759. result.y = this._pivotMatrix.m[13];
  18760. result.z = this._pivotMatrix.m[14];
  18761. this.getPivotPointToRef(result);
  18762. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18763. return this;
  18764. };
  18765. /**
  18766. * Defines the passed node as the parent of the current node.
  18767. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18768. * Returns the TransformNode.
  18769. */
  18770. TransformNode.prototype.setParent = function (node) {
  18771. if (node === null) {
  18772. var rotation = BABYLON.Tmp.Quaternion[0];
  18773. var position = BABYLON.Tmp.Vector3[0];
  18774. var scale = BABYLON.Tmp.Vector3[1];
  18775. if (this.parent && this.parent.computeWorldMatrix) {
  18776. this.parent.computeWorldMatrix(true);
  18777. }
  18778. this.computeWorldMatrix(true);
  18779. this.getWorldMatrix().decompose(scale, rotation, position);
  18780. if (this.rotationQuaternion) {
  18781. this.rotationQuaternion.copyFrom(rotation);
  18782. }
  18783. else {
  18784. rotation.toEulerAnglesToRef(this.rotation);
  18785. }
  18786. this.scaling.x = scale.x;
  18787. this.scaling.y = scale.y;
  18788. this.scaling.z = scale.z;
  18789. this.position.x = position.x;
  18790. this.position.y = position.y;
  18791. this.position.z = position.z;
  18792. }
  18793. else {
  18794. var rotation = BABYLON.Tmp.Quaternion[0];
  18795. var position = BABYLON.Tmp.Vector3[0];
  18796. var scale = BABYLON.Tmp.Vector3[1];
  18797. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18798. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18799. this.computeWorldMatrix(true);
  18800. node.computeWorldMatrix(true);
  18801. node.getWorldMatrix().invertToRef(invParentMatrix);
  18802. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18803. diffMatrix.decompose(scale, rotation, position);
  18804. if (this.rotationQuaternion) {
  18805. this.rotationQuaternion.copyFrom(rotation);
  18806. }
  18807. else {
  18808. rotation.toEulerAnglesToRef(this.rotation);
  18809. }
  18810. this.position.x = position.x;
  18811. this.position.y = position.y;
  18812. this.position.z = position.z;
  18813. this.scaling.x = scale.x;
  18814. this.scaling.y = scale.y;
  18815. this.scaling.z = scale.z;
  18816. }
  18817. this.parent = node;
  18818. return this;
  18819. };
  18820. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18821. get: function () {
  18822. return this._nonUniformScaling;
  18823. },
  18824. enumerable: true,
  18825. configurable: true
  18826. });
  18827. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18828. if (this._nonUniformScaling === value) {
  18829. return false;
  18830. }
  18831. this._nonUniformScaling = true;
  18832. return true;
  18833. };
  18834. /**
  18835. * Attach the current TransformNode to another TransformNode associated with a bone
  18836. * @param bone Bone affecting the TransformNode
  18837. * @param affectedTransformNode TransformNode associated with the bone
  18838. */
  18839. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18840. this._transformToBoneReferal = affectedTransformNode;
  18841. this.parent = bone;
  18842. if (bone.getWorldMatrix().determinant() < 0) {
  18843. this.scalingDeterminant *= -1;
  18844. }
  18845. return this;
  18846. };
  18847. TransformNode.prototype.detachFromBone = function () {
  18848. if (!this.parent) {
  18849. return this;
  18850. }
  18851. if (this.parent.getWorldMatrix().determinant() < 0) {
  18852. this.scalingDeterminant *= -1;
  18853. }
  18854. this._transformToBoneReferal = null;
  18855. this.parent = null;
  18856. return this;
  18857. };
  18858. /**
  18859. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18860. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18861. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18862. * The passed axis is also normalized.
  18863. * Returns the TransformNode.
  18864. */
  18865. TransformNode.prototype.rotate = function (axis, amount, space) {
  18866. axis.normalize();
  18867. if (!this.rotationQuaternion) {
  18868. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18869. this.rotation = BABYLON.Vector3.Zero();
  18870. }
  18871. var rotationQuaternion;
  18872. if (!space || space === BABYLON.Space.LOCAL) {
  18873. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18874. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18875. }
  18876. else {
  18877. if (this.parent) {
  18878. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18879. invertParentWorldMatrix.invert();
  18880. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18881. }
  18882. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18883. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18884. }
  18885. return this;
  18886. };
  18887. /**
  18888. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18889. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18890. * The passed axis is also normalized.
  18891. * Returns the TransformNode.
  18892. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18893. */
  18894. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18895. axis.normalize();
  18896. if (!this.rotationQuaternion) {
  18897. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18898. this.rotation.copyFromFloats(0, 0, 0);
  18899. }
  18900. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18901. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18902. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18903. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18904. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18905. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18906. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18907. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18908. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18909. return this;
  18910. };
  18911. /**
  18912. * Translates the mesh along the axis vector for the passed distance in the given space.
  18913. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18914. * Returns the TransformNode.
  18915. */
  18916. TransformNode.prototype.translate = function (axis, distance, space) {
  18917. var displacementVector = axis.scale(distance);
  18918. if (!space || space === BABYLON.Space.LOCAL) {
  18919. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18920. this.setPositionWithLocalVector(tempV3);
  18921. }
  18922. else {
  18923. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18924. }
  18925. return this;
  18926. };
  18927. /**
  18928. * Adds a rotation step to the mesh current rotation.
  18929. * x, y, z are Euler angles expressed in radians.
  18930. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18931. * This means this rotation is made in the mesh local space only.
  18932. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18933. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18934. * ```javascript
  18935. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18936. * ```
  18937. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18938. * 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.
  18939. * Returns the TransformNode.
  18940. */
  18941. TransformNode.prototype.addRotation = function (x, y, z) {
  18942. var rotationQuaternion;
  18943. if (this.rotationQuaternion) {
  18944. rotationQuaternion = this.rotationQuaternion;
  18945. }
  18946. else {
  18947. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18948. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18949. }
  18950. var accumulation = BABYLON.Tmp.Quaternion[0];
  18951. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18952. rotationQuaternion.multiplyInPlace(accumulation);
  18953. if (!this.rotationQuaternion) {
  18954. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18955. }
  18956. return this;
  18957. };
  18958. /**
  18959. * Computes the mesh World matrix and returns it.
  18960. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18961. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18962. * If the parameter `force`is set to `true`, the actual computation is done.
  18963. * Returns the mesh World Matrix.
  18964. */
  18965. TransformNode.prototype.computeWorldMatrix = function (force) {
  18966. if (this._isWorldMatrixFrozen) {
  18967. return this._worldMatrix;
  18968. }
  18969. if (!force && this.isSynchronized(true)) {
  18970. this._currentRenderId = this.getScene().getRenderId();
  18971. return this._worldMatrix;
  18972. }
  18973. this._cache.position.copyFrom(this.position);
  18974. this._cache.scaling.copyFrom(this.scaling);
  18975. this._cache.pivotMatrixUpdated = false;
  18976. this._cache.billboardMode = this.billboardMode;
  18977. this._currentRenderId = this.getScene().getRenderId();
  18978. this._childRenderId = this.getScene().getRenderId();
  18979. this._isDirty = false;
  18980. // Scaling
  18981. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18982. // Rotation
  18983. //rotate, if quaternion is set and rotation was used
  18984. if (this.rotationQuaternion) {
  18985. var len = this.rotation.length();
  18986. if (len) {
  18987. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18988. this.rotation.copyFromFloats(0, 0, 0);
  18989. }
  18990. }
  18991. if (this.rotationQuaternion) {
  18992. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18993. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18994. }
  18995. else {
  18996. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18997. this._cache.rotation.copyFrom(this.rotation);
  18998. }
  18999. // Translation
  19000. var camera = this.getScene().activeCamera;
  19001. if (this.infiniteDistance && !this.parent && camera) {
  19002. var cameraWorldMatrix = camera.getWorldMatrix();
  19003. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19004. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19005. }
  19006. else {
  19007. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19008. }
  19009. // Composing transformations
  19010. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19011. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19012. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19013. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19014. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19015. // Need to decompose each rotation here
  19016. var currentPosition = BABYLON.Tmp.Vector3[3];
  19017. if (this.parent && this.parent.getWorldMatrix) {
  19018. if (this._transformToBoneReferal) {
  19019. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19020. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19021. }
  19022. else {
  19023. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19024. }
  19025. }
  19026. else {
  19027. currentPosition.copyFrom(this.position);
  19028. }
  19029. currentPosition.subtractInPlace(camera.globalPosition);
  19030. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19031. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19032. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19033. }
  19034. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19035. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19036. }
  19037. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19038. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19039. }
  19040. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19041. }
  19042. else {
  19043. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19044. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19045. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19046. }
  19047. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19048. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19049. }
  19050. // Local world
  19051. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19052. // Parent
  19053. if (this.parent && this.parent.getWorldMatrix) {
  19054. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19055. if (this._transformToBoneReferal) {
  19056. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19057. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19058. }
  19059. else {
  19060. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19061. }
  19062. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19063. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19064. this._worldMatrix.copyFrom(this._localWorld);
  19065. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19066. }
  19067. else {
  19068. if (this._transformToBoneReferal) {
  19069. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19070. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19071. }
  19072. else {
  19073. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19074. }
  19075. }
  19076. this._markSyncedWithParent();
  19077. }
  19078. else {
  19079. this._worldMatrix.copyFrom(this._localWorld);
  19080. }
  19081. // Post multiply inverse of pivotMatrix
  19082. if (this._postMultiplyPivotMatrix) {
  19083. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19084. }
  19085. // Normal matrix
  19086. if (this.scaling.isNonUniform) {
  19087. this._updateNonUniformScalingState(true);
  19088. }
  19089. else if (this.parent && this.parent._nonUniformScaling) {
  19090. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19091. }
  19092. else {
  19093. this._updateNonUniformScalingState(false);
  19094. }
  19095. this._afterComputeWorldMatrix();
  19096. // Absolute position
  19097. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19098. // Callbacks
  19099. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19100. if (!this._poseMatrix) {
  19101. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19102. }
  19103. // Cache the determinant
  19104. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19105. return this._worldMatrix;
  19106. };
  19107. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19108. };
  19109. /**
  19110. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19111. * @param func: callback function to add
  19112. *
  19113. * Returns the TransformNode.
  19114. */
  19115. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19116. this.onAfterWorldMatrixUpdateObservable.add(func);
  19117. return this;
  19118. };
  19119. /**
  19120. * Removes a registered callback function.
  19121. * Returns the TransformNode.
  19122. */
  19123. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19124. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19125. return this;
  19126. };
  19127. /**
  19128. * Clone the current transform node
  19129. * Returns the new transform node
  19130. * @param name Name of the new clone
  19131. * @param newParent New parent for the clone
  19132. * @param doNotCloneChildren Do not clone children hierarchy
  19133. */
  19134. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19135. var _this = this;
  19136. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19137. result.name = name;
  19138. result.id = name;
  19139. if (newParent) {
  19140. result.parent = newParent;
  19141. }
  19142. if (!doNotCloneChildren) {
  19143. // Children
  19144. var directDescendants = this.getDescendants(true);
  19145. for (var index = 0; index < directDescendants.length; index++) {
  19146. var child = directDescendants[index];
  19147. if (child.clone) {
  19148. child.clone(name + "." + child.name, result);
  19149. }
  19150. }
  19151. }
  19152. return result;
  19153. };
  19154. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19155. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19156. serializationObject.type = this.getClassName();
  19157. // Parent
  19158. if (this.parent) {
  19159. serializationObject.parentId = this.parent.id;
  19160. }
  19161. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19162. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19163. }
  19164. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19165. serializationObject.isEnabled = this.isEnabled();
  19166. // Parent
  19167. if (this.parent) {
  19168. serializationObject.parentId = this.parent.id;
  19169. }
  19170. return serializationObject;
  19171. };
  19172. // Statics
  19173. /**
  19174. * Returns a new TransformNode object parsed from the source provided.
  19175. * The parameter `parsedMesh` is the source.
  19176. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19177. */
  19178. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19179. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19180. if (BABYLON.Tags) {
  19181. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19182. }
  19183. if (parsedTransformNode.localMatrix) {
  19184. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19185. }
  19186. else if (parsedTransformNode.pivotMatrix) {
  19187. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19188. }
  19189. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19190. // Parent
  19191. if (parsedTransformNode.parentId) {
  19192. transformNode._waitingParentId = parsedTransformNode.parentId;
  19193. }
  19194. return transformNode;
  19195. };
  19196. /**
  19197. * Releases resources associated with this transform node.
  19198. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19199. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19200. */
  19201. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19202. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19203. // Animations
  19204. this.getScene().stopAnimation(this);
  19205. // Remove from scene
  19206. this.getScene().removeTransformNode(this);
  19207. this.onAfterWorldMatrixUpdateObservable.clear();
  19208. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19209. };
  19210. // Statics
  19211. TransformNode.BILLBOARDMODE_NONE = 0;
  19212. TransformNode.BILLBOARDMODE_X = 1;
  19213. TransformNode.BILLBOARDMODE_Y = 2;
  19214. TransformNode.BILLBOARDMODE_Z = 4;
  19215. TransformNode.BILLBOARDMODE_ALL = 7;
  19216. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19217. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19218. __decorate([
  19219. BABYLON.serializeAsVector3()
  19220. ], TransformNode.prototype, "_rotation", void 0);
  19221. __decorate([
  19222. BABYLON.serializeAsQuaternion()
  19223. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19224. __decorate([
  19225. BABYLON.serializeAsVector3()
  19226. ], TransformNode.prototype, "_scaling", void 0);
  19227. __decorate([
  19228. BABYLON.serialize()
  19229. ], TransformNode.prototype, "billboardMode", void 0);
  19230. __decorate([
  19231. BABYLON.serialize()
  19232. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19233. __decorate([
  19234. BABYLON.serialize()
  19235. ], TransformNode.prototype, "infiniteDistance", void 0);
  19236. __decorate([
  19237. BABYLON.serializeAsVector3()
  19238. ], TransformNode.prototype, "position", void 0);
  19239. return TransformNode;
  19240. }(BABYLON.Node));
  19241. BABYLON.TransformNode = TransformNode;
  19242. })(BABYLON || (BABYLON = {}));
  19243. //# sourceMappingURL=babylon.transformNode.js.map
  19244. var BABYLON;
  19245. (function (BABYLON) {
  19246. /**
  19247. * Class used to store all common mesh properties
  19248. */
  19249. var AbstractMesh = /** @class */ (function (_super) {
  19250. __extends(AbstractMesh, _super);
  19251. // Constructor
  19252. /**
  19253. * Creates a new AbstractMesh
  19254. * @param name defines the name of the mesh
  19255. * @param scene defines the hosting scene
  19256. */
  19257. function AbstractMesh(name, scene) {
  19258. if (scene === void 0) { scene = null; }
  19259. var _this = _super.call(this, name, scene, false) || this;
  19260. _this._facetNb = 0; // facet number
  19261. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19262. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19263. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19264. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19265. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19266. _this._subDiv = {
  19267. max: 1,
  19268. X: 1,
  19269. Y: 1,
  19270. Z: 1
  19271. };
  19272. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19273. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19274. // Events
  19275. /**
  19276. * An event triggered when this mesh collides with another one
  19277. */
  19278. _this.onCollideObservable = new BABYLON.Observable();
  19279. /**
  19280. * An event triggered when the collision's position changes
  19281. */
  19282. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19283. /**
  19284. * An event triggered when material is changed
  19285. */
  19286. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19287. // Properties
  19288. /**
  19289. * Gets or sets the orientation for POV movement & rotation
  19290. */
  19291. _this.definedFacingForward = true;
  19292. /**
  19293. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19294. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19295. * * 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.
  19296. * @see http://doc.babylonjs.com/features/occlusionquery
  19297. */
  19298. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19299. /**
  19300. * 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:
  19301. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19302. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19303. * * 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.
  19304. * @see http://doc.babylonjs.com/features/occlusionquery
  19305. */
  19306. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19307. /**
  19308. * 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.
  19309. * The default value is -1 which means don't break the query and wait till the result
  19310. * @see http://doc.babylonjs.com/features/occlusionquery
  19311. */
  19312. _this.occlusionRetryCount = -1;
  19313. _this._occlusionInternalRetryCounter = 0;
  19314. _this._isOccluded = false;
  19315. _this._isOcclusionQueryInProgress = false;
  19316. _this._visibility = 1.0;
  19317. /** Gets or sets the alpha index used to sort transparent meshes
  19318. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19319. */
  19320. _this.alphaIndex = Number.MAX_VALUE;
  19321. /**
  19322. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19323. */
  19324. _this.isVisible = true;
  19325. /**
  19326. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19327. */
  19328. _this.isPickable = true;
  19329. /**
  19330. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19331. */
  19332. _this.showBoundingBox = false;
  19333. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19334. _this.showSubMeshesBoundingBox = false;
  19335. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19336. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19337. */
  19338. _this.isBlocker = false;
  19339. /**
  19340. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19341. */
  19342. _this.enablePointerMoveEvents = false;
  19343. /**
  19344. * Specifies the rendering group id for this mesh (0 by default)
  19345. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19346. */
  19347. _this.renderingGroupId = 0;
  19348. _this._receiveShadows = false;
  19349. /**
  19350. * Gets or sets a boolean indicating if the outline must be rendered as well
  19351. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19352. */
  19353. _this.renderOutline = false;
  19354. /** Defines color to use when rendering outline */
  19355. _this.outlineColor = BABYLON.Color3.Red();
  19356. /** Define width to use when rendering outline */
  19357. _this.outlineWidth = 0.02;
  19358. /**
  19359. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19360. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19361. */
  19362. _this.renderOverlay = false;
  19363. /** Defines color to use when rendering overlay */
  19364. _this.overlayColor = BABYLON.Color3.Red();
  19365. /** Defines alpha to use when rendering overlay */
  19366. _this.overlayAlpha = 0.5;
  19367. _this._hasVertexAlpha = false;
  19368. _this._useVertexColors = true;
  19369. _this._computeBonesUsingShaders = true;
  19370. _this._numBoneInfluencers = 4;
  19371. _this._applyFog = true;
  19372. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19373. _this.useOctreeForRenderingSelection = true;
  19374. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19375. _this.useOctreeForPicking = true;
  19376. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19377. _this.useOctreeForCollisions = true;
  19378. _this._layerMask = 0x0FFFFFFF;
  19379. /**
  19380. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19381. */
  19382. _this.alwaysSelectAsActiveMesh = false;
  19383. /**
  19384. * Gets or sets the current action manager
  19385. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19386. */
  19387. _this.actionManager = null;
  19388. /**
  19389. * Gets or sets impostor used for physic simulation
  19390. * @see http://doc.babylonjs.com/features/physics_engine
  19391. */
  19392. _this.physicsImpostor = null;
  19393. // Collisions
  19394. _this._checkCollisions = false;
  19395. _this._collisionMask = -1;
  19396. _this._collisionGroup = -1;
  19397. /**
  19398. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19399. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19400. */
  19401. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19402. /**
  19403. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19404. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19405. */
  19406. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19407. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19408. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19409. // Edges
  19410. /**
  19411. * Defines edge width used when edgesRenderer is enabled
  19412. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19413. */
  19414. _this.edgesWidth = 1;
  19415. /**
  19416. * Defines edge color used when edgesRenderer is enabled
  19417. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19418. */
  19419. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19420. // Cache
  19421. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19422. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19423. /** @hidden */
  19424. _this._renderId = 0;
  19425. /** @hidden */
  19426. _this._intersectionsInProgress = new Array();
  19427. /** @hidden */
  19428. _this._unIndexed = false;
  19429. /** @hidden */
  19430. _this._lightSources = new Array();
  19431. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19432. if (collidedMesh === void 0) { collidedMesh = null; }
  19433. //TODO move this to the collision coordinator!
  19434. if (_this.getScene().workerCollisions)
  19435. newPosition.multiplyInPlace(_this._collider._radius);
  19436. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19437. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19438. _this.position.addInPlace(_this._diffPositionForCollisions);
  19439. }
  19440. if (collidedMesh) {
  19441. _this.onCollideObservable.notifyObservers(collidedMesh);
  19442. }
  19443. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19444. };
  19445. _this.getScene().addMesh(_this);
  19446. _this._resyncLightSources();
  19447. return _this;
  19448. }
  19449. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19450. /**
  19451. * No billboard
  19452. */
  19453. get: function () {
  19454. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19455. },
  19456. enumerable: true,
  19457. configurable: true
  19458. });
  19459. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19460. /** Billboard on X axis */
  19461. get: function () {
  19462. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19463. },
  19464. enumerable: true,
  19465. configurable: true
  19466. });
  19467. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19468. /** Billboard on Y axis */
  19469. get: function () {
  19470. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19471. },
  19472. enumerable: true,
  19473. configurable: true
  19474. });
  19475. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19476. /** Billboard on Z axis */
  19477. get: function () {
  19478. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19479. },
  19480. enumerable: true,
  19481. configurable: true
  19482. });
  19483. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19484. /** Billboard on all axes */
  19485. get: function () {
  19486. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19487. },
  19488. enumerable: true,
  19489. configurable: true
  19490. });
  19491. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19492. /**
  19493. * Gets the number of facets in the mesh
  19494. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19495. */
  19496. get: function () {
  19497. return this._facetNb;
  19498. },
  19499. enumerable: true,
  19500. configurable: true
  19501. });
  19502. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19503. /**
  19504. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19505. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19506. */
  19507. get: function () {
  19508. return this._partitioningSubdivisions;
  19509. },
  19510. set: function (nb) {
  19511. this._partitioningSubdivisions = nb;
  19512. },
  19513. enumerable: true,
  19514. configurable: true
  19515. });
  19516. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19517. /**
  19518. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19519. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19520. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19521. */
  19522. get: function () {
  19523. return this._partitioningBBoxRatio;
  19524. },
  19525. set: function (ratio) {
  19526. this._partitioningBBoxRatio = ratio;
  19527. },
  19528. enumerable: true,
  19529. configurable: true
  19530. });
  19531. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19532. /**
  19533. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19534. * Works only for updatable meshes.
  19535. * Doesn't work with multi-materials
  19536. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19537. */
  19538. get: function () {
  19539. return this._facetDepthSort;
  19540. },
  19541. set: function (sort) {
  19542. this._facetDepthSort = sort;
  19543. },
  19544. enumerable: true,
  19545. configurable: true
  19546. });
  19547. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19548. /**
  19549. * The location (Vector3) where the facet depth sort must be computed from.
  19550. * By default, the active camera position.
  19551. * Used only when facet depth sort is enabled
  19552. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19553. */
  19554. get: function () {
  19555. return this._facetDepthSortFrom;
  19556. },
  19557. set: function (location) {
  19558. this._facetDepthSortFrom = location;
  19559. },
  19560. enumerable: true,
  19561. configurable: true
  19562. });
  19563. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19564. /**
  19565. * gets a boolean indicating if facetData is enabled
  19566. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19567. */
  19568. get: function () {
  19569. return this._facetDataEnabled;
  19570. },
  19571. enumerable: true,
  19572. configurable: true
  19573. });
  19574. /** @hidden */
  19575. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19576. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19577. return false;
  19578. }
  19579. this._markSubMeshesAsMiscDirty();
  19580. return true;
  19581. };
  19582. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19583. /** Set a function to call when this mesh collides with another one */
  19584. set: function (callback) {
  19585. if (this._onCollideObserver) {
  19586. this.onCollideObservable.remove(this._onCollideObserver);
  19587. }
  19588. this._onCollideObserver = this.onCollideObservable.add(callback);
  19589. },
  19590. enumerable: true,
  19591. configurable: true
  19592. });
  19593. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19594. /** Set a function to call when the collision's position changes */
  19595. set: function (callback) {
  19596. if (this._onCollisionPositionChangeObserver) {
  19597. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19598. }
  19599. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19600. },
  19601. enumerable: true,
  19602. configurable: true
  19603. });
  19604. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19605. /**
  19606. * 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
  19607. * @see http://doc.babylonjs.com/features/occlusionquery
  19608. */
  19609. get: function () {
  19610. return this._isOccluded;
  19611. },
  19612. set: function (value) {
  19613. this._isOccluded = value;
  19614. },
  19615. enumerable: true,
  19616. configurable: true
  19617. });
  19618. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19619. /**
  19620. * Flag to check the progress status of the query
  19621. * @see http://doc.babylonjs.com/features/occlusionquery
  19622. */
  19623. get: function () {
  19624. return this._isOcclusionQueryInProgress;
  19625. },
  19626. enumerable: true,
  19627. configurable: true
  19628. });
  19629. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19630. /**
  19631. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19632. */
  19633. get: function () {
  19634. return this._visibility;
  19635. },
  19636. /**
  19637. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19638. */
  19639. set: function (value) {
  19640. if (this._visibility === value) {
  19641. return;
  19642. }
  19643. this._visibility = value;
  19644. this._markSubMeshesAsMiscDirty();
  19645. },
  19646. enumerable: true,
  19647. configurable: true
  19648. });
  19649. Object.defineProperty(AbstractMesh.prototype, "material", {
  19650. /** Gets or sets current material */
  19651. get: function () {
  19652. return this._material;
  19653. },
  19654. set: function (value) {
  19655. if (this._material === value) {
  19656. return;
  19657. }
  19658. this._material = value;
  19659. if (this.onMaterialChangedObservable.hasObservers) {
  19660. this.onMaterialChangedObservable.notifyObservers(this);
  19661. }
  19662. if (!this.subMeshes) {
  19663. return;
  19664. }
  19665. this._unBindEffect();
  19666. },
  19667. enumerable: true,
  19668. configurable: true
  19669. });
  19670. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19671. /**
  19672. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19673. * @see http://doc.babylonjs.com/babylon101/shadows
  19674. */
  19675. get: function () {
  19676. return this._receiveShadows;
  19677. },
  19678. set: function (value) {
  19679. if (this._receiveShadows === value) {
  19680. return;
  19681. }
  19682. this._receiveShadows = value;
  19683. this._markSubMeshesAsLightDirty();
  19684. },
  19685. enumerable: true,
  19686. configurable: true
  19687. });
  19688. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19689. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19690. get: function () {
  19691. return this._hasVertexAlpha;
  19692. },
  19693. set: function (value) {
  19694. if (this._hasVertexAlpha === value) {
  19695. return;
  19696. }
  19697. this._hasVertexAlpha = value;
  19698. this._markSubMeshesAsAttributesDirty();
  19699. this._markSubMeshesAsMiscDirty();
  19700. },
  19701. enumerable: true,
  19702. configurable: true
  19703. });
  19704. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19705. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  19706. get: function () {
  19707. return this._useVertexColors;
  19708. },
  19709. set: function (value) {
  19710. if (this._useVertexColors === value) {
  19711. return;
  19712. }
  19713. this._useVertexColors = value;
  19714. this._markSubMeshesAsAttributesDirty();
  19715. },
  19716. enumerable: true,
  19717. configurable: true
  19718. });
  19719. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19720. /**
  19721. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19722. */
  19723. get: function () {
  19724. return this._computeBonesUsingShaders;
  19725. },
  19726. set: function (value) {
  19727. if (this._computeBonesUsingShaders === value) {
  19728. return;
  19729. }
  19730. this._computeBonesUsingShaders = value;
  19731. this._markSubMeshesAsAttributesDirty();
  19732. },
  19733. enumerable: true,
  19734. configurable: true
  19735. });
  19736. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19737. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19738. get: function () {
  19739. return this._numBoneInfluencers;
  19740. },
  19741. set: function (value) {
  19742. if (this._numBoneInfluencers === value) {
  19743. return;
  19744. }
  19745. this._numBoneInfluencers = value;
  19746. this._markSubMeshesAsAttributesDirty();
  19747. },
  19748. enumerable: true,
  19749. configurable: true
  19750. });
  19751. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19752. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19753. get: function () {
  19754. return this._applyFog;
  19755. },
  19756. set: function (value) {
  19757. if (this._applyFog === value) {
  19758. return;
  19759. }
  19760. this._applyFog = value;
  19761. this._markSubMeshesAsMiscDirty();
  19762. },
  19763. enumerable: true,
  19764. configurable: true
  19765. });
  19766. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19767. /**
  19768. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19769. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19770. */
  19771. get: function () {
  19772. return this._layerMask;
  19773. },
  19774. set: function (value) {
  19775. if (value === this._layerMask) {
  19776. return;
  19777. }
  19778. this._layerMask = value;
  19779. this._resyncLightSources();
  19780. },
  19781. enumerable: true,
  19782. configurable: true
  19783. });
  19784. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19785. /**
  19786. * Gets or sets a collision mask used to mask collisions (default is -1).
  19787. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19788. */
  19789. get: function () {
  19790. return this._collisionMask;
  19791. },
  19792. set: function (mask) {
  19793. this._collisionMask = !isNaN(mask) ? mask : -1;
  19794. },
  19795. enumerable: true,
  19796. configurable: true
  19797. });
  19798. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19799. /**
  19800. * Gets or sets the current collision group mask (-1 by default).
  19801. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19802. */
  19803. get: function () {
  19804. return this._collisionGroup;
  19805. },
  19806. set: function (mask) {
  19807. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19808. },
  19809. enumerable: true,
  19810. configurable: true
  19811. });
  19812. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19813. /** @hidden */
  19814. get: function () {
  19815. return null;
  19816. },
  19817. enumerable: true,
  19818. configurable: true
  19819. });
  19820. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19821. get: function () {
  19822. return this._skeleton;
  19823. },
  19824. /**
  19825. * Gets or sets a skeleton to apply skining transformations
  19826. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19827. */
  19828. set: function (value) {
  19829. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19830. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19831. }
  19832. if (value && value.needInitialSkinMatrix) {
  19833. value._registerMeshWithPoseMatrix(this);
  19834. }
  19835. this._skeleton = value;
  19836. if (!this._skeleton) {
  19837. this._bonesTransformMatrices = null;
  19838. }
  19839. this._markSubMeshesAsAttributesDirty();
  19840. },
  19841. enumerable: true,
  19842. configurable: true
  19843. });
  19844. /**
  19845. * Returns the string "AbstractMesh"
  19846. * @returns "AbstractMesh"
  19847. */
  19848. AbstractMesh.prototype.getClassName = function () {
  19849. return "AbstractMesh";
  19850. };
  19851. /**
  19852. * Gets a string representation of the current mesh
  19853. * @param fullDetails defines a boolean indicating if full details must be included
  19854. * @returns a string representation of the current mesh
  19855. */
  19856. AbstractMesh.prototype.toString = function (fullDetails) {
  19857. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19858. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19859. if (this._skeleton) {
  19860. ret += ", skeleton: " + this._skeleton.name;
  19861. }
  19862. if (fullDetails) {
  19863. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19864. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19865. }
  19866. return ret;
  19867. };
  19868. /** @hidden */
  19869. AbstractMesh.prototype._rebuild = function () {
  19870. if (this._occlusionQuery) {
  19871. this._occlusionQuery = null;
  19872. }
  19873. if (this._edgesRenderer) {
  19874. this._edgesRenderer._rebuild();
  19875. }
  19876. if (!this.subMeshes) {
  19877. return;
  19878. }
  19879. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19880. var subMesh = _a[_i];
  19881. subMesh._rebuild();
  19882. }
  19883. };
  19884. /** @hidden */
  19885. AbstractMesh.prototype._resyncLightSources = function () {
  19886. this._lightSources.length = 0;
  19887. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19888. var light = _a[_i];
  19889. if (!light.isEnabled()) {
  19890. continue;
  19891. }
  19892. if (light.canAffectMesh(this)) {
  19893. this._lightSources.push(light);
  19894. }
  19895. }
  19896. this._markSubMeshesAsLightDirty();
  19897. };
  19898. /** @hidden */
  19899. AbstractMesh.prototype._resyncLighSource = function (light) {
  19900. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19901. var index = this._lightSources.indexOf(light);
  19902. if (index === -1) {
  19903. if (!isIn) {
  19904. return;
  19905. }
  19906. this._lightSources.push(light);
  19907. }
  19908. else {
  19909. if (isIn) {
  19910. return;
  19911. }
  19912. this._lightSources.splice(index, 1);
  19913. }
  19914. this._markSubMeshesAsLightDirty();
  19915. };
  19916. /** @hidden */
  19917. AbstractMesh.prototype._unBindEffect = function () {
  19918. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19919. var subMesh = _a[_i];
  19920. subMesh.setEffect(null);
  19921. }
  19922. };
  19923. /** @hidden */
  19924. AbstractMesh.prototype._removeLightSource = function (light) {
  19925. var index = this._lightSources.indexOf(light);
  19926. if (index === -1) {
  19927. return;
  19928. }
  19929. this._lightSources.splice(index, 1);
  19930. this._markSubMeshesAsLightDirty();
  19931. };
  19932. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19933. if (!this.subMeshes) {
  19934. return;
  19935. }
  19936. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19937. var subMesh = _a[_i];
  19938. if (subMesh._materialDefines) {
  19939. func(subMesh._materialDefines);
  19940. }
  19941. }
  19942. };
  19943. /** @hidden */
  19944. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19945. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19946. };
  19947. /** @hidden */
  19948. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19949. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19950. };
  19951. /** @hidden */
  19952. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19953. if (!this.subMeshes) {
  19954. return;
  19955. }
  19956. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19957. var subMesh = _a[_i];
  19958. var material = subMesh.getMaterial();
  19959. if (material) {
  19960. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19961. }
  19962. }
  19963. };
  19964. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19965. /**
  19966. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19967. */
  19968. get: function () {
  19969. return this._scaling;
  19970. },
  19971. set: function (newScaling) {
  19972. this._scaling = newScaling;
  19973. if (this.physicsImpostor) {
  19974. this.physicsImpostor.forceUpdate();
  19975. }
  19976. },
  19977. enumerable: true,
  19978. configurable: true
  19979. });
  19980. // Methods
  19981. /**
  19982. * Disables the mesh edge rendering mode
  19983. * @returns the currentAbstractMesh
  19984. */
  19985. AbstractMesh.prototype.disableEdgesRendering = function () {
  19986. if (this._edgesRenderer) {
  19987. this._edgesRenderer.dispose();
  19988. this._edgesRenderer = null;
  19989. }
  19990. return this;
  19991. };
  19992. /**
  19993. * Enables the edge rendering mode on the mesh.
  19994. * This mode makes the mesh edges visible
  19995. * @param epsilon defines the maximal distance between two angles to detect a face
  19996. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  19997. * @returns the currentAbstractMesh
  19998. * @see https://www.babylonjs-playground.com/#19O9TU#0
  19999. */
  20000. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20001. if (epsilon === void 0) { epsilon = 0.95; }
  20002. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20003. this.disableEdgesRendering();
  20004. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20005. return this;
  20006. };
  20007. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20008. /**
  20009. * Returns true if the mesh is blocked. Implemented by child classes
  20010. */
  20011. get: function () {
  20012. return false;
  20013. },
  20014. enumerable: true,
  20015. configurable: true
  20016. });
  20017. /**
  20018. * Returns the mesh itself by default. Implemented by child classes
  20019. * @param camera defines the camera to use to pick the right LOD level
  20020. * @returns the currentAbstractMesh
  20021. */
  20022. AbstractMesh.prototype.getLOD = function (camera) {
  20023. return this;
  20024. };
  20025. /**
  20026. * Returns 0 by default. Implemented by child classes
  20027. * @returns an integer
  20028. */
  20029. AbstractMesh.prototype.getTotalVertices = function () {
  20030. return 0;
  20031. };
  20032. /**
  20033. * Returns null by default. Implemented by child classes
  20034. * @returns null
  20035. */
  20036. AbstractMesh.prototype.getIndices = function () {
  20037. return null;
  20038. };
  20039. /**
  20040. * Returns the array of the requested vertex data kind. Implemented by child classes
  20041. * @param kind defines the vertex data kind to use
  20042. * @returns null
  20043. */
  20044. AbstractMesh.prototype.getVerticesData = function (kind) {
  20045. return null;
  20046. };
  20047. /**
  20048. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20049. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20050. * Note that a new underlying VertexBuffer object is created each call.
  20051. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20052. * @param kind defines vertex data kind:
  20053. * * BABYLON.VertexBuffer.PositionKind
  20054. * * BABYLON.VertexBuffer.UVKind
  20055. * * BABYLON.VertexBuffer.UV2Kind
  20056. * * BABYLON.VertexBuffer.UV3Kind
  20057. * * BABYLON.VertexBuffer.UV4Kind
  20058. * * BABYLON.VertexBuffer.UV5Kind
  20059. * * BABYLON.VertexBuffer.UV6Kind
  20060. * * BABYLON.VertexBuffer.ColorKind
  20061. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20062. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20063. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20064. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20065. * @param data defines the data source
  20066. * @param updatable defines if the data must be flagged as updatable (or static)
  20067. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  20068. * @returns the current mesh
  20069. */
  20070. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20071. return this;
  20072. };
  20073. /**
  20074. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20075. * If the mesh has no geometry, it is simply returned as it is.
  20076. * @param kind defines vertex data kind:
  20077. * * BABYLON.VertexBuffer.PositionKind
  20078. * * BABYLON.VertexBuffer.UVKind
  20079. * * BABYLON.VertexBuffer.UV2Kind
  20080. * * BABYLON.VertexBuffer.UV3Kind
  20081. * * BABYLON.VertexBuffer.UV4Kind
  20082. * * BABYLON.VertexBuffer.UV5Kind
  20083. * * BABYLON.VertexBuffer.UV6Kind
  20084. * * BABYLON.VertexBuffer.ColorKind
  20085. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20086. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20087. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20088. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20089. * @param data defines the data source
  20090. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  20091. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20092. * @returns the current mesh
  20093. */
  20094. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20095. return this;
  20096. };
  20097. /**
  20098. * Sets the mesh indices,
  20099. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20100. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20101. * @param totalVertices Defines the total number of vertices
  20102. * @returns the current mesh
  20103. */
  20104. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20105. return this;
  20106. };
  20107. /**
  20108. * Gets a boolean indicating if specific vertex data is present
  20109. * @param kind defines the vertex data kind to use
  20110. * @returns true is data kind is present
  20111. */
  20112. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20113. return false;
  20114. };
  20115. /**
  20116. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20117. * @returns a BoundingInfo
  20118. */
  20119. AbstractMesh.prototype.getBoundingInfo = function () {
  20120. if (this._masterMesh) {
  20121. return this._masterMesh.getBoundingInfo();
  20122. }
  20123. if (!this._boundingInfo) {
  20124. // this._boundingInfo is being created here
  20125. this._updateBoundingInfo();
  20126. }
  20127. // cannot be null.
  20128. return this._boundingInfo;
  20129. };
  20130. /**
  20131. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20132. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20133. * @returns the current mesh
  20134. */
  20135. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20136. if (includeDescendants === void 0) { includeDescendants = true; }
  20137. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20138. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20139. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20140. if (maxDimension === 0) {
  20141. return this;
  20142. }
  20143. var scale = 1 / maxDimension;
  20144. this.scaling.scaleInPlace(scale);
  20145. return this;
  20146. };
  20147. /**
  20148. * Overwrite the current bounding info
  20149. * @param boundingInfo defines the new bounding info
  20150. * @returns the current mesh
  20151. */
  20152. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20153. this._boundingInfo = boundingInfo;
  20154. return this;
  20155. };
  20156. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20157. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20158. get: function () {
  20159. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20160. },
  20161. enumerable: true,
  20162. configurable: true
  20163. });
  20164. /** @hidden */
  20165. AbstractMesh.prototype._preActivate = function () {
  20166. };
  20167. /** @hidden */
  20168. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20169. };
  20170. /** @hidden */
  20171. AbstractMesh.prototype._activate = function (renderId) {
  20172. this._renderId = renderId;
  20173. };
  20174. /**
  20175. * Gets the current world matrix
  20176. * @returns a Matrix
  20177. */
  20178. AbstractMesh.prototype.getWorldMatrix = function () {
  20179. if (this._masterMesh) {
  20180. return this._masterMesh.getWorldMatrix();
  20181. }
  20182. return _super.prototype.getWorldMatrix.call(this);
  20183. };
  20184. /** @hidden */
  20185. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20186. if (this._masterMesh) {
  20187. return this._masterMesh._getWorldMatrixDeterminant();
  20188. }
  20189. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20190. };
  20191. // ================================== Point of View Movement =================================
  20192. /**
  20193. * Perform relative position change from the point of view of behind the front of the mesh.
  20194. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20195. * Supports definition of mesh facing forward or backward
  20196. * @param amountRight defines the distance on the right axis
  20197. * @param amountUp defines the distance on the up axis
  20198. * @param amountForward defines the distance on the forward axis
  20199. * @returns the current mesh
  20200. */
  20201. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20202. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20203. return this;
  20204. };
  20205. /**
  20206. * Calculate relative position change from the point of view of behind the front of the mesh.
  20207. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20208. * Supports definition of mesh facing forward or backward
  20209. * @param amountRight defines the distance on the right axis
  20210. * @param amountUp defines the distance on the up axis
  20211. * @param amountForward defines the distance on the forward axis
  20212. * @returns the new displacement vector
  20213. */
  20214. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20215. var rotMatrix = new BABYLON.Matrix();
  20216. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20217. rotQuaternion.toRotationMatrix(rotMatrix);
  20218. var translationDelta = BABYLON.Vector3.Zero();
  20219. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20220. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20221. return translationDelta;
  20222. };
  20223. // ================================== Point of View Rotation =================================
  20224. /**
  20225. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20226. * Supports definition of mesh facing forward or backward
  20227. * @param flipBack defines the flip
  20228. * @param twirlClockwise defines the twirl
  20229. * @param tiltRight defines the tilt
  20230. * @returns the current mesh
  20231. */
  20232. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20233. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20234. return this;
  20235. };
  20236. /**
  20237. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20238. * Supports definition of mesh facing forward or backward.
  20239. * @param flipBack defines the flip
  20240. * @param twirlClockwise defines the twirl
  20241. * @param tiltRight defines the tilt
  20242. * @returns the new rotation vector
  20243. */
  20244. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20245. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20246. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20247. };
  20248. /**
  20249. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20250. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20251. * @returns the new bounding vectors
  20252. */
  20253. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  20254. if (includeDescendants === void 0) { includeDescendants = true; }
  20255. this.computeWorldMatrix(true);
  20256. var min;
  20257. var max;
  20258. var boundingInfo = this.getBoundingInfo();
  20259. if (!this.subMeshes) {
  20260. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20261. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20262. }
  20263. else {
  20264. min = boundingInfo.boundingBox.minimumWorld;
  20265. max = boundingInfo.boundingBox.maximumWorld;
  20266. }
  20267. if (includeDescendants) {
  20268. var descendants = this.getDescendants(false);
  20269. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20270. var descendant = descendants_1[_i];
  20271. var childMesh = descendant;
  20272. childMesh.computeWorldMatrix(true);
  20273. //make sure we have the needed params to get mix and max
  20274. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20275. continue;
  20276. }
  20277. var childBoundingInfo = childMesh.getBoundingInfo();
  20278. var boundingBox = childBoundingInfo.boundingBox;
  20279. var minBox = boundingBox.minimumWorld;
  20280. var maxBox = boundingBox.maximumWorld;
  20281. BABYLON.Tools.CheckExtends(minBox, min, max);
  20282. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20283. }
  20284. }
  20285. return {
  20286. min: min,
  20287. max: max
  20288. };
  20289. };
  20290. /** @hidden */
  20291. AbstractMesh.prototype._updateBoundingInfo = function () {
  20292. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20293. this._boundingInfo.update(this.worldMatrixFromCache);
  20294. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20295. return this;
  20296. };
  20297. /** @hidden */
  20298. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20299. if (!this.subMeshes) {
  20300. return this;
  20301. }
  20302. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20303. var subMesh = this.subMeshes[subIndex];
  20304. if (!subMesh.IsGlobal) {
  20305. subMesh.updateBoundingInfo(matrix);
  20306. }
  20307. }
  20308. return this;
  20309. };
  20310. /** @hidden */
  20311. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20312. // Bounding info
  20313. this._updateBoundingInfo();
  20314. };
  20315. /**
  20316. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20317. * A mesh is in the frustum if its bounding box intersects the frustum
  20318. * @param frustumPlanes defines the frustum to test
  20319. * @returns true if the mesh is in the frustum planes
  20320. */
  20321. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20322. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20323. };
  20324. /**
  20325. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20326. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20327. * @param frustumPlanes defines the frustum to test
  20328. * @returns true if the mesh is completely in the frustum planes
  20329. */
  20330. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20331. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20332. ;
  20333. };
  20334. /**
  20335. * True if the mesh intersects another mesh or a SolidParticle object
  20336. * @param mesh defines a target mesh or SolidParticle to test
  20337. * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  20338. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20339. * @returns true if there is an intersection
  20340. */
  20341. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20342. if (precise === void 0) { precise = false; }
  20343. if (!this._boundingInfo || !mesh._boundingInfo) {
  20344. return false;
  20345. }
  20346. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20347. return true;
  20348. }
  20349. if (includeDescendants) {
  20350. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20351. var child = _a[_i];
  20352. if (child.intersectsMesh(mesh, precise, true)) {
  20353. return true;
  20354. }
  20355. }
  20356. }
  20357. return false;
  20358. };
  20359. /**
  20360. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20361. * @param point defines the point to test
  20362. * @returns true if there is an intersection
  20363. */
  20364. AbstractMesh.prototype.intersectsPoint = function (point) {
  20365. if (!this._boundingInfo) {
  20366. return false;
  20367. }
  20368. return this._boundingInfo.intersectsPoint(point);
  20369. };
  20370. /**
  20371. * Gets the current physics impostor
  20372. * @see http://doc.babylonjs.com/features/physics_engine
  20373. * @returns a physics impostor or null
  20374. */
  20375. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20376. return this.physicsImpostor;
  20377. };
  20378. /**
  20379. * Gets the position of the current mesh in camera space
  20380. * @param camera defines the camera to use
  20381. * @returns a position
  20382. */
  20383. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20384. if (camera === void 0) { camera = null; }
  20385. if (!camera) {
  20386. camera = this.getScene().activeCamera;
  20387. }
  20388. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20389. };
  20390. /**
  20391. * Returns the distance from the mesh to the active camera
  20392. * @param camera defines the camera to use
  20393. * @returns the distance
  20394. */
  20395. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20396. if (camera === void 0) { camera = null; }
  20397. if (!camera) {
  20398. camera = this.getScene().activeCamera;
  20399. }
  20400. return this.absolutePosition.subtract(camera.position).length();
  20401. };
  20402. /**
  20403. * Apply a physic impulse to the mesh
  20404. * @param force defines the force to apply
  20405. * @param contactPoint defines where to apply the force
  20406. * @returns the current mesh
  20407. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20408. */
  20409. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20410. if (!this.physicsImpostor) {
  20411. return this;
  20412. }
  20413. this.physicsImpostor.applyImpulse(force, contactPoint);
  20414. return this;
  20415. };
  20416. /**
  20417. * Creates a physic joint between two meshes
  20418. * @param otherMesh defines the other mesh to use
  20419. * @param pivot1 defines the pivot to use on this mesh
  20420. * @param pivot2 defines the pivot to use on the other mesh
  20421. * @param options defines additional options (can be plugin dependent)
  20422. * @returns the current mesh
  20423. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20424. */
  20425. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20426. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20427. return this;
  20428. }
  20429. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20430. mainPivot: pivot1,
  20431. connectedPivot: pivot2,
  20432. nativeParams: options
  20433. });
  20434. return this;
  20435. };
  20436. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20437. // Collisions
  20438. /**
  20439. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20440. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20441. */
  20442. get: function () {
  20443. return this._checkCollisions;
  20444. },
  20445. set: function (collisionEnabled) {
  20446. this._checkCollisions = collisionEnabled;
  20447. if (this.getScene().workerCollisions) {
  20448. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20449. }
  20450. },
  20451. enumerable: true,
  20452. configurable: true
  20453. });
  20454. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20455. /**
  20456. * Gets Collider object used to compute collisions (not physics)
  20457. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20458. */
  20459. get: function () {
  20460. return this._collider;
  20461. },
  20462. enumerable: true,
  20463. configurable: true
  20464. });
  20465. /**
  20466. * Move the mesh using collision engine
  20467. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20468. * @param displacement defines the requested displacement vector
  20469. * @returns the current mesh
  20470. */
  20471. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20472. var globalPosition = this.getAbsolutePosition();
  20473. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20474. if (!this._collider) {
  20475. this._collider = new BABYLON.Collider();
  20476. }
  20477. this._collider._radius = this.ellipsoid;
  20478. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20479. return this;
  20480. };
  20481. // Submeshes octree
  20482. /**
  20483. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20484. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20485. * @param maxCapacity defines the maximum size of each block (64 by default)
  20486. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20487. * @returns the new octree
  20488. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20489. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20490. */
  20491. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20492. if (maxCapacity === void 0) { maxCapacity = 64; }
  20493. if (maxDepth === void 0) { maxDepth = 2; }
  20494. if (!this._submeshesOctree) {
  20495. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20496. }
  20497. this.computeWorldMatrix(true);
  20498. var boundingInfo = this.getBoundingInfo();
  20499. // Update octree
  20500. var bbox = boundingInfo.boundingBox;
  20501. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20502. return this._submeshesOctree;
  20503. };
  20504. // Collisions
  20505. /** @hidden */
  20506. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20507. this._generatePointsArray();
  20508. if (!this._positions) {
  20509. return this;
  20510. }
  20511. // Transformation
  20512. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20513. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20514. subMesh._lastColliderWorldVertices = [];
  20515. subMesh._trianglePlanes = [];
  20516. var start = subMesh.verticesStart;
  20517. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20518. for (var i = start; i < end; i++) {
  20519. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20520. }
  20521. }
  20522. // Collide
  20523. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20524. if (collider.collisionFound) {
  20525. collider.collidedMesh = this;
  20526. }
  20527. return this;
  20528. };
  20529. /** @hidden */
  20530. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20531. var subMeshes;
  20532. var len;
  20533. // Octrees
  20534. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20535. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20536. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20537. len = intersections.length;
  20538. subMeshes = intersections.data;
  20539. }
  20540. else {
  20541. subMeshes = this.subMeshes;
  20542. len = subMeshes.length;
  20543. }
  20544. for (var index = 0; index < len; index++) {
  20545. var subMesh = subMeshes[index];
  20546. // Bounding test
  20547. if (len > 1 && !subMesh._checkCollision(collider))
  20548. continue;
  20549. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20550. }
  20551. return this;
  20552. };
  20553. /** @hidden */
  20554. AbstractMesh.prototype._checkCollision = function (collider) {
  20555. // Bounding box test
  20556. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20557. return this;
  20558. // Transformation matrix
  20559. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20560. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20561. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20562. return this;
  20563. };
  20564. // Picking
  20565. /** @hidden */
  20566. AbstractMesh.prototype._generatePointsArray = function () {
  20567. return false;
  20568. };
  20569. /**
  20570. * Checks if the passed Ray intersects with the mesh
  20571. * @param ray defines the ray to use
  20572. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20573. * @returns the picking info
  20574. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20575. */
  20576. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20577. var pickingInfo = new BABYLON.PickingInfo();
  20578. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20579. return pickingInfo;
  20580. }
  20581. if (!this._generatePointsArray()) {
  20582. return pickingInfo;
  20583. }
  20584. var intersectInfo = null;
  20585. // Octrees
  20586. var subMeshes;
  20587. var len;
  20588. if (this._submeshesOctree && this.useOctreeForPicking) {
  20589. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20590. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20591. len = intersections.length;
  20592. subMeshes = intersections.data;
  20593. }
  20594. else {
  20595. subMeshes = this.subMeshes;
  20596. len = subMeshes.length;
  20597. }
  20598. for (var index = 0; index < len; index++) {
  20599. var subMesh = subMeshes[index];
  20600. // Bounding test
  20601. if (len > 1 && !subMesh.canIntersects(ray))
  20602. continue;
  20603. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20604. if (currentIntersectInfo) {
  20605. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20606. intersectInfo = currentIntersectInfo;
  20607. intersectInfo.subMeshId = index;
  20608. if (fastCheck) {
  20609. break;
  20610. }
  20611. }
  20612. }
  20613. }
  20614. if (intersectInfo) {
  20615. // Get picked point
  20616. var world = this.getWorldMatrix();
  20617. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20618. var direction = ray.direction.clone();
  20619. direction = direction.scale(intersectInfo.distance);
  20620. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20621. var pickedPoint = worldOrigin.add(worldDirection);
  20622. // Return result
  20623. pickingInfo.hit = true;
  20624. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20625. pickingInfo.pickedPoint = pickedPoint;
  20626. pickingInfo.pickedMesh = this;
  20627. pickingInfo.bu = intersectInfo.bu || 0;
  20628. pickingInfo.bv = intersectInfo.bv || 0;
  20629. pickingInfo.faceId = intersectInfo.faceId;
  20630. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20631. return pickingInfo;
  20632. }
  20633. return pickingInfo;
  20634. };
  20635. /**
  20636. * Clones the current mesh
  20637. * @param name defines the mesh name
  20638. * @param newParent defines the new mesh parent
  20639. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20640. * @returns the new mesh
  20641. */
  20642. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20643. return null;
  20644. };
  20645. /**
  20646. * Disposes all the submeshes of the current meshnp
  20647. * @returns the current mesh
  20648. */
  20649. AbstractMesh.prototype.releaseSubMeshes = function () {
  20650. if (this.subMeshes) {
  20651. while (this.subMeshes.length) {
  20652. this.subMeshes[0].dispose();
  20653. }
  20654. }
  20655. else {
  20656. this.subMeshes = new Array();
  20657. }
  20658. return this;
  20659. };
  20660. /**
  20661. * Releases resources associated with this abstract mesh.
  20662. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20663. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20664. */
  20665. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20666. var _this = this;
  20667. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20668. var index;
  20669. // Smart Array Retainers.
  20670. this.getScene().freeActiveMeshes();
  20671. this.getScene().freeRenderingGroups();
  20672. // Action manager
  20673. if (this.actionManager !== undefined && this.actionManager !== null) {
  20674. this.actionManager.dispose();
  20675. this.actionManager = null;
  20676. }
  20677. // Skeleton
  20678. this._skeleton = null;
  20679. // Physics
  20680. if (this.physicsImpostor) {
  20681. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20682. }
  20683. // Intersections in progress
  20684. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20685. var other = this._intersectionsInProgress[index];
  20686. var pos = other._intersectionsInProgress.indexOf(this);
  20687. other._intersectionsInProgress.splice(pos, 1);
  20688. }
  20689. this._intersectionsInProgress = [];
  20690. // Lights
  20691. var lights = this.getScene().lights;
  20692. lights.forEach(function (light) {
  20693. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20694. if (meshIndex !== -1) {
  20695. light.includedOnlyMeshes.splice(meshIndex, 1);
  20696. }
  20697. meshIndex = light.excludedMeshes.indexOf(_this);
  20698. if (meshIndex !== -1) {
  20699. light.excludedMeshes.splice(meshIndex, 1);
  20700. }
  20701. // Shadow generators
  20702. var generator = light.getShadowGenerator();
  20703. if (generator) {
  20704. var shadowMap = generator.getShadowMap();
  20705. if (shadowMap && shadowMap.renderList) {
  20706. meshIndex = shadowMap.renderList.indexOf(_this);
  20707. if (meshIndex !== -1) {
  20708. shadowMap.renderList.splice(meshIndex, 1);
  20709. }
  20710. }
  20711. }
  20712. });
  20713. // Edges
  20714. if (this._edgesRenderer) {
  20715. this._edgesRenderer.dispose();
  20716. this._edgesRenderer = null;
  20717. }
  20718. // SubMeshes
  20719. if (this.getClassName() !== "InstancedMesh") {
  20720. this.releaseSubMeshes();
  20721. }
  20722. // Octree
  20723. var sceneOctree = this.getScene().selectionOctree;
  20724. if (sceneOctree !== undefined && sceneOctree !== null) {
  20725. var index = sceneOctree.dynamicContent.indexOf(this);
  20726. if (index !== -1) {
  20727. sceneOctree.dynamicContent.splice(index, 1);
  20728. }
  20729. }
  20730. // Query
  20731. var engine = this.getScene().getEngine();
  20732. if (this._occlusionQuery) {
  20733. this._isOcclusionQueryInProgress = false;
  20734. engine.deleteQuery(this._occlusionQuery);
  20735. this._occlusionQuery = null;
  20736. }
  20737. // Engine
  20738. engine.wipeCaches();
  20739. // Remove from scene
  20740. this.getScene().removeMesh(this);
  20741. if (disposeMaterialAndTextures) {
  20742. if (this.material) {
  20743. this.material.dispose(false, true);
  20744. }
  20745. }
  20746. if (!doNotRecurse) {
  20747. // Particles
  20748. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20749. if (this.getScene().particleSystems[index].emitter === this) {
  20750. this.getScene().particleSystems[index].dispose();
  20751. index--;
  20752. }
  20753. }
  20754. }
  20755. // facet data
  20756. if (this._facetDataEnabled) {
  20757. this.disableFacetData();
  20758. }
  20759. this.onAfterWorldMatrixUpdateObservable.clear();
  20760. this.onCollideObservable.clear();
  20761. this.onCollisionPositionChangeObservable.clear();
  20762. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20763. };
  20764. /**
  20765. * Adds the passed mesh as a child to the current mesh
  20766. * @param mesh defines the child mesh
  20767. * @returns the current mesh
  20768. */
  20769. AbstractMesh.prototype.addChild = function (mesh) {
  20770. mesh.setParent(this);
  20771. return this;
  20772. };
  20773. /**
  20774. * Removes the passed mesh from the current mesh children list
  20775. * @param mesh defines the child mesh
  20776. * @returns the current mesh
  20777. */
  20778. AbstractMesh.prototype.removeChild = function (mesh) {
  20779. mesh.setParent(null);
  20780. return this;
  20781. };
  20782. // Facet data
  20783. /** @hidden */
  20784. AbstractMesh.prototype._initFacetData = function () {
  20785. if (!this._facetNormals) {
  20786. this._facetNormals = new Array();
  20787. }
  20788. if (!this._facetPositions) {
  20789. this._facetPositions = new Array();
  20790. }
  20791. if (!this._facetPartitioning) {
  20792. this._facetPartitioning = new Array();
  20793. }
  20794. this._facetNb = (this.getIndices().length / 3) | 0;
  20795. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20796. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20797. for (var f = 0; f < this._facetNb; f++) {
  20798. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20799. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20800. }
  20801. this._facetDataEnabled = true;
  20802. return this;
  20803. };
  20804. /**
  20805. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20806. * This method can be called within the render loop.
  20807. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation
  20808. * @returns the current mesh
  20809. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20810. */
  20811. AbstractMesh.prototype.updateFacetData = function () {
  20812. if (!this._facetDataEnabled) {
  20813. this._initFacetData();
  20814. }
  20815. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20816. var indices = this.getIndices();
  20817. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20818. var bInfo = this.getBoundingInfo();
  20819. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20820. // init arrays, matrix and sort function on first call
  20821. this._facetDepthSortEnabled = true;
  20822. if (indices instanceof Uint16Array) {
  20823. this._depthSortedIndices = new Uint16Array(indices);
  20824. }
  20825. else if (indices instanceof Uint32Array) {
  20826. this._depthSortedIndices = new Uint32Array(indices);
  20827. }
  20828. else {
  20829. var needs32bits = false;
  20830. for (var i = 0; i < indices.length; i++) {
  20831. if (indices[i] > 65535) {
  20832. needs32bits = true;
  20833. break;
  20834. }
  20835. }
  20836. if (needs32bits) {
  20837. this._depthSortedIndices = new Uint32Array(indices);
  20838. }
  20839. else {
  20840. this._depthSortedIndices = new Uint16Array(indices);
  20841. }
  20842. }
  20843. this._facetDepthSortFunction = function (f1, f2) {
  20844. return (f2.sqDistance - f1.sqDistance);
  20845. };
  20846. if (!this._facetDepthSortFrom) {
  20847. var camera = this.getScene().activeCamera;
  20848. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20849. }
  20850. this._depthSortedFacets = [];
  20851. for (var f = 0; f < this._facetNb; f++) {
  20852. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20853. this._depthSortedFacets.push(depthSortedFacet);
  20854. }
  20855. this._invertedMatrix = BABYLON.Matrix.Identity();
  20856. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20857. }
  20858. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20859. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20860. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20861. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20862. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20863. this._subDiv.max = this._partitioningSubdivisions;
  20864. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20865. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20866. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20867. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20868. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20869. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20870. // set the parameters for ComputeNormals()
  20871. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20872. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20873. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20874. this._facetParameters.bInfo = bInfo;
  20875. this._facetParameters.bbSize = this._bbSize;
  20876. this._facetParameters.subDiv = this._subDiv;
  20877. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20878. this._facetParameters.depthSort = this._facetDepthSort;
  20879. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20880. this.computeWorldMatrix(true);
  20881. this._worldMatrix.invertToRef(this._invertedMatrix);
  20882. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20883. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20884. }
  20885. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20886. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20887. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20888. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20889. var l = (this._depthSortedIndices.length / 3) | 0;
  20890. for (var f = 0; f < l; f++) {
  20891. var sind = this._depthSortedFacets[f].ind;
  20892. this._depthSortedIndices[f * 3] = indices[sind];
  20893. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20894. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20895. }
  20896. this.updateIndices(this._depthSortedIndices);
  20897. }
  20898. return this;
  20899. };
  20900. /**
  20901. * Returns the facetLocalNormals array.
  20902. * The normals are expressed in the mesh local spac
  20903. * @returns an array of Vector3
  20904. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20905. */
  20906. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20907. if (!this._facetNormals) {
  20908. this.updateFacetData();
  20909. }
  20910. return this._facetNormals;
  20911. };
  20912. /**
  20913. * Returns the facetLocalPositions array.
  20914. * The facet positions are expressed in the mesh local space
  20915. * @returns an array of Vector3
  20916. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20917. */
  20918. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20919. if (!this._facetPositions) {
  20920. this.updateFacetData();
  20921. }
  20922. return this._facetPositions;
  20923. };
  20924. /**
  20925. * Returns the facetLocalPartioning array
  20926. * @returns an array of array of numbers
  20927. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20928. */
  20929. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20930. if (!this._facetPartitioning) {
  20931. this.updateFacetData();
  20932. }
  20933. return this._facetPartitioning;
  20934. };
  20935. /**
  20936. * Returns the i-th facet position in the world system.
  20937. * This method allocates a new Vector3 per call
  20938. * @param i defines the facet index
  20939. * @returns a new Vector3
  20940. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20941. */
  20942. AbstractMesh.prototype.getFacetPosition = function (i) {
  20943. var pos = BABYLON.Vector3.Zero();
  20944. this.getFacetPositionToRef(i, pos);
  20945. return pos;
  20946. };
  20947. /**
  20948. * Sets the reference Vector3 with the i-th facet position in the world system
  20949. * @param i defines the facet index
  20950. * @param ref defines the target vector
  20951. * @returns the current mesh
  20952. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20953. */
  20954. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20955. var localPos = (this.getFacetLocalPositions())[i];
  20956. var world = this.getWorldMatrix();
  20957. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20958. return this;
  20959. };
  20960. /**
  20961. * Returns the i-th facet normal in the world system.
  20962. * This method allocates a new Vector3 per call
  20963. * @param i defines the facet index
  20964. * @returns a new Vector3
  20965. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20966. */
  20967. AbstractMesh.prototype.getFacetNormal = function (i) {
  20968. var norm = BABYLON.Vector3.Zero();
  20969. this.getFacetNormalToRef(i, norm);
  20970. return norm;
  20971. };
  20972. /**
  20973. * Sets the reference Vector3 with the i-th facet normal in the world system
  20974. * @param i defines the facet index
  20975. * @param ref defines the target vector
  20976. * @returns the current mesh
  20977. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20978. */
  20979. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20980. var localNorm = (this.getFacetLocalNormals())[i];
  20981. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20982. return this;
  20983. };
  20984. /**
  20985. * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system)
  20986. * @param x defines x coordinate
  20987. * @param y defines y coordinate
  20988. * @param z defines z coordinate
  20989. * @returns the array of facet indexes
  20990. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20991. */
  20992. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20993. var bInfo = this.getBoundingInfo();
  20994. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20995. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20996. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20997. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20998. return null;
  20999. }
  21000. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21001. };
  21002. /**
  21003. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21004. * @param projected sets as the (x,y,z) world projection on the facet
  21005. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21006. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21007. * @param x defines x coordinate
  21008. * @param y defines y coordinate
  21009. * @param z defines z coordinate
  21010. * @returns the face index if found (or null instead)
  21011. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21012. */
  21013. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21014. if (checkFace === void 0) { checkFace = false; }
  21015. if (facing === void 0) { facing = true; }
  21016. var world = this.getWorldMatrix();
  21017. var invMat = BABYLON.Tmp.Matrix[5];
  21018. world.invertToRef(invMat);
  21019. var invVect = BABYLON.Tmp.Vector3[8];
  21020. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21021. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21022. if (projected) {
  21023. // tranform the local computed projected vector to world coordinates
  21024. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21025. }
  21026. return closest;
  21027. };
  21028. /**
  21029. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21030. * @param projected sets as the (x,y,z) local projection on the facet
  21031. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21032. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21033. * @param x defines x coordinate
  21034. * @param y defines y coordinate
  21035. * @param z defines z coordinate
  21036. * @returns the face index if found (or null instead)
  21037. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21038. */
  21039. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21040. if (checkFace === void 0) { checkFace = false; }
  21041. if (facing === void 0) { facing = true; }
  21042. var closest = null;
  21043. var tmpx = 0.0;
  21044. var tmpy = 0.0;
  21045. var tmpz = 0.0;
  21046. var d = 0.0; // tmp dot facet normal * facet position
  21047. var t0 = 0.0;
  21048. var projx = 0.0;
  21049. var projy = 0.0;
  21050. var projz = 0.0;
  21051. // Get all the facets in the same partitioning block than (x, y, z)
  21052. var facetPositions = this.getFacetLocalPositions();
  21053. var facetNormals = this.getFacetLocalNormals();
  21054. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21055. if (!facetsInBlock) {
  21056. return null;
  21057. }
  21058. // Get the closest facet to (x, y, z)
  21059. var shortest = Number.MAX_VALUE; // init distance vars
  21060. var tmpDistance = shortest;
  21061. var fib; // current facet in the block
  21062. var norm; // current facet normal
  21063. var p0; // current facet barycenter position
  21064. // loop on all the facets in the current partitioning block
  21065. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21066. fib = facetsInBlock[idx];
  21067. norm = facetNormals[fib];
  21068. p0 = facetPositions[fib];
  21069. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21070. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21071. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21072. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21073. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21074. projx = x + norm.x * t0;
  21075. projy = y + norm.y * t0;
  21076. projz = z + norm.z * t0;
  21077. tmpx = projx - x;
  21078. tmpy = projy - y;
  21079. tmpz = projz - z;
  21080. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21081. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21082. shortest = tmpDistance;
  21083. closest = fib;
  21084. if (projected) {
  21085. projected.x = projx;
  21086. projected.y = projy;
  21087. projected.z = projz;
  21088. }
  21089. }
  21090. }
  21091. }
  21092. return closest;
  21093. };
  21094. /**
  21095. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21096. * @returns the parameters
  21097. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21098. */
  21099. AbstractMesh.prototype.getFacetDataParameters = function () {
  21100. return this._facetParameters;
  21101. };
  21102. /**
  21103. * Disables the feature FacetData and frees the related memory
  21104. * @returns the current mesh
  21105. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21106. */
  21107. AbstractMesh.prototype.disableFacetData = function () {
  21108. if (this._facetDataEnabled) {
  21109. this._facetDataEnabled = false;
  21110. this._facetPositions = new Array();
  21111. this._facetNormals = new Array();
  21112. this._facetPartitioning = new Array();
  21113. this._facetParameters = null;
  21114. this._depthSortedIndices = new Uint32Array(0);
  21115. }
  21116. return this;
  21117. };
  21118. /**
  21119. * Updates the AbstractMesh indices array
  21120. * @param indices defines the data source
  21121. * @returns the current mesh
  21122. */
  21123. AbstractMesh.prototype.updateIndices = function (indices) {
  21124. return this;
  21125. };
  21126. /**
  21127. * Creates new normals data for the mesh
  21128. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21129. * @returns the current mesh
  21130. */
  21131. AbstractMesh.prototype.createNormals = function (updatable) {
  21132. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21133. var indices = this.getIndices();
  21134. var normals;
  21135. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21136. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21137. }
  21138. else {
  21139. normals = [];
  21140. }
  21141. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21142. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21143. return this;
  21144. };
  21145. /**
  21146. * Align the mesh with a normal
  21147. * @param normal defines the normal to use
  21148. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21149. * @returns the current mesh
  21150. */
  21151. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21152. if (!upDirection) {
  21153. upDirection = BABYLON.Axis.Y;
  21154. }
  21155. var axisX = BABYLON.Tmp.Vector3[0];
  21156. var axisZ = BABYLON.Tmp.Vector3[1];
  21157. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21158. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21159. if (this.rotationQuaternion) {
  21160. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21161. }
  21162. else {
  21163. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21164. }
  21165. return this;
  21166. };
  21167. /** @hidden */
  21168. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21169. var engine = this.getEngine();
  21170. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21171. this._isOccluded = false;
  21172. return;
  21173. }
  21174. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21175. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21176. if (isOcclusionQueryAvailable) {
  21177. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21178. this._isOcclusionQueryInProgress = false;
  21179. this._occlusionInternalRetryCounter = 0;
  21180. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21181. }
  21182. else {
  21183. this._occlusionInternalRetryCounter++;
  21184. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21185. this._isOcclusionQueryInProgress = false;
  21186. this._occlusionInternalRetryCounter = 0;
  21187. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21188. // if strict continue the last state of the object.
  21189. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21190. }
  21191. else {
  21192. return;
  21193. }
  21194. }
  21195. }
  21196. var scene = this.getScene();
  21197. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21198. if (!this._occlusionQuery) {
  21199. this._occlusionQuery = engine.createQuery();
  21200. }
  21201. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21202. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21203. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21204. this._isOcclusionQueryInProgress = true;
  21205. };
  21206. /** No occlusion */
  21207. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21208. /** Occlusion set to optimisitic */
  21209. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21210. /** Occlusion set to strict */
  21211. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21212. /** Use an accurante occlusion algorithm */
  21213. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21214. /** Use a conservative occlusion algorithm */
  21215. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21216. return AbstractMesh;
  21217. }(BABYLON.TransformNode));
  21218. BABYLON.AbstractMesh = AbstractMesh;
  21219. })(BABYLON || (BABYLON = {}));
  21220. //# sourceMappingURL=babylon.abstractMesh.js.map
  21221. var BABYLON;
  21222. (function (BABYLON) {
  21223. /**
  21224. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21225. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21226. * 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.
  21227. */
  21228. var Light = /** @class */ (function (_super) {
  21229. __extends(Light, _super);
  21230. /**
  21231. * Creates a Light object in the scene.
  21232. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21233. * @param name The firendly name of the light
  21234. * @param scene The scene the light belongs too
  21235. */
  21236. function Light(name, scene) {
  21237. var _this = _super.call(this, name, scene) || this;
  21238. /**
  21239. * Diffuse gives the basic color to an object.
  21240. */
  21241. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21242. /**
  21243. * Specular produces a highlight color on an object.
  21244. * Note: This is note affecting PBR materials.
  21245. */
  21246. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21247. /**
  21248. * Strength of the light.
  21249. * Note: By default it is define in the framework own unit.
  21250. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21251. */
  21252. _this.intensity = 1.0;
  21253. /**
  21254. * Defines how far from the source the light is impacting in scene units.
  21255. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21256. */
  21257. _this.range = Number.MAX_VALUE;
  21258. /**
  21259. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21260. * of light.
  21261. */
  21262. _this._photometricScale = 1.0;
  21263. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21264. _this._radius = 0.00001;
  21265. /**
  21266. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21267. * exceeding the number allowed of the materials.
  21268. */
  21269. _this.renderPriority = 0;
  21270. /**
  21271. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21272. * the current shadow generator.
  21273. */
  21274. _this.shadowEnabled = true;
  21275. _this._excludeWithLayerMask = 0;
  21276. _this._includeOnlyWithLayerMask = 0;
  21277. _this._lightmapMode = 0;
  21278. /**
  21279. * @hidden Internal use only.
  21280. */
  21281. _this._excludedMeshesIds = new Array();
  21282. /**
  21283. * @hidden Internal use only.
  21284. */
  21285. _this._includedOnlyMeshesIds = new Array();
  21286. _this.getScene().addLight(_this);
  21287. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21288. _this._buildUniformLayout();
  21289. _this.includedOnlyMeshes = new Array();
  21290. _this.excludedMeshes = new Array();
  21291. _this._resyncMeshes();
  21292. return _this;
  21293. }
  21294. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21295. /**
  21296. * If every light affecting the material is in this lightmapMode,
  21297. * material.lightmapTexture adds or multiplies
  21298. * (depends on material.useLightmapAsShadowmap)
  21299. * after every other light calculations.
  21300. */
  21301. get: function () {
  21302. return Light._LIGHTMAP_DEFAULT;
  21303. },
  21304. enumerable: true,
  21305. configurable: true
  21306. });
  21307. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21308. /**
  21309. * material.lightmapTexture as only diffuse lighting from this light
  21310. * adds only specular lighting from this light
  21311. * adds dynamic shadows
  21312. */
  21313. get: function () {
  21314. return Light._LIGHTMAP_SPECULAR;
  21315. },
  21316. enumerable: true,
  21317. configurable: true
  21318. });
  21319. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21320. /**
  21321. * material.lightmapTexture as only lighting
  21322. * no light calculation from this light
  21323. * only adds dynamic shadows from this light
  21324. */
  21325. get: function () {
  21326. return Light._LIGHTMAP_SHADOWSONLY;
  21327. },
  21328. enumerable: true,
  21329. configurable: true
  21330. });
  21331. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21332. /**
  21333. * Each light type uses the default quantity according to its type:
  21334. * point/spot lights use luminous intensity
  21335. * directional lights use illuminance
  21336. */
  21337. get: function () {
  21338. return Light._INTENSITYMODE_AUTOMATIC;
  21339. },
  21340. enumerable: true,
  21341. configurable: true
  21342. });
  21343. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21344. /**
  21345. * lumen (lm)
  21346. */
  21347. get: function () {
  21348. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21349. },
  21350. enumerable: true,
  21351. configurable: true
  21352. });
  21353. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21354. /**
  21355. * candela (lm/sr)
  21356. */
  21357. get: function () {
  21358. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21359. },
  21360. enumerable: true,
  21361. configurable: true
  21362. });
  21363. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21364. /**
  21365. * lux (lm/m^2)
  21366. */
  21367. get: function () {
  21368. return Light._INTENSITYMODE_ILLUMINANCE;
  21369. },
  21370. enumerable: true,
  21371. configurable: true
  21372. });
  21373. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21374. /**
  21375. * nit (cd/m^2)
  21376. */
  21377. get: function () {
  21378. return Light._INTENSITYMODE_LUMINANCE;
  21379. },
  21380. enumerable: true,
  21381. configurable: true
  21382. });
  21383. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21384. /**
  21385. * Light type const id of the point light.
  21386. */
  21387. get: function () {
  21388. return Light._LIGHTTYPEID_POINTLIGHT;
  21389. },
  21390. enumerable: true,
  21391. configurable: true
  21392. });
  21393. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21394. /**
  21395. * Light type const id of the directional light.
  21396. */
  21397. get: function () {
  21398. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21399. },
  21400. enumerable: true,
  21401. configurable: true
  21402. });
  21403. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21404. /**
  21405. * Light type const id of the spot light.
  21406. */
  21407. get: function () {
  21408. return Light._LIGHTTYPEID_SPOTLIGHT;
  21409. },
  21410. enumerable: true,
  21411. configurable: true
  21412. });
  21413. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21414. /**
  21415. * Light type const id of the hemispheric light.
  21416. */
  21417. get: function () {
  21418. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21419. },
  21420. enumerable: true,
  21421. configurable: true
  21422. });
  21423. Object.defineProperty(Light.prototype, "intensityMode", {
  21424. /**
  21425. * Gets the photometric scale used to interpret the intensity.
  21426. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21427. */
  21428. get: function () {
  21429. return this._intensityMode;
  21430. },
  21431. /**
  21432. * Sets the photometric scale used to interpret the intensity.
  21433. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21434. */
  21435. set: function (value) {
  21436. this._intensityMode = value;
  21437. this._computePhotometricScale();
  21438. },
  21439. enumerable: true,
  21440. configurable: true
  21441. });
  21442. ;
  21443. ;
  21444. Object.defineProperty(Light.prototype, "radius", {
  21445. /**
  21446. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21447. */
  21448. get: function () {
  21449. return this._radius;
  21450. },
  21451. /**
  21452. * sets the light radius used by PBR Materials to simulate soft area lights.
  21453. */
  21454. set: function (value) {
  21455. this._radius = value;
  21456. this._computePhotometricScale();
  21457. },
  21458. enumerable: true,
  21459. configurable: true
  21460. });
  21461. ;
  21462. ;
  21463. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21464. /**
  21465. * Gets the only meshes impacted by this light.
  21466. */
  21467. get: function () {
  21468. return this._includedOnlyMeshes;
  21469. },
  21470. /**
  21471. * Sets the only meshes impacted by this light.
  21472. */
  21473. set: function (value) {
  21474. this._includedOnlyMeshes = value;
  21475. this._hookArrayForIncludedOnly(value);
  21476. },
  21477. enumerable: true,
  21478. configurable: true
  21479. });
  21480. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21481. /**
  21482. * Gets the meshes not impacted by this light.
  21483. */
  21484. get: function () {
  21485. return this._excludedMeshes;
  21486. },
  21487. /**
  21488. * Sets the meshes not impacted by this light.
  21489. */
  21490. set: function (value) {
  21491. this._excludedMeshes = value;
  21492. this._hookArrayForExcluded(value);
  21493. },
  21494. enumerable: true,
  21495. configurable: true
  21496. });
  21497. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21498. /**
  21499. * Gets the layer id use to find what meshes are not impacted by the light.
  21500. * Inactive if 0
  21501. */
  21502. get: function () {
  21503. return this._excludeWithLayerMask;
  21504. },
  21505. /**
  21506. * Sets the layer id use to find what meshes are not impacted by the light.
  21507. * Inactive if 0
  21508. */
  21509. set: function (value) {
  21510. this._excludeWithLayerMask = value;
  21511. this._resyncMeshes();
  21512. },
  21513. enumerable: true,
  21514. configurable: true
  21515. });
  21516. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21517. /**
  21518. * Gets the layer id use to find what meshes are impacted by the light.
  21519. * Inactive if 0
  21520. */
  21521. get: function () {
  21522. return this._includeOnlyWithLayerMask;
  21523. },
  21524. /**
  21525. * Sets the layer id use to find what meshes are impacted by the light.
  21526. * Inactive if 0
  21527. */
  21528. set: function (value) {
  21529. this._includeOnlyWithLayerMask = value;
  21530. this._resyncMeshes();
  21531. },
  21532. enumerable: true,
  21533. configurable: true
  21534. });
  21535. Object.defineProperty(Light.prototype, "lightmapMode", {
  21536. /**
  21537. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21538. */
  21539. get: function () {
  21540. return this._lightmapMode;
  21541. },
  21542. /**
  21543. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21544. */
  21545. set: function (value) {
  21546. if (this._lightmapMode === value) {
  21547. return;
  21548. }
  21549. this._lightmapMode = value;
  21550. this._markMeshesAsLightDirty();
  21551. },
  21552. enumerable: true,
  21553. configurable: true
  21554. });
  21555. /**
  21556. * Returns the string "Light".
  21557. * @returns the class name
  21558. */
  21559. Light.prototype.getClassName = function () {
  21560. return "Light";
  21561. };
  21562. /**
  21563. * Converts the light information to a readable string for debug purpose.
  21564. * @param fullDetails Supports for multiple levels of logging within scene loading
  21565. * @returns the human readable light info
  21566. */
  21567. Light.prototype.toString = function (fullDetails) {
  21568. var ret = "Name: " + this.name;
  21569. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21570. if (this.animations) {
  21571. for (var i = 0; i < this.animations.length; i++) {
  21572. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21573. }
  21574. }
  21575. if (fullDetails) {
  21576. }
  21577. return ret;
  21578. };
  21579. /**
  21580. * Set the enabled state of this node.
  21581. * @param value - the new enabled state
  21582. */
  21583. Light.prototype.setEnabled = function (value) {
  21584. _super.prototype.setEnabled.call(this, value);
  21585. this._resyncMeshes();
  21586. };
  21587. /**
  21588. * Returns the Light associated shadow generator if any.
  21589. * @return the associated shadow generator.
  21590. */
  21591. Light.prototype.getShadowGenerator = function () {
  21592. return this._shadowGenerator;
  21593. };
  21594. /**
  21595. * Returns a Vector3, the absolute light position in the World.
  21596. * @returns the world space position of the light
  21597. */
  21598. Light.prototype.getAbsolutePosition = function () {
  21599. return BABYLON.Vector3.Zero();
  21600. };
  21601. /**
  21602. * Specifies if the light will affect the passed mesh.
  21603. * @param mesh The mesh to test against the light
  21604. * @return true the mesh is affected otherwise, false.
  21605. */
  21606. Light.prototype.canAffectMesh = function (mesh) {
  21607. if (!mesh) {
  21608. return true;
  21609. }
  21610. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21611. return false;
  21612. }
  21613. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21614. return false;
  21615. }
  21616. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21617. return false;
  21618. }
  21619. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21620. return false;
  21621. }
  21622. return true;
  21623. };
  21624. /**
  21625. * Computes and Returns the light World matrix.
  21626. * @returns the world matrix
  21627. */
  21628. Light.prototype.getWorldMatrix = function () {
  21629. this._currentRenderId = this.getScene().getRenderId();
  21630. this._childRenderId = this._currentRenderId;
  21631. var worldMatrix = this._getWorldMatrix();
  21632. if (this.parent && this.parent.getWorldMatrix) {
  21633. if (!this._parentedWorldMatrix) {
  21634. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21635. }
  21636. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21637. this._markSyncedWithParent();
  21638. return this._parentedWorldMatrix;
  21639. }
  21640. return worldMatrix;
  21641. };
  21642. /**
  21643. * Sort function to order lights for rendering.
  21644. * @param a First Light object to compare to second.
  21645. * @param b Second Light object to compare first.
  21646. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21647. */
  21648. Light.CompareLightsPriority = function (a, b) {
  21649. //shadow-casting lights have priority over non-shadow-casting lights
  21650. //the renderPrioirty is a secondary sort criterion
  21651. if (a.shadowEnabled !== b.shadowEnabled) {
  21652. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21653. }
  21654. return b.renderPriority - a.renderPriority;
  21655. };
  21656. /**
  21657. * Releases resources associated with this node.
  21658. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21659. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21660. */
  21661. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21662. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21663. if (this._shadowGenerator) {
  21664. this._shadowGenerator.dispose();
  21665. this._shadowGenerator = null;
  21666. }
  21667. // Animations
  21668. this.getScene().stopAnimation(this);
  21669. // Remove from meshes
  21670. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21671. var mesh = _a[_i];
  21672. mesh._removeLightSource(this);
  21673. }
  21674. this._uniformBuffer.dispose();
  21675. // Remove from scene
  21676. this.getScene().removeLight(this);
  21677. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21678. };
  21679. /**
  21680. * Returns the light type ID (integer).
  21681. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21682. */
  21683. Light.prototype.getTypeID = function () {
  21684. return 0;
  21685. };
  21686. /**
  21687. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21688. * @returns the scaled intensity in intensity mode unit
  21689. */
  21690. Light.prototype.getScaledIntensity = function () {
  21691. return this._photometricScale * this.intensity;
  21692. };
  21693. /**
  21694. * Returns a new Light object, named "name", from the current one.
  21695. * @param name The name of the cloned light
  21696. * @returns the new created light
  21697. */
  21698. Light.prototype.clone = function (name) {
  21699. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21700. if (!constructor) {
  21701. return null;
  21702. }
  21703. return BABYLON.SerializationHelper.Clone(constructor, this);
  21704. };
  21705. /**
  21706. * Serializes the current light into a Serialization object.
  21707. * @returns the serialized object.
  21708. */
  21709. Light.prototype.serialize = function () {
  21710. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21711. // Type
  21712. serializationObject.type = this.getTypeID();
  21713. // Parent
  21714. if (this.parent) {
  21715. serializationObject.parentId = this.parent.id;
  21716. }
  21717. // Inclusion / exclusions
  21718. if (this.excludedMeshes.length > 0) {
  21719. serializationObject.excludedMeshesIds = [];
  21720. this.excludedMeshes.forEach(function (mesh) {
  21721. serializationObject.excludedMeshesIds.push(mesh.id);
  21722. });
  21723. }
  21724. if (this.includedOnlyMeshes.length > 0) {
  21725. serializationObject.includedOnlyMeshesIds = [];
  21726. this.includedOnlyMeshes.forEach(function (mesh) {
  21727. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21728. });
  21729. }
  21730. // Animations
  21731. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21732. serializationObject.ranges = this.serializeAnimationRanges();
  21733. return serializationObject;
  21734. };
  21735. /**
  21736. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21737. * This new light is named "name" and added to the passed scene.
  21738. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21739. * @param name The friendly name of the light
  21740. * @param scene The scene the new light will belong to
  21741. * @returns the constructor function
  21742. */
  21743. Light.GetConstructorFromName = function (type, name, scene) {
  21744. switch (type) {
  21745. case 0:
  21746. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21747. case 1:
  21748. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21749. case 2:
  21750. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21751. case 3:
  21752. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21753. }
  21754. return null;
  21755. };
  21756. /**
  21757. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21758. * @param parsedLight The JSON representation of the light
  21759. * @param scene The scene to create the parsed light in
  21760. * @returns the created light after parsing
  21761. */
  21762. Light.Parse = function (parsedLight, scene) {
  21763. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21764. if (!constructor) {
  21765. return null;
  21766. }
  21767. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21768. // Inclusion / exclusions
  21769. if (parsedLight.excludedMeshesIds) {
  21770. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21771. }
  21772. if (parsedLight.includedOnlyMeshesIds) {
  21773. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21774. }
  21775. // Parent
  21776. if (parsedLight.parentId) {
  21777. light._waitingParentId = parsedLight.parentId;
  21778. }
  21779. // Animations
  21780. if (parsedLight.animations) {
  21781. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21782. var parsedAnimation = parsedLight.animations[animationIndex];
  21783. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21784. }
  21785. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21786. }
  21787. if (parsedLight.autoAnimate) {
  21788. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21789. }
  21790. return light;
  21791. };
  21792. Light.prototype._hookArrayForExcluded = function (array) {
  21793. var _this = this;
  21794. var oldPush = array.push;
  21795. array.push = function () {
  21796. var items = [];
  21797. for (var _i = 0; _i < arguments.length; _i++) {
  21798. items[_i] = arguments[_i];
  21799. }
  21800. var result = oldPush.apply(array, items);
  21801. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21802. var item = items_1[_a];
  21803. item._resyncLighSource(_this);
  21804. }
  21805. return result;
  21806. };
  21807. var oldSplice = array.splice;
  21808. array.splice = function (index, deleteCount) {
  21809. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21810. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21811. var item = deleted_1[_i];
  21812. item._resyncLighSource(_this);
  21813. }
  21814. return deleted;
  21815. };
  21816. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21817. var item = array_1[_i];
  21818. item._resyncLighSource(this);
  21819. }
  21820. };
  21821. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21822. var _this = this;
  21823. var oldPush = array.push;
  21824. array.push = function () {
  21825. var items = [];
  21826. for (var _i = 0; _i < arguments.length; _i++) {
  21827. items[_i] = arguments[_i];
  21828. }
  21829. var result = oldPush.apply(array, items);
  21830. _this._resyncMeshes();
  21831. return result;
  21832. };
  21833. var oldSplice = array.splice;
  21834. array.splice = function (index, deleteCount) {
  21835. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21836. _this._resyncMeshes();
  21837. return deleted;
  21838. };
  21839. this._resyncMeshes();
  21840. };
  21841. Light.prototype._resyncMeshes = function () {
  21842. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21843. var mesh = _a[_i];
  21844. mesh._resyncLighSource(this);
  21845. }
  21846. };
  21847. /**
  21848. * Forces the meshes to update their light related information in their rendering used effects
  21849. * @hidden Internal Use Only
  21850. */
  21851. Light.prototype._markMeshesAsLightDirty = function () {
  21852. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21853. var mesh = _a[_i];
  21854. if (mesh._lightSources.indexOf(this) !== -1) {
  21855. mesh._markSubMeshesAsLightDirty();
  21856. }
  21857. }
  21858. };
  21859. /**
  21860. * Recomputes the cached photometric scale if needed.
  21861. */
  21862. Light.prototype._computePhotometricScale = function () {
  21863. this._photometricScale = this._getPhotometricScale();
  21864. this.getScene().resetCachedMaterial();
  21865. };
  21866. /**
  21867. * Returns the Photometric Scale according to the light type and intensity mode.
  21868. */
  21869. Light.prototype._getPhotometricScale = function () {
  21870. var photometricScale = 0.0;
  21871. var lightTypeID = this.getTypeID();
  21872. //get photometric mode
  21873. var photometricMode = this.intensityMode;
  21874. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21875. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21876. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21877. }
  21878. else {
  21879. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21880. }
  21881. }
  21882. //compute photometric scale
  21883. switch (lightTypeID) {
  21884. case Light.LIGHTTYPEID_POINTLIGHT:
  21885. case Light.LIGHTTYPEID_SPOTLIGHT:
  21886. switch (photometricMode) {
  21887. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21888. photometricScale = 1.0 / (4.0 * Math.PI);
  21889. break;
  21890. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21891. photometricScale = 1.0;
  21892. break;
  21893. case Light.INTENSITYMODE_LUMINANCE:
  21894. photometricScale = this.radius * this.radius;
  21895. break;
  21896. }
  21897. break;
  21898. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21899. switch (photometricMode) {
  21900. case Light.INTENSITYMODE_ILLUMINANCE:
  21901. photometricScale = 1.0;
  21902. break;
  21903. case Light.INTENSITYMODE_LUMINANCE:
  21904. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21905. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21906. var apexAngleRadians = this.radius;
  21907. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21908. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21909. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21910. photometricScale = solidAngle;
  21911. break;
  21912. }
  21913. break;
  21914. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21915. // No fall off in hemisperic light.
  21916. photometricScale = 1.0;
  21917. break;
  21918. }
  21919. return photometricScale;
  21920. };
  21921. /**
  21922. * Reorder the light in the scene according to their defined priority.
  21923. * @hidden Internal Use Only
  21924. */
  21925. Light.prototype._reorderLightsInScene = function () {
  21926. var scene = this.getScene();
  21927. if (this._renderPriority != 0) {
  21928. scene.requireLightSorting = true;
  21929. }
  21930. this.getScene().sortLightsByPriority();
  21931. };
  21932. //lightmapMode Consts
  21933. Light._LIGHTMAP_DEFAULT = 0;
  21934. Light._LIGHTMAP_SPECULAR = 1;
  21935. Light._LIGHTMAP_SHADOWSONLY = 2;
  21936. // Intensity Mode Consts
  21937. Light._INTENSITYMODE_AUTOMATIC = 0;
  21938. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21939. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21940. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21941. Light._INTENSITYMODE_LUMINANCE = 4;
  21942. // Light types ids const.
  21943. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21944. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21945. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21946. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21947. __decorate([
  21948. BABYLON.serializeAsColor3()
  21949. ], Light.prototype, "diffuse", void 0);
  21950. __decorate([
  21951. BABYLON.serializeAsColor3()
  21952. ], Light.prototype, "specular", void 0);
  21953. __decorate([
  21954. BABYLON.serialize()
  21955. ], Light.prototype, "intensity", void 0);
  21956. __decorate([
  21957. BABYLON.serialize()
  21958. ], Light.prototype, "range", void 0);
  21959. __decorate([
  21960. BABYLON.serialize()
  21961. ], Light.prototype, "intensityMode", null);
  21962. __decorate([
  21963. BABYLON.serialize()
  21964. ], Light.prototype, "radius", null);
  21965. __decorate([
  21966. BABYLON.serialize()
  21967. ], Light.prototype, "_renderPriority", void 0);
  21968. __decorate([
  21969. BABYLON.expandToProperty("_reorderLightsInScene")
  21970. ], Light.prototype, "renderPriority", void 0);
  21971. __decorate([
  21972. BABYLON.serialize()
  21973. ], Light.prototype, "shadowEnabled", void 0);
  21974. __decorate([
  21975. BABYLON.serialize("excludeWithLayerMask")
  21976. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21977. __decorate([
  21978. BABYLON.serialize("includeOnlyWithLayerMask")
  21979. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21980. __decorate([
  21981. BABYLON.serialize("lightmapMode")
  21982. ], Light.prototype, "_lightmapMode", void 0);
  21983. return Light;
  21984. }(BABYLON.Node));
  21985. BABYLON.Light = Light;
  21986. })(BABYLON || (BABYLON = {}));
  21987. //# sourceMappingURL=babylon.light.js.map
  21988. var BABYLON;
  21989. (function (BABYLON) {
  21990. var Camera = /** @class */ (function (_super) {
  21991. __extends(Camera, _super);
  21992. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  21993. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  21994. var _this = _super.call(this, name, scene) || this;
  21995. /**
  21996. * The vector the camera should consider as up.
  21997. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21998. */
  21999. _this.upVector = BABYLON.Vector3.Up();
  22000. _this.orthoLeft = null;
  22001. _this.orthoRight = null;
  22002. _this.orthoBottom = null;
  22003. _this.orthoTop = null;
  22004. /**
  22005. * FOV is set in Radians. (default is 0.8)
  22006. */
  22007. _this.fov = 0.8;
  22008. _this.minZ = 1;
  22009. _this.maxZ = 10000.0;
  22010. _this.inertia = 0.9;
  22011. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22012. _this.isIntermediate = false;
  22013. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22014. /**
  22015. * Restricts the camera to viewing objects with the same layerMask.
  22016. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22017. */
  22018. _this.layerMask = 0x0FFFFFFF;
  22019. /**
  22020. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22021. */
  22022. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22023. // Camera rig members
  22024. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22025. _this._rigCameras = new Array();
  22026. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22027. _this._skipRendering = false;
  22028. _this.customRenderTargets = new Array();
  22029. // Observables
  22030. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22031. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22032. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22033. _this.onRestoreStateObservable = new BABYLON.Observable();
  22034. // Cache
  22035. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22036. _this._projectionMatrix = new BABYLON.Matrix();
  22037. _this._doNotComputeProjectionMatrix = false;
  22038. _this._worldMatrix = BABYLON.Matrix.Identity();
  22039. _this._postProcesses = new Array();
  22040. _this._transformMatrix = BABYLON.Matrix.Zero();
  22041. _this._activeMeshes = new BABYLON.SmartArray(256);
  22042. _this._globalPosition = BABYLON.Vector3.Zero();
  22043. _this._refreshFrustumPlanes = true;
  22044. _this.getScene().addCamera(_this);
  22045. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22046. _this.getScene().activeCamera = _this;
  22047. }
  22048. _this.position = position;
  22049. return _this;
  22050. }
  22051. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22052. get: function () {
  22053. return Camera._PERSPECTIVE_CAMERA;
  22054. },
  22055. enumerable: true,
  22056. configurable: true
  22057. });
  22058. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22059. get: function () {
  22060. return Camera._ORTHOGRAPHIC_CAMERA;
  22061. },
  22062. enumerable: true,
  22063. configurable: true
  22064. });
  22065. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22066. /**
  22067. * This is the default FOV mode for perspective cameras.
  22068. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22069. *
  22070. */
  22071. get: function () {
  22072. return Camera._FOVMODE_VERTICAL_FIXED;
  22073. },
  22074. enumerable: true,
  22075. configurable: true
  22076. });
  22077. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22078. /**
  22079. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22080. *
  22081. */
  22082. get: function () {
  22083. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22084. },
  22085. enumerable: true,
  22086. configurable: true
  22087. });
  22088. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22089. get: function () {
  22090. return Camera._RIG_MODE_NONE;
  22091. },
  22092. enumerable: true,
  22093. configurable: true
  22094. });
  22095. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22096. get: function () {
  22097. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22098. },
  22099. enumerable: true,
  22100. configurable: true
  22101. });
  22102. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22103. get: function () {
  22104. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22105. },
  22106. enumerable: true,
  22107. configurable: true
  22108. });
  22109. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22110. get: function () {
  22111. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22112. },
  22113. enumerable: true,
  22114. configurable: true
  22115. });
  22116. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22117. get: function () {
  22118. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22119. },
  22120. enumerable: true,
  22121. configurable: true
  22122. });
  22123. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22124. get: function () {
  22125. return Camera._RIG_MODE_VR;
  22126. },
  22127. enumerable: true,
  22128. configurable: true
  22129. });
  22130. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22131. get: function () {
  22132. return Camera._RIG_MODE_WEBVR;
  22133. },
  22134. enumerable: true,
  22135. configurable: true
  22136. });
  22137. /**
  22138. * Store current camera state (fov, position, etc..)
  22139. */
  22140. Camera.prototype.storeState = function () {
  22141. this._stateStored = true;
  22142. this._storedFov = this.fov;
  22143. return this;
  22144. };
  22145. /**
  22146. * Restores the camera state values if it has been stored. You must call storeState() first
  22147. */
  22148. Camera.prototype._restoreStateValues = function () {
  22149. if (!this._stateStored) {
  22150. return false;
  22151. }
  22152. this.fov = this._storedFov;
  22153. return true;
  22154. };
  22155. /**
  22156. * Restored camera state. You must call storeState() first
  22157. */
  22158. Camera.prototype.restoreState = function () {
  22159. if (this._restoreStateValues()) {
  22160. this.onRestoreStateObservable.notifyObservers(this);
  22161. return true;
  22162. }
  22163. return false;
  22164. };
  22165. Camera.prototype.getClassName = function () {
  22166. return "Camera";
  22167. };
  22168. /**
  22169. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22170. */
  22171. Camera.prototype.toString = function (fullDetails) {
  22172. var ret = "Name: " + this.name;
  22173. ret += ", type: " + this.getClassName();
  22174. if (this.animations) {
  22175. for (var i = 0; i < this.animations.length; i++) {
  22176. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22177. }
  22178. }
  22179. if (fullDetails) {
  22180. }
  22181. return ret;
  22182. };
  22183. Object.defineProperty(Camera.prototype, "globalPosition", {
  22184. get: function () {
  22185. return this._globalPosition;
  22186. },
  22187. enumerable: true,
  22188. configurable: true
  22189. });
  22190. Camera.prototype.getActiveMeshes = function () {
  22191. return this._activeMeshes;
  22192. };
  22193. Camera.prototype.isActiveMesh = function (mesh) {
  22194. return (this._activeMeshes.indexOf(mesh) !== -1);
  22195. };
  22196. /**
  22197. * Is this camera ready to be used/rendered
  22198. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22199. * @return true if the camera is ready
  22200. */
  22201. Camera.prototype.isReady = function (completeCheck) {
  22202. if (completeCheck === void 0) { completeCheck = false; }
  22203. if (completeCheck) {
  22204. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22205. var pp = _a[_i];
  22206. if (pp && !pp.isReady()) {
  22207. return false;
  22208. }
  22209. }
  22210. }
  22211. return _super.prototype.isReady.call(this, completeCheck);
  22212. };
  22213. //Cache
  22214. Camera.prototype._initCache = function () {
  22215. _super.prototype._initCache.call(this);
  22216. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22217. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22218. this._cache.mode = undefined;
  22219. this._cache.minZ = undefined;
  22220. this._cache.maxZ = undefined;
  22221. this._cache.fov = undefined;
  22222. this._cache.fovMode = undefined;
  22223. this._cache.aspectRatio = undefined;
  22224. this._cache.orthoLeft = undefined;
  22225. this._cache.orthoRight = undefined;
  22226. this._cache.orthoBottom = undefined;
  22227. this._cache.orthoTop = undefined;
  22228. this._cache.renderWidth = undefined;
  22229. this._cache.renderHeight = undefined;
  22230. };
  22231. Camera.prototype._updateCache = function (ignoreParentClass) {
  22232. if (!ignoreParentClass) {
  22233. _super.prototype._updateCache.call(this);
  22234. }
  22235. this._cache.position.copyFrom(this.position);
  22236. this._cache.upVector.copyFrom(this.upVector);
  22237. };
  22238. // Synchronized
  22239. Camera.prototype._isSynchronized = function () {
  22240. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22241. };
  22242. Camera.prototype._isSynchronizedViewMatrix = function () {
  22243. if (!_super.prototype._isSynchronized.call(this))
  22244. return false;
  22245. return this._cache.position.equals(this.position)
  22246. && this._cache.upVector.equals(this.upVector)
  22247. && this.isSynchronizedWithParent();
  22248. };
  22249. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22250. var check = this._cache.mode === this.mode
  22251. && this._cache.minZ === this.minZ
  22252. && this._cache.maxZ === this.maxZ;
  22253. if (!check) {
  22254. return false;
  22255. }
  22256. var engine = this.getEngine();
  22257. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22258. check = this._cache.fov === this.fov
  22259. && this._cache.fovMode === this.fovMode
  22260. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22261. }
  22262. else {
  22263. check = this._cache.orthoLeft === this.orthoLeft
  22264. && this._cache.orthoRight === this.orthoRight
  22265. && this._cache.orthoBottom === this.orthoBottom
  22266. && this._cache.orthoTop === this.orthoTop
  22267. && this._cache.renderWidth === engine.getRenderWidth()
  22268. && this._cache.renderHeight === engine.getRenderHeight();
  22269. }
  22270. return check;
  22271. };
  22272. // Controls
  22273. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22274. };
  22275. Camera.prototype.detachControl = function (element) {
  22276. };
  22277. Camera.prototype.update = function () {
  22278. this._checkInputs();
  22279. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22280. this._updateRigCameras();
  22281. }
  22282. };
  22283. Camera.prototype._checkInputs = function () {
  22284. this.onAfterCheckInputsObservable.notifyObservers(this);
  22285. };
  22286. Object.defineProperty(Camera.prototype, "rigCameras", {
  22287. get: function () {
  22288. return this._rigCameras;
  22289. },
  22290. enumerable: true,
  22291. configurable: true
  22292. });
  22293. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22294. get: function () {
  22295. return this._rigPostProcess;
  22296. },
  22297. enumerable: true,
  22298. configurable: true
  22299. });
  22300. /**
  22301. * Internal, gets the first post proces.
  22302. * @returns the first post process to be run on this camera.
  22303. */
  22304. Camera.prototype._getFirstPostProcess = function () {
  22305. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22306. if (this._postProcesses[ppIndex] !== null) {
  22307. return this._postProcesses[ppIndex];
  22308. }
  22309. }
  22310. return null;
  22311. };
  22312. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22313. // invalidate framebuffer
  22314. var firstPostProcess = this._getFirstPostProcess();
  22315. if (firstPostProcess) {
  22316. firstPostProcess.markTextureDirty();
  22317. }
  22318. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22319. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22320. var cam = this._rigCameras[i];
  22321. var rigPostProcess = cam._rigPostProcess;
  22322. // for VR rig, there does not have to be a post process
  22323. if (rigPostProcess) {
  22324. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22325. if (isPass) {
  22326. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22327. cam.isIntermediate = this._postProcesses.length === 0;
  22328. }
  22329. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22330. rigPostProcess.markTextureDirty();
  22331. }
  22332. else {
  22333. cam._postProcesses = this._postProcesses.slice(0);
  22334. }
  22335. }
  22336. };
  22337. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22338. if (insertAt === void 0) { insertAt = null; }
  22339. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22340. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22341. return 0;
  22342. }
  22343. if (insertAt == null || insertAt < 0) {
  22344. this._postProcesses.push(postProcess);
  22345. }
  22346. else if (this._postProcesses[insertAt] === null) {
  22347. this._postProcesses[insertAt] = postProcess;
  22348. }
  22349. else {
  22350. this._postProcesses.splice(insertAt, 0, postProcess);
  22351. }
  22352. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22353. return this._postProcesses.indexOf(postProcess);
  22354. };
  22355. Camera.prototype.detachPostProcess = function (postProcess) {
  22356. var idx = this._postProcesses.indexOf(postProcess);
  22357. if (idx !== -1) {
  22358. this._postProcesses[idx] = null;
  22359. }
  22360. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22361. };
  22362. Camera.prototype.getWorldMatrix = function () {
  22363. if (this._isSynchronizedViewMatrix()) {
  22364. return this._worldMatrix;
  22365. }
  22366. // Getting the the view matrix will also compute the world matrix.
  22367. this.getViewMatrix();
  22368. return this._worldMatrix;
  22369. };
  22370. Camera.prototype._getViewMatrix = function () {
  22371. return BABYLON.Matrix.Identity();
  22372. };
  22373. Camera.prototype.getViewMatrix = function (force) {
  22374. if (!force && this._isSynchronizedViewMatrix()) {
  22375. return this._computedViewMatrix;
  22376. }
  22377. this.updateCache();
  22378. this._computedViewMatrix = this._getViewMatrix();
  22379. this._currentRenderId = this.getScene().getRenderId();
  22380. this._childRenderId = this._currentRenderId;
  22381. this._refreshFrustumPlanes = true;
  22382. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22383. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22384. }
  22385. this.onViewMatrixChangedObservable.notifyObservers(this);
  22386. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22387. return this._computedViewMatrix;
  22388. };
  22389. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22390. this._doNotComputeProjectionMatrix = true;
  22391. if (projection !== undefined) {
  22392. this._projectionMatrix = projection;
  22393. }
  22394. };
  22395. ;
  22396. Camera.prototype.unfreezeProjectionMatrix = function () {
  22397. this._doNotComputeProjectionMatrix = false;
  22398. };
  22399. ;
  22400. Camera.prototype.getProjectionMatrix = function (force) {
  22401. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22402. return this._projectionMatrix;
  22403. }
  22404. // Cache
  22405. this._cache.mode = this.mode;
  22406. this._cache.minZ = this.minZ;
  22407. this._cache.maxZ = this.maxZ;
  22408. // Matrix
  22409. this._refreshFrustumPlanes = true;
  22410. var engine = this.getEngine();
  22411. var scene = this.getScene();
  22412. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22413. this._cache.fov = this.fov;
  22414. this._cache.fovMode = this.fovMode;
  22415. this._cache.aspectRatio = engine.getAspectRatio(this);
  22416. if (this.minZ <= 0) {
  22417. this.minZ = 0.1;
  22418. }
  22419. if (scene.useRightHandedSystem) {
  22420. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22421. }
  22422. else {
  22423. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22424. }
  22425. }
  22426. else {
  22427. var halfWidth = engine.getRenderWidth() / 2.0;
  22428. var halfHeight = engine.getRenderHeight() / 2.0;
  22429. if (scene.useRightHandedSystem) {
  22430. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22431. }
  22432. else {
  22433. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22434. }
  22435. this._cache.orthoLeft = this.orthoLeft;
  22436. this._cache.orthoRight = this.orthoRight;
  22437. this._cache.orthoBottom = this.orthoBottom;
  22438. this._cache.orthoTop = this.orthoTop;
  22439. this._cache.renderWidth = engine.getRenderWidth();
  22440. this._cache.renderHeight = engine.getRenderHeight();
  22441. }
  22442. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22443. return this._projectionMatrix;
  22444. };
  22445. Camera.prototype.getTranformationMatrix = function () {
  22446. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22447. return this._transformMatrix;
  22448. };
  22449. Camera.prototype.updateFrustumPlanes = function () {
  22450. if (!this._refreshFrustumPlanes) {
  22451. return;
  22452. }
  22453. this.getTranformationMatrix();
  22454. if (!this._frustumPlanes) {
  22455. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22456. }
  22457. else {
  22458. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22459. }
  22460. this._refreshFrustumPlanes = false;
  22461. };
  22462. Camera.prototype.isInFrustum = function (target) {
  22463. this.updateFrustumPlanes();
  22464. return target.isInFrustum(this._frustumPlanes);
  22465. };
  22466. Camera.prototype.isCompletelyInFrustum = function (target) {
  22467. this.updateFrustumPlanes();
  22468. return target.isCompletelyInFrustum(this._frustumPlanes);
  22469. };
  22470. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22471. if (length === void 0) { length = 100; }
  22472. if (!transform) {
  22473. transform = this.getWorldMatrix();
  22474. }
  22475. if (!origin) {
  22476. origin = this.position;
  22477. }
  22478. var forward = new BABYLON.Vector3(0, 0, 1);
  22479. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22480. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22481. return new BABYLON.Ray(origin, direction, length);
  22482. };
  22483. /**
  22484. * Releases resources associated with this node.
  22485. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22486. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22487. */
  22488. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22489. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22490. // Observables
  22491. this.onViewMatrixChangedObservable.clear();
  22492. this.onProjectionMatrixChangedObservable.clear();
  22493. this.onAfterCheckInputsObservable.clear();
  22494. this.onRestoreStateObservable.clear();
  22495. // Inputs
  22496. if (this.inputs) {
  22497. this.inputs.clear();
  22498. }
  22499. // Animations
  22500. this.getScene().stopAnimation(this);
  22501. // Remove from scene
  22502. this.getScene().removeCamera(this);
  22503. while (this._rigCameras.length > 0) {
  22504. var camera = this._rigCameras.pop();
  22505. if (camera) {
  22506. camera.dispose();
  22507. }
  22508. }
  22509. // Postprocesses
  22510. if (this._rigPostProcess) {
  22511. this._rigPostProcess.dispose(this);
  22512. this._rigPostProcess = null;
  22513. this._postProcesses = [];
  22514. }
  22515. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22516. this._rigPostProcess = null;
  22517. this._postProcesses = [];
  22518. }
  22519. else {
  22520. var i = this._postProcesses.length;
  22521. while (--i >= 0) {
  22522. var postProcess = this._postProcesses[i];
  22523. if (postProcess) {
  22524. postProcess.dispose(this);
  22525. }
  22526. }
  22527. }
  22528. // Render targets
  22529. var i = this.customRenderTargets.length;
  22530. while (--i >= 0) {
  22531. this.customRenderTargets[i].dispose();
  22532. }
  22533. this.customRenderTargets = [];
  22534. // Active Meshes
  22535. this._activeMeshes.dispose();
  22536. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22537. };
  22538. Object.defineProperty(Camera.prototype, "leftCamera", {
  22539. // ---- Camera rigs section ----
  22540. get: function () {
  22541. if (this._rigCameras.length < 1) {
  22542. return null;
  22543. }
  22544. return this._rigCameras[0];
  22545. },
  22546. enumerable: true,
  22547. configurable: true
  22548. });
  22549. Object.defineProperty(Camera.prototype, "rightCamera", {
  22550. get: function () {
  22551. if (this._rigCameras.length < 2) {
  22552. return null;
  22553. }
  22554. return this._rigCameras[1];
  22555. },
  22556. enumerable: true,
  22557. configurable: true
  22558. });
  22559. Camera.prototype.getLeftTarget = function () {
  22560. if (this._rigCameras.length < 1) {
  22561. return null;
  22562. }
  22563. return this._rigCameras[0].getTarget();
  22564. };
  22565. Camera.prototype.getRightTarget = function () {
  22566. if (this._rigCameras.length < 2) {
  22567. return null;
  22568. }
  22569. return this._rigCameras[1].getTarget();
  22570. };
  22571. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22572. if (this.cameraRigMode === mode) {
  22573. return;
  22574. }
  22575. while (this._rigCameras.length > 0) {
  22576. var camera = this._rigCameras.pop();
  22577. if (camera) {
  22578. camera.dispose();
  22579. }
  22580. }
  22581. this.cameraRigMode = mode;
  22582. this._cameraRigParams = {};
  22583. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22584. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22585. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22586. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22587. // create the rig cameras, unless none
  22588. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22589. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22590. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22591. if (leftCamera && rightCamera) {
  22592. this._rigCameras.push(leftCamera);
  22593. this._rigCameras.push(rightCamera);
  22594. }
  22595. }
  22596. switch (this.cameraRigMode) {
  22597. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22598. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22599. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22600. break;
  22601. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22602. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22603. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22604. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22605. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22606. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22607. break;
  22608. case Camera.RIG_MODE_VR:
  22609. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22610. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22611. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22612. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22613. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22614. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22615. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22616. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22617. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22618. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22619. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22620. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22621. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22622. if (metrics.compensateDistortion) {
  22623. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22624. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22625. }
  22626. break;
  22627. case Camera.RIG_MODE_WEBVR:
  22628. if (rigParams.vrDisplay) {
  22629. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22630. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22631. //Left eye
  22632. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22633. this._rigCameras[0].setCameraRigParameter("left", true);
  22634. //leaving this for future reference
  22635. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22636. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22637. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22638. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22639. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22640. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22641. this._rigCameras[0].parent = this;
  22642. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22643. //Right eye
  22644. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22645. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22646. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22647. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22648. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22649. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22650. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22651. this._rigCameras[1].parent = this;
  22652. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22653. if (Camera.UseAlternateWebVRRendering) {
  22654. this._rigCameras[1]._skipRendering = true;
  22655. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22656. }
  22657. }
  22658. break;
  22659. }
  22660. this._cascadePostProcessesToRigCams();
  22661. this.update();
  22662. };
  22663. Camera.prototype._getVRProjectionMatrix = function () {
  22664. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22665. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22666. return this._projectionMatrix;
  22667. };
  22668. Camera.prototype._updateCameraRotationMatrix = function () {
  22669. //Here for WebVR
  22670. };
  22671. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22672. //Here for WebVR
  22673. };
  22674. /**
  22675. * This function MUST be overwritten by the different WebVR cameras available.
  22676. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22677. */
  22678. Camera.prototype._getWebVRProjectionMatrix = function () {
  22679. return BABYLON.Matrix.Identity();
  22680. };
  22681. /**
  22682. * This function MUST be overwritten by the different WebVR cameras available.
  22683. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22684. */
  22685. Camera.prototype._getWebVRViewMatrix = function () {
  22686. return BABYLON.Matrix.Identity();
  22687. };
  22688. Camera.prototype.setCameraRigParameter = function (name, value) {
  22689. if (!this._cameraRigParams) {
  22690. this._cameraRigParams = {};
  22691. }
  22692. this._cameraRigParams[name] = value;
  22693. //provisionnally:
  22694. if (name === "interaxialDistance") {
  22695. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22696. }
  22697. };
  22698. /**
  22699. * needs to be overridden by children so sub has required properties to be copied
  22700. */
  22701. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22702. return null;
  22703. };
  22704. /**
  22705. * May need to be overridden by children
  22706. */
  22707. Camera.prototype._updateRigCameras = function () {
  22708. for (var i = 0; i < this._rigCameras.length; i++) {
  22709. this._rigCameras[i].minZ = this.minZ;
  22710. this._rigCameras[i].maxZ = this.maxZ;
  22711. this._rigCameras[i].fov = this.fov;
  22712. }
  22713. // only update viewport when ANAGLYPH
  22714. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22715. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22716. }
  22717. };
  22718. Camera.prototype._setupInputs = function () {
  22719. };
  22720. Camera.prototype.serialize = function () {
  22721. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22722. // Type
  22723. serializationObject.type = this.getClassName();
  22724. // Parent
  22725. if (this.parent) {
  22726. serializationObject.parentId = this.parent.id;
  22727. }
  22728. if (this.inputs) {
  22729. this.inputs.serialize(serializationObject);
  22730. }
  22731. // Animations
  22732. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22733. serializationObject.ranges = this.serializeAnimationRanges();
  22734. return serializationObject;
  22735. };
  22736. Camera.prototype.clone = function (name) {
  22737. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22738. };
  22739. Camera.prototype.getDirection = function (localAxis) {
  22740. var result = BABYLON.Vector3.Zero();
  22741. this.getDirectionToRef(localAxis, result);
  22742. return result;
  22743. };
  22744. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22745. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22746. };
  22747. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22748. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22749. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22750. switch (type) {
  22751. case "ArcRotateCamera":
  22752. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22753. case "DeviceOrientationCamera":
  22754. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22755. case "FollowCamera":
  22756. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22757. case "ArcFollowCamera":
  22758. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22759. case "GamepadCamera":
  22760. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22761. case "TouchCamera":
  22762. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22763. case "VirtualJoysticksCamera":
  22764. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22765. case "WebVRFreeCamera":
  22766. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22767. case "WebVRGamepadCamera":
  22768. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22769. case "VRDeviceOrientationFreeCamera":
  22770. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22771. case "VRDeviceOrientationGamepadCamera":
  22772. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22773. case "AnaglyphArcRotateCamera":
  22774. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22775. case "AnaglyphFreeCamera":
  22776. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22777. case "AnaglyphGamepadCamera":
  22778. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22779. case "AnaglyphUniversalCamera":
  22780. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22781. case "StereoscopicArcRotateCamera":
  22782. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22783. case "StereoscopicFreeCamera":
  22784. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22785. case "StereoscopicGamepadCamera":
  22786. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22787. case "StereoscopicUniversalCamera":
  22788. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22789. case "FreeCamera": // Forcing Universal here
  22790. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22791. default: // Universal Camera is the default value
  22792. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22793. }
  22794. };
  22795. Camera.prototype.computeWorldMatrix = function () {
  22796. return this.getWorldMatrix();
  22797. };
  22798. Camera.Parse = function (parsedCamera, scene) {
  22799. var type = parsedCamera.type;
  22800. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22801. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22802. // Parent
  22803. if (parsedCamera.parentId) {
  22804. camera._waitingParentId = parsedCamera.parentId;
  22805. }
  22806. //If camera has an input manager, let it parse inputs settings
  22807. if (camera.inputs) {
  22808. camera.inputs.parse(parsedCamera);
  22809. camera._setupInputs();
  22810. }
  22811. if (camera.setPosition) { // need to force position
  22812. camera.position.copyFromFloats(0, 0, 0);
  22813. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22814. }
  22815. // Target
  22816. if (parsedCamera.target) {
  22817. if (camera.setTarget) {
  22818. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22819. }
  22820. }
  22821. // Apply 3d rig, when found
  22822. if (parsedCamera.cameraRigMode) {
  22823. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22824. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22825. }
  22826. // Animations
  22827. if (parsedCamera.animations) {
  22828. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22829. var parsedAnimation = parsedCamera.animations[animationIndex];
  22830. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22831. }
  22832. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22833. }
  22834. if (parsedCamera.autoAnimate) {
  22835. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22836. }
  22837. return camera;
  22838. };
  22839. // Statics
  22840. Camera._PERSPECTIVE_CAMERA = 0;
  22841. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22842. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22843. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22844. Camera._RIG_MODE_NONE = 0;
  22845. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22846. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22847. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22848. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22849. Camera._RIG_MODE_VR = 20;
  22850. Camera._RIG_MODE_WEBVR = 21;
  22851. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22852. Camera.UseAlternateWebVRRendering = false;
  22853. __decorate([
  22854. BABYLON.serializeAsVector3()
  22855. ], Camera.prototype, "position", void 0);
  22856. __decorate([
  22857. BABYLON.serializeAsVector3()
  22858. ], Camera.prototype, "upVector", void 0);
  22859. __decorate([
  22860. BABYLON.serialize()
  22861. ], Camera.prototype, "orthoLeft", void 0);
  22862. __decorate([
  22863. BABYLON.serialize()
  22864. ], Camera.prototype, "orthoRight", void 0);
  22865. __decorate([
  22866. BABYLON.serialize()
  22867. ], Camera.prototype, "orthoBottom", void 0);
  22868. __decorate([
  22869. BABYLON.serialize()
  22870. ], Camera.prototype, "orthoTop", void 0);
  22871. __decorate([
  22872. BABYLON.serialize()
  22873. ], Camera.prototype, "fov", void 0);
  22874. __decorate([
  22875. BABYLON.serialize()
  22876. ], Camera.prototype, "minZ", void 0);
  22877. __decorate([
  22878. BABYLON.serialize()
  22879. ], Camera.prototype, "maxZ", void 0);
  22880. __decorate([
  22881. BABYLON.serialize()
  22882. ], Camera.prototype, "inertia", void 0);
  22883. __decorate([
  22884. BABYLON.serialize()
  22885. ], Camera.prototype, "mode", void 0);
  22886. __decorate([
  22887. BABYLON.serialize()
  22888. ], Camera.prototype, "layerMask", void 0);
  22889. __decorate([
  22890. BABYLON.serialize()
  22891. ], Camera.prototype, "fovMode", void 0);
  22892. __decorate([
  22893. BABYLON.serialize()
  22894. ], Camera.prototype, "cameraRigMode", void 0);
  22895. __decorate([
  22896. BABYLON.serialize()
  22897. ], Camera.prototype, "interaxialDistance", void 0);
  22898. __decorate([
  22899. BABYLON.serialize()
  22900. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22901. return Camera;
  22902. }(BABYLON.Node));
  22903. BABYLON.Camera = Camera;
  22904. })(BABYLON || (BABYLON = {}));
  22905. //# sourceMappingURL=babylon.camera.js.map
  22906. var BABYLON;
  22907. (function (BABYLON) {
  22908. var RenderingManager = /** @class */ (function () {
  22909. function RenderingManager(scene) {
  22910. this._renderingGroups = new Array();
  22911. this._autoClearDepthStencil = {};
  22912. this._customOpaqueSortCompareFn = {};
  22913. this._customAlphaTestSortCompareFn = {};
  22914. this._customTransparentSortCompareFn = {};
  22915. this._renderinGroupInfo = null;
  22916. this._scene = scene;
  22917. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22918. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22919. }
  22920. }
  22921. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22922. if (depth === void 0) { depth = true; }
  22923. if (stencil === void 0) { stencil = true; }
  22924. if (this._depthStencilBufferAlreadyCleaned) {
  22925. return;
  22926. }
  22927. this._scene.getEngine().clear(null, false, depth, stencil);
  22928. this._depthStencilBufferAlreadyCleaned = true;
  22929. };
  22930. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22931. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22932. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22933. var info = null;
  22934. if (observable) {
  22935. if (!this._renderinGroupInfo) {
  22936. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22937. }
  22938. info = this._renderinGroupInfo;
  22939. info.scene = this._scene;
  22940. info.camera = this._scene.activeCamera;
  22941. }
  22942. // Dispatch sprites
  22943. if (renderSprites) {
  22944. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22945. var manager = this._scene.spriteManagers[index];
  22946. this.dispatchSprites(manager);
  22947. }
  22948. }
  22949. // Render
  22950. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22951. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22952. var renderingGroup = this._renderingGroups[index];
  22953. if (!renderingGroup && !observable)
  22954. continue;
  22955. var renderingGroupMask = 0;
  22956. // Fire PRECLEAR stage
  22957. if (observable && info) {
  22958. renderingGroupMask = Math.pow(2, index);
  22959. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22960. info.renderingGroupId = index;
  22961. observable.notifyObservers(info, renderingGroupMask);
  22962. }
  22963. // Clear depth/stencil if needed
  22964. if (RenderingManager.AUTOCLEAR) {
  22965. var autoClear = this._autoClearDepthStencil[index];
  22966. if (autoClear && autoClear.autoClear) {
  22967. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22968. }
  22969. }
  22970. if (observable && info) {
  22971. // Fire PREOPAQUE stage
  22972. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22973. observable.notifyObservers(info, renderingGroupMask);
  22974. // Fire PRETRANSPARENT stage
  22975. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22976. observable.notifyObservers(info, renderingGroupMask);
  22977. }
  22978. if (renderingGroup)
  22979. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22980. // Fire POSTTRANSPARENT stage
  22981. if (observable && info) {
  22982. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22983. observable.notifyObservers(info, renderingGroupMask);
  22984. }
  22985. }
  22986. };
  22987. RenderingManager.prototype.reset = function () {
  22988. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22989. var renderingGroup = this._renderingGroups[index];
  22990. if (renderingGroup) {
  22991. renderingGroup.prepare();
  22992. }
  22993. }
  22994. };
  22995. RenderingManager.prototype.dispose = function () {
  22996. this.freeRenderingGroups();
  22997. this._renderingGroups.length = 0;
  22998. };
  22999. /**
  23000. * Clear the info related to rendering groups preventing retention points during dispose.
  23001. */
  23002. RenderingManager.prototype.freeRenderingGroups = function () {
  23003. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23004. var renderingGroup = this._renderingGroups[index];
  23005. if (renderingGroup) {
  23006. renderingGroup.dispose();
  23007. }
  23008. }
  23009. };
  23010. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23011. if (this._renderingGroups[renderingGroupId] === undefined) {
  23012. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23013. }
  23014. };
  23015. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23016. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23017. this._prepareRenderingGroup(renderingGroupId);
  23018. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23019. };
  23020. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23021. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23022. this._prepareRenderingGroup(renderingGroupId);
  23023. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23024. };
  23025. /**
  23026. * @param subMesh The submesh to dispatch
  23027. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23028. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23029. */
  23030. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23031. if (mesh === undefined) {
  23032. mesh = subMesh.getMesh();
  23033. }
  23034. var renderingGroupId = mesh.renderingGroupId || 0;
  23035. this._prepareRenderingGroup(renderingGroupId);
  23036. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23037. };
  23038. /**
  23039. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23040. * This allowed control for front to back rendering or reversly depending of the special needs.
  23041. *
  23042. * @param renderingGroupId The rendering group id corresponding to its index
  23043. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23044. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23045. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23046. */
  23047. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23048. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23049. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23050. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23051. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23052. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23053. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23054. if (this._renderingGroups[renderingGroupId]) {
  23055. var group = this._renderingGroups[renderingGroupId];
  23056. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23057. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23058. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23059. }
  23060. };
  23061. /**
  23062. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23063. *
  23064. * @param renderingGroupId The rendering group id corresponding to its index
  23065. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23066. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23067. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23068. */
  23069. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23070. if (depth === void 0) { depth = true; }
  23071. if (stencil === void 0) { stencil = true; }
  23072. this._autoClearDepthStencil[renderingGroupId] = {
  23073. autoClear: autoClearDepthStencil,
  23074. depth: depth,
  23075. stencil: stencil
  23076. };
  23077. };
  23078. /**
  23079. * The max id used for rendering groups (not included)
  23080. */
  23081. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23082. /**
  23083. * The min id used for rendering groups (included)
  23084. */
  23085. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23086. /**
  23087. * Used to globally prevent autoclearing scenes.
  23088. */
  23089. RenderingManager.AUTOCLEAR = true;
  23090. return RenderingManager;
  23091. }());
  23092. BABYLON.RenderingManager = RenderingManager;
  23093. })(BABYLON || (BABYLON = {}));
  23094. //# sourceMappingURL=babylon.renderingManager.js.map
  23095. var BABYLON;
  23096. (function (BABYLON) {
  23097. var RenderingGroup = /** @class */ (function () {
  23098. /**
  23099. * Creates a new rendering group.
  23100. * @param index The rendering group index
  23101. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23102. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23103. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23104. */
  23105. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23106. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23107. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23108. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23109. this.index = index;
  23110. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23111. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23112. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23113. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23114. this._particleSystems = new BABYLON.SmartArray(256);
  23115. this._spriteManagers = new BABYLON.SmartArray(256);
  23116. this._edgesRenderers = new BABYLON.SmartArray(16);
  23117. this._scene = scene;
  23118. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23119. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23120. this.transparentSortCompareFn = transparentSortCompareFn;
  23121. }
  23122. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23123. /**
  23124. * Set the opaque sort comparison function.
  23125. * If null the sub meshes will be render in the order they were created
  23126. */
  23127. set: function (value) {
  23128. this._opaqueSortCompareFn = value;
  23129. if (value) {
  23130. this._renderOpaque = this.renderOpaqueSorted;
  23131. }
  23132. else {
  23133. this._renderOpaque = RenderingGroup.renderUnsorted;
  23134. }
  23135. },
  23136. enumerable: true,
  23137. configurable: true
  23138. });
  23139. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23140. /**
  23141. * Set the alpha test sort comparison function.
  23142. * If null the sub meshes will be render in the order they were created
  23143. */
  23144. set: function (value) {
  23145. this._alphaTestSortCompareFn = value;
  23146. if (value) {
  23147. this._renderAlphaTest = this.renderAlphaTestSorted;
  23148. }
  23149. else {
  23150. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23151. }
  23152. },
  23153. enumerable: true,
  23154. configurable: true
  23155. });
  23156. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23157. /**
  23158. * Set the transparent sort comparison function.
  23159. * If null the sub meshes will be render in the order they were created
  23160. */
  23161. set: function (value) {
  23162. if (value) {
  23163. this._transparentSortCompareFn = value;
  23164. }
  23165. else {
  23166. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23167. }
  23168. this._renderTransparent = this.renderTransparentSorted;
  23169. },
  23170. enumerable: true,
  23171. configurable: true
  23172. });
  23173. /**
  23174. * Render all the sub meshes contained in the group.
  23175. * @param customRenderFunction Used to override the default render behaviour of the group.
  23176. * @returns true if rendered some submeshes.
  23177. */
  23178. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23179. if (customRenderFunction) {
  23180. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23181. return;
  23182. }
  23183. var engine = this._scene.getEngine();
  23184. // Depth only
  23185. if (this._depthOnlySubMeshes.length !== 0) {
  23186. engine.setColorWrite(false);
  23187. this._renderAlphaTest(this._depthOnlySubMeshes);
  23188. engine.setColorWrite(true);
  23189. }
  23190. // Opaque
  23191. if (this._opaqueSubMeshes.length !== 0) {
  23192. this._renderOpaque(this._opaqueSubMeshes);
  23193. }
  23194. // Alpha test
  23195. if (this._alphaTestSubMeshes.length !== 0) {
  23196. this._renderAlphaTest(this._alphaTestSubMeshes);
  23197. }
  23198. var stencilState = engine.getStencilBuffer();
  23199. engine.setStencilBuffer(false);
  23200. // Sprites
  23201. if (renderSprites) {
  23202. this._renderSprites();
  23203. }
  23204. // Particles
  23205. if (renderParticles) {
  23206. this._renderParticles(activeMeshes);
  23207. }
  23208. if (this.onBeforeTransparentRendering) {
  23209. this.onBeforeTransparentRendering();
  23210. }
  23211. // Transparent
  23212. if (this._transparentSubMeshes.length !== 0) {
  23213. this._renderTransparent(this._transparentSubMeshes);
  23214. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23215. }
  23216. // Set back stencil to false in case it changes before the edge renderer.
  23217. engine.setStencilBuffer(false);
  23218. // Edges
  23219. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23220. this._edgesRenderers.data[edgesRendererIndex].render();
  23221. }
  23222. // Restore Stencil state.
  23223. engine.setStencilBuffer(stencilState);
  23224. };
  23225. /**
  23226. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23227. * @param subMeshes The submeshes to render
  23228. */
  23229. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23230. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23231. };
  23232. /**
  23233. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23234. * @param subMeshes The submeshes to render
  23235. */
  23236. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23237. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23238. };
  23239. /**
  23240. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23241. * @param subMeshes The submeshes to render
  23242. */
  23243. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23244. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23245. };
  23246. /**
  23247. * Renders the submeshes in a specified order.
  23248. * @param subMeshes The submeshes to sort before render
  23249. * @param sortCompareFn The comparison function use to sort
  23250. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23251. * @param transparent Specifies to activate blending if true
  23252. */
  23253. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23254. var subIndex = 0;
  23255. var subMesh;
  23256. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23257. for (; subIndex < subMeshes.length; subIndex++) {
  23258. subMesh = subMeshes.data[subIndex];
  23259. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23260. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23261. }
  23262. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23263. if (sortCompareFn) {
  23264. sortedArray.sort(sortCompareFn);
  23265. }
  23266. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23267. subMesh = sortedArray[subIndex];
  23268. if (transparent) {
  23269. var material = subMesh.getMaterial();
  23270. if (material && material.needDepthPrePass) {
  23271. var engine = material.getScene().getEngine();
  23272. engine.setColorWrite(false);
  23273. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23274. subMesh.render(false);
  23275. engine.setColorWrite(true);
  23276. }
  23277. }
  23278. subMesh.render(transparent);
  23279. }
  23280. };
  23281. /**
  23282. * Renders the submeshes in the order they were dispatched (no sort applied).
  23283. * @param subMeshes The submeshes to render
  23284. */
  23285. RenderingGroup.renderUnsorted = function (subMeshes) {
  23286. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23287. var submesh = subMeshes.data[subIndex];
  23288. submesh.render(false);
  23289. }
  23290. };
  23291. /**
  23292. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23293. * are rendered back to front if in the same alpha index.
  23294. *
  23295. * @param a The first submesh
  23296. * @param b The second submesh
  23297. * @returns The result of the comparison
  23298. */
  23299. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23300. // Alpha index first
  23301. if (a._alphaIndex > b._alphaIndex) {
  23302. return 1;
  23303. }
  23304. if (a._alphaIndex < b._alphaIndex) {
  23305. return -1;
  23306. }
  23307. // Then distance to camera
  23308. return RenderingGroup.backToFrontSortCompare(a, b);
  23309. };
  23310. /**
  23311. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23312. * are rendered back to front.
  23313. *
  23314. * @param a The first submesh
  23315. * @param b The second submesh
  23316. * @returns The result of the comparison
  23317. */
  23318. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23319. // Then distance to camera
  23320. if (a._distanceToCamera < b._distanceToCamera) {
  23321. return 1;
  23322. }
  23323. if (a._distanceToCamera > b._distanceToCamera) {
  23324. return -1;
  23325. }
  23326. return 0;
  23327. };
  23328. /**
  23329. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23330. * are rendered front to back (prevent overdraw).
  23331. *
  23332. * @param a The first submesh
  23333. * @param b The second submesh
  23334. * @returns The result of the comparison
  23335. */
  23336. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23337. // Then distance to camera
  23338. if (a._distanceToCamera < b._distanceToCamera) {
  23339. return -1;
  23340. }
  23341. if (a._distanceToCamera > b._distanceToCamera) {
  23342. return 1;
  23343. }
  23344. return 0;
  23345. };
  23346. /**
  23347. * Resets the different lists of submeshes to prepare a new frame.
  23348. */
  23349. RenderingGroup.prototype.prepare = function () {
  23350. this._opaqueSubMeshes.reset();
  23351. this._transparentSubMeshes.reset();
  23352. this._alphaTestSubMeshes.reset();
  23353. this._depthOnlySubMeshes.reset();
  23354. this._particleSystems.reset();
  23355. this._spriteManagers.reset();
  23356. this._edgesRenderers.reset();
  23357. };
  23358. RenderingGroup.prototype.dispose = function () {
  23359. this._opaqueSubMeshes.dispose();
  23360. this._transparentSubMeshes.dispose();
  23361. this._alphaTestSubMeshes.dispose();
  23362. this._depthOnlySubMeshes.dispose();
  23363. this._particleSystems.dispose();
  23364. this._spriteManagers.dispose();
  23365. this._edgesRenderers.dispose();
  23366. };
  23367. /**
  23368. * Inserts the submesh in its correct queue depending on its material.
  23369. * @param subMesh The submesh to dispatch
  23370. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23371. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23372. */
  23373. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23374. // Get mesh and materials if not provided
  23375. if (mesh === undefined) {
  23376. mesh = subMesh.getMesh();
  23377. }
  23378. if (material === undefined) {
  23379. material = subMesh.getMaterial();
  23380. }
  23381. if (material === null || material === undefined) {
  23382. return;
  23383. }
  23384. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23385. this._transparentSubMeshes.push(subMesh);
  23386. }
  23387. else if (material.needAlphaTesting()) { // Alpha test
  23388. if (material.needDepthPrePass) {
  23389. this._depthOnlySubMeshes.push(subMesh);
  23390. }
  23391. this._alphaTestSubMeshes.push(subMesh);
  23392. }
  23393. else {
  23394. if (material.needDepthPrePass) {
  23395. this._depthOnlySubMeshes.push(subMesh);
  23396. }
  23397. this._opaqueSubMeshes.push(subMesh); // Opaque
  23398. }
  23399. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23400. this._edgesRenderers.push(mesh._edgesRenderer);
  23401. }
  23402. };
  23403. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23404. this._spriteManagers.push(spriteManager);
  23405. };
  23406. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23407. this._particleSystems.push(particleSystem);
  23408. };
  23409. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23410. if (this._particleSystems.length === 0) {
  23411. return;
  23412. }
  23413. // Particles
  23414. var activeCamera = this._scene.activeCamera;
  23415. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23416. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23417. var particleSystem = this._particleSystems.data[particleIndex];
  23418. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23419. continue;
  23420. }
  23421. var emitter = particleSystem.emitter;
  23422. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23423. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23424. }
  23425. }
  23426. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23427. };
  23428. RenderingGroup.prototype._renderSprites = function () {
  23429. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23430. return;
  23431. }
  23432. // Sprites
  23433. var activeCamera = this._scene.activeCamera;
  23434. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23435. for (var id = 0; id < this._spriteManagers.length; id++) {
  23436. var spriteManager = this._spriteManagers.data[id];
  23437. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23438. spriteManager.render();
  23439. }
  23440. }
  23441. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23442. };
  23443. return RenderingGroup;
  23444. }());
  23445. BABYLON.RenderingGroup = RenderingGroup;
  23446. })(BABYLON || (BABYLON = {}));
  23447. //# sourceMappingURL=babylon.renderingGroup.js.map
  23448. var BABYLON;
  23449. (function (BABYLON) {
  23450. /** @hidden */
  23451. var ClickInfo = /** @class */ (function () {
  23452. function ClickInfo() {
  23453. this._singleClick = false;
  23454. this._doubleClick = false;
  23455. this._hasSwiped = false;
  23456. this._ignore = false;
  23457. }
  23458. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23459. get: function () {
  23460. return this._singleClick;
  23461. },
  23462. set: function (b) {
  23463. this._singleClick = b;
  23464. },
  23465. enumerable: true,
  23466. configurable: true
  23467. });
  23468. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23469. get: function () {
  23470. return this._doubleClick;
  23471. },
  23472. set: function (b) {
  23473. this._doubleClick = b;
  23474. },
  23475. enumerable: true,
  23476. configurable: true
  23477. });
  23478. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23479. get: function () {
  23480. return this._hasSwiped;
  23481. },
  23482. set: function (b) {
  23483. this._hasSwiped = b;
  23484. },
  23485. enumerable: true,
  23486. configurable: true
  23487. });
  23488. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23489. get: function () {
  23490. return this._ignore;
  23491. },
  23492. set: function (b) {
  23493. this._ignore = b;
  23494. },
  23495. enumerable: true,
  23496. configurable: true
  23497. });
  23498. return ClickInfo;
  23499. }());
  23500. /**
  23501. * This class is used by the onRenderingGroupObservable
  23502. */
  23503. var RenderingGroupInfo = /** @class */ (function () {
  23504. function RenderingGroupInfo() {
  23505. }
  23506. /**
  23507. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23508. * This stage will be fired no matter what
  23509. */
  23510. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23511. /**
  23512. * Called before opaque object are rendered.
  23513. * This stage will be fired only if there's 3D Opaque content to render
  23514. */
  23515. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23516. /**
  23517. * Called after the opaque objects are rendered and before the transparent ones
  23518. * This stage will be fired only if there's 3D transparent content to render
  23519. */
  23520. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23521. /**
  23522. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23523. * This stage will be fired no matter what
  23524. */
  23525. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23526. return RenderingGroupInfo;
  23527. }());
  23528. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23529. /**
  23530. * Represents a scene to be rendered by the engine.
  23531. * @see http://doc.babylonjs.com/features/scene
  23532. */
  23533. var Scene = /** @class */ (function () {
  23534. /**
  23535. * Creates a new Scene
  23536. * @param engine defines the engine to use to render this scene
  23537. */
  23538. function Scene(engine) {
  23539. // Members
  23540. /**
  23541. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23542. */
  23543. this.autoClear = true;
  23544. /**
  23545. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23546. */
  23547. this.autoClearDepthAndStencil = true;
  23548. /**
  23549. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23550. */
  23551. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23552. /**
  23553. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23554. */
  23555. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23556. this._forceWireframe = false;
  23557. this._forcePointsCloud = false;
  23558. /**
  23559. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23560. */
  23561. this.forceShowBoundingBoxes = false;
  23562. /**
  23563. * Gets or sets a boolean indicating if animations are enabled
  23564. */
  23565. this.animationsEnabled = true;
  23566. this._animationPropertiesOverride = null;
  23567. /**
  23568. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23569. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23570. */
  23571. this.useConstantAnimationDeltaTime = false;
  23572. /**
  23573. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23574. * Please note that it requires to run a ray cast through the scene on every frame
  23575. */
  23576. this.constantlyUpdateMeshUnderPointer = false;
  23577. /**
  23578. * Defines the HTML cursor to use when hovering over interactive elements
  23579. */
  23580. this.hoverCursor = "pointer";
  23581. /**
  23582. * Defines the HTML default cursor to use (empty by default)
  23583. */
  23584. this.defaultCursor = "";
  23585. /**
  23586. * This is used to call preventDefault() on pointer down
  23587. * in order to block unwanted artifacts like system double clicks
  23588. */
  23589. this.preventDefaultOnPointerDown = true;
  23590. // Metadata
  23591. /**
  23592. * Gets or sets user defined metadata
  23593. */
  23594. this.metadata = null;
  23595. /**
  23596. * Use this array to add regular expressions used to disable offline support for specific urls
  23597. */
  23598. this.disableOfflineSupportExceptionRules = new Array();
  23599. /**
  23600. * An event triggered when the scene is disposed.
  23601. */
  23602. this.onDisposeObservable = new BABYLON.Observable();
  23603. this._onDisposeObserver = null;
  23604. /**
  23605. * An event triggered before rendering the scene (right after animations and physics)
  23606. */
  23607. this.onBeforeRenderObservable = new BABYLON.Observable();
  23608. this._onBeforeRenderObserver = null;
  23609. /**
  23610. * An event triggered after rendering the scene
  23611. */
  23612. this.onAfterRenderObservable = new BABYLON.Observable();
  23613. this._onAfterRenderObserver = null;
  23614. /**
  23615. * An event triggered before animating the scene
  23616. */
  23617. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23618. /**
  23619. * An event triggered after animations processing
  23620. */
  23621. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23622. /**
  23623. * An event triggered before draw calls are ready to be sent
  23624. */
  23625. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23626. /**
  23627. * An event triggered after draw calls have been sent
  23628. */
  23629. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23630. /**
  23631. * An event triggered when physic simulation is about to be run
  23632. */
  23633. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23634. /**
  23635. * An event triggered when physic simulation has been done
  23636. */
  23637. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23638. /**
  23639. * An event triggered when the scene is ready
  23640. */
  23641. this.onReadyObservable = new BABYLON.Observable();
  23642. /**
  23643. * An event triggered before rendering a camera
  23644. */
  23645. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23646. this._onBeforeCameraRenderObserver = null;
  23647. /**
  23648. * An event triggered after rendering a camera
  23649. */
  23650. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23651. this._onAfterCameraRenderObserver = null;
  23652. /**
  23653. * An event triggered when active meshes evaluation is about to start
  23654. */
  23655. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23656. /**
  23657. * An event triggered when active meshes evaluation is done
  23658. */
  23659. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23660. /**
  23661. * An event triggered when particles rendering is about to start
  23662. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23663. */
  23664. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23665. /**
  23666. * An event triggered when particles rendering is done
  23667. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23668. */
  23669. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23670. /**
  23671. * An event triggered when sprites rendering is about to start
  23672. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23673. */
  23674. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23675. /**
  23676. * An event triggered when sprites rendering is done
  23677. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23678. */
  23679. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23680. /**
  23681. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23682. */
  23683. this.onDataLoadedObservable = new BABYLON.Observable();
  23684. /**
  23685. * An event triggered when a camera is created
  23686. */
  23687. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23688. /**
  23689. * An event triggered when a camera is removed
  23690. */
  23691. this.onCameraRemovedObservable = new BABYLON.Observable();
  23692. /**
  23693. * An event triggered when a light is created
  23694. */
  23695. this.onNewLightAddedObservable = new BABYLON.Observable();
  23696. /**
  23697. * An event triggered when a light is removed
  23698. */
  23699. this.onLightRemovedObservable = new BABYLON.Observable();
  23700. /**
  23701. * An event triggered when a geometry is created
  23702. */
  23703. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23704. /**
  23705. * An event triggered when a geometry is removed
  23706. */
  23707. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23708. /**
  23709. * An event triggered when a transform node is created
  23710. */
  23711. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23712. /**
  23713. * An event triggered when a transform node is removed
  23714. */
  23715. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23716. /**
  23717. * An event triggered when a mesh is created
  23718. */
  23719. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23720. /**
  23721. * An event triggered when a mesh is removed
  23722. */
  23723. this.onMeshRemovedObservable = new BABYLON.Observable();
  23724. /**
  23725. * An event triggered when render targets are about to be rendered
  23726. * Can happen multiple times per frame.
  23727. */
  23728. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23729. /**
  23730. * An event triggered when render targets were rendered.
  23731. * Can happen multiple times per frame.
  23732. */
  23733. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23734. /**
  23735. * An event triggered before calculating deterministic simulation step
  23736. */
  23737. this.onBeforeStepObservable = new BABYLON.Observable();
  23738. /**
  23739. * An event triggered after calculating deterministic simulation step
  23740. */
  23741. this.onAfterStepObservable = new BABYLON.Observable();
  23742. /**
  23743. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23744. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23745. * 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)
  23746. */
  23747. this.onRenderingGroupObservable = new BABYLON.Observable();
  23748. // Animations
  23749. /**
  23750. * Gets a list of Animations associated with the scene
  23751. */
  23752. this.animations = [];
  23753. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23754. /**
  23755. * 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).
  23756. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23757. */
  23758. this.onPrePointerObservable = new BABYLON.Observable();
  23759. /**
  23760. * Observable event triggered each time an input event is received from the rendering canvas
  23761. */
  23762. this.onPointerObservable = new BABYLON.Observable();
  23763. this._meshPickProceed = false;
  23764. this._currentPickResult = null;
  23765. this._previousPickResult = null;
  23766. this._totalPointersPressed = 0;
  23767. this._doubleClickOccured = false;
  23768. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23769. this.cameraToUseForPointers = null;
  23770. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23771. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23772. this._startingPointerTime = 0;
  23773. this._previousStartingPointerTime = 0;
  23774. // Deterministic lockstep
  23775. this._timeAccumulator = 0;
  23776. this._currentStepId = 0;
  23777. this._currentInternalStep = 0;
  23778. // Keyboard
  23779. /**
  23780. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23781. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23782. */
  23783. this.onPreKeyboardObservable = new BABYLON.Observable();
  23784. /**
  23785. * Observable event triggered each time an keyboard event is received from the hosting window
  23786. */
  23787. this.onKeyboardObservable = new BABYLON.Observable();
  23788. // Coordinates system
  23789. this._useRightHandedSystem = false;
  23790. // Fog
  23791. this._fogEnabled = true;
  23792. this._fogMode = Scene.FOGMODE_NONE;
  23793. /**
  23794. * Gets or sets the fog color to use
  23795. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23796. */
  23797. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23798. /**
  23799. * Gets or sets the fog density to use
  23800. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23801. */
  23802. this.fogDensity = 0.1;
  23803. /**
  23804. * Gets or sets the fog start distance to use
  23805. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23806. */
  23807. this.fogStart = 0;
  23808. /**
  23809. * Gets or sets the fog end distance to use
  23810. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23811. */
  23812. this.fogEnd = 1000.0;
  23813. // Lights
  23814. this._shadowsEnabled = true;
  23815. this._lightsEnabled = true;
  23816. /**
  23817. * All of the lights added to this scene
  23818. * @see http://doc.babylonjs.com/babylon101/lights
  23819. */
  23820. this.lights = new Array();
  23821. // Cameras
  23822. /** All of the cameras added to this scene.
  23823. * @see http://doc.babylonjs.com/babylon101/cameras
  23824. */
  23825. this.cameras = new Array();
  23826. /** All of the active cameras added to this scene. */
  23827. this.activeCameras = new Array();
  23828. // Meshes
  23829. /**
  23830. * All of the tranform nodes added to this scene
  23831. * @see http://doc.babylonjs.com/how_to/transformnode
  23832. */
  23833. this.transformNodes = new Array();
  23834. /**
  23835. * All of the (abstract) meshes added to this scene
  23836. */
  23837. this.meshes = new Array();
  23838. /**
  23839. * All of the animation groups added to this scene
  23840. * @see http://doc.babylonjs.com/how_to/group
  23841. */
  23842. this.animationGroups = new Array();
  23843. // Geometries
  23844. this._geometries = new Array();
  23845. /**
  23846. * All of the materials added to this scene
  23847. * @see http://doc.babylonjs.com/babylon101/materials
  23848. */
  23849. this.materials = new Array();
  23850. /**
  23851. * All of the multi-materials added to this scene
  23852. * @see http://doc.babylonjs.com/how_to/multi_materials
  23853. */
  23854. this.multiMaterials = new Array();
  23855. // Textures
  23856. this._texturesEnabled = true;
  23857. /**
  23858. * All of the textures added to this scene
  23859. */
  23860. this.textures = new Array();
  23861. // Particles
  23862. /**
  23863. * Gets or sets a boolean indicating if particles are enabled on this scene
  23864. */
  23865. this.particlesEnabled = true;
  23866. /**
  23867. * All of the particle systems added to this scene
  23868. * @see http://doc.babylonjs.com/babylon101/particles
  23869. */
  23870. this.particleSystems = new Array();
  23871. // Sprites
  23872. /**
  23873. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23874. */
  23875. this.spritesEnabled = true;
  23876. /**
  23877. * All of the sprite managers added to this scene
  23878. * @see http://doc.babylonjs.com/babylon101/sprites
  23879. */
  23880. this.spriteManagers = new Array();
  23881. /**
  23882. * The list of layers (background and foreground) of the scene
  23883. */
  23884. this.layers = new Array();
  23885. /**
  23886. * The list of effect layers (highlights/glow) added to the scene
  23887. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23888. * @see http://doc.babylonjs.com/how_to/glow_layer
  23889. */
  23890. this.effectLayers = new Array();
  23891. // Skeletons
  23892. this._skeletonsEnabled = true;
  23893. /**
  23894. * The list of skeletons added to the scene
  23895. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23896. */
  23897. this.skeletons = new Array();
  23898. // Morph targets
  23899. /**
  23900. * The list of morph target managers added to the scene
  23901. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23902. */
  23903. this.morphTargetManagers = new Array();
  23904. // Lens flares
  23905. /**
  23906. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23907. */
  23908. this.lensFlaresEnabled = true;
  23909. /**
  23910. * The list of lens flare system added to the scene
  23911. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23912. */
  23913. this.lensFlareSystems = new Array();
  23914. // Collisions
  23915. /**
  23916. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23917. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23918. */
  23919. this.collisionsEnabled = true;
  23920. /**
  23921. * Defines the gravity applied to this scene (used only for collisions)
  23922. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23923. */
  23924. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23925. // Postprocesses
  23926. /**
  23927. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23928. */
  23929. this.postProcessesEnabled = true;
  23930. /**
  23931. * The list of postprocesses added to the scene
  23932. */
  23933. this.postProcesses = new Array();
  23934. // Customs render targets
  23935. /**
  23936. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23937. */
  23938. this.renderTargetsEnabled = true;
  23939. /**
  23940. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23941. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23942. */
  23943. this.dumpNextRenderTargets = false;
  23944. /**
  23945. * The list of user defined render targets added to the scene
  23946. */
  23947. this.customRenderTargets = new Array();
  23948. /**
  23949. * Gets the list of meshes imported to the scene through SceneLoader
  23950. */
  23951. this.importedMeshesFiles = new Array();
  23952. // Probes
  23953. /**
  23954. * Gets or sets a boolean indicating if probes are enabled on this scene
  23955. */
  23956. this.probesEnabled = true;
  23957. /**
  23958. * The list of reflection probes added to the scene
  23959. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23960. */
  23961. this.reflectionProbes = new Array();
  23962. /** @hidden */
  23963. this._actionManagers = new Array();
  23964. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23965. // Procedural textures
  23966. /**
  23967. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23968. */
  23969. this.proceduralTexturesEnabled = true;
  23970. /**
  23971. * The list of procedural textures added to the scene
  23972. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23973. */
  23974. this.proceduralTextures = new Array();
  23975. /**
  23976. * The list of sound tracks added to the scene
  23977. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23978. */
  23979. this.soundTracks = new Array();
  23980. this._audioEnabled = true;
  23981. this._headphone = false;
  23982. // Performance counters
  23983. this._totalVertices = new BABYLON.PerfCounter();
  23984. /** @hidden */
  23985. this._activeIndices = new BABYLON.PerfCounter();
  23986. /** @hidden */
  23987. this._activeParticles = new BABYLON.PerfCounter();
  23988. /** @hidden */
  23989. this._activeBones = new BABYLON.PerfCounter();
  23990. this._animationTime = 0;
  23991. /**
  23992. * Gets or sets a general scale for animation speed
  23993. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23994. */
  23995. this.animationTimeScale = 1;
  23996. this._renderId = 0;
  23997. this._executeWhenReadyTimeoutId = -1;
  23998. this._intermediateRendering = false;
  23999. this._viewUpdateFlag = -1;
  24000. this._projectionUpdateFlag = -1;
  24001. this._alternateViewUpdateFlag = -1;
  24002. this._alternateProjectionUpdateFlag = -1;
  24003. /** @hidden */
  24004. this._toBeDisposed = new BABYLON.SmartArray(256);
  24005. this._activeRequests = new Array();
  24006. this._pendingData = new Array();
  24007. this._isDisposed = false;
  24008. /**
  24009. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24010. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24011. */
  24012. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24013. this._activeMeshes = new BABYLON.SmartArray(256);
  24014. this._processedMaterials = new BABYLON.SmartArray(256);
  24015. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24016. /** @hidden */
  24017. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24018. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24019. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24020. /** @hidden */
  24021. this._activeAnimatables = new Array();
  24022. this._transformMatrix = BABYLON.Matrix.Zero();
  24023. this._useAlternateCameraConfiguration = false;
  24024. this._alternateRendering = false;
  24025. /**
  24026. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24027. * This is useful if there are more lights that the maximum simulteanous authorized
  24028. */
  24029. this.requireLightSorting = false;
  24030. this._depthRenderer = {};
  24031. this._activeMeshesFrozen = false;
  24032. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24033. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24034. this._engine.scenes.push(this);
  24035. this._uid = null;
  24036. this._renderingManager = new BABYLON.RenderingManager(this);
  24037. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24038. if (BABYLON.OutlineRenderer) {
  24039. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24040. }
  24041. if (BABYLON.Tools.IsWindowObjectExist()) {
  24042. this.attachControl();
  24043. }
  24044. //simplification queue
  24045. if (BABYLON.SimplificationQueue) {
  24046. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24047. }
  24048. //collision coordinator initialization. For now legacy per default.
  24049. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24050. // Uniform Buffer
  24051. this._createUbo();
  24052. // Default Image processing definition.
  24053. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24054. }
  24055. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24056. /** The fog is deactivated */
  24057. get: function () {
  24058. return Scene._FOGMODE_NONE;
  24059. },
  24060. enumerable: true,
  24061. configurable: true
  24062. });
  24063. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24064. /** The fog density is following an exponential function */
  24065. get: function () {
  24066. return Scene._FOGMODE_EXP;
  24067. },
  24068. enumerable: true,
  24069. configurable: true
  24070. });
  24071. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24072. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24073. get: function () {
  24074. return Scene._FOGMODE_EXP2;
  24075. },
  24076. enumerable: true,
  24077. configurable: true
  24078. });
  24079. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24080. /** The fog density is following a linear function. */
  24081. get: function () {
  24082. return Scene._FOGMODE_LINEAR;
  24083. },
  24084. enumerable: true,
  24085. configurable: true
  24086. });
  24087. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24088. /**
  24089. * Texture used in all pbr material as the reflection texture.
  24090. * As in the majority of the scene they are the same (exception for multi room and so on),
  24091. * this is easier to reference from here than from all the materials.
  24092. */
  24093. get: function () {
  24094. return this._environmentTexture;
  24095. },
  24096. /**
  24097. * Texture used in all pbr material as the reflection texture.
  24098. * As in the majority of the scene they are the same (exception for multi room and so on),
  24099. * this is easier to set here than in all the materials.
  24100. */
  24101. set: function (value) {
  24102. if (this._environmentTexture === value) {
  24103. return;
  24104. }
  24105. this._environmentTexture = value;
  24106. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24107. },
  24108. enumerable: true,
  24109. configurable: true
  24110. });
  24111. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24112. /**
  24113. * Default image processing configuration used either in the rendering
  24114. * Forward main pass or through the imageProcessingPostProcess if present.
  24115. * As in the majority of the scene they are the same (exception for multi camera),
  24116. * this is easier to reference from here than from all the materials and post process.
  24117. *
  24118. * No setter as we it is a shared configuration, you can set the values instead.
  24119. */
  24120. get: function () {
  24121. return this._imageProcessingConfiguration;
  24122. },
  24123. enumerable: true,
  24124. configurable: true
  24125. });
  24126. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24127. get: function () {
  24128. return this._forceWireframe;
  24129. },
  24130. /**
  24131. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24132. */
  24133. set: function (value) {
  24134. if (this._forceWireframe === value) {
  24135. return;
  24136. }
  24137. this._forceWireframe = value;
  24138. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24139. },
  24140. enumerable: true,
  24141. configurable: true
  24142. });
  24143. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24144. get: function () {
  24145. return this._forcePointsCloud;
  24146. },
  24147. /**
  24148. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24149. */
  24150. set: function (value) {
  24151. if (this._forcePointsCloud === value) {
  24152. return;
  24153. }
  24154. this._forcePointsCloud = value;
  24155. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24156. },
  24157. enumerable: true,
  24158. configurable: true
  24159. });
  24160. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24161. /**
  24162. * Gets or sets the animation properties override
  24163. */
  24164. get: function () {
  24165. return this._animationPropertiesOverride;
  24166. },
  24167. set: function (value) {
  24168. this._animationPropertiesOverride = value;
  24169. },
  24170. enumerable: true,
  24171. configurable: true
  24172. });
  24173. Object.defineProperty(Scene.prototype, "onDispose", {
  24174. /** Sets a function to be executed when this scene is disposed. */
  24175. set: function (callback) {
  24176. if (this._onDisposeObserver) {
  24177. this.onDisposeObservable.remove(this._onDisposeObserver);
  24178. }
  24179. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24180. },
  24181. enumerable: true,
  24182. configurable: true
  24183. });
  24184. Object.defineProperty(Scene.prototype, "beforeRender", {
  24185. /** Sets a function to be executed before rendering this scene */
  24186. set: function (callback) {
  24187. if (this._onBeforeRenderObserver) {
  24188. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24189. }
  24190. if (callback) {
  24191. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24192. }
  24193. },
  24194. enumerable: true,
  24195. configurable: true
  24196. });
  24197. Object.defineProperty(Scene.prototype, "afterRender", {
  24198. /** Sets a function to be executed after rendering this scene */
  24199. set: function (callback) {
  24200. if (this._onAfterRenderObserver) {
  24201. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24202. }
  24203. if (callback) {
  24204. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24205. }
  24206. },
  24207. enumerable: true,
  24208. configurable: true
  24209. });
  24210. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24211. /** Sets a function to be executed before rendering a camera*/
  24212. set: function (callback) {
  24213. if (this._onBeforeCameraRenderObserver) {
  24214. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24215. }
  24216. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24217. },
  24218. enumerable: true,
  24219. configurable: true
  24220. });
  24221. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24222. /** Sets a function to be executed after rendering a camera*/
  24223. set: function (callback) {
  24224. if (this._onAfterCameraRenderObserver) {
  24225. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24226. }
  24227. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24228. },
  24229. enumerable: true,
  24230. configurable: true
  24231. });
  24232. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24233. /**
  24234. * Gets the gamepad manager associated with the scene
  24235. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24236. */
  24237. get: function () {
  24238. if (!this._gamepadManager) {
  24239. this._gamepadManager = new BABYLON.GamepadManager(this);
  24240. }
  24241. return this._gamepadManager;
  24242. },
  24243. enumerable: true,
  24244. configurable: true
  24245. });
  24246. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24247. /**
  24248. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24249. */
  24250. get: function () {
  24251. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24252. },
  24253. enumerable: true,
  24254. configurable: true
  24255. });
  24256. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24257. get: function () {
  24258. return this._useRightHandedSystem;
  24259. },
  24260. /**
  24261. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24262. */
  24263. set: function (value) {
  24264. if (this._useRightHandedSystem === value) {
  24265. return;
  24266. }
  24267. this._useRightHandedSystem = value;
  24268. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24269. },
  24270. enumerable: true,
  24271. configurable: true
  24272. });
  24273. /**
  24274. * Sets the step Id used by deterministic lock step
  24275. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24276. * @param newStepId defines the step Id
  24277. */
  24278. Scene.prototype.setStepId = function (newStepId) {
  24279. this._currentStepId = newStepId;
  24280. };
  24281. ;
  24282. /**
  24283. * Gets the step Id used by deterministic lock step
  24284. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24285. * @returns the step Id
  24286. */
  24287. Scene.prototype.getStepId = function () {
  24288. return this._currentStepId;
  24289. };
  24290. ;
  24291. /**
  24292. * Gets the internal step used by deterministic lock step
  24293. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24294. * @returns the internal step
  24295. */
  24296. Scene.prototype.getInternalStep = function () {
  24297. return this._currentInternalStep;
  24298. };
  24299. ;
  24300. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24301. get: function () {
  24302. return this._fogEnabled;
  24303. },
  24304. /**
  24305. * Gets or sets a boolean indicating if fog is enabled on this scene
  24306. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24307. */
  24308. set: function (value) {
  24309. if (this._fogEnabled === value) {
  24310. return;
  24311. }
  24312. this._fogEnabled = value;
  24313. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24314. },
  24315. enumerable: true,
  24316. configurable: true
  24317. });
  24318. Object.defineProperty(Scene.prototype, "fogMode", {
  24319. get: function () {
  24320. return this._fogMode;
  24321. },
  24322. /**
  24323. * Gets or sets the fog mode to use
  24324. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24325. */
  24326. set: function (value) {
  24327. if (this._fogMode === value) {
  24328. return;
  24329. }
  24330. this._fogMode = value;
  24331. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24332. },
  24333. enumerable: true,
  24334. configurable: true
  24335. });
  24336. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24337. get: function () {
  24338. return this._shadowsEnabled;
  24339. },
  24340. /**
  24341. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24342. */
  24343. set: function (value) {
  24344. if (this._shadowsEnabled === value) {
  24345. return;
  24346. }
  24347. this._shadowsEnabled = value;
  24348. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24349. },
  24350. enumerable: true,
  24351. configurable: true
  24352. });
  24353. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24354. get: function () {
  24355. return this._lightsEnabled;
  24356. },
  24357. /**
  24358. * Gets or sets a boolean indicating if lights are enabled on this scene
  24359. */
  24360. set: function (value) {
  24361. if (this._lightsEnabled === value) {
  24362. return;
  24363. }
  24364. this._lightsEnabled = value;
  24365. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24366. },
  24367. enumerable: true,
  24368. configurable: true
  24369. });
  24370. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24371. /** The default material used on meshes when no material is affected */
  24372. get: function () {
  24373. if (!this._defaultMaterial) {
  24374. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24375. }
  24376. return this._defaultMaterial;
  24377. },
  24378. /** The default material used on meshes when no material is affected */
  24379. set: function (value) {
  24380. this._defaultMaterial = value;
  24381. },
  24382. enumerable: true,
  24383. configurable: true
  24384. });
  24385. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24386. get: function () {
  24387. return this._texturesEnabled;
  24388. },
  24389. /**
  24390. * Gets or sets a boolean indicating if textures are enabled on this scene
  24391. */
  24392. set: function (value) {
  24393. if (this._texturesEnabled === value) {
  24394. return;
  24395. }
  24396. this._texturesEnabled = value;
  24397. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24398. },
  24399. enumerable: true,
  24400. configurable: true
  24401. });
  24402. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24403. get: function () {
  24404. return this._skeletonsEnabled;
  24405. },
  24406. /**
  24407. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24408. */
  24409. set: function (value) {
  24410. if (this._skeletonsEnabled === value) {
  24411. return;
  24412. }
  24413. this._skeletonsEnabled = value;
  24414. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24415. },
  24416. enumerable: true,
  24417. configurable: true
  24418. });
  24419. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24420. /**
  24421. * Gets the postprocess render pipeline manager
  24422. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24423. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24424. */
  24425. get: function () {
  24426. if (!this._postProcessRenderPipelineManager) {
  24427. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24428. }
  24429. return this._postProcessRenderPipelineManager;
  24430. },
  24431. enumerable: true,
  24432. configurable: true
  24433. });
  24434. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24435. /**
  24436. * Gets the main soundtrack associated with the scene
  24437. */
  24438. get: function () {
  24439. if (!this._mainSoundTrack) {
  24440. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24441. }
  24442. return this._mainSoundTrack;
  24443. },
  24444. enumerable: true,
  24445. configurable: true
  24446. });
  24447. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24448. /** @hidden */
  24449. get: function () {
  24450. return this._alternateRendering;
  24451. },
  24452. enumerable: true,
  24453. configurable: true
  24454. });
  24455. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24456. /**
  24457. * Gets the list of frustum planes (built from the active camera)
  24458. */
  24459. get: function () {
  24460. return this._frustumPlanes;
  24461. },
  24462. enumerable: true,
  24463. configurable: true
  24464. });
  24465. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24466. /**
  24467. * Gets the current geometry buffer associated to the scene.
  24468. */
  24469. get: function () {
  24470. return this._geometryBufferRenderer;
  24471. },
  24472. /**
  24473. * Sets the current geometry buffer for the scene.
  24474. */
  24475. set: function (geometryBufferRenderer) {
  24476. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24477. this._geometryBufferRenderer = geometryBufferRenderer;
  24478. }
  24479. },
  24480. enumerable: true,
  24481. configurable: true
  24482. });
  24483. Object.defineProperty(Scene.prototype, "debugLayer", {
  24484. /**
  24485. * Gets the debug layer associated with the scene
  24486. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24487. */
  24488. get: function () {
  24489. if (!this._debugLayer) {
  24490. this._debugLayer = new BABYLON.DebugLayer(this);
  24491. }
  24492. return this._debugLayer;
  24493. },
  24494. enumerable: true,
  24495. configurable: true
  24496. });
  24497. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24498. /**
  24499. * Gets a boolean indicating if collisions are processed on a web worker
  24500. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24501. */
  24502. get: function () {
  24503. return this._workerCollisions;
  24504. },
  24505. set: function (enabled) {
  24506. if (!BABYLON.CollisionCoordinatorLegacy) {
  24507. return;
  24508. }
  24509. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24510. this._workerCollisions = enabled;
  24511. if (this.collisionCoordinator) {
  24512. this.collisionCoordinator.destroy();
  24513. }
  24514. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24515. this.collisionCoordinator.init(this);
  24516. },
  24517. enumerable: true,
  24518. configurable: true
  24519. });
  24520. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24521. /**
  24522. * Gets the octree used to boost mesh selection (picking)
  24523. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24524. */
  24525. get: function () {
  24526. return this._selectionOctree;
  24527. },
  24528. enumerable: true,
  24529. configurable: true
  24530. });
  24531. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24532. /**
  24533. * Gets the mesh that is currently under the pointer
  24534. */
  24535. get: function () {
  24536. return this._pointerOverMesh;
  24537. },
  24538. enumerable: true,
  24539. configurable: true
  24540. });
  24541. Object.defineProperty(Scene.prototype, "pointerX", {
  24542. /**
  24543. * Gets the current on-screen X position of the pointer
  24544. */
  24545. get: function () {
  24546. return this._pointerX;
  24547. },
  24548. enumerable: true,
  24549. configurable: true
  24550. });
  24551. Object.defineProperty(Scene.prototype, "pointerY", {
  24552. /**
  24553. * Gets the current on-screen Y position of the pointer
  24554. */
  24555. get: function () {
  24556. return this._pointerY;
  24557. },
  24558. enumerable: true,
  24559. configurable: true
  24560. });
  24561. /**
  24562. * Gets the cached material (ie. the latest rendered one)
  24563. * @returns the cached material
  24564. */
  24565. Scene.prototype.getCachedMaterial = function () {
  24566. return this._cachedMaterial;
  24567. };
  24568. /**
  24569. * Gets the cached effect (ie. the latest rendered one)
  24570. * @returns the cached effect
  24571. */
  24572. Scene.prototype.getCachedEffect = function () {
  24573. return this._cachedEffect;
  24574. };
  24575. /**
  24576. * Gets the cached visibility state (ie. the latest rendered one)
  24577. * @returns the cached visibility state
  24578. */
  24579. Scene.prototype.getCachedVisibility = function () {
  24580. return this._cachedVisibility;
  24581. };
  24582. /**
  24583. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24584. * @param material defines the current material
  24585. * @param effect defines the current effect
  24586. * @param visibility defines the current visibility state
  24587. * @returns true if one parameter is not cached
  24588. */
  24589. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24590. if (visibility === void 0) { visibility = 1; }
  24591. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24592. };
  24593. /**
  24594. * Gets the bounding box renderer associated with the scene
  24595. * @returns a BoundingBoxRenderer
  24596. */
  24597. Scene.prototype.getBoundingBoxRenderer = function () {
  24598. if (!this._boundingBoxRenderer) {
  24599. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24600. }
  24601. return this._boundingBoxRenderer;
  24602. };
  24603. /**
  24604. * Gets the outline renderer associated with the scene
  24605. * @returns a OutlineRenderer
  24606. */
  24607. Scene.prototype.getOutlineRenderer = function () {
  24608. return this._outlineRenderer;
  24609. };
  24610. /**
  24611. * Gets the engine associated with the scene
  24612. * @returns an Engine
  24613. */
  24614. Scene.prototype.getEngine = function () {
  24615. return this._engine;
  24616. };
  24617. /**
  24618. * Gets the total number of vertices rendered per frame
  24619. * @returns the total number of vertices rendered per frame
  24620. */
  24621. Scene.prototype.getTotalVertices = function () {
  24622. return this._totalVertices.current;
  24623. };
  24624. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24625. /**
  24626. * Gets the performance counter for total vertices
  24627. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24628. */
  24629. get: function () {
  24630. return this._totalVertices;
  24631. },
  24632. enumerable: true,
  24633. configurable: true
  24634. });
  24635. /**
  24636. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24637. * @returns the total number of active indices rendered per frame
  24638. */
  24639. Scene.prototype.getActiveIndices = function () {
  24640. return this._activeIndices.current;
  24641. };
  24642. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24643. /**
  24644. * Gets the performance counter for active indices
  24645. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24646. */
  24647. get: function () {
  24648. return this._activeIndices;
  24649. },
  24650. enumerable: true,
  24651. configurable: true
  24652. });
  24653. /**
  24654. * Gets the total number of active particles rendered per frame
  24655. * @returns the total number of active particles rendered per frame
  24656. */
  24657. Scene.prototype.getActiveParticles = function () {
  24658. return this._activeParticles.current;
  24659. };
  24660. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24661. /**
  24662. * Gets the performance counter for active particles
  24663. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24664. */
  24665. get: function () {
  24666. return this._activeParticles;
  24667. },
  24668. enumerable: true,
  24669. configurable: true
  24670. });
  24671. /**
  24672. * Gets the total number of active bones rendered per frame
  24673. * @returns the total number of active bones rendered per frame
  24674. */
  24675. Scene.prototype.getActiveBones = function () {
  24676. return this._activeBones.current;
  24677. };
  24678. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24679. /**
  24680. * Gets the performance counter for active bones
  24681. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24682. */
  24683. get: function () {
  24684. return this._activeBones;
  24685. },
  24686. enumerable: true,
  24687. configurable: true
  24688. });
  24689. /** @hidden */
  24690. Scene.prototype.getInterFramePerfCounter = function () {
  24691. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24692. return 0;
  24693. };
  24694. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24695. /** @hidden */
  24696. get: function () {
  24697. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24698. return null;
  24699. },
  24700. enumerable: true,
  24701. configurable: true
  24702. });
  24703. /** @hidden */
  24704. Scene.prototype.getLastFrameDuration = function () {
  24705. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24706. return 0;
  24707. };
  24708. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24709. /** @hidden */
  24710. get: function () {
  24711. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24712. return null;
  24713. },
  24714. enumerable: true,
  24715. configurable: true
  24716. });
  24717. /** @hidden */
  24718. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24719. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24720. return 0;
  24721. };
  24722. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24723. /** @hidden */
  24724. get: function () {
  24725. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24726. return null;
  24727. },
  24728. enumerable: true,
  24729. configurable: true
  24730. });
  24731. /**
  24732. * Gets the array of active meshes
  24733. * @returns an array of AbstractMesh
  24734. */
  24735. Scene.prototype.getActiveMeshes = function () {
  24736. return this._activeMeshes;
  24737. };
  24738. /** @hidden */
  24739. Scene.prototype.getRenderTargetsDuration = function () {
  24740. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24741. return 0;
  24742. };
  24743. /** @hidden */
  24744. Scene.prototype.getRenderDuration = function () {
  24745. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24746. return 0;
  24747. };
  24748. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24749. /** @hidden */
  24750. get: function () {
  24751. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24752. return null;
  24753. },
  24754. enumerable: true,
  24755. configurable: true
  24756. });
  24757. /** @hidden */
  24758. Scene.prototype.getParticlesDuration = function () {
  24759. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24760. return 0;
  24761. };
  24762. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24763. /** @hidden */
  24764. get: function () {
  24765. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24766. return null;
  24767. },
  24768. enumerable: true,
  24769. configurable: true
  24770. });
  24771. /** @hidden */
  24772. Scene.prototype.getSpritesDuration = function () {
  24773. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24774. return 0;
  24775. };
  24776. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24777. /** @hidden */
  24778. get: function () {
  24779. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24780. return null;
  24781. },
  24782. enumerable: true,
  24783. configurable: true
  24784. });
  24785. /**
  24786. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24787. * @returns a number
  24788. */
  24789. Scene.prototype.getAnimationRatio = function () {
  24790. return this._animationRatio;
  24791. };
  24792. /**
  24793. * Gets an unique Id for the current frame
  24794. * @returns a number
  24795. */
  24796. Scene.prototype.getRenderId = function () {
  24797. return this._renderId;
  24798. };
  24799. /** Call this function if you want to manually increment the render Id*/
  24800. Scene.prototype.incrementRenderId = function () {
  24801. this._renderId++;
  24802. };
  24803. Scene.prototype._updatePointerPosition = function (evt) {
  24804. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24805. if (!canvasRect) {
  24806. return;
  24807. }
  24808. this._pointerX = evt.clientX - canvasRect.left;
  24809. this._pointerY = evt.clientY - canvasRect.top;
  24810. this._unTranslatedPointerX = this._pointerX;
  24811. this._unTranslatedPointerY = this._pointerY;
  24812. };
  24813. Scene.prototype._createUbo = function () {
  24814. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24815. this._sceneUbo.addUniform("viewProjection", 16);
  24816. this._sceneUbo.addUniform("view", 16);
  24817. };
  24818. Scene.prototype._createAlternateUbo = function () {
  24819. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24820. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24821. this._alternateSceneUbo.addUniform("view", 16);
  24822. };
  24823. // Pointers handling
  24824. /**
  24825. * Use this method to simulate a pointer move on a mesh
  24826. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24827. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24828. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24829. * @returns the current scene
  24830. */
  24831. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24832. var evt = new PointerEvent("pointermove", pointerEventInit);
  24833. return this._processPointerMove(pickResult, evt);
  24834. };
  24835. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24836. var canvas = this._engine.getRenderingCanvas();
  24837. if (!canvas) {
  24838. return this;
  24839. }
  24840. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24841. this.setPointerOverSprite(null);
  24842. this.setPointerOverMesh(pickResult.pickedMesh);
  24843. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24844. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24845. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24846. }
  24847. else {
  24848. canvas.style.cursor = this.hoverCursor;
  24849. }
  24850. }
  24851. else {
  24852. canvas.style.cursor = this.defaultCursor;
  24853. }
  24854. }
  24855. else {
  24856. this.setPointerOverMesh(null);
  24857. // Sprites
  24858. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24859. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24860. this.setPointerOverSprite(pickResult.pickedSprite);
  24861. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24862. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24863. }
  24864. else {
  24865. canvas.style.cursor = this.hoverCursor;
  24866. }
  24867. }
  24868. else {
  24869. this.setPointerOverSprite(null);
  24870. // Restore pointer
  24871. canvas.style.cursor = this.defaultCursor;
  24872. }
  24873. }
  24874. if (pickResult) {
  24875. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24876. if (this.onPointerMove) {
  24877. this.onPointerMove(evt, pickResult, type);
  24878. }
  24879. if (this.onPointerObservable.hasObservers()) {
  24880. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24881. this.onPointerObservable.notifyObservers(pi, type);
  24882. }
  24883. }
  24884. return this;
  24885. };
  24886. /**
  24887. * Use this method to simulate a pointer down on a mesh
  24888. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24889. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24890. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24891. * @returns the current scene
  24892. */
  24893. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24894. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24895. return this._processPointerDown(pickResult, evt);
  24896. };
  24897. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24898. var _this = this;
  24899. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24900. this._pickedDownMesh = pickResult.pickedMesh;
  24901. var actionManager = pickResult.pickedMesh.actionManager;
  24902. if (actionManager) {
  24903. if (actionManager.hasPickTriggers) {
  24904. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24905. switch (evt.button) {
  24906. case 0:
  24907. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24908. break;
  24909. case 1:
  24910. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24911. break;
  24912. case 2:
  24913. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24914. break;
  24915. }
  24916. }
  24917. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24918. window.setTimeout(function () {
  24919. 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);
  24920. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24921. if (_this._totalPointersPressed !== 0 &&
  24922. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24923. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24924. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24925. _this._startingPointerTime = 0;
  24926. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24927. }
  24928. }
  24929. }, Scene.LongPressDelay);
  24930. }
  24931. }
  24932. }
  24933. if (pickResult) {
  24934. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24935. if (this.onPointerDown) {
  24936. this.onPointerDown(evt, pickResult, type);
  24937. }
  24938. if (this.onPointerObservable.hasObservers()) {
  24939. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24940. this.onPointerObservable.notifyObservers(pi, type);
  24941. }
  24942. }
  24943. return this;
  24944. };
  24945. /**
  24946. * Use this method to simulate a pointer up on a mesh
  24947. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24948. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24949. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24950. * @returns the current scene
  24951. */
  24952. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24953. var evt = new PointerEvent("pointerup", pointerEventInit);
  24954. var clickInfo = new ClickInfo();
  24955. clickInfo.singleClick = true;
  24956. clickInfo.ignore = true;
  24957. return this._processPointerUp(pickResult, evt, clickInfo);
  24958. };
  24959. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24960. if (pickResult && pickResult && pickResult.pickedMesh) {
  24961. this._pickedUpMesh = pickResult.pickedMesh;
  24962. if (this._pickedDownMesh === this._pickedUpMesh) {
  24963. if (this.onPointerPick) {
  24964. this.onPointerPick(evt, pickResult);
  24965. }
  24966. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24967. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24968. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24969. this.onPointerObservable.notifyObservers(pi, type_1);
  24970. }
  24971. }
  24972. if (pickResult.pickedMesh.actionManager) {
  24973. if (clickInfo.ignore) {
  24974. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24975. }
  24976. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24977. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24978. }
  24979. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24980. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24981. }
  24982. }
  24983. }
  24984. if (this._pickedDownMesh &&
  24985. this._pickedDownMesh.actionManager &&
  24986. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  24987. this._pickedDownMesh !== this._pickedUpMesh) {
  24988. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  24989. }
  24990. var type = BABYLON.PointerEventTypes.POINTERUP;
  24991. if (this.onPointerObservable.hasObservers()) {
  24992. if (!clickInfo.ignore) {
  24993. if (!clickInfo.hasSwiped) {
  24994. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24995. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  24996. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  24997. this.onPointerObservable.notifyObservers(pi, type_2);
  24998. }
  24999. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25000. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25001. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25002. this.onPointerObservable.notifyObservers(pi, type_3);
  25003. }
  25004. }
  25005. }
  25006. else {
  25007. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25008. this.onPointerObservable.notifyObservers(pi, type);
  25009. }
  25010. }
  25011. if (this.onPointerUp) {
  25012. this.onPointerUp(evt, pickResult, type);
  25013. }
  25014. return this;
  25015. };
  25016. /**
  25017. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25018. * @param attachUp defines if you want to attach events to pointerup
  25019. * @param attachDown defines if you want to attach events to pointerdown
  25020. * @param attachMove defines if you want to attach events to pointermove
  25021. */
  25022. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25023. var _this = this;
  25024. if (attachUp === void 0) { attachUp = true; }
  25025. if (attachDown === void 0) { attachDown = true; }
  25026. if (attachMove === void 0) { attachMove = true; }
  25027. this._initActionManager = function (act, clickInfo) {
  25028. if (!_this._meshPickProceed) {
  25029. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25030. _this._currentPickResult = pickResult;
  25031. if (pickResult) {
  25032. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25033. }
  25034. _this._meshPickProceed = true;
  25035. }
  25036. return act;
  25037. };
  25038. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25039. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25040. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25041. btn !== _this._previousButtonPressed) {
  25042. _this._doubleClickOccured = false;
  25043. clickInfo.singleClick = true;
  25044. clickInfo.ignore = false;
  25045. cb(clickInfo, _this._currentPickResult);
  25046. }
  25047. };
  25048. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25049. var clickInfo = new ClickInfo();
  25050. _this._currentPickResult = null;
  25051. var act = null;
  25052. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25053. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25054. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25055. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25056. act = _this._initActionManager(act, clickInfo);
  25057. if (act)
  25058. checkPicking = act.hasPickTriggers;
  25059. }
  25060. if (checkPicking) {
  25061. var btn = evt.button;
  25062. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25063. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25064. if (!clickInfo.hasSwiped) {
  25065. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25066. if (!checkSingleClickImmediately) {
  25067. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25068. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25069. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25070. act = _this._initActionManager(act, clickInfo);
  25071. if (act)
  25072. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25073. }
  25074. }
  25075. if (checkSingleClickImmediately) {
  25076. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25077. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25078. btn !== _this._previousButtonPressed) {
  25079. clickInfo.singleClick = true;
  25080. cb(clickInfo, _this._currentPickResult);
  25081. }
  25082. }
  25083. // at least one double click is required to be check and exclusive double click is enabled
  25084. else {
  25085. // wait that no double click has been raised during the double click delay
  25086. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25087. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25088. }
  25089. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25090. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25091. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25092. act = _this._initActionManager(act, clickInfo);
  25093. if (act)
  25094. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25095. }
  25096. if (checkDoubleClick) {
  25097. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25098. if (btn === _this._previousButtonPressed &&
  25099. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25100. !_this._doubleClickOccured) {
  25101. // pointer has not moved for 2 clicks, it's a double click
  25102. if (!clickInfo.hasSwiped &&
  25103. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25104. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25105. _this._previousStartingPointerTime = 0;
  25106. _this._doubleClickOccured = true;
  25107. clickInfo.doubleClick = true;
  25108. clickInfo.ignore = false;
  25109. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25110. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25111. }
  25112. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25113. cb(clickInfo, _this._currentPickResult);
  25114. }
  25115. // if the two successive clicks are too far, it's just two simple clicks
  25116. else {
  25117. _this._doubleClickOccured = false;
  25118. _this._previousStartingPointerTime = _this._startingPointerTime;
  25119. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25120. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25121. _this._previousButtonPressed = btn;
  25122. if (Scene.ExclusiveDoubleClickMode) {
  25123. if (_this._previousDelayedSimpleClickTimeout) {
  25124. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25125. }
  25126. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25127. cb(clickInfo, _this._previousPickResult);
  25128. }
  25129. else {
  25130. cb(clickInfo, _this._currentPickResult);
  25131. }
  25132. }
  25133. }
  25134. // just the first click of the double has been raised
  25135. else {
  25136. _this._doubleClickOccured = false;
  25137. _this._previousStartingPointerTime = _this._startingPointerTime;
  25138. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25139. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25140. _this._previousButtonPressed = btn;
  25141. }
  25142. }
  25143. }
  25144. }
  25145. clickInfo.ignore = true;
  25146. cb(clickInfo, _this._currentPickResult);
  25147. };
  25148. this._spritePredicate = function (sprite) {
  25149. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25150. };
  25151. this._onPointerMove = function (evt) {
  25152. _this._updatePointerPosition(evt);
  25153. // PreObservable support
  25154. if (_this.onPrePointerObservable.hasObservers()) {
  25155. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25156. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25157. _this.onPrePointerObservable.notifyObservers(pi, type);
  25158. if (pi.skipOnPointerObservable) {
  25159. return;
  25160. }
  25161. }
  25162. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25163. return;
  25164. }
  25165. if (!_this.pointerMovePredicate) {
  25166. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25167. }
  25168. // Meshes
  25169. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25170. _this._processPointerMove(pickResult, evt);
  25171. };
  25172. this._onPointerDown = function (evt) {
  25173. _this._totalPointersPressed++;
  25174. _this._pickedDownMesh = null;
  25175. _this._meshPickProceed = false;
  25176. _this._updatePointerPosition(evt);
  25177. if (_this.preventDefaultOnPointerDown && canvas) {
  25178. evt.preventDefault();
  25179. canvas.focus();
  25180. }
  25181. // PreObservable support
  25182. if (_this.onPrePointerObservable.hasObservers()) {
  25183. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25184. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25185. _this.onPrePointerObservable.notifyObservers(pi, type);
  25186. if (pi.skipOnPointerObservable) {
  25187. return;
  25188. }
  25189. }
  25190. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25191. return;
  25192. }
  25193. _this._startingPointerPosition.x = _this._pointerX;
  25194. _this._startingPointerPosition.y = _this._pointerY;
  25195. _this._startingPointerTime = Date.now();
  25196. if (!_this.pointerDownPredicate) {
  25197. _this.pointerDownPredicate = function (mesh) {
  25198. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25199. };
  25200. }
  25201. // Meshes
  25202. _this._pickedDownMesh = null;
  25203. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25204. _this._processPointerDown(pickResult, evt);
  25205. // Sprites
  25206. _this._pickedDownSprite = null;
  25207. if (_this.spriteManagers.length > 0) {
  25208. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25209. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25210. if (pickResult.pickedSprite.actionManager) {
  25211. _this._pickedDownSprite = pickResult.pickedSprite;
  25212. switch (evt.button) {
  25213. case 0:
  25214. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25215. break;
  25216. case 1:
  25217. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25218. break;
  25219. case 2:
  25220. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25221. break;
  25222. }
  25223. if (pickResult.pickedSprite.actionManager) {
  25224. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25225. }
  25226. }
  25227. }
  25228. }
  25229. };
  25230. this._onPointerUp = function (evt) {
  25231. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25232. return; // So we need to test it the pointer down was pressed before.
  25233. }
  25234. _this._totalPointersPressed--;
  25235. _this._pickedUpMesh = null;
  25236. _this._meshPickProceed = false;
  25237. _this._updatePointerPosition(evt);
  25238. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25239. // PreObservable support
  25240. if (_this.onPrePointerObservable.hasObservers()) {
  25241. if (!clickInfo.ignore) {
  25242. if (!clickInfo.hasSwiped) {
  25243. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25244. var type = BABYLON.PointerEventTypes.POINTERTAP;
  25245. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25246. _this.onPrePointerObservable.notifyObservers(pi, type);
  25247. if (pi.skipOnPointerObservable) {
  25248. return;
  25249. }
  25250. }
  25251. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25252. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25253. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25254. _this.onPrePointerObservable.notifyObservers(pi, type);
  25255. if (pi.skipOnPointerObservable) {
  25256. return;
  25257. }
  25258. }
  25259. }
  25260. }
  25261. else {
  25262. var type = BABYLON.PointerEventTypes.POINTERUP;
  25263. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25264. _this.onPrePointerObservable.notifyObservers(pi, type);
  25265. if (pi.skipOnPointerObservable) {
  25266. return;
  25267. }
  25268. }
  25269. }
  25270. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25271. return;
  25272. }
  25273. if (!_this.pointerUpPredicate) {
  25274. _this.pointerUpPredicate = function (mesh) {
  25275. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25276. };
  25277. }
  25278. // Meshes
  25279. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25280. _this._initActionManager(null, clickInfo);
  25281. }
  25282. if (!pickResult) {
  25283. pickResult = _this._currentPickResult;
  25284. }
  25285. _this._processPointerUp(pickResult, evt, clickInfo);
  25286. // Sprites
  25287. if (_this.spriteManagers.length > 0) {
  25288. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25289. if (spritePickResult) {
  25290. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25291. if (spritePickResult.pickedSprite.actionManager) {
  25292. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25293. if (spritePickResult.pickedSprite.actionManager) {
  25294. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25295. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25296. }
  25297. }
  25298. }
  25299. }
  25300. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25301. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25302. }
  25303. }
  25304. }
  25305. _this._previousPickResult = _this._currentPickResult;
  25306. });
  25307. };
  25308. this._onKeyDown = function (evt) {
  25309. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25310. if (_this.onPreKeyboardObservable.hasObservers()) {
  25311. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25312. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25313. if (pi.skipOnPointerObservable) {
  25314. return;
  25315. }
  25316. }
  25317. if (_this.onKeyboardObservable.hasObservers()) {
  25318. var pi = new BABYLON.KeyboardInfo(type, evt);
  25319. _this.onKeyboardObservable.notifyObservers(pi, type);
  25320. }
  25321. if (_this.actionManager) {
  25322. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25323. }
  25324. };
  25325. this._onKeyUp = function (evt) {
  25326. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25327. if (_this.onPreKeyboardObservable.hasObservers()) {
  25328. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25329. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25330. if (pi.skipOnPointerObservable) {
  25331. return;
  25332. }
  25333. }
  25334. if (_this.onKeyboardObservable.hasObservers()) {
  25335. var pi = new BABYLON.KeyboardInfo(type, evt);
  25336. _this.onKeyboardObservable.notifyObservers(pi, type);
  25337. }
  25338. if (_this.actionManager) {
  25339. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25340. }
  25341. };
  25342. var engine = this.getEngine();
  25343. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25344. if (!canvas) {
  25345. return;
  25346. }
  25347. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25348. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25349. });
  25350. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25351. if (!canvas) {
  25352. return;
  25353. }
  25354. canvas.removeEventListener("keydown", _this._onKeyDown);
  25355. canvas.removeEventListener("keyup", _this._onKeyUp);
  25356. });
  25357. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25358. var canvas = this._engine.getRenderingCanvas();
  25359. if (!canvas) {
  25360. return;
  25361. }
  25362. if (attachMove) {
  25363. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25364. // Wheel
  25365. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25366. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25367. }
  25368. if (attachDown) {
  25369. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25370. }
  25371. if (attachUp) {
  25372. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25373. }
  25374. canvas.tabIndex = 1;
  25375. };
  25376. /** Detaches all event handlers*/
  25377. Scene.prototype.detachControl = function () {
  25378. var engine = this.getEngine();
  25379. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25380. var canvas = engine.getRenderingCanvas();
  25381. if (!canvas) {
  25382. return;
  25383. }
  25384. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25385. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25386. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25387. if (this._onCanvasBlurObserver) {
  25388. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25389. }
  25390. if (this._onCanvasFocusObserver) {
  25391. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25392. }
  25393. // Wheel
  25394. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25395. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25396. // Keyboard
  25397. canvas.removeEventListener("keydown", this._onKeyDown);
  25398. canvas.removeEventListener("keyup", this._onKeyUp);
  25399. // Observables
  25400. this.onKeyboardObservable.clear();
  25401. this.onPreKeyboardObservable.clear();
  25402. this.onPointerObservable.clear();
  25403. this.onPrePointerObservable.clear();
  25404. };
  25405. /**
  25406. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25407. * Delay loaded resources are not taking in account
  25408. * @return true if all required resources are ready
  25409. */
  25410. Scene.prototype.isReady = function () {
  25411. if (this._isDisposed) {
  25412. return false;
  25413. }
  25414. if (this._pendingData.length > 0) {
  25415. return false;
  25416. }
  25417. var index;
  25418. var engine = this.getEngine();
  25419. // Geometries
  25420. for (index = 0; index < this._geometries.length; index++) {
  25421. var geometry = this._geometries[index];
  25422. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25423. return false;
  25424. }
  25425. }
  25426. // Meshes
  25427. for (index = 0; index < this.meshes.length; index++) {
  25428. var mesh = this.meshes[index];
  25429. if (!mesh.isEnabled()) {
  25430. continue;
  25431. }
  25432. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25433. continue;
  25434. }
  25435. if (!mesh.isReady(true)) {
  25436. return false;
  25437. }
  25438. // Effect layers
  25439. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25440. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25441. var layer = _a[_i];
  25442. if (!layer.hasMesh(mesh)) {
  25443. continue;
  25444. }
  25445. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25446. var subMesh = _c[_b];
  25447. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25448. return false;
  25449. }
  25450. }
  25451. }
  25452. }
  25453. // Post-processes
  25454. if (this.activeCameras && this.activeCameras.length > 0) {
  25455. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25456. var camera = _e[_d];
  25457. if (!camera.isReady(true)) {
  25458. return false;
  25459. }
  25460. }
  25461. }
  25462. else if (this.activeCamera) {
  25463. if (!this.activeCamera.isReady(true)) {
  25464. return false;
  25465. }
  25466. }
  25467. // Particles
  25468. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25469. var particleSystem = _g[_f];
  25470. if (!particleSystem.isReady()) {
  25471. return false;
  25472. }
  25473. }
  25474. return true;
  25475. };
  25476. /** Resets all cached information relative to material (including effect and visibility) */
  25477. Scene.prototype.resetCachedMaterial = function () {
  25478. this._cachedMaterial = null;
  25479. this._cachedEffect = null;
  25480. this._cachedVisibility = null;
  25481. };
  25482. /**
  25483. * Registers a function to be called before every frame render
  25484. * @param func defines the function to register
  25485. */
  25486. Scene.prototype.registerBeforeRender = function (func) {
  25487. this.onBeforeRenderObservable.add(func);
  25488. };
  25489. /**
  25490. * Unregisters a function called before every frame render
  25491. * @param func defines the function to unregister
  25492. */
  25493. Scene.prototype.unregisterBeforeRender = function (func) {
  25494. this.onBeforeRenderObservable.removeCallback(func);
  25495. };
  25496. /**
  25497. * Registers a function to be called after every frame render
  25498. * @param func defines the function to register
  25499. */
  25500. Scene.prototype.registerAfterRender = function (func) {
  25501. this.onAfterRenderObservable.add(func);
  25502. };
  25503. /**
  25504. * Unregisters a function called after every frame render
  25505. * @param func defines the function to unregister
  25506. */
  25507. Scene.prototype.unregisterAfterRender = function (func) {
  25508. this.onAfterRenderObservable.removeCallback(func);
  25509. };
  25510. Scene.prototype._executeOnceBeforeRender = function (func) {
  25511. var _this = this;
  25512. var execFunc = function () {
  25513. func();
  25514. setTimeout(function () {
  25515. _this.unregisterBeforeRender(execFunc);
  25516. });
  25517. };
  25518. this.registerBeforeRender(execFunc);
  25519. };
  25520. /**
  25521. * The provided function will run before render once and will be disposed afterwards.
  25522. * A timeout delay can be provided so that the function will be executed in N ms.
  25523. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25524. * @param func The function to be executed.
  25525. * @param timeout optional delay in ms
  25526. */
  25527. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25528. var _this = this;
  25529. if (timeout !== undefined) {
  25530. setTimeout(function () {
  25531. _this._executeOnceBeforeRender(func);
  25532. }, timeout);
  25533. }
  25534. else {
  25535. this._executeOnceBeforeRender(func);
  25536. }
  25537. };
  25538. /** @hidden */
  25539. Scene.prototype._addPendingData = function (data) {
  25540. this._pendingData.push(data);
  25541. };
  25542. /** @hidden */
  25543. Scene.prototype._removePendingData = function (data) {
  25544. var wasLoading = this.isLoading;
  25545. var index = this._pendingData.indexOf(data);
  25546. if (index !== -1) {
  25547. this._pendingData.splice(index, 1);
  25548. }
  25549. if (wasLoading && !this.isLoading) {
  25550. this.onDataLoadedObservable.notifyObservers(this);
  25551. }
  25552. };
  25553. /**
  25554. * Returns the number of items waiting to be loaded
  25555. * @returns the number of items waiting to be loaded
  25556. */
  25557. Scene.prototype.getWaitingItemsCount = function () {
  25558. return this._pendingData.length;
  25559. };
  25560. Object.defineProperty(Scene.prototype, "isLoading", {
  25561. /**
  25562. * Returns a boolean indicating if the scene is still loading data
  25563. */
  25564. get: function () {
  25565. return this._pendingData.length > 0;
  25566. },
  25567. enumerable: true,
  25568. configurable: true
  25569. });
  25570. /**
  25571. * Registers a function to be executed when the scene is ready
  25572. * @param {Function} func - the function to be executed
  25573. */
  25574. Scene.prototype.executeWhenReady = function (func) {
  25575. var _this = this;
  25576. this.onReadyObservable.add(func);
  25577. if (this._executeWhenReadyTimeoutId !== -1) {
  25578. return;
  25579. }
  25580. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25581. _this._checkIsReady();
  25582. }, 150);
  25583. };
  25584. /**
  25585. * Returns a promise that resolves when the scene is ready
  25586. * @returns A promise that resolves when the scene is ready
  25587. */
  25588. Scene.prototype.whenReadyAsync = function () {
  25589. var _this = this;
  25590. return new Promise(function (resolve) {
  25591. _this.executeWhenReady(function () {
  25592. resolve();
  25593. });
  25594. });
  25595. };
  25596. /** @hidden */
  25597. Scene.prototype._checkIsReady = function () {
  25598. var _this = this;
  25599. if (this.isReady()) {
  25600. this.onReadyObservable.notifyObservers(this);
  25601. this.onReadyObservable.clear();
  25602. this._executeWhenReadyTimeoutId = -1;
  25603. return;
  25604. }
  25605. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25606. _this._checkIsReady();
  25607. }, 150);
  25608. };
  25609. // Animations
  25610. /**
  25611. * Will start the animation sequence of a given target
  25612. * @param target defines the target
  25613. * @param from defines from which frame should animation start
  25614. * @param to defines until which frame should animation run.
  25615. * @param weight defines the weight to apply to the animation (1.0 by default)
  25616. * @param loop defines if the animation loops
  25617. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25618. * @param onAnimationEnd defines the function to be executed when the animation ends
  25619. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25620. * @returns the animatable object created for this animation
  25621. */
  25622. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25623. if (weight === void 0) { weight = 1.0; }
  25624. if (speedRatio === void 0) { speedRatio = 1.0; }
  25625. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25626. returnedAnimatable.weight = weight;
  25627. return returnedAnimatable;
  25628. };
  25629. /**
  25630. * Will start the animation sequence of a given target
  25631. * @param target defines the target
  25632. * @param from defines from which frame should animation start
  25633. * @param to defines until which frame should animation run.
  25634. * @param loop defines if the animation loops
  25635. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25636. * @param onAnimationEnd defines the function to be executed when the animation ends
  25637. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25638. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25639. * @returns the animatable object created for this animation
  25640. */
  25641. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25642. if (speedRatio === void 0) { speedRatio = 1.0; }
  25643. if (stopCurrent === void 0) { stopCurrent = true; }
  25644. if (from > to && speedRatio > 0) {
  25645. speedRatio *= -1;
  25646. }
  25647. if (stopCurrent) {
  25648. this.stopAnimation(target);
  25649. }
  25650. if (!animatable) {
  25651. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25652. }
  25653. // Local animations
  25654. if (target.animations) {
  25655. animatable.appendAnimations(target, target.animations);
  25656. }
  25657. // Children animations
  25658. if (target.getAnimatables) {
  25659. var animatables = target.getAnimatables();
  25660. for (var index = 0; index < animatables.length; index++) {
  25661. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25662. }
  25663. }
  25664. animatable.reset();
  25665. return animatable;
  25666. };
  25667. /**
  25668. * Begin a new animation on a given node
  25669. * @param target defines the target where the animation will take place
  25670. * @param animations defines the list of animations to start
  25671. * @param from defines the initial value
  25672. * @param to defines the final value
  25673. * @param loop defines if you want animation to loop (off by default)
  25674. * @param speedRatio defines the speed ratio to apply to all animations
  25675. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25676. * @returns the list of created animatables
  25677. */
  25678. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25679. if (speedRatio === undefined) {
  25680. speedRatio = 1.0;
  25681. }
  25682. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25683. return animatable;
  25684. };
  25685. /**
  25686. * Begin a new animation on a given node and its hierarchy
  25687. * @param target defines the root node where the animation will take place
  25688. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  25689. * @param animations defines the list of animations to start
  25690. * @param from defines the initial value
  25691. * @param to defines the final value
  25692. * @param loop defines if you want animation to loop (off by default)
  25693. * @param speedRatio defines the speed ratio to apply to all animations
  25694. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25695. * @returns the list of animatables created for all nodes
  25696. */
  25697. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25698. var children = target.getDescendants(directDescendantsOnly);
  25699. var result = [];
  25700. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25701. var child = children_1[_i];
  25702. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25703. }
  25704. return result;
  25705. };
  25706. /**
  25707. * Gets the animatable associated with a specific target
  25708. * @param target defines the target of the animatable
  25709. * @returns the required animatable if found
  25710. */
  25711. Scene.prototype.getAnimatableByTarget = function (target) {
  25712. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25713. if (this._activeAnimatables[index].target === target) {
  25714. return this._activeAnimatables[index];
  25715. }
  25716. }
  25717. return null;
  25718. };
  25719. /**
  25720. * Gets all animatables associated with a given target
  25721. * @param target defines the target to look animatables for
  25722. * @returns an array of Animatables
  25723. */
  25724. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25725. var result = [];
  25726. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25727. if (this._activeAnimatables[index].target === target) {
  25728. result.push(this._activeAnimatables[index]);
  25729. }
  25730. }
  25731. return result;
  25732. };
  25733. Object.defineProperty(Scene.prototype, "animatables", {
  25734. /**
  25735. * Gets all animatable attached to the scene
  25736. */
  25737. get: function () {
  25738. return this._activeAnimatables;
  25739. },
  25740. enumerable: true,
  25741. configurable: true
  25742. });
  25743. /**
  25744. * Will stop the animation of the given target
  25745. * @param target - the target
  25746. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25747. */
  25748. Scene.prototype.stopAnimation = function (target, animationName) {
  25749. var animatables = this.getAllAnimatablesByTarget(target);
  25750. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25751. var animatable = animatables_1[_i];
  25752. animatable.stop(animationName);
  25753. }
  25754. };
  25755. /**
  25756. * Stops and removes all animations that have been applied to the scene
  25757. */
  25758. Scene.prototype.stopAllAnimations = function () {
  25759. if (this._activeAnimatables) {
  25760. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25761. this._activeAnimatables[i].stop();
  25762. }
  25763. this._activeAnimatables = [];
  25764. }
  25765. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25766. var group = _a[_i];
  25767. group.stop();
  25768. }
  25769. };
  25770. Scene.prototype._animate = function () {
  25771. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25772. return;
  25773. }
  25774. // Getting time
  25775. var now = BABYLON.Tools.Now;
  25776. if (!this._animationTimeLast) {
  25777. if (this._pendingData.length > 0) {
  25778. return;
  25779. }
  25780. this._animationTimeLast = now;
  25781. }
  25782. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25783. this._animationTime += deltaTime;
  25784. this._animationTimeLast = now;
  25785. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25786. this._activeAnimatables[index]._animate(this._animationTime);
  25787. }
  25788. // Late animation bindings
  25789. this._processLateAnimationBindings();
  25790. };
  25791. /** @hidden */
  25792. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  25793. var target = runtimeAnimation.target;
  25794. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25795. if (!target._lateAnimationHolders) {
  25796. target._lateAnimationHolders = {};
  25797. }
  25798. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25799. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25800. totalWeight: 0,
  25801. animations: []
  25802. };
  25803. }
  25804. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25805. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25806. };
  25807. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder, originalValue) {
  25808. var normalizer = 1.0;
  25809. var finalPosition = BABYLON.Tmp.Vector3[0];
  25810. var finalScaling = BABYLON.Tmp.Vector3[1];
  25811. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25812. var startIndex = 0;
  25813. var originalAnimation = holder.animations[0];
  25814. var scale = 1;
  25815. if (holder.totalWeight < 1.0) {
  25816. // We need to mix the original value in
  25817. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25818. scale = 1.0 - holder.totalWeight;
  25819. }
  25820. else {
  25821. startIndex = 1;
  25822. // We need to normalize the weights
  25823. normalizer = holder.totalWeight;
  25824. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25825. scale = originalAnimation.weight / normalizer;
  25826. if (scale == 1) {
  25827. return originalAnimation.currentValue;
  25828. }
  25829. }
  25830. finalScaling.scaleInPlace(scale);
  25831. finalPosition.scaleInPlace(scale);
  25832. finalQuaternion.scaleInPlace(scale);
  25833. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25834. var runtimeAnimation = holder.animations[animIndex];
  25835. var scale = runtimeAnimation.weight / normalizer;
  25836. var currentPosition = BABYLON.Tmp.Vector3[2];
  25837. var currentScaling = BABYLON.Tmp.Vector3[3];
  25838. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25839. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25840. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25841. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25842. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25843. }
  25844. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25845. return originalAnimation._workValue;
  25846. };
  25847. Scene.prototype._processLateAnimationBindings = function () {
  25848. if (!this._registeredForLateAnimationBindings.length) {
  25849. return;
  25850. }
  25851. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25852. var target = this._registeredForLateAnimationBindings.data[index];
  25853. for (var path in target._lateAnimationHolders) {
  25854. var holder = target._lateAnimationHolders[path];
  25855. var originalAnimation = holder.animations[0];
  25856. var originalValue = originalAnimation.originalValue;
  25857. var finalTarget = originalAnimation.target;
  25858. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25859. var finalValue = void 0;
  25860. if (matrixDecomposeMode) {
  25861. finalValue = this._processLateAnimationBindingsForMatrices(holder, originalValue);
  25862. }
  25863. else {
  25864. var startIndex = 0;
  25865. var normalizer = 1.0;
  25866. if (holder.totalWeight < 1.0) {
  25867. // We need to mix the original value in
  25868. if (originalValue.scale) {
  25869. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25870. }
  25871. else {
  25872. finalValue = originalValue * (1.0 - holder.totalWeight);
  25873. }
  25874. }
  25875. else {
  25876. // We need to normalize the weights
  25877. normalizer = holder.totalWeight;
  25878. var scale_1 = originalAnimation.weight / normalizer;
  25879. if (scale_1 !== 1) {
  25880. if (originalAnimation.currentValue.scale) {
  25881. finalValue = originalAnimation.currentValue.scale(scale_1);
  25882. }
  25883. else {
  25884. finalValue = originalAnimation.currentValue * scale_1;
  25885. }
  25886. }
  25887. else {
  25888. finalValue = originalAnimation.currentValue;
  25889. }
  25890. startIndex = 1;
  25891. }
  25892. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25893. var runtimeAnimation = holder.animations[animIndex];
  25894. var scale = runtimeAnimation.weight / normalizer;
  25895. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25896. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25897. }
  25898. else {
  25899. finalValue += runtimeAnimation.currentValue * scale;
  25900. }
  25901. }
  25902. }
  25903. finalTarget[path] = finalValue;
  25904. }
  25905. target._lateAnimationHolders = {};
  25906. }
  25907. this._registeredForLateAnimationBindings.reset();
  25908. };
  25909. // Matrix
  25910. /** @hidden */
  25911. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25912. this._useAlternateCameraConfiguration = active;
  25913. };
  25914. /**
  25915. * Gets the current view matrix
  25916. * @returns a Matrix
  25917. */
  25918. Scene.prototype.getViewMatrix = function () {
  25919. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25920. };
  25921. /**
  25922. * Gets the current projection matrix
  25923. * @returns a Matrix
  25924. */
  25925. Scene.prototype.getProjectionMatrix = function () {
  25926. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25927. };
  25928. /**
  25929. * Gets the current transform matrix
  25930. * @returns a Matrix made of View * Projection
  25931. */
  25932. Scene.prototype.getTransformMatrix = function () {
  25933. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  25934. };
  25935. /**
  25936. * Sets the current transform matrix
  25937. * @param view defines the View matrix to use
  25938. * @param projection defines the Projection matrix to use
  25939. */
  25940. Scene.prototype.setTransformMatrix = function (view, projection) {
  25941. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  25942. return;
  25943. }
  25944. this._viewUpdateFlag = view.updateFlag;
  25945. this._projectionUpdateFlag = projection.updateFlag;
  25946. this._viewMatrix = view;
  25947. this._projectionMatrix = projection;
  25948. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  25949. // Update frustum
  25950. if (!this._frustumPlanes) {
  25951. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  25952. }
  25953. else {
  25954. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  25955. }
  25956. if (this.activeCamera && this.activeCamera._alternateCamera) {
  25957. var otherCamera = this.activeCamera._alternateCamera;
  25958. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  25959. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  25960. }
  25961. if (this._sceneUbo.useUbo) {
  25962. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  25963. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  25964. this._sceneUbo.update();
  25965. }
  25966. };
  25967. /** @hidden */
  25968. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  25969. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  25970. return;
  25971. }
  25972. this._alternateViewUpdateFlag = view.updateFlag;
  25973. this._alternateProjectionUpdateFlag = projection.updateFlag;
  25974. this._alternateViewMatrix = view;
  25975. this._alternateProjectionMatrix = projection;
  25976. if (!this._alternateTransformMatrix) {
  25977. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  25978. }
  25979. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  25980. if (!this._alternateSceneUbo) {
  25981. this._createAlternateUbo();
  25982. }
  25983. if (this._alternateSceneUbo.useUbo) {
  25984. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  25985. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  25986. this._alternateSceneUbo.update();
  25987. }
  25988. };
  25989. /**
  25990. * Gets the uniform buffer used to store scene data
  25991. * @returns a UniformBuffer
  25992. */
  25993. Scene.prototype.getSceneUniformBuffer = function () {
  25994. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  25995. };
  25996. /**
  25997. * Gets an unique (relatively to the current scene) Id
  25998. * @returns an unique number for the scene
  25999. */
  26000. Scene.prototype.getUniqueId = function () {
  26001. var result = Scene._uniqueIdCounter;
  26002. Scene._uniqueIdCounter++;
  26003. return result;
  26004. };
  26005. /**
  26006. * Add a mesh to the list of scene's meshes
  26007. * @param newMesh defines the mesh to add
  26008. */
  26009. Scene.prototype.addMesh = function (newMesh) {
  26010. this.meshes.push(newMesh);
  26011. //notify the collision coordinator
  26012. if (this.collisionCoordinator) {
  26013. this.collisionCoordinator.onMeshAdded(newMesh);
  26014. }
  26015. newMesh._resyncLightSources();
  26016. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26017. };
  26018. /**
  26019. * Remove a mesh for the list of scene's meshes
  26020. * @param toRemove defines the mesh to remove
  26021. * @returns the index where the mesh was in the mesh list
  26022. */
  26023. Scene.prototype.removeMesh = function (toRemove) {
  26024. var index = this.meshes.indexOf(toRemove);
  26025. if (index !== -1) {
  26026. // Remove from the scene if mesh found
  26027. this.meshes.splice(index, 1);
  26028. }
  26029. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26030. return index;
  26031. };
  26032. /**
  26033. * Add a transform node to the list of scene's transform nodes
  26034. * @param newTransformNode defines the transform node to add
  26035. */
  26036. Scene.prototype.addTransformNode = function (newTransformNode) {
  26037. this.transformNodes.push(newTransformNode);
  26038. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26039. };
  26040. /**
  26041. * Remove a transform node for the list of scene's transform nodes
  26042. * @param toRemove defines the transform node to remove
  26043. * @returns the index where the transform node was in the transform node list
  26044. */
  26045. Scene.prototype.removeTransformNode = function (toRemove) {
  26046. var index = this.transformNodes.indexOf(toRemove);
  26047. if (index !== -1) {
  26048. // Remove from the scene if found
  26049. this.transformNodes.splice(index, 1);
  26050. }
  26051. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26052. return index;
  26053. };
  26054. /**
  26055. * Remove a skeleton for the list of scene's skeletons
  26056. * @param toRemove defines the skeleton to remove
  26057. * @returns the index where the skeleton was in the skeleton list
  26058. */
  26059. Scene.prototype.removeSkeleton = function (toRemove) {
  26060. var index = this.skeletons.indexOf(toRemove);
  26061. if (index !== -1) {
  26062. // Remove from the scene if found
  26063. this.skeletons.splice(index, 1);
  26064. }
  26065. return index;
  26066. };
  26067. /**
  26068. * Remove a morph target for the list of scene's morph targets
  26069. * @param toRemove defines the morph target to remove
  26070. * @returns the index where the morph target was in the morph target list
  26071. */
  26072. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26073. var index = this.morphTargetManagers.indexOf(toRemove);
  26074. if (index !== -1) {
  26075. // Remove from the scene if found
  26076. this.morphTargetManagers.splice(index, 1);
  26077. }
  26078. return index;
  26079. };
  26080. /**
  26081. * Remove a light for the list of scene's lights
  26082. * @param toRemove defines the light to remove
  26083. * @returns the index where the light was in the light list
  26084. */
  26085. Scene.prototype.removeLight = function (toRemove) {
  26086. var index = this.lights.indexOf(toRemove);
  26087. if (index !== -1) {
  26088. // Remove from meshes
  26089. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26090. var mesh = _a[_i];
  26091. mesh._removeLightSource(toRemove);
  26092. }
  26093. // Remove from the scene if mesh found
  26094. this.lights.splice(index, 1);
  26095. this.sortLightsByPriority();
  26096. }
  26097. this.onLightRemovedObservable.notifyObservers(toRemove);
  26098. return index;
  26099. };
  26100. /**
  26101. * Remove a camera for the list of scene's cameras
  26102. * @param toRemove defines the camera to remove
  26103. * @returns the index where the camera was in the camera list
  26104. */
  26105. Scene.prototype.removeCamera = function (toRemove) {
  26106. var index = this.cameras.indexOf(toRemove);
  26107. if (index !== -1) {
  26108. // Remove from the scene if mesh found
  26109. this.cameras.splice(index, 1);
  26110. }
  26111. // Remove from activeCameras
  26112. var index2 = this.activeCameras.indexOf(toRemove);
  26113. if (index2 !== -1) {
  26114. // Remove from the scene if mesh found
  26115. this.activeCameras.splice(index2, 1);
  26116. }
  26117. // Reset the activeCamera
  26118. if (this.activeCamera === toRemove) {
  26119. if (this.cameras.length > 0) {
  26120. this.activeCamera = this.cameras[0];
  26121. }
  26122. else {
  26123. this.activeCamera = null;
  26124. }
  26125. }
  26126. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26127. return index;
  26128. };
  26129. /**
  26130. * Remove a particle system for the list of scene's particle systems
  26131. * @param toRemove defines the particle system to remove
  26132. * @returns the index where the particle system was in the particle system list
  26133. */
  26134. Scene.prototype.removeParticleSystem = function (toRemove) {
  26135. var index = this.particleSystems.indexOf(toRemove);
  26136. if (index !== -1) {
  26137. this.particleSystems.splice(index, 1);
  26138. }
  26139. return index;
  26140. };
  26141. /**
  26142. * Remove a animation for the list of scene's animations
  26143. * @param toRemove defines the animation to remove
  26144. * @returns the index where the animation was in the animation list
  26145. */
  26146. Scene.prototype.removeAnimation = function (toRemove) {
  26147. var index = this.animations.indexOf(toRemove);
  26148. if (index !== -1) {
  26149. this.animations.splice(index, 1);
  26150. }
  26151. return index;
  26152. };
  26153. /**
  26154. * Removes the given animation group from this scene.
  26155. * @param toRemove The animation group to remove
  26156. * @returns The index of the removed animation group
  26157. */
  26158. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26159. var index = this.animationGroups.indexOf(toRemove);
  26160. if (index !== -1) {
  26161. this.animationGroups.splice(index, 1);
  26162. }
  26163. return index;
  26164. };
  26165. /**
  26166. * Removes the given multi-material from this scene.
  26167. * @param toRemove The multi-material to remove
  26168. * @returns The index of the removed multi-material
  26169. */
  26170. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26171. var index = this.multiMaterials.indexOf(toRemove);
  26172. if (index !== -1) {
  26173. this.multiMaterials.splice(index, 1);
  26174. }
  26175. return index;
  26176. };
  26177. /**
  26178. * Removes the given material from this scene.
  26179. * @param toRemove The material to remove
  26180. * @returns The index of the removed material
  26181. */
  26182. Scene.prototype.removeMaterial = function (toRemove) {
  26183. var index = this.materials.indexOf(toRemove);
  26184. if (index !== -1) {
  26185. this.materials.splice(index, 1);
  26186. }
  26187. return index;
  26188. };
  26189. /**
  26190. * Removes the given lens flare system from this scene.
  26191. * @param toRemove The lens flare system to remove
  26192. * @returns The index of the removed lens flare system
  26193. */
  26194. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26195. var index = this.lensFlareSystems.indexOf(toRemove);
  26196. if (index !== -1) {
  26197. this.lensFlareSystems.splice(index, 1);
  26198. }
  26199. return index;
  26200. };
  26201. /**
  26202. * Removes the given action manager from this scene.
  26203. * @param toRemove The action manager to remove
  26204. * @returns The index of the removed action manager
  26205. */
  26206. Scene.prototype.removeActionManager = function (toRemove) {
  26207. var index = this._actionManagers.indexOf(toRemove);
  26208. if (index !== -1) {
  26209. this._actionManagers.splice(index, 1);
  26210. }
  26211. return index;
  26212. };
  26213. /**
  26214. * Removes the given effect layer from this scene.
  26215. * @param toRemove defines the effect layer to remove
  26216. * @returns the index of the removed effect layer
  26217. */
  26218. Scene.prototype.removeEffectLayer = function (toRemove) {
  26219. var index = this.effectLayers.indexOf(toRemove);
  26220. if (index !== -1) {
  26221. this.effectLayers.splice(index, 1);
  26222. }
  26223. return index;
  26224. };
  26225. /**
  26226. * Removes the given texture from this scene.
  26227. * @param toRemove The texture to remove
  26228. * @returns The index of the removed texture
  26229. */
  26230. Scene.prototype.removeTexture = function (toRemove) {
  26231. var index = this.textures.indexOf(toRemove);
  26232. if (index !== -1) {
  26233. this.textures.splice(index, 1);
  26234. }
  26235. return index;
  26236. };
  26237. /**
  26238. * Adds the given light to this scene
  26239. * @param newLight The light to add
  26240. */
  26241. Scene.prototype.addLight = function (newLight) {
  26242. this.lights.push(newLight);
  26243. this.sortLightsByPriority();
  26244. // Add light to all meshes (To support if the light is removed and then readded)
  26245. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26246. var mesh = _a[_i];
  26247. if (mesh._lightSources.indexOf(newLight) === -1) {
  26248. mesh._lightSources.push(newLight);
  26249. mesh._resyncLightSources();
  26250. }
  26251. }
  26252. this.onNewLightAddedObservable.notifyObservers(newLight);
  26253. };
  26254. /**
  26255. * Sorts the list list based on light priorities
  26256. */
  26257. Scene.prototype.sortLightsByPriority = function () {
  26258. if (this.requireLightSorting) {
  26259. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26260. }
  26261. };
  26262. /**
  26263. * Adds the given camera to this scene
  26264. * @param newCamera The camera to add
  26265. */
  26266. Scene.prototype.addCamera = function (newCamera) {
  26267. this.cameras.push(newCamera);
  26268. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26269. };
  26270. /**
  26271. * Adds the given skeleton to this scene
  26272. * @param newSkeleton The skeleton to add
  26273. */
  26274. Scene.prototype.addSkeleton = function (newSkeleton) {
  26275. this.skeletons.push(newSkeleton);
  26276. };
  26277. /**
  26278. * Adds the given particle system to this scene
  26279. * @param newParticleSystem The particle system to add
  26280. */
  26281. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26282. this.particleSystems.push(newParticleSystem);
  26283. };
  26284. /**
  26285. * Adds the given animation to this scene
  26286. * @param newAnimation The animation to add
  26287. */
  26288. Scene.prototype.addAnimation = function (newAnimation) {
  26289. this.animations.push(newAnimation);
  26290. };
  26291. /**
  26292. * Adds the given animation group to this scene.
  26293. * @param newAnimationGroup The animation group to add
  26294. */
  26295. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26296. this.animationGroups.push(newAnimationGroup);
  26297. };
  26298. /**
  26299. * Adds the given multi-material to this scene
  26300. * @param newMultiMaterial The multi-material to add
  26301. */
  26302. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26303. this.multiMaterials.push(newMultiMaterial);
  26304. };
  26305. /**
  26306. * Adds the given material to this scene
  26307. * @param newMaterial The material to add
  26308. */
  26309. Scene.prototype.addMaterial = function (newMaterial) {
  26310. this.materials.push(newMaterial);
  26311. };
  26312. /**
  26313. * Adds the given morph target to this scene
  26314. * @param newMorphTargetManager The morph target to add
  26315. */
  26316. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26317. this.morphTargetManagers.push(newMorphTargetManager);
  26318. };
  26319. /**
  26320. * Adds the given geometry to this scene
  26321. * @param newGeometry The geometry to add
  26322. */
  26323. Scene.prototype.addGeometry = function (newGeometry) {
  26324. this._geometries.push(newGeometry);
  26325. };
  26326. /**
  26327. * Adds the given lens flare system to this scene
  26328. * @param newLensFlareSystem The lens flare system to add
  26329. */
  26330. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26331. this.lensFlareSystems.push(newLensFlareSystem);
  26332. };
  26333. /**
  26334. * Adds the given effect layer to this scene
  26335. * @param newEffectLayer defines the effect layer to add
  26336. */
  26337. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26338. this.effectLayers.push(newEffectLayer);
  26339. };
  26340. /**
  26341. * Adds the given action manager to this scene
  26342. * @param newActionManager The action manager to add
  26343. */
  26344. Scene.prototype.addActionManager = function (newActionManager) {
  26345. this._actionManagers.push(newActionManager);
  26346. };
  26347. /**
  26348. * Adds the given texture to this scene.
  26349. * @param newTexture The texture to add
  26350. */
  26351. Scene.prototype.addTexture = function (newTexture) {
  26352. this.textures.push(newTexture);
  26353. };
  26354. /**
  26355. * Switch active camera
  26356. * @param newCamera defines the new active camera
  26357. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26358. */
  26359. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26360. if (attachControl === void 0) { attachControl = true; }
  26361. var canvas = this._engine.getRenderingCanvas();
  26362. if (!canvas) {
  26363. return;
  26364. }
  26365. if (this.activeCamera) {
  26366. this.activeCamera.detachControl(canvas);
  26367. }
  26368. this.activeCamera = newCamera;
  26369. if (attachControl) {
  26370. newCamera.attachControl(canvas);
  26371. }
  26372. };
  26373. /**
  26374. * sets the active camera of the scene using its ID
  26375. * @param id defines the camera's ID
  26376. * @return the new active camera or null if none found.
  26377. */
  26378. Scene.prototype.setActiveCameraByID = function (id) {
  26379. var camera = this.getCameraByID(id);
  26380. if (camera) {
  26381. this.activeCamera = camera;
  26382. return camera;
  26383. }
  26384. return null;
  26385. };
  26386. /**
  26387. * sets the active camera of the scene using its name
  26388. * @param name defines the camera's name
  26389. * @returns the new active camera or null if none found.
  26390. */
  26391. Scene.prototype.setActiveCameraByName = function (name) {
  26392. var camera = this.getCameraByName(name);
  26393. if (camera) {
  26394. this.activeCamera = camera;
  26395. return camera;
  26396. }
  26397. return null;
  26398. };
  26399. /**
  26400. * get an animation group using its name
  26401. * @param name defines the material's name
  26402. * @return the animation group or null if none found.
  26403. */
  26404. Scene.prototype.getAnimationGroupByName = function (name) {
  26405. for (var index = 0; index < this.animationGroups.length; index++) {
  26406. if (this.animationGroups[index].name === name) {
  26407. return this.animationGroups[index];
  26408. }
  26409. }
  26410. return null;
  26411. };
  26412. /**
  26413. * get a material using its id
  26414. * @param id defines the material's ID
  26415. * @return the material or null if none found.
  26416. */
  26417. Scene.prototype.getMaterialByID = function (id) {
  26418. for (var index = 0; index < this.materials.length; index++) {
  26419. if (this.materials[index].id === id) {
  26420. return this.materials[index];
  26421. }
  26422. }
  26423. return null;
  26424. };
  26425. /**
  26426. * Gets a material using its name
  26427. * @param name defines the material's name
  26428. * @return the material or null if none found.
  26429. */
  26430. Scene.prototype.getMaterialByName = function (name) {
  26431. for (var index = 0; index < this.materials.length; index++) {
  26432. if (this.materials[index].name === name) {
  26433. return this.materials[index];
  26434. }
  26435. }
  26436. return null;
  26437. };
  26438. /**
  26439. * Gets a lens flare system using its name
  26440. * @param name defines the name to look for
  26441. * @returns the lens flare system or null if not found
  26442. */
  26443. Scene.prototype.getLensFlareSystemByName = function (name) {
  26444. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26445. if (this.lensFlareSystems[index].name === name) {
  26446. return this.lensFlareSystems[index];
  26447. }
  26448. }
  26449. return null;
  26450. };
  26451. /**
  26452. * Gets a lens flare system using its id
  26453. * @param id defines the id to look for
  26454. * @returns the lens flare system or null if not found
  26455. */
  26456. Scene.prototype.getLensFlareSystemByID = function (id) {
  26457. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26458. if (this.lensFlareSystems[index].id === id) {
  26459. return this.lensFlareSystems[index];
  26460. }
  26461. }
  26462. return null;
  26463. };
  26464. /**
  26465. * Gets a camera using its id
  26466. * @param id defines the id to look for
  26467. * @returns the camera or null if not found
  26468. */
  26469. Scene.prototype.getCameraByID = function (id) {
  26470. for (var index = 0; index < this.cameras.length; index++) {
  26471. if (this.cameras[index].id === id) {
  26472. return this.cameras[index];
  26473. }
  26474. }
  26475. return null;
  26476. };
  26477. /**
  26478. * Gets a camera using its unique id
  26479. * @param uniqueId defines the unique id to look for
  26480. * @returns the camera or null if not found
  26481. */
  26482. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26483. for (var index = 0; index < this.cameras.length; index++) {
  26484. if (this.cameras[index].uniqueId === uniqueId) {
  26485. return this.cameras[index];
  26486. }
  26487. }
  26488. return null;
  26489. };
  26490. /**
  26491. * Gets a camera using its name
  26492. * @param name defines the camera's name
  26493. * @return the camera or null if none found.
  26494. */
  26495. Scene.prototype.getCameraByName = function (name) {
  26496. for (var index = 0; index < this.cameras.length; index++) {
  26497. if (this.cameras[index].name === name) {
  26498. return this.cameras[index];
  26499. }
  26500. }
  26501. return null;
  26502. };
  26503. /**
  26504. * Gets a bone using its id
  26505. * @param id defines the bone's id
  26506. * @return the bone or null if not found
  26507. */
  26508. Scene.prototype.getBoneByID = function (id) {
  26509. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26510. var skeleton = this.skeletons[skeletonIndex];
  26511. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26512. if (skeleton.bones[boneIndex].id === id) {
  26513. return skeleton.bones[boneIndex];
  26514. }
  26515. }
  26516. }
  26517. return null;
  26518. };
  26519. /**
  26520. * Gets a bone using its id
  26521. * @param name defines the bone's name
  26522. * @return the bone or null if not found
  26523. */
  26524. Scene.prototype.getBoneByName = function (name) {
  26525. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26526. var skeleton = this.skeletons[skeletonIndex];
  26527. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26528. if (skeleton.bones[boneIndex].name === name) {
  26529. return skeleton.bones[boneIndex];
  26530. }
  26531. }
  26532. }
  26533. return null;
  26534. };
  26535. /**
  26536. * Gets a light node using its name
  26537. * @param name defines the the light's name
  26538. * @return the light or null if none found.
  26539. */
  26540. Scene.prototype.getLightByName = function (name) {
  26541. for (var index = 0; index < this.lights.length; index++) {
  26542. if (this.lights[index].name === name) {
  26543. return this.lights[index];
  26544. }
  26545. }
  26546. return null;
  26547. };
  26548. /**
  26549. * Gets a light node using its id
  26550. * @param id defines the light's id
  26551. * @return the light or null if none found.
  26552. */
  26553. Scene.prototype.getLightByID = function (id) {
  26554. for (var index = 0; index < this.lights.length; index++) {
  26555. if (this.lights[index].id === id) {
  26556. return this.lights[index];
  26557. }
  26558. }
  26559. return null;
  26560. };
  26561. /**
  26562. * Gets a light node using its scene-generated unique ID
  26563. * @param uniqueId defines the light's unique id
  26564. * @return the light or null if none found.
  26565. */
  26566. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26567. for (var index = 0; index < this.lights.length; index++) {
  26568. if (this.lights[index].uniqueId === uniqueId) {
  26569. return this.lights[index];
  26570. }
  26571. }
  26572. return null;
  26573. };
  26574. /**
  26575. * Gets a particle system by id
  26576. * @param id defines the particle system id
  26577. * @return the corresponding system or null if none found
  26578. */
  26579. Scene.prototype.getParticleSystemByID = function (id) {
  26580. for (var index = 0; index < this.particleSystems.length; index++) {
  26581. if (this.particleSystems[index].id === id) {
  26582. return this.particleSystems[index];
  26583. }
  26584. }
  26585. return null;
  26586. };
  26587. /**
  26588. * Gets a geometry using its ID
  26589. * @param id defines the geometry's id
  26590. * @return the geometry or null if none found.
  26591. */
  26592. Scene.prototype.getGeometryByID = function (id) {
  26593. for (var index = 0; index < this._geometries.length; index++) {
  26594. if (this._geometries[index].id === id) {
  26595. return this._geometries[index];
  26596. }
  26597. }
  26598. return null;
  26599. };
  26600. /**
  26601. * Add a new geometry to this scene
  26602. * @param geometry defines the geometry to be added to the scene.
  26603. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26604. * @return a boolean defining if the geometry was added or not
  26605. */
  26606. Scene.prototype.pushGeometry = function (geometry, force) {
  26607. if (!force && this.getGeometryByID(geometry.id)) {
  26608. return false;
  26609. }
  26610. this._geometries.push(geometry);
  26611. //notify the collision coordinator
  26612. if (this.collisionCoordinator) {
  26613. this.collisionCoordinator.onGeometryAdded(geometry);
  26614. }
  26615. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26616. return true;
  26617. };
  26618. /**
  26619. * Removes an existing geometry
  26620. * @param geometry defines the geometry to be removed from the scene
  26621. * @return a boolean defining if the geometry was removed or not
  26622. */
  26623. Scene.prototype.removeGeometry = function (geometry) {
  26624. var index = this._geometries.indexOf(geometry);
  26625. if (index > -1) {
  26626. this._geometries.splice(index, 1);
  26627. //notify the collision coordinator
  26628. if (this.collisionCoordinator) {
  26629. this.collisionCoordinator.onGeometryDeleted(geometry);
  26630. }
  26631. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26632. return true;
  26633. }
  26634. return false;
  26635. };
  26636. /**
  26637. * Gets the list of geometries attached to the scene
  26638. * @returns an array of Geometry
  26639. */
  26640. Scene.prototype.getGeometries = function () {
  26641. return this._geometries;
  26642. };
  26643. /**
  26644. * Gets the first added mesh found of a given ID
  26645. * @param id defines the id to search for
  26646. * @return the mesh found or null if not found at all
  26647. */
  26648. Scene.prototype.getMeshByID = function (id) {
  26649. for (var index = 0; index < this.meshes.length; index++) {
  26650. if (this.meshes[index].id === id) {
  26651. return this.meshes[index];
  26652. }
  26653. }
  26654. return null;
  26655. };
  26656. /**
  26657. * Gets a list of meshes using their id
  26658. * @param id defines the id to search for
  26659. * @returns a list of meshes
  26660. */
  26661. Scene.prototype.getMeshesByID = function (id) {
  26662. return this.meshes.filter(function (m) {
  26663. return m.id === id;
  26664. });
  26665. };
  26666. /**
  26667. * Gets the first added transform node found of a given ID
  26668. * @param id defines the id to search for
  26669. * @return the found transform node or null if not found at all.
  26670. */
  26671. Scene.prototype.getTransformNodeByID = function (id) {
  26672. for (var index = 0; index < this.transformNodes.length; index++) {
  26673. if (this.transformNodes[index].id === id) {
  26674. return this.transformNodes[index];
  26675. }
  26676. }
  26677. return null;
  26678. };
  26679. /**
  26680. * Gets a list of transform nodes using their id
  26681. * @param id defines the id to search for
  26682. * @returns a list of transform nodes
  26683. */
  26684. Scene.prototype.getTransformNodesByID = function (id) {
  26685. return this.transformNodes.filter(function (m) {
  26686. return m.id === id;
  26687. });
  26688. };
  26689. /**
  26690. * Gets a mesh with its auto-generated unique id
  26691. * @param uniqueId defines the unique id to search for
  26692. * @return the found mesh or null if not found at all.
  26693. */
  26694. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26695. for (var index = 0; index < this.meshes.length; index++) {
  26696. if (this.meshes[index].uniqueId === uniqueId) {
  26697. return this.meshes[index];
  26698. }
  26699. }
  26700. return null;
  26701. };
  26702. /**
  26703. * Gets a the last added mesh using a given id
  26704. * @param id defines the id to search for
  26705. * @return the found mesh or null if not found at all.
  26706. */
  26707. Scene.prototype.getLastMeshByID = function (id) {
  26708. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26709. if (this.meshes[index].id === id) {
  26710. return this.meshes[index];
  26711. }
  26712. }
  26713. return null;
  26714. };
  26715. /**
  26716. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26717. * @param id defines the id to search for
  26718. * @return the found node or null if not found at all
  26719. */
  26720. Scene.prototype.getLastEntryByID = function (id) {
  26721. var index;
  26722. for (index = this.meshes.length - 1; index >= 0; index--) {
  26723. if (this.meshes[index].id === id) {
  26724. return this.meshes[index];
  26725. }
  26726. }
  26727. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26728. if (this.transformNodes[index].id === id) {
  26729. return this.transformNodes[index];
  26730. }
  26731. }
  26732. for (index = this.cameras.length - 1; index >= 0; index--) {
  26733. if (this.cameras[index].id === id) {
  26734. return this.cameras[index];
  26735. }
  26736. }
  26737. for (index = this.lights.length - 1; index >= 0; index--) {
  26738. if (this.lights[index].id === id) {
  26739. return this.lights[index];
  26740. }
  26741. }
  26742. return null;
  26743. };
  26744. /**
  26745. * Gets a node (Mesh, Camera, Light) using a given id
  26746. * @param id defines the id to search for
  26747. * @return the found node or null if not found at all
  26748. */
  26749. Scene.prototype.getNodeByID = function (id) {
  26750. var mesh = this.getMeshByID(id);
  26751. if (mesh) {
  26752. return mesh;
  26753. }
  26754. var light = this.getLightByID(id);
  26755. if (light) {
  26756. return light;
  26757. }
  26758. var camera = this.getCameraByID(id);
  26759. if (camera) {
  26760. return camera;
  26761. }
  26762. var bone = this.getBoneByID(id);
  26763. return bone;
  26764. };
  26765. /**
  26766. * Gets a node (Mesh, Camera, Light) using a given name
  26767. * @param name defines the name to search for
  26768. * @return the found node or null if not found at all.
  26769. */
  26770. Scene.prototype.getNodeByName = function (name) {
  26771. var mesh = this.getMeshByName(name);
  26772. if (mesh) {
  26773. return mesh;
  26774. }
  26775. var light = this.getLightByName(name);
  26776. if (light) {
  26777. return light;
  26778. }
  26779. var camera = this.getCameraByName(name);
  26780. if (camera) {
  26781. return camera;
  26782. }
  26783. var bone = this.getBoneByName(name);
  26784. return bone;
  26785. };
  26786. /**
  26787. * Gets a mesh using a given name
  26788. * @param name defines the name to search for
  26789. * @return the found mesh or null if not found at all.
  26790. */
  26791. Scene.prototype.getMeshByName = function (name) {
  26792. for (var index = 0; index < this.meshes.length; index++) {
  26793. if (this.meshes[index].name === name) {
  26794. return this.meshes[index];
  26795. }
  26796. }
  26797. return null;
  26798. };
  26799. /**
  26800. * Gets a transform node using a given name
  26801. * @param name defines the name to search for
  26802. * @return the found transform node or null if not found at all.
  26803. */
  26804. Scene.prototype.getTransformNodeByName = function (name) {
  26805. for (var index = 0; index < this.transformNodes.length; index++) {
  26806. if (this.transformNodes[index].name === name) {
  26807. return this.transformNodes[index];
  26808. }
  26809. }
  26810. return null;
  26811. };
  26812. /**
  26813. * Gets a sound using a given name
  26814. * @param name defines the name to search for
  26815. * @return the found sound or null if not found at all.
  26816. */
  26817. Scene.prototype.getSoundByName = function (name) {
  26818. var index;
  26819. if (BABYLON.AudioEngine) {
  26820. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26821. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26822. return this.mainSoundTrack.soundCollection[index];
  26823. }
  26824. }
  26825. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26826. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26827. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26828. return this.soundTracks[sdIndex].soundCollection[index];
  26829. }
  26830. }
  26831. }
  26832. }
  26833. return null;
  26834. };
  26835. /**
  26836. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26837. * @param id defines the id to search for
  26838. * @return the found skeleton or null if not found at all.
  26839. */
  26840. Scene.prototype.getLastSkeletonByID = function (id) {
  26841. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26842. if (this.skeletons[index].id === id) {
  26843. return this.skeletons[index];
  26844. }
  26845. }
  26846. return null;
  26847. };
  26848. /**
  26849. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26850. * @param id defines the id to search for
  26851. * @return the found skeleton or null if not found at all.
  26852. */
  26853. Scene.prototype.getSkeletonById = function (id) {
  26854. for (var index = 0; index < this.skeletons.length; index++) {
  26855. if (this.skeletons[index].id === id) {
  26856. return this.skeletons[index];
  26857. }
  26858. }
  26859. return null;
  26860. };
  26861. /**
  26862. * Gets a skeleton using a given name
  26863. * @param name defines the name to search for
  26864. * @return the found skeleton or null if not found at all.
  26865. */
  26866. Scene.prototype.getSkeletonByName = function (name) {
  26867. for (var index = 0; index < this.skeletons.length; index++) {
  26868. if (this.skeletons[index].name === name) {
  26869. return this.skeletons[index];
  26870. }
  26871. }
  26872. return null;
  26873. };
  26874. /**
  26875. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26876. * @param id defines the id to search for
  26877. * @return the found morph target manager or null if not found at all.
  26878. */
  26879. Scene.prototype.getMorphTargetManagerById = function (id) {
  26880. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26881. if (this.morphTargetManagers[index].uniqueId === id) {
  26882. return this.morphTargetManagers[index];
  26883. }
  26884. }
  26885. return null;
  26886. };
  26887. /**
  26888. * Gets a boolean indicating if the given mesh is active
  26889. * @param mesh defines the mesh to look for
  26890. * @returns true if the mesh is in the active list
  26891. */
  26892. Scene.prototype.isActiveMesh = function (mesh) {
  26893. return (this._activeMeshes.indexOf(mesh) !== -1);
  26894. };
  26895. /**
  26896. * Return a the first highlight layer of the scene with a given name.
  26897. * @param name The name of the highlight layer to look for.
  26898. * @return The highlight layer if found otherwise null.
  26899. */
  26900. Scene.prototype.getHighlightLayerByName = function (name) {
  26901. for (var index = 0; index < this.effectLayers.length; index++) {
  26902. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26903. return this.effectLayers[index];
  26904. }
  26905. }
  26906. return null;
  26907. };
  26908. /**
  26909. * Return a the first highlight layer of the scene with a given name.
  26910. * @param name The name of the highlight layer to look for.
  26911. * @return The highlight layer if found otherwise null.
  26912. */
  26913. Scene.prototype.getGlowLayerByName = function (name) {
  26914. for (var index = 0; index < this.effectLayers.length; index++) {
  26915. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  26916. return this.effectLayers[index];
  26917. }
  26918. }
  26919. return null;
  26920. };
  26921. Object.defineProperty(Scene.prototype, "uid", {
  26922. /**
  26923. * Return a unique id as a string which can serve as an identifier for the scene
  26924. */
  26925. get: function () {
  26926. if (!this._uid) {
  26927. this._uid = BABYLON.Tools.RandomId();
  26928. }
  26929. return this._uid;
  26930. },
  26931. enumerable: true,
  26932. configurable: true
  26933. });
  26934. /**
  26935. * Add an externaly attached data from its key.
  26936. * This method call will fail and return false, if such key already exists.
  26937. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26938. * @param key the unique key that identifies the data
  26939. * @param data the data object to associate to the key for this Engine instance
  26940. * @return true if no such key were already present and the data was added successfully, false otherwise
  26941. */
  26942. Scene.prototype.addExternalData = function (key, data) {
  26943. if (!this._externalData) {
  26944. this._externalData = new BABYLON.StringDictionary();
  26945. }
  26946. return this._externalData.add(key, data);
  26947. };
  26948. /**
  26949. * Get an externaly attached data from its key
  26950. * @param key the unique key that identifies the data
  26951. * @return the associated data, if present (can be null), or undefined if not present
  26952. */
  26953. Scene.prototype.getExternalData = function (key) {
  26954. if (!this._externalData) {
  26955. return null;
  26956. }
  26957. return this._externalData.get(key);
  26958. };
  26959. /**
  26960. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26961. * @param key the unique key that identifies the data
  26962. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26963. * @return the associated data, can be null if the factory returned null.
  26964. */
  26965. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  26966. if (!this._externalData) {
  26967. this._externalData = new BABYLON.StringDictionary();
  26968. }
  26969. return this._externalData.getOrAddWithFactory(key, factory);
  26970. };
  26971. /**
  26972. * Remove an externaly attached data from the Engine instance
  26973. * @param key the unique key that identifies the data
  26974. * @return true if the data was successfully removed, false if it doesn't exist
  26975. */
  26976. Scene.prototype.removeExternalData = function (key) {
  26977. return this._externalData.remove(key);
  26978. };
  26979. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  26980. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  26981. if (mesh.showSubMeshesBoundingBox) {
  26982. var boundingInfo = subMesh.getBoundingInfo();
  26983. if (boundingInfo !== null && boundingInfo !== undefined) {
  26984. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26985. }
  26986. }
  26987. var material = subMesh.getMaterial();
  26988. if (material !== null && material !== undefined) {
  26989. // Render targets
  26990. if (material.getRenderTargetTextures !== undefined) {
  26991. if (this._processedMaterials.indexOf(material) === -1) {
  26992. this._processedMaterials.push(material);
  26993. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  26994. }
  26995. }
  26996. // Dispatch
  26997. this._activeIndices.addCount(subMesh.indexCount, false);
  26998. this._renderingManager.dispatch(subMesh, mesh, material);
  26999. }
  27000. }
  27001. };
  27002. /**
  27003. * Clear the processed materials smart array preventing retention point in material dispose.
  27004. */
  27005. Scene.prototype.freeProcessedMaterials = function () {
  27006. this._processedMaterials.dispose();
  27007. };
  27008. /**
  27009. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27010. */
  27011. Scene.prototype.freeActiveMeshes = function () {
  27012. this._activeMeshes.dispose();
  27013. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27014. this.activeCamera._activeMeshes.dispose();
  27015. }
  27016. if (this.activeCameras) {
  27017. for (var i = 0; i < this.activeCameras.length; i++) {
  27018. var activeCamera = this.activeCameras[i];
  27019. if (activeCamera && activeCamera._activeMeshes) {
  27020. activeCamera._activeMeshes.dispose();
  27021. }
  27022. }
  27023. }
  27024. };
  27025. /**
  27026. * Clear the info related to rendering groups preventing retention points during dispose.
  27027. */
  27028. Scene.prototype.freeRenderingGroups = function () {
  27029. if (this._renderingManager) {
  27030. this._renderingManager.freeRenderingGroups();
  27031. }
  27032. if (this.textures) {
  27033. for (var i = 0; i < this.textures.length; i++) {
  27034. var texture = this.textures[i];
  27035. if (texture && texture.renderList) {
  27036. texture.freeRenderingGroups();
  27037. }
  27038. }
  27039. }
  27040. };
  27041. /** @hidden */
  27042. Scene.prototype._isInIntermediateRendering = function () {
  27043. return this._intermediateRendering;
  27044. };
  27045. /**
  27046. * Defines the current active mesh candidate provider
  27047. * @param provider defines the provider to use
  27048. */
  27049. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27050. this._activeMeshCandidateProvider = provider;
  27051. };
  27052. /**
  27053. * Gets the current active mesh candidate provider
  27054. * @returns the current active mesh candidate provider
  27055. */
  27056. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27057. return this._activeMeshCandidateProvider;
  27058. };
  27059. /**
  27060. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27061. * @returns the current scene
  27062. */
  27063. Scene.prototype.freezeActiveMeshes = function () {
  27064. if (!this.activeCamera) {
  27065. return this;
  27066. }
  27067. if (!this._frustumPlanes) {
  27068. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27069. }
  27070. this._evaluateActiveMeshes();
  27071. this._activeMeshesFrozen = true;
  27072. return this;
  27073. };
  27074. /**
  27075. * Use this function to restart evaluating active meshes on every frame
  27076. * @returns the current scene
  27077. */
  27078. Scene.prototype.unfreezeActiveMeshes = function () {
  27079. this._activeMeshesFrozen = false;
  27080. return this;
  27081. };
  27082. Scene.prototype._evaluateActiveMeshes = function () {
  27083. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27084. return;
  27085. }
  27086. if (!this.activeCamera) {
  27087. return;
  27088. }
  27089. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27090. this.activeCamera._activeMeshes.reset();
  27091. this._activeMeshes.reset();
  27092. this._renderingManager.reset();
  27093. this._processedMaterials.reset();
  27094. this._activeParticleSystems.reset();
  27095. this._activeSkeletons.reset();
  27096. this._softwareSkinnedMeshes.reset();
  27097. if (this._boundingBoxRenderer) {
  27098. this._boundingBoxRenderer.reset();
  27099. }
  27100. // Meshes
  27101. var meshes;
  27102. var len;
  27103. var checkIsEnabled = true;
  27104. // Determine mesh candidates
  27105. if (this._activeMeshCandidateProvider !== undefined) {
  27106. // Use _activeMeshCandidateProvider
  27107. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27108. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27109. if (meshes !== undefined) {
  27110. len = meshes.length;
  27111. }
  27112. else {
  27113. len = 0;
  27114. }
  27115. }
  27116. else if (this._selectionOctree !== undefined) {
  27117. // Octree
  27118. var selection = this._selectionOctree.select(this._frustumPlanes);
  27119. meshes = selection.data;
  27120. len = selection.length;
  27121. }
  27122. else {
  27123. // Full scene traversal
  27124. len = this.meshes.length;
  27125. meshes = this.meshes;
  27126. }
  27127. // Check each mesh
  27128. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27129. mesh = meshes[meshIndex];
  27130. if (mesh.isBlocked) {
  27131. continue;
  27132. }
  27133. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27134. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27135. continue;
  27136. }
  27137. mesh.computeWorldMatrix();
  27138. // Intersections
  27139. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27140. this._meshesForIntersections.pushNoDuplicate(mesh);
  27141. }
  27142. // Switch to current LOD
  27143. meshLOD = mesh.getLOD(this.activeCamera);
  27144. if (meshLOD === undefined || meshLOD === null) {
  27145. continue;
  27146. }
  27147. mesh._preActivate();
  27148. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27149. this._activeMeshes.push(mesh);
  27150. this.activeCamera._activeMeshes.push(mesh);
  27151. mesh._activate(this._renderId);
  27152. if (meshLOD !== mesh) {
  27153. meshLOD._activate(this._renderId);
  27154. }
  27155. this._activeMesh(mesh, meshLOD);
  27156. }
  27157. }
  27158. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27159. // Particle systems
  27160. if (this.particlesEnabled) {
  27161. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27162. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27163. var particleSystem = this.particleSystems[particleIndex];
  27164. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27165. continue;
  27166. }
  27167. var emitter = particleSystem.emitter;
  27168. if (!emitter.position || emitter.isEnabled()) {
  27169. this._activeParticleSystems.push(particleSystem);
  27170. particleSystem.animate();
  27171. this._renderingManager.dispatchParticles(particleSystem);
  27172. }
  27173. }
  27174. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27175. }
  27176. };
  27177. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27178. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27179. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27180. mesh.skeleton.prepare();
  27181. }
  27182. if (!mesh.computeBonesUsingShaders) {
  27183. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27184. }
  27185. }
  27186. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27187. var boundingInfo = sourceMesh.getBoundingInfo();
  27188. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27189. }
  27190. if (mesh !== undefined && mesh !== null
  27191. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27192. // Submeshes Octrees
  27193. var len;
  27194. var subMeshes;
  27195. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27196. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27197. len = intersections.length;
  27198. subMeshes = intersections.data;
  27199. }
  27200. else {
  27201. subMeshes = mesh.subMeshes;
  27202. len = subMeshes.length;
  27203. }
  27204. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27205. subMesh = subMeshes[subIndex];
  27206. this._evaluateSubMesh(subMesh, mesh);
  27207. }
  27208. }
  27209. };
  27210. /**
  27211. * Update the transform matrix to update from the current active camera
  27212. * @param force defines a boolean used to force the update even if cache is up to date
  27213. */
  27214. Scene.prototype.updateTransformMatrix = function (force) {
  27215. if (!this.activeCamera) {
  27216. return;
  27217. }
  27218. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27219. };
  27220. /**
  27221. * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
  27222. * @param alternateCamera defines the camera to use
  27223. */
  27224. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27225. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27226. };
  27227. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27228. if (camera && camera._skipRendering) {
  27229. return;
  27230. }
  27231. var engine = this._engine;
  27232. this.activeCamera = camera;
  27233. if (!this.activeCamera)
  27234. throw new Error("Active camera not set");
  27235. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27236. // Viewport
  27237. engine.setViewport(this.activeCamera.viewport);
  27238. // Camera
  27239. this.resetCachedMaterial();
  27240. this._renderId++;
  27241. this.updateTransformMatrix();
  27242. if (camera._alternateCamera) {
  27243. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27244. this._alternateRendering = true;
  27245. }
  27246. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27247. // Meshes
  27248. this._evaluateActiveMeshes();
  27249. // Software skinning
  27250. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27251. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27252. mesh.applySkeleton(mesh.skeleton);
  27253. }
  27254. // Render targets
  27255. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27256. var needsRestoreFrameBuffer = false;
  27257. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27258. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27259. }
  27260. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27261. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27262. }
  27263. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27264. this._intermediateRendering = true;
  27265. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27266. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27267. var renderTarget = this._renderTargets.data[renderIndex];
  27268. if (renderTarget._shouldRender()) {
  27269. this._renderId++;
  27270. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27271. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27272. }
  27273. }
  27274. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27275. this._intermediateRendering = false;
  27276. this._renderId++;
  27277. needsRestoreFrameBuffer = true; // Restore back buffer
  27278. }
  27279. // Render EffecttLayer Texture
  27280. var stencilState = this._engine.getStencilBuffer();
  27281. var renderEffects = false;
  27282. var needStencil = false;
  27283. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27284. this._intermediateRendering = true;
  27285. for (var i = 0; i < this.effectLayers.length; i++) {
  27286. var effectLayer = this.effectLayers[i];
  27287. if (effectLayer.shouldRender() &&
  27288. (!effectLayer.camera ||
  27289. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27290. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27291. renderEffects = true;
  27292. needStencil = needStencil || effectLayer.needStencil();
  27293. var renderTarget = effectLayer._mainTexture;
  27294. if (renderTarget._shouldRender()) {
  27295. this._renderId++;
  27296. renderTarget.render(false, false);
  27297. needsRestoreFrameBuffer = true;
  27298. }
  27299. }
  27300. }
  27301. this._intermediateRendering = false;
  27302. this._renderId++;
  27303. }
  27304. if (needsRestoreFrameBuffer) {
  27305. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27306. }
  27307. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27308. // Prepare Frame
  27309. this.postProcessManager._prepareFrame();
  27310. // Backgrounds
  27311. var layerIndex;
  27312. var layer;
  27313. if (this.layers.length) {
  27314. engine.setDepthBuffer(false);
  27315. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27316. layer = this.layers[layerIndex];
  27317. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27318. layer.render();
  27319. }
  27320. }
  27321. engine.setDepthBuffer(true);
  27322. }
  27323. // Activate effect Layer stencil
  27324. if (needStencil) {
  27325. this._engine.setStencilBuffer(true);
  27326. }
  27327. // Render
  27328. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27329. this._renderingManager.render(null, null, true, true);
  27330. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27331. // Restore effect Layer stencil
  27332. if (needStencil) {
  27333. this._engine.setStencilBuffer(stencilState);
  27334. }
  27335. // Bounding boxes
  27336. if (this._boundingBoxRenderer) {
  27337. this._boundingBoxRenderer.render();
  27338. }
  27339. // Lens flares
  27340. if (this.lensFlaresEnabled) {
  27341. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27342. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27343. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27344. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27345. lensFlareSystem.render();
  27346. }
  27347. }
  27348. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27349. }
  27350. // Effect Layer
  27351. if (renderEffects) {
  27352. engine.setDepthBuffer(false);
  27353. for (var i = 0; i < this.effectLayers.length; i++) {
  27354. if (this.effectLayers[i].shouldRender()) {
  27355. this.effectLayers[i].render();
  27356. }
  27357. }
  27358. engine.setDepthBuffer(true);
  27359. }
  27360. // Foregrounds
  27361. if (this.layers.length) {
  27362. engine.setDepthBuffer(false);
  27363. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27364. layer = this.layers[layerIndex];
  27365. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27366. layer.render();
  27367. }
  27368. }
  27369. engine.setDepthBuffer(true);
  27370. }
  27371. // Finalize frame
  27372. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27373. // Reset some special arrays
  27374. this._renderTargets.reset();
  27375. this._alternateRendering = false;
  27376. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27377. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27378. };
  27379. Scene.prototype._processSubCameras = function (camera) {
  27380. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27381. this._renderForCamera(camera);
  27382. return;
  27383. }
  27384. // rig cameras
  27385. for (var index = 0; index < camera._rigCameras.length; index++) {
  27386. this._renderForCamera(camera._rigCameras[index], camera);
  27387. }
  27388. this.activeCamera = camera;
  27389. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27390. };
  27391. Scene.prototype._checkIntersections = function () {
  27392. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27393. var sourceMesh = this._meshesForIntersections.data[index];
  27394. if (!sourceMesh.actionManager) {
  27395. continue;
  27396. }
  27397. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27398. var action = sourceMesh.actionManager.actions[actionIndex];
  27399. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27400. var parameters = action.getTriggerParameter();
  27401. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27402. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27403. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27404. if (areIntersecting && currentIntersectionInProgress === -1) {
  27405. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27406. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27407. sourceMesh._intersectionsInProgress.push(otherMesh);
  27408. }
  27409. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27410. sourceMesh._intersectionsInProgress.push(otherMesh);
  27411. }
  27412. }
  27413. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27414. //They intersected, and now they don't.
  27415. //is this trigger an exit trigger? execute an event.
  27416. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27417. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27418. }
  27419. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27420. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27421. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27422. return otherMesh === parameterMesh;
  27423. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27424. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27425. }
  27426. }
  27427. }
  27428. }
  27429. }
  27430. };
  27431. /**
  27432. * Render the scene
  27433. */
  27434. Scene.prototype.render = function () {
  27435. if (this.isDisposed) {
  27436. return;
  27437. }
  27438. this._activeParticles.fetchNewFrame();
  27439. this._totalVertices.fetchNewFrame();
  27440. this._activeIndices.fetchNewFrame();
  27441. this._activeBones.fetchNewFrame();
  27442. this._meshesForIntersections.reset();
  27443. this.resetCachedMaterial();
  27444. this.onBeforeAnimationsObservable.notifyObservers(this);
  27445. // Actions
  27446. if (this.actionManager) {
  27447. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27448. }
  27449. //Simplification Queue
  27450. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27451. this.simplificationQueue.executeNext();
  27452. }
  27453. if (this._engine.isDeterministicLockStep()) {
  27454. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27455. var defaultFPS = (60.0 / 1000.0);
  27456. var defaultFrameTime = 1000 / 60; // frame time in MS
  27457. if (this._physicsEngine) {
  27458. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27459. }
  27460. var stepsTaken = 0;
  27461. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27462. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27463. internalSteps = Math.min(internalSteps, maxSubSteps);
  27464. do {
  27465. this.onBeforeStepObservable.notifyObservers(this);
  27466. // Animations
  27467. this._animationRatio = defaultFrameTime * defaultFPS;
  27468. this._animate();
  27469. this.onAfterAnimationsObservable.notifyObservers(this);
  27470. // Physics
  27471. if (this._physicsEngine) {
  27472. this.onBeforePhysicsObservable.notifyObservers(this);
  27473. this._physicsEngine._step(defaultFrameTime / 1000);
  27474. this.onAfterPhysicsObservable.notifyObservers(this);
  27475. }
  27476. this.onAfterStepObservable.notifyObservers(this);
  27477. this._currentStepId++;
  27478. stepsTaken++;
  27479. deltaTime -= defaultFrameTime;
  27480. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27481. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27482. }
  27483. else {
  27484. // Animations
  27485. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27486. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27487. this._animate();
  27488. this.onAfterAnimationsObservable.notifyObservers(this);
  27489. // Physics
  27490. if (this._physicsEngine) {
  27491. this.onBeforePhysicsObservable.notifyObservers(this);
  27492. this._physicsEngine._step(deltaTime / 1000.0);
  27493. this.onAfterPhysicsObservable.notifyObservers(this);
  27494. }
  27495. }
  27496. // update gamepad manager
  27497. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27498. this._gamepadManager._checkGamepadsStatus();
  27499. }
  27500. // Update Cameras
  27501. if (this.activeCameras.length > 0) {
  27502. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27503. var camera = this.activeCameras[cameraIndex];
  27504. camera.update();
  27505. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27506. // rig cameras
  27507. for (var index = 0; index < camera._rigCameras.length; index++) {
  27508. camera._rigCameras[index].update();
  27509. }
  27510. }
  27511. }
  27512. }
  27513. else if (this.activeCamera) {
  27514. this.activeCamera.update();
  27515. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27516. // rig cameras
  27517. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27518. this.activeCamera._rigCameras[index].update();
  27519. }
  27520. }
  27521. }
  27522. // Before render
  27523. this.onBeforeRenderObservable.notifyObservers(this);
  27524. // Customs render targets
  27525. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27526. var engine = this.getEngine();
  27527. var currentActiveCamera = this.activeCamera;
  27528. if (this.renderTargetsEnabled) {
  27529. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27530. this._intermediateRendering = true;
  27531. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27532. var renderTarget = this.customRenderTargets[customIndex];
  27533. if (renderTarget._shouldRender()) {
  27534. this._renderId++;
  27535. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27536. if (!this.activeCamera)
  27537. throw new Error("Active camera not set");
  27538. // Viewport
  27539. engine.setViewport(this.activeCamera.viewport);
  27540. // Camera
  27541. this.updateTransformMatrix();
  27542. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27543. }
  27544. }
  27545. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27546. this._intermediateRendering = false;
  27547. this._renderId++;
  27548. }
  27549. // Restore back buffer
  27550. if (this.customRenderTargets.length > 0) {
  27551. engine.restoreDefaultFramebuffer();
  27552. }
  27553. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27554. this.activeCamera = currentActiveCamera;
  27555. // Procedural textures
  27556. if (this.proceduralTexturesEnabled) {
  27557. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27558. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27559. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27560. if (proceduralTexture._shouldRender()) {
  27561. proceduralTexture.render();
  27562. }
  27563. }
  27564. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27565. }
  27566. // Clear
  27567. if (this.autoClearDepthAndStencil || this.autoClear) {
  27568. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27569. }
  27570. // Shadows
  27571. if (this.shadowsEnabled) {
  27572. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27573. var light = this.lights[lightIndex];
  27574. var shadowGenerator = light.getShadowGenerator();
  27575. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27576. var shadowMap = (shadowGenerator.getShadowMap());
  27577. if (this.textures.indexOf(shadowMap) !== -1) {
  27578. this._renderTargets.push(shadowMap);
  27579. }
  27580. }
  27581. }
  27582. }
  27583. // Depth renderer
  27584. for (var key in this._depthRenderer) {
  27585. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27586. }
  27587. // Geometry renderer
  27588. if (this._geometryBufferRenderer) {
  27589. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27590. }
  27591. // RenderPipeline
  27592. if (this._postProcessRenderPipelineManager) {
  27593. this._postProcessRenderPipelineManager.update();
  27594. }
  27595. // Multi-cameras?
  27596. if (this.activeCameras.length > 0) {
  27597. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27598. if (cameraIndex > 0) {
  27599. this._engine.clear(null, false, true, true);
  27600. }
  27601. this._processSubCameras(this.activeCameras[cameraIndex]);
  27602. }
  27603. }
  27604. else {
  27605. if (!this.activeCamera) {
  27606. throw new Error("No camera defined");
  27607. }
  27608. this._processSubCameras(this.activeCamera);
  27609. }
  27610. // Intersection checks
  27611. this._checkIntersections();
  27612. // Update the audio listener attached to the camera
  27613. if (BABYLON.AudioEngine) {
  27614. this._updateAudioParameters();
  27615. }
  27616. // After render
  27617. if (this.afterRender) {
  27618. this.afterRender();
  27619. }
  27620. this.onAfterRenderObservable.notifyObservers(this);
  27621. // Cleaning
  27622. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27623. var data = this._toBeDisposed.data[index];
  27624. if (data) {
  27625. data.dispose();
  27626. }
  27627. this._toBeDisposed[index] = null;
  27628. }
  27629. this._toBeDisposed.reset();
  27630. if (this.dumpNextRenderTargets) {
  27631. this.dumpNextRenderTargets = false;
  27632. }
  27633. this._activeBones.addCount(0, true);
  27634. this._activeIndices.addCount(0, true);
  27635. this._activeParticles.addCount(0, true);
  27636. };
  27637. Scene.prototype._updateAudioParameters = function () {
  27638. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27639. return;
  27640. }
  27641. var listeningCamera;
  27642. var audioEngine = BABYLON.Engine.audioEngine;
  27643. if (this.activeCameras.length > 0) {
  27644. listeningCamera = this.activeCameras[0];
  27645. }
  27646. else {
  27647. listeningCamera = this.activeCamera;
  27648. }
  27649. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27650. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27651. // for VR cameras
  27652. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27653. listeningCamera = listeningCamera.rigCameras[0];
  27654. }
  27655. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27656. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27657. cameraDirection.normalize();
  27658. // To avoid some errors on GearVR
  27659. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27660. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27661. }
  27662. var i;
  27663. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27664. var sound = this.mainSoundTrack.soundCollection[i];
  27665. if (sound.useCustomAttenuation) {
  27666. sound.updateDistanceFromListener();
  27667. }
  27668. }
  27669. for (i = 0; i < this.soundTracks.length; i++) {
  27670. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27671. sound = this.soundTracks[i].soundCollection[j];
  27672. if (sound.useCustomAttenuation) {
  27673. sound.updateDistanceFromListener();
  27674. }
  27675. }
  27676. }
  27677. }
  27678. };
  27679. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27680. // Audio
  27681. /**
  27682. * Gets or sets if audio support is enabled
  27683. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27684. */
  27685. get: function () {
  27686. return this._audioEnabled;
  27687. },
  27688. set: function (value) {
  27689. this._audioEnabled = value;
  27690. if (BABYLON.AudioEngine) {
  27691. if (this._audioEnabled) {
  27692. this._enableAudio();
  27693. }
  27694. else {
  27695. this._disableAudio();
  27696. }
  27697. }
  27698. },
  27699. enumerable: true,
  27700. configurable: true
  27701. });
  27702. Scene.prototype._disableAudio = function () {
  27703. var i;
  27704. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27705. this.mainSoundTrack.soundCollection[i].pause();
  27706. }
  27707. for (i = 0; i < this.soundTracks.length; i++) {
  27708. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27709. this.soundTracks[i].soundCollection[j].pause();
  27710. }
  27711. }
  27712. };
  27713. Scene.prototype._enableAudio = function () {
  27714. var i;
  27715. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27716. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27717. this.mainSoundTrack.soundCollection[i].play();
  27718. }
  27719. }
  27720. for (i = 0; i < this.soundTracks.length; i++) {
  27721. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27722. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27723. this.soundTracks[i].soundCollection[j].play();
  27724. }
  27725. }
  27726. }
  27727. };
  27728. Object.defineProperty(Scene.prototype, "headphone", {
  27729. /**
  27730. * Gets or sets if audio will be output to headphones
  27731. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27732. */
  27733. get: function () {
  27734. return this._headphone;
  27735. },
  27736. set: function (value) {
  27737. this._headphone = value;
  27738. if (BABYLON.AudioEngine) {
  27739. if (this._headphone) {
  27740. this._switchAudioModeForHeadphones();
  27741. }
  27742. else {
  27743. this._switchAudioModeForNormalSpeakers();
  27744. }
  27745. }
  27746. },
  27747. enumerable: true,
  27748. configurable: true
  27749. });
  27750. Scene.prototype._switchAudioModeForHeadphones = function () {
  27751. this.mainSoundTrack.switchPanningModelToHRTF();
  27752. for (var i = 0; i < this.soundTracks.length; i++) {
  27753. this.soundTracks[i].switchPanningModelToHRTF();
  27754. }
  27755. };
  27756. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27757. this.mainSoundTrack.switchPanningModelToEqualPower();
  27758. for (var i = 0; i < this.soundTracks.length; i++) {
  27759. this.soundTracks[i].switchPanningModelToEqualPower();
  27760. }
  27761. };
  27762. /**
  27763. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27764. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27765. * @returns the created depth renderer
  27766. */
  27767. Scene.prototype.enableDepthRenderer = function (camera) {
  27768. camera = camera || this.activeCamera;
  27769. if (!camera) {
  27770. throw "No camera available to enable depth renderer";
  27771. }
  27772. if (!this._depthRenderer[camera.id]) {
  27773. var textureType = 0;
  27774. if (this._engine.getCaps().textureHalfFloatRender) {
  27775. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27776. }
  27777. else if (this._engine.getCaps().textureFloatRender) {
  27778. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27779. }
  27780. else {
  27781. throw "Depth renderer does not support int texture type";
  27782. }
  27783. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27784. }
  27785. return this._depthRenderer[camera.id];
  27786. };
  27787. /**
  27788. * Disables a depth renderer for a given camera
  27789. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27790. */
  27791. Scene.prototype.disableDepthRenderer = function (camera) {
  27792. camera = camera || this.activeCamera;
  27793. if (!camera || !this._depthRenderer[camera.id]) {
  27794. return;
  27795. }
  27796. this._depthRenderer[camera.id].dispose();
  27797. delete this._depthRenderer[camera.id];
  27798. };
  27799. /**
  27800. * Enables a GeometryBufferRender and associates it with the scene
  27801. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27802. * @returns the GeometryBufferRenderer
  27803. */
  27804. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27805. if (ratio === void 0) { ratio = 1; }
  27806. if (this._geometryBufferRenderer) {
  27807. return this._geometryBufferRenderer;
  27808. }
  27809. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27810. if (!this._geometryBufferRenderer.isSupported) {
  27811. this._geometryBufferRenderer = null;
  27812. }
  27813. return this._geometryBufferRenderer;
  27814. };
  27815. /**
  27816. * Disables the GeometryBufferRender associated with the scene
  27817. */
  27818. Scene.prototype.disableGeometryBufferRenderer = function () {
  27819. if (!this._geometryBufferRenderer) {
  27820. return;
  27821. }
  27822. this._geometryBufferRenderer.dispose();
  27823. this._geometryBufferRenderer = null;
  27824. };
  27825. /**
  27826. * Freeze all materials
  27827. * A frozen material will not be updatable but should be faster to render
  27828. */
  27829. Scene.prototype.freezeMaterials = function () {
  27830. for (var i = 0; i < this.materials.length; i++) {
  27831. this.materials[i].freeze();
  27832. }
  27833. };
  27834. /**
  27835. * Unfreeze all materials
  27836. * A frozen material will not be updatable but should be faster to render
  27837. */
  27838. Scene.prototype.unfreezeMaterials = function () {
  27839. for (var i = 0; i < this.materials.length; i++) {
  27840. this.materials[i].unfreeze();
  27841. }
  27842. };
  27843. /**
  27844. * Releases all held ressources
  27845. */
  27846. Scene.prototype.dispose = function () {
  27847. this.beforeRender = null;
  27848. this.afterRender = null;
  27849. this.skeletons = [];
  27850. this.morphTargetManagers = [];
  27851. this.importedMeshesFiles = new Array();
  27852. this.stopAllAnimations();
  27853. this.resetCachedMaterial();
  27854. for (var key in this._depthRenderer) {
  27855. this._depthRenderer[key].dispose();
  27856. }
  27857. if (this._gamepadManager) {
  27858. this._gamepadManager.dispose();
  27859. this._gamepadManager = null;
  27860. }
  27861. // Smart arrays
  27862. if (this.activeCamera) {
  27863. this.activeCamera._activeMeshes.dispose();
  27864. this.activeCamera = null;
  27865. }
  27866. this._activeMeshes.dispose();
  27867. this._renderingManager.dispose();
  27868. this._processedMaterials.dispose();
  27869. this._activeParticleSystems.dispose();
  27870. this._activeSkeletons.dispose();
  27871. this._softwareSkinnedMeshes.dispose();
  27872. this._renderTargets.dispose();
  27873. this._registeredForLateAnimationBindings.dispose();
  27874. if (this._boundingBoxRenderer) {
  27875. this._boundingBoxRenderer.dispose();
  27876. }
  27877. this._meshesForIntersections.dispose();
  27878. this._toBeDisposed.dispose();
  27879. // Abort active requests
  27880. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27881. var request = _a[_i];
  27882. request.abort();
  27883. }
  27884. // Debug layer
  27885. if (this._debugLayer) {
  27886. this._debugLayer.hide();
  27887. }
  27888. // Events
  27889. this.onDisposeObservable.notifyObservers(this);
  27890. this.onDisposeObservable.clear();
  27891. this.onBeforeRenderObservable.clear();
  27892. this.onAfterRenderObservable.clear();
  27893. this.onBeforeRenderTargetsRenderObservable.clear();
  27894. this.onAfterRenderTargetsRenderObservable.clear();
  27895. this.onAfterStepObservable.clear();
  27896. this.onBeforeStepObservable.clear();
  27897. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27898. this.onAfterActiveMeshesEvaluationObservable.clear();
  27899. this.onBeforeParticlesRenderingObservable.clear();
  27900. this.onAfterParticlesRenderingObservable.clear();
  27901. this.onBeforeSpritesRenderingObservable.clear();
  27902. this.onAfterSpritesRenderingObservable.clear();
  27903. this.onBeforeDrawPhaseObservable.clear();
  27904. this.onAfterDrawPhaseObservable.clear();
  27905. this.onBeforePhysicsObservable.clear();
  27906. this.onAfterPhysicsObservable.clear();
  27907. this.onBeforeAnimationsObservable.clear();
  27908. this.onAfterAnimationsObservable.clear();
  27909. this.onDataLoadedObservable.clear();
  27910. this.detachControl();
  27911. // Release sounds & sounds tracks
  27912. if (BABYLON.AudioEngine) {
  27913. this.disposeSounds();
  27914. }
  27915. // VR Helper
  27916. if (this.VRHelper) {
  27917. this.VRHelper.dispose();
  27918. }
  27919. // Detach cameras
  27920. var canvas = this._engine.getRenderingCanvas();
  27921. if (canvas) {
  27922. var index;
  27923. for (index = 0; index < this.cameras.length; index++) {
  27924. this.cameras[index].detachControl(canvas);
  27925. }
  27926. }
  27927. // Release animation groups
  27928. while (this.animationGroups.length) {
  27929. this.animationGroups[0].dispose();
  27930. }
  27931. // Release lights
  27932. while (this.lights.length) {
  27933. this.lights[0].dispose();
  27934. }
  27935. // Release meshes
  27936. while (this.meshes.length) {
  27937. this.meshes[0].dispose(true);
  27938. }
  27939. while (this.transformNodes.length) {
  27940. this.removeTransformNode(this.transformNodes[0]);
  27941. }
  27942. // Release cameras
  27943. while (this.cameras.length) {
  27944. this.cameras[0].dispose();
  27945. }
  27946. // Release materials
  27947. if (this.defaultMaterial) {
  27948. this.defaultMaterial.dispose();
  27949. }
  27950. while (this.multiMaterials.length) {
  27951. this.multiMaterials[0].dispose();
  27952. }
  27953. while (this.materials.length) {
  27954. this.materials[0].dispose();
  27955. }
  27956. // Release particles
  27957. while (this.particleSystems.length) {
  27958. this.particleSystems[0].dispose();
  27959. }
  27960. // Release sprites
  27961. while (this.spriteManagers.length) {
  27962. this.spriteManagers[0].dispose();
  27963. }
  27964. // Release postProcesses
  27965. while (this.postProcesses.length) {
  27966. this.postProcesses[0].dispose();
  27967. }
  27968. // Release layers
  27969. while (this.layers.length) {
  27970. this.layers[0].dispose();
  27971. }
  27972. while (this.effectLayers.length) {
  27973. this.effectLayers[0].dispose();
  27974. }
  27975. // Release textures
  27976. while (this.textures.length) {
  27977. this.textures[0].dispose();
  27978. }
  27979. // Release UBO
  27980. this._sceneUbo.dispose();
  27981. if (this._alternateSceneUbo) {
  27982. this._alternateSceneUbo.dispose();
  27983. }
  27984. // Post-processes
  27985. this.postProcessManager.dispose();
  27986. if (this._postProcessRenderPipelineManager) {
  27987. this._postProcessRenderPipelineManager.dispose();
  27988. }
  27989. // Physics
  27990. if (this._physicsEngine) {
  27991. this.disablePhysicsEngine();
  27992. }
  27993. // Remove from engine
  27994. index = this._engine.scenes.indexOf(this);
  27995. if (index > -1) {
  27996. this._engine.scenes.splice(index, 1);
  27997. }
  27998. this._engine.wipeCaches(true);
  27999. this._isDisposed = true;
  28000. };
  28001. Object.defineProperty(Scene.prototype, "isDisposed", {
  28002. /**
  28003. * Gets if the scene is already disposed
  28004. */
  28005. get: function () {
  28006. return this._isDisposed;
  28007. },
  28008. enumerable: true,
  28009. configurable: true
  28010. });
  28011. /**
  28012. * Releases sounds & soundtracks
  28013. */
  28014. Scene.prototype.disposeSounds = function () {
  28015. if (!this._mainSoundTrack) {
  28016. return;
  28017. }
  28018. this.mainSoundTrack.dispose();
  28019. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28020. this.soundTracks[scIndex].dispose();
  28021. }
  28022. };
  28023. // Octrees
  28024. /**
  28025. * Get the world extend vectors with an optional filter
  28026. *
  28027. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28028. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28029. */
  28030. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28031. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28032. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28033. filterPredicate = filterPredicate || (function () { return true; });
  28034. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28035. mesh.computeWorldMatrix(true);
  28036. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28037. return;
  28038. }
  28039. var boundingInfo = mesh.getBoundingInfo();
  28040. var minBox = boundingInfo.boundingBox.minimumWorld;
  28041. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28042. BABYLON.Tools.CheckExtends(minBox, min, max);
  28043. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28044. });
  28045. return {
  28046. min: min,
  28047. max: max
  28048. };
  28049. };
  28050. /**
  28051. * Creates or updates the octree used to boost selection (picking)
  28052. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28053. * @param maxCapacity defines the maximum capacity per leaf
  28054. * @param maxDepth defines the maximum depth of the octree
  28055. * @returns an octree of AbstractMesh
  28056. */
  28057. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28058. if (maxCapacity === void 0) { maxCapacity = 64; }
  28059. if (maxDepth === void 0) { maxDepth = 2; }
  28060. if (!this._selectionOctree) {
  28061. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28062. }
  28063. var worldExtends = this.getWorldExtends();
  28064. // Update octree
  28065. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28066. return this._selectionOctree;
  28067. };
  28068. // Picking
  28069. /**
  28070. * Creates a ray that can be used to pick in the scene
  28071. * @param x defines the x coordinate of the origin (on-screen)
  28072. * @param y defines the y coordinate of the origin (on-screen)
  28073. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28074. * @param camera defines the camera to use for the picking
  28075. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28076. * @returns a Ray
  28077. */
  28078. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28079. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28080. var result = BABYLON.Ray.Zero();
  28081. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28082. return result;
  28083. };
  28084. /**
  28085. * Creates a ray that can be used to pick in the scene
  28086. * @param x defines the x coordinate of the origin (on-screen)
  28087. * @param y defines the y coordinate of the origin (on-screen)
  28088. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28089. * @param result defines the ray where to store the picking ray
  28090. * @param camera defines the camera to use for the picking
  28091. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28092. * @returns the current scene
  28093. */
  28094. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28095. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28096. var engine = this._engine;
  28097. if (!camera) {
  28098. if (!this.activeCamera)
  28099. throw new Error("Active camera not set");
  28100. camera = this.activeCamera;
  28101. }
  28102. var cameraViewport = camera.viewport;
  28103. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28104. // Moving coordinates to local viewport world
  28105. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28106. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28107. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28108. return this;
  28109. };
  28110. /**
  28111. * Creates a ray that can be used to pick in the scene
  28112. * @param x defines the x coordinate of the origin (on-screen)
  28113. * @param y defines the y coordinate of the origin (on-screen)
  28114. * @param camera defines the camera to use for the picking
  28115. * @returns a Ray
  28116. */
  28117. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28118. var result = BABYLON.Ray.Zero();
  28119. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28120. return result;
  28121. };
  28122. /**
  28123. * Creates a ray that can be used to pick in the scene
  28124. * @param x defines the x coordinate of the origin (on-screen)
  28125. * @param y defines the y coordinate of the origin (on-screen)
  28126. * @param result defines the ray where to store the picking ray
  28127. * @param camera defines the camera to use for the picking
  28128. * @returns the current scene
  28129. */
  28130. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28131. if (!BABYLON.PickingInfo) {
  28132. return this;
  28133. }
  28134. var engine = this._engine;
  28135. if (!camera) {
  28136. if (!this.activeCamera)
  28137. throw new Error("Active camera not set");
  28138. camera = this.activeCamera;
  28139. }
  28140. var cameraViewport = camera.viewport;
  28141. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28142. var identity = BABYLON.Matrix.Identity();
  28143. // Moving coordinates to local viewport world
  28144. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28145. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28146. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28147. return this;
  28148. };
  28149. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28150. if (!BABYLON.PickingInfo) {
  28151. return null;
  28152. }
  28153. var pickingInfo = null;
  28154. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28155. var mesh = this.meshes[meshIndex];
  28156. if (predicate) {
  28157. if (!predicate(mesh)) {
  28158. continue;
  28159. }
  28160. }
  28161. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28162. continue;
  28163. }
  28164. var world = mesh.getWorldMatrix();
  28165. var ray = rayFunction(world);
  28166. var result = mesh.intersects(ray, fastCheck);
  28167. if (!result || !result.hit)
  28168. continue;
  28169. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28170. continue;
  28171. pickingInfo = result;
  28172. if (fastCheck) {
  28173. break;
  28174. }
  28175. }
  28176. return pickingInfo || new BABYLON.PickingInfo();
  28177. };
  28178. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28179. if (!BABYLON.PickingInfo) {
  28180. return null;
  28181. }
  28182. var pickingInfos = new Array();
  28183. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28184. var mesh = this.meshes[meshIndex];
  28185. if (predicate) {
  28186. if (!predicate(mesh)) {
  28187. continue;
  28188. }
  28189. }
  28190. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28191. continue;
  28192. }
  28193. var world = mesh.getWorldMatrix();
  28194. var ray = rayFunction(world);
  28195. var result = mesh.intersects(ray, false);
  28196. if (!result || !result.hit)
  28197. continue;
  28198. pickingInfos.push(result);
  28199. }
  28200. return pickingInfos;
  28201. };
  28202. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28203. if (!BABYLON.PickingInfo) {
  28204. return null;
  28205. }
  28206. var pickingInfo = null;
  28207. if (!camera) {
  28208. if (!this.activeCamera) {
  28209. return null;
  28210. }
  28211. camera = this.activeCamera;
  28212. }
  28213. if (this.spriteManagers.length > 0) {
  28214. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28215. var spriteManager = this.spriteManagers[spriteIndex];
  28216. if (!spriteManager.isPickable) {
  28217. continue;
  28218. }
  28219. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28220. if (!result || !result.hit)
  28221. continue;
  28222. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28223. continue;
  28224. pickingInfo = result;
  28225. if (fastCheck) {
  28226. break;
  28227. }
  28228. }
  28229. }
  28230. return pickingInfo || new BABYLON.PickingInfo();
  28231. };
  28232. /** Launch a ray to try to pick a mesh in the scene
  28233. * @param x position on screen
  28234. * @param y position on screen
  28235. * @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
  28236. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28237. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28238. * @returns a PickingInfo
  28239. */
  28240. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28241. var _this = this;
  28242. if (!BABYLON.PickingInfo) {
  28243. return null;
  28244. }
  28245. return this._internalPick(function (world) {
  28246. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28247. return _this._tempPickingRay;
  28248. }, predicate, fastCheck);
  28249. };
  28250. /** Launch a ray to try to pick a sprite in the scene
  28251. * @param x position on screen
  28252. * @param y position on screen
  28253. * @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
  28254. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28255. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28256. * @returns a PickingInfo
  28257. */
  28258. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28259. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28260. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28261. };
  28262. /** Use the given ray to pick a mesh in the scene
  28263. * @param ray The ray to use to pick meshes
  28264. * @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
  28265. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28266. * @returns a PickingInfo
  28267. */
  28268. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28269. var _this = this;
  28270. return this._internalPick(function (world) {
  28271. if (!_this._pickWithRayInverseMatrix) {
  28272. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28273. }
  28274. world.invertToRef(_this._pickWithRayInverseMatrix);
  28275. if (!_this._cachedRayForTransform) {
  28276. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28277. }
  28278. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28279. return _this._cachedRayForTransform;
  28280. }, predicate, fastCheck);
  28281. };
  28282. /**
  28283. * Launch a ray to try to pick a mesh in the scene
  28284. * @param x X position on screen
  28285. * @param y Y position on screen
  28286. * @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
  28287. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28288. * @returns an array of PickingInfo
  28289. */
  28290. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28291. var _this = this;
  28292. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28293. };
  28294. /**
  28295. * Launch a ray to try to pick a mesh in the scene
  28296. * @param ray Ray to use
  28297. * @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
  28298. * @returns an array of PickingInfo
  28299. */
  28300. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28301. var _this = this;
  28302. return this._internalMultiPick(function (world) {
  28303. if (!_this._pickWithRayInverseMatrix) {
  28304. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28305. }
  28306. world.invertToRef(_this._pickWithRayInverseMatrix);
  28307. if (!_this._cachedRayForTransform) {
  28308. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28309. }
  28310. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28311. return _this._cachedRayForTransform;
  28312. }, predicate);
  28313. };
  28314. /**
  28315. * Force the value of meshUnderPointer
  28316. * @param mesh defines the mesh to use
  28317. */
  28318. Scene.prototype.setPointerOverMesh = function (mesh) {
  28319. if (this._pointerOverMesh === mesh) {
  28320. return;
  28321. }
  28322. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28323. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28324. }
  28325. this._pointerOverMesh = mesh;
  28326. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28327. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28328. }
  28329. };
  28330. /**
  28331. * Gets the mesh under the pointer
  28332. * @returns a Mesh or null if no mesh is under the pointer
  28333. */
  28334. Scene.prototype.getPointerOverMesh = function () {
  28335. return this._pointerOverMesh;
  28336. };
  28337. /**
  28338. * Force the sprite under the pointer
  28339. * @param sprite defines the sprite to use
  28340. */
  28341. Scene.prototype.setPointerOverSprite = function (sprite) {
  28342. if (this._pointerOverSprite === sprite) {
  28343. return;
  28344. }
  28345. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28346. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28347. }
  28348. this._pointerOverSprite = sprite;
  28349. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28350. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28351. }
  28352. };
  28353. /**
  28354. * Gets the sprite under the pointer
  28355. * @returns a Sprite or null if no sprite is under the pointer
  28356. */
  28357. Scene.prototype.getPointerOverSprite = function () {
  28358. return this._pointerOverSprite;
  28359. };
  28360. // Physics
  28361. /**
  28362. * Gets the current physics engine
  28363. * @returns a PhysicsEngine or null if none attached
  28364. */
  28365. Scene.prototype.getPhysicsEngine = function () {
  28366. return this._physicsEngine;
  28367. };
  28368. /**
  28369. * Enables physics to the current scene
  28370. * @param gravity defines the scene's gravity for the physics engine
  28371. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28372. * @return a boolean indicating if the physics engine was initialized
  28373. */
  28374. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28375. if (gravity === void 0) { gravity = null; }
  28376. if (this._physicsEngine) {
  28377. return true;
  28378. }
  28379. try {
  28380. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28381. return true;
  28382. }
  28383. catch (e) {
  28384. BABYLON.Tools.Error(e.message);
  28385. return false;
  28386. }
  28387. };
  28388. /**
  28389. * Disables and disposes the physics engine associated with the scene
  28390. */
  28391. Scene.prototype.disablePhysicsEngine = function () {
  28392. if (!this._physicsEngine) {
  28393. return;
  28394. }
  28395. this._physicsEngine.dispose();
  28396. this._physicsEngine = null;
  28397. };
  28398. /**
  28399. * Gets a boolean indicating if there is an active physics engine
  28400. * @returns a boolean indicating if there is an active physics engine
  28401. */
  28402. Scene.prototype.isPhysicsEnabled = function () {
  28403. return this._physicsEngine !== undefined;
  28404. };
  28405. /**
  28406. * Deletes a physics compound impostor
  28407. * @param compound defines the compound to delete
  28408. */
  28409. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28410. var mesh = compound.parts[0].mesh;
  28411. if (mesh.physicsImpostor) {
  28412. mesh.physicsImpostor.dispose( /*true*/);
  28413. mesh.physicsImpostor = null;
  28414. }
  28415. };
  28416. // Misc.
  28417. /** @hidden */
  28418. Scene.prototype._rebuildGeometries = function () {
  28419. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28420. var geometry = _a[_i];
  28421. geometry._rebuild();
  28422. }
  28423. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28424. var mesh = _c[_b];
  28425. mesh._rebuild();
  28426. }
  28427. if (this.postProcessManager) {
  28428. this.postProcessManager._rebuild();
  28429. }
  28430. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28431. var layer = _e[_d];
  28432. layer._rebuild();
  28433. }
  28434. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28435. var effectLayer = _g[_f];
  28436. effectLayer._rebuild();
  28437. }
  28438. if (this._boundingBoxRenderer) {
  28439. this._boundingBoxRenderer._rebuild();
  28440. }
  28441. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28442. var system = _j[_h];
  28443. system.rebuild();
  28444. }
  28445. if (this._postProcessRenderPipelineManager) {
  28446. this._postProcessRenderPipelineManager._rebuild();
  28447. }
  28448. };
  28449. /** @hidden */
  28450. Scene.prototype._rebuildTextures = function () {
  28451. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28452. var texture = _a[_i];
  28453. texture._rebuild();
  28454. }
  28455. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28456. };
  28457. /**
  28458. * Creates a default light for the scene.
  28459. * @param replace Whether to replace the existing lights in the scene.
  28460. */
  28461. Scene.prototype.createDefaultLight = function (replace) {
  28462. if (replace === void 0) { replace = false; }
  28463. // Dispose existing light in replace mode.
  28464. if (replace) {
  28465. if (this.lights) {
  28466. for (var i = 0; i < this.lights.length; i++) {
  28467. this.lights[i].dispose();
  28468. }
  28469. }
  28470. }
  28471. // Light
  28472. if (this.lights.length === 0) {
  28473. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28474. }
  28475. };
  28476. /**
  28477. * Creates a default camera for the scene.
  28478. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28479. * @param replace Whether to replace the existing active camera in the scene.
  28480. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28481. */
  28482. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28483. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28484. if (replace === void 0) { replace = false; }
  28485. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28486. // Dispose existing camera in replace mode.
  28487. if (replace) {
  28488. if (this.activeCamera) {
  28489. this.activeCamera.dispose();
  28490. this.activeCamera = null;
  28491. }
  28492. }
  28493. // Camera
  28494. if (!this.activeCamera) {
  28495. var worldExtends = this.getWorldExtends();
  28496. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28497. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28498. var camera;
  28499. var radius = worldSize.length() * 1.5;
  28500. // empty scene scenario!
  28501. if (!isFinite(radius)) {
  28502. radius = 1;
  28503. worldCenter.copyFromFloats(0, 0, 0);
  28504. }
  28505. if (createArcRotateCamera) {
  28506. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28507. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28508. arcRotateCamera.wheelPrecision = 100 / radius;
  28509. camera = arcRotateCamera;
  28510. }
  28511. else {
  28512. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28513. freeCamera.setTarget(worldCenter);
  28514. camera = freeCamera;
  28515. }
  28516. camera.minZ = radius * 0.01;
  28517. camera.maxZ = radius * 1000;
  28518. camera.speed = radius * 0.2;
  28519. this.activeCamera = camera;
  28520. var canvas = this.getEngine().getRenderingCanvas();
  28521. if (attachCameraControls && canvas) {
  28522. camera.attachControl(canvas);
  28523. }
  28524. }
  28525. };
  28526. /**
  28527. * Creates a default camera and a default light
  28528. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28529. * @param replace defines if the camera and/or light will replace the existing ones
  28530. * @param attachCameraControls defines if attachControl will be called on the new camera
  28531. */
  28532. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28533. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28534. if (replace === void 0) { replace = false; }
  28535. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28536. this.createDefaultLight(replace);
  28537. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28538. };
  28539. /**
  28540. * Creates a new sky box
  28541. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28542. * @param environmentTexture defines the texture to use as environment texture
  28543. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28544. * @param scale defines the overall scale of the skybox
  28545. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28546. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28547. * @returns a new mesh holding the sky box
  28548. */
  28549. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28550. if (pbr === void 0) { pbr = false; }
  28551. if (scale === void 0) { scale = 1000; }
  28552. if (blur === void 0) { blur = 0; }
  28553. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28554. if (!environmentTexture) {
  28555. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28556. return null;
  28557. }
  28558. if (setGlobalEnvTexture) {
  28559. if (environmentTexture) {
  28560. this.environmentTexture = environmentTexture;
  28561. }
  28562. }
  28563. // Skybox
  28564. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28565. if (pbr) {
  28566. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28567. hdrSkyboxMaterial.backFaceCulling = false;
  28568. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28569. if (hdrSkyboxMaterial.reflectionTexture) {
  28570. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28571. }
  28572. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28573. hdrSkyboxMaterial.disableLighting = true;
  28574. hdrSkyboxMaterial.twoSidedLighting = true;
  28575. hdrSkybox.infiniteDistance = true;
  28576. hdrSkybox.material = hdrSkyboxMaterial;
  28577. }
  28578. else {
  28579. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28580. skyboxMaterial.backFaceCulling = false;
  28581. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28582. if (skyboxMaterial.reflectionTexture) {
  28583. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28584. }
  28585. skyboxMaterial.disableLighting = true;
  28586. hdrSkybox.infiniteDistance = true;
  28587. hdrSkybox.material = skyboxMaterial;
  28588. }
  28589. return hdrSkybox;
  28590. };
  28591. /**
  28592. * Creates a new environment
  28593. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28594. * @param options defines the options you can use to configure the environment
  28595. * @returns the new EnvironmentHelper
  28596. */
  28597. Scene.prototype.createDefaultEnvironment = function (options) {
  28598. if (BABYLON.EnvironmentHelper) {
  28599. return new BABYLON.EnvironmentHelper(options, this);
  28600. }
  28601. return null;
  28602. };
  28603. /**
  28604. * Creates a new VREXperienceHelper
  28605. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28606. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28607. * @returns a new VREXperienceHelper
  28608. */
  28609. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28610. if (webVROptions === void 0) { webVROptions = {}; }
  28611. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28612. };
  28613. // Tags
  28614. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28615. if (tagsQuery === undefined) {
  28616. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28617. return list;
  28618. }
  28619. var listByTags = [];
  28620. forEach = forEach || (function (item) { return; });
  28621. for (var i in list) {
  28622. var item = list[i];
  28623. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28624. listByTags.push(item);
  28625. forEach(item);
  28626. }
  28627. }
  28628. return listByTags;
  28629. };
  28630. /**
  28631. * Get a list of meshes by tags
  28632. * @param tagsQuery defines the tags query to use
  28633. * @param forEach defines a predicate used to filter results
  28634. * @returns an array of Mesh
  28635. */
  28636. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28637. return this._getByTags(this.meshes, tagsQuery, forEach);
  28638. };
  28639. /**
  28640. * Get a list of cameras by tags
  28641. * @param tagsQuery defines the tags query to use
  28642. * @param forEach defines a predicate used to filter results
  28643. * @returns an array of Camera
  28644. */
  28645. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28646. return this._getByTags(this.cameras, tagsQuery, forEach);
  28647. };
  28648. /**
  28649. * Get a list of lights by tags
  28650. * @param tagsQuery defines the tags query to use
  28651. * @param forEach defines a predicate used to filter results
  28652. * @returns an array of Light
  28653. */
  28654. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28655. return this._getByTags(this.lights, tagsQuery, forEach);
  28656. };
  28657. /**
  28658. * Get a list of materials by tags
  28659. * @param tagsQuery defines the tags query to use
  28660. * @param forEach defines a predicate used to filter results
  28661. * @returns an array of Material
  28662. */
  28663. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28664. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28665. };
  28666. /**
  28667. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28668. * This allowed control for front to back rendering or reversly depending of the special needs.
  28669. *
  28670. * @param renderingGroupId The rendering group id corresponding to its index
  28671. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28672. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28673. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28674. */
  28675. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28676. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28677. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28678. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28679. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28680. };
  28681. /**
  28682. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28683. *
  28684. * @param renderingGroupId The rendering group id corresponding to its index
  28685. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28686. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28687. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28688. */
  28689. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28690. if (depth === void 0) { depth = true; }
  28691. if (stencil === void 0) { stencil = true; }
  28692. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28693. };
  28694. /**
  28695. * Will flag all materials as dirty to trigger new shader compilation
  28696. * @param flag defines the flag used to specify which material part must be marked as dirty
  28697. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28698. */
  28699. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28700. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28701. var material = _a[_i];
  28702. if (predicate && !predicate(material)) {
  28703. continue;
  28704. }
  28705. material.markAsDirty(flag);
  28706. }
  28707. };
  28708. /** @hidden */
  28709. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28710. var _this = this;
  28711. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28712. this._activeRequests.push(request);
  28713. request.onCompleteObservable.add(function (request) {
  28714. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28715. });
  28716. return request;
  28717. };
  28718. /** @hidden */
  28719. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28720. var _this = this;
  28721. return new Promise(function (resolve, reject) {
  28722. _this._loadFile(url, function (data) {
  28723. resolve(data);
  28724. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28725. reject(exception);
  28726. });
  28727. });
  28728. };
  28729. // Statics
  28730. Scene._FOGMODE_NONE = 0;
  28731. Scene._FOGMODE_EXP = 1;
  28732. Scene._FOGMODE_EXP2 = 2;
  28733. Scene._FOGMODE_LINEAR = 3;
  28734. Scene._uniqueIdCounter = 0;
  28735. /**
  28736. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28737. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28738. */
  28739. Scene.MinDeltaTime = 1.0;
  28740. /**
  28741. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28742. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28743. */
  28744. Scene.MaxDeltaTime = 1000.0;
  28745. /** The distance in pixel that you have to move to prevent some events */
  28746. Scene.DragMovementThreshold = 10; // in pixels
  28747. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28748. Scene.LongPressDelay = 500; // in milliseconds
  28749. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28750. Scene.DoubleClickDelay = 300; // in milliseconds
  28751. /** If you need to check double click without raising a single click at first click, enable this flag */
  28752. Scene.ExclusiveDoubleClickMode = false;
  28753. return Scene;
  28754. }());
  28755. BABYLON.Scene = Scene;
  28756. })(BABYLON || (BABYLON = {}));
  28757. //# sourceMappingURL=babylon.scene.js.map
  28758. var BABYLON;
  28759. (function (BABYLON) {
  28760. /**
  28761. * Set of assets to keep when moving a scene into an asset container.
  28762. */
  28763. var KeepAssets = /** @class */ (function () {
  28764. function KeepAssets() {
  28765. /**
  28766. * Cameras to keep.
  28767. */
  28768. this.cameras = new Array();
  28769. /**
  28770. * Lights to keep.
  28771. */
  28772. this.lights = new Array();
  28773. /**
  28774. * Meshes to keep.
  28775. */
  28776. this.meshes = new Array();
  28777. /**
  28778. * Skeletons to keep.
  28779. */
  28780. this.skeletons = new Array();
  28781. /**
  28782. * ParticleSystems to keep.
  28783. */
  28784. this.particleSystems = new Array();
  28785. /**
  28786. * Animations to keep.
  28787. */
  28788. this.animations = new Array();
  28789. /**
  28790. * AnimationGroups to keep.
  28791. */
  28792. this.animationGroups = new Array();
  28793. /**
  28794. * MultiMaterials to keep.
  28795. */
  28796. this.multiMaterials = new Array();
  28797. /**
  28798. * Materials to keep.
  28799. */
  28800. this.materials = new Array();
  28801. /**
  28802. * MorphTargetManagers to keep.
  28803. */
  28804. this.morphTargetManagers = new Array();
  28805. /**
  28806. * Geometries to keep.
  28807. */
  28808. this.geometries = new Array();
  28809. /**
  28810. * TransformNodes to keep.
  28811. */
  28812. this.transformNodes = new Array();
  28813. /**
  28814. * LensFlareSystems to keep.
  28815. */
  28816. this.lensFlareSystems = new Array();
  28817. /**
  28818. * ShadowGenerators to keep.
  28819. */
  28820. this.shadowGenerators = new Array();
  28821. /**
  28822. * ActionManagers to keep.
  28823. */
  28824. this.actionManagers = new Array();
  28825. /**
  28826. * Sounds to keep.
  28827. */
  28828. this.sounds = new Array();
  28829. /**
  28830. * Textures to keep.
  28831. */
  28832. this.textures = new Array();
  28833. /**
  28834. * Effect layers to keep.
  28835. */
  28836. this.effectLayers = new Array();
  28837. }
  28838. return KeepAssets;
  28839. }());
  28840. BABYLON.KeepAssets = KeepAssets;
  28841. /**
  28842. * Container with a set of assets that can be added or removed from a scene.
  28843. */
  28844. var AssetContainer = /** @class */ (function () {
  28845. /**
  28846. * Instantiates an AssetContainer.
  28847. * @param scene The scene the AssetContainer belongs to.
  28848. */
  28849. function AssetContainer(scene) {
  28850. // Objects
  28851. /**
  28852. * Cameras populated in the container.
  28853. */
  28854. this.cameras = new Array();
  28855. /**
  28856. * Lights populated in the container.
  28857. */
  28858. this.lights = new Array();
  28859. /**
  28860. * Meshes populated in the container.
  28861. */
  28862. this.meshes = new Array();
  28863. /**
  28864. * Skeletons populated in the container.
  28865. */
  28866. this.skeletons = new Array();
  28867. /**
  28868. * ParticleSystems populated in the container.
  28869. */
  28870. this.particleSystems = new Array();
  28871. /**
  28872. * Animations populated in the container.
  28873. */
  28874. this.animations = new Array();
  28875. /**
  28876. * AnimationGroups populated in the container.
  28877. */
  28878. this.animationGroups = new Array();
  28879. /**
  28880. * MultiMaterials populated in the container.
  28881. */
  28882. this.multiMaterials = new Array();
  28883. /**
  28884. * Materials populated in the container.
  28885. */
  28886. this.materials = new Array();
  28887. /**
  28888. * MorphTargetManagers populated in the container.
  28889. */
  28890. this.morphTargetManagers = new Array();
  28891. /**
  28892. * Geometries populated in the container.
  28893. */
  28894. this.geometries = new Array();
  28895. /**
  28896. * TransformNodes populated in the container.
  28897. */
  28898. this.transformNodes = new Array();
  28899. /**
  28900. * LensFlareSystems populated in the container.
  28901. */
  28902. this.lensFlareSystems = new Array();
  28903. /**
  28904. * ShadowGenerators populated in the container.
  28905. */
  28906. this.shadowGenerators = new Array();
  28907. /**
  28908. * ActionManagers populated in the container.
  28909. */
  28910. this.actionManagers = new Array();
  28911. /**
  28912. * Sounds populated in the container.
  28913. */
  28914. this.sounds = new Array();
  28915. /**
  28916. * Textures populated in the container.
  28917. */
  28918. this.textures = new Array();
  28919. /**
  28920. * Effect layers populated in the container.
  28921. */
  28922. this.effectLayers = new Array();
  28923. this.scene = scene;
  28924. }
  28925. /**
  28926. * Adds all the assets from the container to the scene.
  28927. */
  28928. AssetContainer.prototype.addAllToScene = function () {
  28929. var _this = this;
  28930. this.cameras.forEach(function (o) {
  28931. _this.scene.addCamera(o);
  28932. });
  28933. this.lights.forEach(function (o) {
  28934. _this.scene.addLight(o);
  28935. });
  28936. this.meshes.forEach(function (o) {
  28937. _this.scene.addMesh(o);
  28938. });
  28939. this.skeletons.forEach(function (o) {
  28940. _this.scene.addSkeleton(o);
  28941. });
  28942. this.particleSystems.forEach(function (o) {
  28943. _this.scene.addParticleSystem(o);
  28944. });
  28945. this.animations.forEach(function (o) {
  28946. _this.scene.addAnimation(o);
  28947. });
  28948. this.animationGroups.forEach(function (o) {
  28949. _this.scene.addAnimationGroup(o);
  28950. });
  28951. this.multiMaterials.forEach(function (o) {
  28952. _this.scene.addMultiMaterial(o);
  28953. });
  28954. this.materials.forEach(function (o) {
  28955. _this.scene.addMaterial(o);
  28956. });
  28957. this.morphTargetManagers.forEach(function (o) {
  28958. _this.scene.addMorphTargetManager(o);
  28959. });
  28960. this.geometries.forEach(function (o) {
  28961. _this.scene.addGeometry(o);
  28962. });
  28963. this.transformNodes.forEach(function (o) {
  28964. _this.scene.addTransformNode(o);
  28965. });
  28966. this.lensFlareSystems.forEach(function (o) {
  28967. _this.scene.addLensFlareSystem(o);
  28968. });
  28969. this.actionManagers.forEach(function (o) {
  28970. _this.scene.addActionManager(o);
  28971. });
  28972. this.sounds.forEach(function (o) {
  28973. o.play();
  28974. o.autoplay = true;
  28975. _this.scene.mainSoundTrack.AddSound(o);
  28976. });
  28977. this.textures.forEach(function (o) {
  28978. _this.scene.addTexture(o);
  28979. });
  28980. this.effectLayers.forEach(function (o) {
  28981. _this.scene.addEffectLayer(o);
  28982. });
  28983. };
  28984. /**
  28985. * Removes all the assets in the container from the scene
  28986. */
  28987. AssetContainer.prototype.removeAllFromScene = function () {
  28988. var _this = this;
  28989. this.cameras.forEach(function (o) {
  28990. _this.scene.removeCamera(o);
  28991. });
  28992. this.lights.forEach(function (o) {
  28993. _this.scene.removeLight(o);
  28994. });
  28995. this.meshes.forEach(function (o) {
  28996. _this.scene.removeMesh(o);
  28997. });
  28998. this.skeletons.forEach(function (o) {
  28999. _this.scene.removeSkeleton(o);
  29000. });
  29001. this.particleSystems.forEach(function (o) {
  29002. _this.scene.removeParticleSystem(o);
  29003. });
  29004. this.animations.forEach(function (o) {
  29005. _this.scene.removeAnimation(o);
  29006. });
  29007. this.animationGroups.forEach(function (o) {
  29008. _this.scene.removeAnimationGroup(o);
  29009. });
  29010. this.multiMaterials.forEach(function (o) {
  29011. _this.scene.removeMultiMaterial(o);
  29012. });
  29013. this.materials.forEach(function (o) {
  29014. _this.scene.removeMaterial(o);
  29015. });
  29016. this.morphTargetManagers.forEach(function (o) {
  29017. _this.scene.removeMorphTargetManager(o);
  29018. });
  29019. this.geometries.forEach(function (o) {
  29020. _this.scene.removeGeometry(o);
  29021. });
  29022. this.transformNodes.forEach(function (o) {
  29023. _this.scene.removeTransformNode(o);
  29024. });
  29025. this.lensFlareSystems.forEach(function (o) {
  29026. _this.scene.removeLensFlareSystem(o);
  29027. });
  29028. this.actionManagers.forEach(function (o) {
  29029. _this.scene.removeActionManager(o);
  29030. });
  29031. this.sounds.forEach(function (o) {
  29032. o.stop();
  29033. o.autoplay = false;
  29034. _this.scene.mainSoundTrack.RemoveSound(o);
  29035. });
  29036. this.textures.forEach(function (o) {
  29037. _this.scene.removeTexture(o);
  29038. });
  29039. this.effectLayers.forEach(function (o) {
  29040. _this.scene.removeEffectLayer(o);
  29041. });
  29042. };
  29043. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29044. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29045. var asset = sourceAssets_1[_i];
  29046. var move = true;
  29047. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29048. var keepAsset = keepAssets_1[_a];
  29049. if (asset === keepAsset) {
  29050. move = false;
  29051. break;
  29052. }
  29053. }
  29054. if (move) {
  29055. targetAssets.push(asset);
  29056. }
  29057. }
  29058. };
  29059. /**
  29060. * Removes all the assets contained in the scene and adds them to the container.
  29061. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29062. */
  29063. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29064. if (keepAssets === undefined) {
  29065. keepAssets = new KeepAssets();
  29066. }
  29067. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29068. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29069. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29070. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29071. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29072. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29073. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29074. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29075. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29076. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29077. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29078. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29079. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29080. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29081. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29082. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29083. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29084. this.removeAllFromScene();
  29085. };
  29086. return AssetContainer;
  29087. }());
  29088. BABYLON.AssetContainer = AssetContainer;
  29089. })(BABYLON || (BABYLON = {}));
  29090. //# sourceMappingURL=babylon.assetContainer.js.map
  29091. var BABYLON;
  29092. (function (BABYLON) {
  29093. var Buffer = /** @class */ (function () {
  29094. /**
  29095. * Constructor
  29096. * @param engine the engine
  29097. * @param data the data to use for this buffer
  29098. * @param updatable whether the data is updatable
  29099. * @param stride the stride (optional)
  29100. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29101. * @param instanced whether the buffer is instanced (optional)
  29102. * @param useBytes set to true if the stride in in bytes (optional)
  29103. */
  29104. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29105. if (stride === void 0) { stride = 0; }
  29106. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29107. if (instanced === void 0) { instanced = false; }
  29108. if (useBytes === void 0) { useBytes = false; }
  29109. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29110. this._engine = engine.getScene().getEngine();
  29111. }
  29112. else {
  29113. this._engine = engine;
  29114. }
  29115. this._updatable = updatable;
  29116. this._instanced = instanced;
  29117. this._data = data;
  29118. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29119. if (!postponeInternalCreation) { // by default
  29120. this.create();
  29121. }
  29122. }
  29123. /**
  29124. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29125. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29126. * @param offset defines offset in the buffer (0 by default)
  29127. * @param size defines the size in floats of attributes (position is 3 for instance)
  29128. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29129. * @param instanced defines if the vertex buffer contains indexed data
  29130. * @param useBytes defines if the offset and stride are in bytes
  29131. * @returns the new vertex buffer
  29132. */
  29133. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29134. if (useBytes === void 0) { useBytes = false; }
  29135. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29136. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29137. // a lot of these parameters are ignored as they are overriden by the buffer
  29138. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29139. };
  29140. // Properties
  29141. Buffer.prototype.isUpdatable = function () {
  29142. return this._updatable;
  29143. };
  29144. Buffer.prototype.getData = function () {
  29145. return this._data;
  29146. };
  29147. Buffer.prototype.getBuffer = function () {
  29148. return this._buffer;
  29149. };
  29150. /**
  29151. * Gets the stride in float32 units (i.e. byte stride / 4).
  29152. * May not be an integer if the byte stride is not divisible by 4.
  29153. * DEPRECATED. Use byteStride instead.
  29154. * @returns the stride in float32 units
  29155. */
  29156. Buffer.prototype.getStrideSize = function () {
  29157. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29158. };
  29159. // Methods
  29160. Buffer.prototype.create = function (data) {
  29161. if (data === void 0) { data = null; }
  29162. if (!data && this._buffer) {
  29163. return; // nothing to do
  29164. }
  29165. data = data || this._data;
  29166. if (!data) {
  29167. return;
  29168. }
  29169. if (!this._buffer) { // create buffer
  29170. if (this._updatable) {
  29171. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29172. this._data = data;
  29173. }
  29174. else {
  29175. this._buffer = this._engine.createVertexBuffer(data);
  29176. }
  29177. }
  29178. else if (this._updatable) { // update buffer
  29179. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29180. this._data = data;
  29181. }
  29182. };
  29183. Buffer.prototype._rebuild = function () {
  29184. this._buffer = null;
  29185. this.create(this._data);
  29186. };
  29187. Buffer.prototype.update = function (data) {
  29188. this.create(data);
  29189. };
  29190. /**
  29191. * Updates the data directly.
  29192. * @param data the new data
  29193. * @param offset the new offset
  29194. * @param vertexCount the vertex count (optional)
  29195. * @param useBytes set to true if the offset is in bytes
  29196. */
  29197. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29198. if (useBytes === void 0) { useBytes = false; }
  29199. if (!this._buffer) {
  29200. return;
  29201. }
  29202. if (this._updatable) { // update buffer
  29203. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29204. this._data = null;
  29205. }
  29206. };
  29207. Buffer.prototype.dispose = function () {
  29208. if (!this._buffer) {
  29209. return;
  29210. }
  29211. if (this._engine._releaseBuffer(this._buffer)) {
  29212. this._buffer = null;
  29213. }
  29214. };
  29215. return Buffer;
  29216. }());
  29217. BABYLON.Buffer = Buffer;
  29218. })(BABYLON || (BABYLON = {}));
  29219. //# sourceMappingURL=babylon.buffer.js.map
  29220. var BABYLON;
  29221. (function (BABYLON) {
  29222. var VertexBuffer = /** @class */ (function () {
  29223. /**
  29224. * Constructor
  29225. * @param engine the engine
  29226. * @param data the data to use for this vertex buffer
  29227. * @param kind the vertex buffer kind
  29228. * @param updatable whether the data is updatable
  29229. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29230. * @param stride the stride (optional)
  29231. * @param instanced whether the buffer is instanced (optional)
  29232. * @param offset the offset of the data (optional)
  29233. * @param size the number of components (optional)
  29234. * @param type the type of the component (optional)
  29235. * @param normalized whether the data contains normalized data (optional)
  29236. * @param useBytes set to true if stride and offset are in bytes (optional)
  29237. */
  29238. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29239. if (normalized === void 0) { normalized = false; }
  29240. if (useBytes === void 0) { useBytes = false; }
  29241. if (data instanceof BABYLON.Buffer) {
  29242. this._buffer = data;
  29243. this._ownsBuffer = false;
  29244. }
  29245. else {
  29246. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29247. this._ownsBuffer = true;
  29248. }
  29249. this._kind = kind;
  29250. if (type == undefined) {
  29251. var data_1 = this.getData();
  29252. this.type = VertexBuffer.FLOAT;
  29253. if (data_1 instanceof Int8Array)
  29254. this.type = VertexBuffer.BYTE;
  29255. else if (data_1 instanceof Uint8Array)
  29256. this.type = VertexBuffer.UNSIGNED_BYTE;
  29257. else if (data_1 instanceof Int16Array)
  29258. this.type = VertexBuffer.SHORT;
  29259. else if (data_1 instanceof Uint16Array)
  29260. this.type = VertexBuffer.UNSIGNED_SHORT;
  29261. else if (data_1 instanceof Int32Array)
  29262. this.type = VertexBuffer.INT;
  29263. else if (data_1 instanceof Uint32Array)
  29264. this.type = VertexBuffer.UNSIGNED_INT;
  29265. }
  29266. else {
  29267. this.type = type;
  29268. }
  29269. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29270. if (useBytes) {
  29271. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29272. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29273. this.byteOffset = offset || 0;
  29274. }
  29275. else {
  29276. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29277. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29278. this.byteOffset = (offset || 0) * typeByteLength;
  29279. }
  29280. this.normalized = normalized;
  29281. this._instanced = instanced !== undefined ? instanced : false;
  29282. this._instanceDivisor = instanced ? 1 : 0;
  29283. }
  29284. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29285. /**
  29286. * Gets or sets the instance divisor when in instanced mode
  29287. */
  29288. get: function () {
  29289. return this._instanceDivisor;
  29290. },
  29291. set: function (value) {
  29292. this._instanceDivisor = value;
  29293. if (value == 0) {
  29294. this._instanced = false;
  29295. }
  29296. else {
  29297. this._instanced = true;
  29298. }
  29299. },
  29300. enumerable: true,
  29301. configurable: true
  29302. });
  29303. VertexBuffer.prototype._rebuild = function () {
  29304. if (!this._buffer) {
  29305. return;
  29306. }
  29307. this._buffer._rebuild();
  29308. };
  29309. /**
  29310. * Returns the kind of the VertexBuffer (string).
  29311. */
  29312. VertexBuffer.prototype.getKind = function () {
  29313. return this._kind;
  29314. };
  29315. // Properties
  29316. /**
  29317. * Boolean : is the VertexBuffer updatable ?
  29318. */
  29319. VertexBuffer.prototype.isUpdatable = function () {
  29320. return this._buffer.isUpdatable();
  29321. };
  29322. /**
  29323. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29324. */
  29325. VertexBuffer.prototype.getData = function () {
  29326. return this._buffer.getData();
  29327. };
  29328. /**
  29329. * Returns the WebGLBuffer associated to the VertexBuffer.
  29330. */
  29331. VertexBuffer.prototype.getBuffer = function () {
  29332. return this._buffer.getBuffer();
  29333. };
  29334. /**
  29335. * Returns the stride as a multiple of the type byte length.
  29336. * DEPRECATED. Use byteStride instead.
  29337. */
  29338. VertexBuffer.prototype.getStrideSize = function () {
  29339. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29340. };
  29341. /**
  29342. * Returns the offset as a multiple of the type byte length.
  29343. * DEPRECATED. Use byteOffset instead.
  29344. */
  29345. VertexBuffer.prototype.getOffset = function () {
  29346. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29347. };
  29348. /**
  29349. * Returns the number of components per vertex attribute (integer).
  29350. */
  29351. VertexBuffer.prototype.getSize = function () {
  29352. return this._size;
  29353. };
  29354. /**
  29355. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29356. */
  29357. VertexBuffer.prototype.getIsInstanced = function () {
  29358. return this._instanced;
  29359. };
  29360. /**
  29361. * Returns the instancing divisor, zero for non-instanced (integer).
  29362. */
  29363. VertexBuffer.prototype.getInstanceDivisor = function () {
  29364. return this._instanceDivisor;
  29365. };
  29366. // Methods
  29367. /**
  29368. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29369. * Returns the created WebGLBuffer.
  29370. */
  29371. VertexBuffer.prototype.create = function (data) {
  29372. return this._buffer.create(data);
  29373. };
  29374. /**
  29375. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29376. * This function will create a new buffer if the current one is not updatable
  29377. * Returns the updated WebGLBuffer.
  29378. */
  29379. VertexBuffer.prototype.update = function (data) {
  29380. return this._buffer.update(data);
  29381. };
  29382. /**
  29383. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29384. * Returns the directly updated WebGLBuffer.
  29385. * @param data the new data
  29386. * @param offset the new offset
  29387. * @param useBytes set to true if the offset is in bytes
  29388. */
  29389. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29390. if (useBytes === void 0) { useBytes = false; }
  29391. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29392. };
  29393. /**
  29394. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29395. */
  29396. VertexBuffer.prototype.dispose = function () {
  29397. if (this._ownsBuffer) {
  29398. this._buffer.dispose();
  29399. }
  29400. };
  29401. /**
  29402. * Enumerates each value of this vertex buffer as numbers.
  29403. * @param count the number of values to enumerate
  29404. * @param callback the callback function called for each value
  29405. */
  29406. VertexBuffer.prototype.forEach = function (count, callback) {
  29407. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29408. };
  29409. Object.defineProperty(VertexBuffer, "PositionKind", {
  29410. get: function () {
  29411. return VertexBuffer._PositionKind;
  29412. },
  29413. enumerable: true,
  29414. configurable: true
  29415. });
  29416. Object.defineProperty(VertexBuffer, "NormalKind", {
  29417. get: function () {
  29418. return VertexBuffer._NormalKind;
  29419. },
  29420. enumerable: true,
  29421. configurable: true
  29422. });
  29423. Object.defineProperty(VertexBuffer, "TangentKind", {
  29424. get: function () {
  29425. return VertexBuffer._TangentKind;
  29426. },
  29427. enumerable: true,
  29428. configurable: true
  29429. });
  29430. Object.defineProperty(VertexBuffer, "UVKind", {
  29431. get: function () {
  29432. return VertexBuffer._UVKind;
  29433. },
  29434. enumerable: true,
  29435. configurable: true
  29436. });
  29437. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29438. get: function () {
  29439. return VertexBuffer._UV2Kind;
  29440. },
  29441. enumerable: true,
  29442. configurable: true
  29443. });
  29444. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29445. get: function () {
  29446. return VertexBuffer._UV3Kind;
  29447. },
  29448. enumerable: true,
  29449. configurable: true
  29450. });
  29451. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29452. get: function () {
  29453. return VertexBuffer._UV4Kind;
  29454. },
  29455. enumerable: true,
  29456. configurable: true
  29457. });
  29458. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29459. get: function () {
  29460. return VertexBuffer._UV5Kind;
  29461. },
  29462. enumerable: true,
  29463. configurable: true
  29464. });
  29465. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29466. get: function () {
  29467. return VertexBuffer._UV6Kind;
  29468. },
  29469. enumerable: true,
  29470. configurable: true
  29471. });
  29472. Object.defineProperty(VertexBuffer, "ColorKind", {
  29473. get: function () {
  29474. return VertexBuffer._ColorKind;
  29475. },
  29476. enumerable: true,
  29477. configurable: true
  29478. });
  29479. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29480. get: function () {
  29481. return VertexBuffer._MatricesIndicesKind;
  29482. },
  29483. enumerable: true,
  29484. configurable: true
  29485. });
  29486. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29487. get: function () {
  29488. return VertexBuffer._MatricesWeightsKind;
  29489. },
  29490. enumerable: true,
  29491. configurable: true
  29492. });
  29493. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29494. get: function () {
  29495. return VertexBuffer._MatricesIndicesExtraKind;
  29496. },
  29497. enumerable: true,
  29498. configurable: true
  29499. });
  29500. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29501. get: function () {
  29502. return VertexBuffer._MatricesWeightsExtraKind;
  29503. },
  29504. enumerable: true,
  29505. configurable: true
  29506. });
  29507. /**
  29508. * Deduces the stride given a kind.
  29509. * @param kind The kind string to deduce
  29510. * @returns The deduced stride
  29511. */
  29512. VertexBuffer.DeduceStride = function (kind) {
  29513. switch (kind) {
  29514. case VertexBuffer.UVKind:
  29515. case VertexBuffer.UV2Kind:
  29516. case VertexBuffer.UV3Kind:
  29517. case VertexBuffer.UV4Kind:
  29518. case VertexBuffer.UV5Kind:
  29519. case VertexBuffer.UV6Kind:
  29520. return 2;
  29521. case VertexBuffer.NormalKind:
  29522. case VertexBuffer.PositionKind:
  29523. return 3;
  29524. case VertexBuffer.ColorKind:
  29525. case VertexBuffer.MatricesIndicesKind:
  29526. case VertexBuffer.MatricesIndicesExtraKind:
  29527. case VertexBuffer.MatricesWeightsKind:
  29528. case VertexBuffer.MatricesWeightsExtraKind:
  29529. case VertexBuffer.TangentKind:
  29530. return 4;
  29531. default:
  29532. throw new Error("Invalid kind '" + kind + "'");
  29533. }
  29534. };
  29535. /**
  29536. * Gets the byte length of the given type.
  29537. * @param type the type
  29538. * @returns the number of bytes
  29539. */
  29540. VertexBuffer.GetTypeByteLength = function (type) {
  29541. switch (type) {
  29542. case VertexBuffer.BYTE:
  29543. case VertexBuffer.UNSIGNED_BYTE:
  29544. return 1;
  29545. case VertexBuffer.SHORT:
  29546. case VertexBuffer.UNSIGNED_SHORT:
  29547. return 2;
  29548. case VertexBuffer.INT:
  29549. case VertexBuffer.FLOAT:
  29550. return 4;
  29551. default:
  29552. throw new Error("Invalid type '" + type + "'");
  29553. }
  29554. };
  29555. /**
  29556. * Enumerates each value of the given parameters as numbers.
  29557. * @param data the data to enumerate
  29558. * @param byteOffset the byte offset of the data
  29559. * @param byteStride the byte stride of the data
  29560. * @param componentCount the number of components per element
  29561. * @param componentType the type of the component
  29562. * @param count the total number of components
  29563. * @param normalized whether the data is normalized
  29564. * @param callback the callback function called for each value
  29565. */
  29566. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29567. if (data instanceof Array) {
  29568. var offset = byteOffset / 4;
  29569. var stride = byteStride / 4;
  29570. for (var index = 0; index < count; index += componentCount) {
  29571. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29572. callback(data[offset + componentIndex], index + componentIndex);
  29573. }
  29574. offset += stride;
  29575. }
  29576. }
  29577. else {
  29578. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29579. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29580. for (var index = 0; index < count; index += componentCount) {
  29581. var componentByteOffset = byteOffset;
  29582. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29583. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29584. callback(value, index + componentIndex);
  29585. componentByteOffset += componentByteLength;
  29586. }
  29587. byteOffset += byteStride;
  29588. }
  29589. }
  29590. };
  29591. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29592. switch (type) {
  29593. case VertexBuffer.BYTE: {
  29594. var value = dataView.getInt8(byteOffset);
  29595. if (normalized) {
  29596. value = (value + 0.5) / 127.5;
  29597. }
  29598. return value;
  29599. }
  29600. case VertexBuffer.UNSIGNED_BYTE: {
  29601. var value = dataView.getUint8(byteOffset);
  29602. if (normalized) {
  29603. value = value / 255;
  29604. }
  29605. return value;
  29606. }
  29607. case VertexBuffer.SHORT: {
  29608. var value = dataView.getInt16(byteOffset, true);
  29609. if (normalized) {
  29610. value = (value + 0.5) / 16383.5;
  29611. }
  29612. return value;
  29613. }
  29614. case VertexBuffer.UNSIGNED_SHORT: {
  29615. var value = dataView.getUint16(byteOffset, true);
  29616. if (normalized) {
  29617. value = value / 65535;
  29618. }
  29619. return value;
  29620. }
  29621. case VertexBuffer.FLOAT: {
  29622. return dataView.getFloat32(byteOffset, true);
  29623. }
  29624. default: {
  29625. throw new Error("Invalid component type " + type);
  29626. }
  29627. }
  29628. };
  29629. /**
  29630. * The byte type.
  29631. */
  29632. VertexBuffer.BYTE = 5120;
  29633. /**
  29634. * The unsigned byte type.
  29635. */
  29636. VertexBuffer.UNSIGNED_BYTE = 5121;
  29637. /**
  29638. * The short type.
  29639. */
  29640. VertexBuffer.SHORT = 5122;
  29641. /**
  29642. * The unsigned short type.
  29643. */
  29644. VertexBuffer.UNSIGNED_SHORT = 5123;
  29645. /**
  29646. * The integer type.
  29647. */
  29648. VertexBuffer.INT = 5124;
  29649. /**
  29650. * The unsigned integer type.
  29651. */
  29652. VertexBuffer.UNSIGNED_INT = 5125;
  29653. /**
  29654. * The float type.
  29655. */
  29656. VertexBuffer.FLOAT = 5126;
  29657. // Enums
  29658. VertexBuffer._PositionKind = "position";
  29659. VertexBuffer._NormalKind = "normal";
  29660. VertexBuffer._TangentKind = "tangent";
  29661. VertexBuffer._UVKind = "uv";
  29662. VertexBuffer._UV2Kind = "uv2";
  29663. VertexBuffer._UV3Kind = "uv3";
  29664. VertexBuffer._UV4Kind = "uv4";
  29665. VertexBuffer._UV5Kind = "uv5";
  29666. VertexBuffer._UV6Kind = "uv6";
  29667. VertexBuffer._ColorKind = "color";
  29668. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29669. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29670. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29671. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29672. return VertexBuffer;
  29673. }());
  29674. BABYLON.VertexBuffer = VertexBuffer;
  29675. })(BABYLON || (BABYLON = {}));
  29676. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29677. var BABYLON;
  29678. (function (BABYLON) {
  29679. /**
  29680. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29681. */
  29682. var DummyInternalTextureTracker = /** @class */ (function () {
  29683. function DummyInternalTextureTracker() {
  29684. /**
  29685. * Gets or set the previous tracker in the list
  29686. */
  29687. this.previous = null;
  29688. /**
  29689. * Gets or set the next tracker in the list
  29690. */
  29691. this.next = null;
  29692. }
  29693. return DummyInternalTextureTracker;
  29694. }());
  29695. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29696. })(BABYLON || (BABYLON = {}));
  29697. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29698. var BABYLON;
  29699. (function (BABYLON) {
  29700. /**
  29701. * Class used to store data associated with WebGL texture data for the engine
  29702. * This class should not be used directly
  29703. */
  29704. var InternalTexture = /** @class */ (function () {
  29705. /**
  29706. * Creates a new InternalTexture
  29707. * @param engine defines the engine to use
  29708. * @param dataSource defines the type of data that will be used
  29709. */
  29710. function InternalTexture(engine, dataSource) {
  29711. /**
  29712. * Observable called when the texture is loaded
  29713. */
  29714. this.onLoadedObservable = new BABYLON.Observable();
  29715. /**
  29716. * Gets or set the previous tracker in the list
  29717. */
  29718. this.previous = null;
  29719. /**
  29720. * Gets or set the next tracker in the list
  29721. */
  29722. this.next = null;
  29723. // Private
  29724. /** @hidden */
  29725. this._initialSlot = -1;
  29726. /** @hidden */
  29727. this._designatedSlot = -1;
  29728. /** @hidden */
  29729. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29730. /** @hidden */
  29731. this._comparisonFunction = 0;
  29732. /** @hidden */
  29733. this._references = 1;
  29734. this._engine = engine;
  29735. this._dataSource = dataSource;
  29736. this._webGLTexture = engine._createTexture();
  29737. }
  29738. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29739. /**
  29740. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29741. */
  29742. get: function () {
  29743. return this._dataSource;
  29744. },
  29745. enumerable: true,
  29746. configurable: true
  29747. });
  29748. /**
  29749. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29750. */
  29751. InternalTexture.prototype.incrementReferences = function () {
  29752. this._references++;
  29753. };
  29754. /**
  29755. * Change the size of the texture (not the size of the content)
  29756. * @param width defines the new width
  29757. * @param height defines the new height
  29758. * @param depth defines the new depth (1 by default)
  29759. */
  29760. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29761. if (depth === void 0) { depth = 1; }
  29762. this.width = width;
  29763. this.height = height;
  29764. this.depth = depth;
  29765. this.baseWidth = width;
  29766. this.baseHeight = height;
  29767. this.baseDepth = depth;
  29768. this._size = width * height * depth;
  29769. };
  29770. /** @hidden */
  29771. InternalTexture.prototype._rebuild = function () {
  29772. var _this = this;
  29773. var proxy;
  29774. this.isReady = false;
  29775. this._cachedCoordinatesMode = null;
  29776. this._cachedWrapU = null;
  29777. this._cachedWrapV = null;
  29778. this._cachedAnisotropicFilteringLevel = null;
  29779. switch (this._dataSource) {
  29780. case InternalTexture.DATASOURCE_TEMP:
  29781. return;
  29782. case InternalTexture.DATASOURCE_URL:
  29783. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29784. _this.isReady = true;
  29785. }, null, this._buffer, undefined, this.format);
  29786. proxy._swapAndDie(this);
  29787. return;
  29788. case InternalTexture.DATASOURCE_RAW:
  29789. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29790. proxy._swapAndDie(this);
  29791. this.isReady = true;
  29792. return;
  29793. case InternalTexture.DATASOURCE_RAW3D:
  29794. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29795. proxy._swapAndDie(this);
  29796. this.isReady = true;
  29797. return;
  29798. case InternalTexture.DATASOURCE_DYNAMIC:
  29799. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29800. proxy._swapAndDie(this);
  29801. // The engine will make sure to update content so no need to flag it as isReady = true
  29802. return;
  29803. case InternalTexture.DATASOURCE_RENDERTARGET:
  29804. var options = new BABYLON.RenderTargetCreationOptions();
  29805. options.generateDepthBuffer = this._generateDepthBuffer;
  29806. options.generateMipMaps = this.generateMipMaps;
  29807. options.generateStencilBuffer = this._generateStencilBuffer;
  29808. options.samplingMode = this.samplingMode;
  29809. options.type = this.type;
  29810. if (this.isCube) {
  29811. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29812. }
  29813. else {
  29814. var size = {
  29815. width: this.width,
  29816. height: this.height
  29817. };
  29818. proxy = this._engine.createRenderTargetTexture(size, options);
  29819. }
  29820. proxy._swapAndDie(this);
  29821. this.isReady = true;
  29822. return;
  29823. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29824. var depthTextureOptions = {
  29825. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29826. comparisonFunction: this._comparisonFunction,
  29827. generateStencil: this._generateStencilBuffer,
  29828. isCube: this.isCube
  29829. };
  29830. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29831. proxy._swapAndDie(this);
  29832. this.isReady = true;
  29833. return;
  29834. case InternalTexture.DATASOURCE_CUBE:
  29835. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29836. _this.isReady = true;
  29837. }, null, this.format, this._extension);
  29838. proxy._swapAndDie(this);
  29839. return;
  29840. case InternalTexture.DATASOURCE_CUBERAW:
  29841. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29842. proxy._swapAndDie(this);
  29843. this.isReady = true;
  29844. return;
  29845. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29846. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29847. if (proxy) {
  29848. proxy._swapAndDie(_this);
  29849. }
  29850. _this.isReady = true;
  29851. }, null, this.format, this._extension);
  29852. return;
  29853. }
  29854. };
  29855. InternalTexture.prototype._swapAndDie = function (target) {
  29856. target._webGLTexture = this._webGLTexture;
  29857. if (this._framebuffer) {
  29858. target._framebuffer = this._framebuffer;
  29859. }
  29860. if (this._depthStencilBuffer) {
  29861. target._depthStencilBuffer = this._depthStencilBuffer;
  29862. }
  29863. if (this._lodTextureHigh) {
  29864. if (target._lodTextureHigh) {
  29865. target._lodTextureHigh.dispose();
  29866. }
  29867. target._lodTextureHigh = this._lodTextureHigh;
  29868. }
  29869. if (this._lodTextureMid) {
  29870. if (target._lodTextureMid) {
  29871. target._lodTextureMid.dispose();
  29872. }
  29873. target._lodTextureMid = this._lodTextureMid;
  29874. }
  29875. if (this._lodTextureLow) {
  29876. if (target._lodTextureLow) {
  29877. target._lodTextureLow.dispose();
  29878. }
  29879. target._lodTextureLow = this._lodTextureLow;
  29880. }
  29881. var cache = this._engine.getLoadedTexturesCache();
  29882. var index = cache.indexOf(this);
  29883. if (index !== -1) {
  29884. cache.splice(index, 1);
  29885. }
  29886. };
  29887. /**
  29888. * Dispose the current allocated resources
  29889. */
  29890. InternalTexture.prototype.dispose = function () {
  29891. if (!this._webGLTexture) {
  29892. return;
  29893. }
  29894. this._references--;
  29895. if (this._references === 0) {
  29896. this._engine._releaseTexture(this);
  29897. this._webGLTexture = null;
  29898. this.previous = null;
  29899. this.next = null;
  29900. }
  29901. };
  29902. /**
  29903. * The source of the texture data is unknown
  29904. */
  29905. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29906. /**
  29907. * Texture data comes from an URL
  29908. */
  29909. InternalTexture.DATASOURCE_URL = 1;
  29910. /**
  29911. * Texture data is only used for temporary storage
  29912. */
  29913. InternalTexture.DATASOURCE_TEMP = 2;
  29914. /**
  29915. * Texture data comes from raw data (ArrayBuffer)
  29916. */
  29917. InternalTexture.DATASOURCE_RAW = 3;
  29918. /**
  29919. * Texture content is dynamic (video or dynamic texture)
  29920. */
  29921. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29922. /**
  29923. * Texture content is generated by rendering to it
  29924. */
  29925. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29926. /**
  29927. * Texture content is part of a multi render target process
  29928. */
  29929. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29930. /**
  29931. * Texture data comes from a cube data file
  29932. */
  29933. InternalTexture.DATASOURCE_CUBE = 7;
  29934. /**
  29935. * Texture data comes from a raw cube data
  29936. */
  29937. InternalTexture.DATASOURCE_CUBERAW = 8;
  29938. /**
  29939. * Texture data come from a prefiltered cube data file
  29940. */
  29941. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29942. /**
  29943. * Texture content is raw 3D data
  29944. */
  29945. InternalTexture.DATASOURCE_RAW3D = 10;
  29946. /**
  29947. * Texture content is a depth texture
  29948. */
  29949. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29950. return InternalTexture;
  29951. }());
  29952. BABYLON.InternalTexture = InternalTexture;
  29953. })(BABYLON || (BABYLON = {}));
  29954. //# sourceMappingURL=babylon.internalTexture.js.map
  29955. var BABYLON;
  29956. (function (BABYLON) {
  29957. var BaseTexture = /** @class */ (function () {
  29958. function BaseTexture(scene) {
  29959. this._hasAlpha = false;
  29960. this.getAlphaFromRGB = false;
  29961. this.level = 1;
  29962. this.coordinatesIndex = 0;
  29963. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29964. /**
  29965. * | Value | Type | Description |
  29966. * | ----- | ------------------ | ----------- |
  29967. * | 0 | CLAMP_ADDRESSMODE | |
  29968. * | 1 | WRAP_ADDRESSMODE | |
  29969. * | 2 | MIRROR_ADDRESSMODE | |
  29970. */
  29971. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29972. /**
  29973. * | Value | Type | Description |
  29974. * | ----- | ------------------ | ----------- |
  29975. * | 0 | CLAMP_ADDRESSMODE | |
  29976. * | 1 | WRAP_ADDRESSMODE | |
  29977. * | 2 | MIRROR_ADDRESSMODE | |
  29978. */
  29979. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29980. /**
  29981. * | Value | Type | Description |
  29982. * | ----- | ------------------ | ----------- |
  29983. * | 0 | CLAMP_ADDRESSMODE | |
  29984. * | 1 | WRAP_ADDRESSMODE | |
  29985. * | 2 | MIRROR_ADDRESSMODE | |
  29986. */
  29987. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29988. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29989. this.isCube = false;
  29990. this.is3D = false;
  29991. this.gammaSpace = true;
  29992. this.invertZ = false;
  29993. this.lodLevelInAlpha = false;
  29994. this.lodGenerationOffset = 0.0;
  29995. this.lodGenerationScale = 0.8;
  29996. this.isRenderTarget = false;
  29997. this.animations = new Array();
  29998. /**
  29999. * An event triggered when the texture is disposed.
  30000. */
  30001. this.onDisposeObservable = new BABYLON.Observable();
  30002. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30003. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30004. if (this._scene) {
  30005. this._scene.textures.push(this);
  30006. }
  30007. this._uid = null;
  30008. }
  30009. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30010. get: function () {
  30011. return this._hasAlpha;
  30012. },
  30013. set: function (value) {
  30014. if (this._hasAlpha === value) {
  30015. return;
  30016. }
  30017. this._hasAlpha = value;
  30018. if (this._scene) {
  30019. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30020. }
  30021. },
  30022. enumerable: true,
  30023. configurable: true
  30024. });
  30025. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30026. get: function () {
  30027. return this._coordinatesMode;
  30028. },
  30029. /**
  30030. * How a texture is mapped.
  30031. *
  30032. * | Value | Type | Description |
  30033. * | ----- | ----------------------------------- | ----------- |
  30034. * | 0 | EXPLICIT_MODE | |
  30035. * | 1 | SPHERICAL_MODE | |
  30036. * | 2 | PLANAR_MODE | |
  30037. * | 3 | CUBIC_MODE | |
  30038. * | 4 | PROJECTION_MODE | |
  30039. * | 5 | SKYBOX_MODE | |
  30040. * | 6 | INVCUBIC_MODE | |
  30041. * | 7 | EQUIRECTANGULAR_MODE | |
  30042. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30043. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30044. */
  30045. set: function (value) {
  30046. if (this._coordinatesMode === value) {
  30047. return;
  30048. }
  30049. this._coordinatesMode = value;
  30050. if (this._scene) {
  30051. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30052. }
  30053. },
  30054. enumerable: true,
  30055. configurable: true
  30056. });
  30057. Object.defineProperty(BaseTexture.prototype, "uid", {
  30058. get: function () {
  30059. if (!this._uid) {
  30060. this._uid = BABYLON.Tools.RandomId();
  30061. }
  30062. return this._uid;
  30063. },
  30064. enumerable: true,
  30065. configurable: true
  30066. });
  30067. BaseTexture.prototype.toString = function () {
  30068. return this.name;
  30069. };
  30070. BaseTexture.prototype.getClassName = function () {
  30071. return "BaseTexture";
  30072. };
  30073. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30074. set: function (callback) {
  30075. if (this._onDisposeObserver) {
  30076. this.onDisposeObservable.remove(this._onDisposeObserver);
  30077. }
  30078. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30079. },
  30080. enumerable: true,
  30081. configurable: true
  30082. });
  30083. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30084. get: function () {
  30085. return true;
  30086. },
  30087. enumerable: true,
  30088. configurable: true
  30089. });
  30090. BaseTexture.prototype.getScene = function () {
  30091. return this._scene;
  30092. };
  30093. BaseTexture.prototype.getTextureMatrix = function () {
  30094. return BABYLON.Matrix.IdentityReadOnly;
  30095. };
  30096. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30097. return BABYLON.Matrix.IdentityReadOnly;
  30098. };
  30099. BaseTexture.prototype.getInternalTexture = function () {
  30100. return this._texture;
  30101. };
  30102. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30103. return !this.isBlocking || this.isReady();
  30104. };
  30105. BaseTexture.prototype.isReady = function () {
  30106. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30107. this.delayLoad();
  30108. return false;
  30109. }
  30110. if (this._texture) {
  30111. return this._texture.isReady;
  30112. }
  30113. return false;
  30114. };
  30115. BaseTexture.prototype.getSize = function () {
  30116. if (this._texture && this._texture.width) {
  30117. return new BABYLON.Size(this._texture.width, this._texture.height);
  30118. }
  30119. if (this._texture && this._texture._size) {
  30120. return new BABYLON.Size(this._texture._size, this._texture._size);
  30121. }
  30122. return BABYLON.Size.Zero();
  30123. };
  30124. BaseTexture.prototype.getBaseSize = function () {
  30125. if (!this.isReady() || !this._texture)
  30126. return BABYLON.Size.Zero();
  30127. if (this._texture._size) {
  30128. return new BABYLON.Size(this._texture._size, this._texture._size);
  30129. }
  30130. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30131. };
  30132. BaseTexture.prototype.scale = function (ratio) {
  30133. };
  30134. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30135. get: function () {
  30136. return false;
  30137. },
  30138. enumerable: true,
  30139. configurable: true
  30140. });
  30141. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30142. if (!this._scene) {
  30143. return null;
  30144. }
  30145. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30146. for (var index = 0; index < texturesCache.length; index++) {
  30147. var texturesCacheEntry = texturesCache[index];
  30148. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30149. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30150. texturesCacheEntry.incrementReferences();
  30151. return texturesCacheEntry;
  30152. }
  30153. }
  30154. }
  30155. return null;
  30156. };
  30157. BaseTexture.prototype._rebuild = function () {
  30158. };
  30159. BaseTexture.prototype.delayLoad = function () {
  30160. };
  30161. BaseTexture.prototype.clone = function () {
  30162. return null;
  30163. };
  30164. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30165. get: function () {
  30166. if (!this._texture) {
  30167. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30168. }
  30169. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30170. },
  30171. enumerable: true,
  30172. configurable: true
  30173. });
  30174. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30175. get: function () {
  30176. if (!this._texture) {
  30177. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30178. }
  30179. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30180. },
  30181. enumerable: true,
  30182. configurable: true
  30183. });
  30184. BaseTexture.prototype.readPixels = function (faceIndex) {
  30185. if (faceIndex === void 0) { faceIndex = 0; }
  30186. if (!this._texture) {
  30187. return null;
  30188. }
  30189. var size = this.getSize();
  30190. var scene = this.getScene();
  30191. if (!scene) {
  30192. return null;
  30193. }
  30194. var engine = scene.getEngine();
  30195. if (this._texture.isCube) {
  30196. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30197. }
  30198. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30199. };
  30200. BaseTexture.prototype.releaseInternalTexture = function () {
  30201. if (this._texture) {
  30202. this._texture.dispose();
  30203. this._texture = null;
  30204. }
  30205. };
  30206. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30207. get: function () {
  30208. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30209. return null;
  30210. }
  30211. if (!this._texture._sphericalPolynomial) {
  30212. this._texture._sphericalPolynomial =
  30213. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30214. }
  30215. return this._texture._sphericalPolynomial;
  30216. },
  30217. set: function (value) {
  30218. if (this._texture) {
  30219. this._texture._sphericalPolynomial = value;
  30220. }
  30221. },
  30222. enumerable: true,
  30223. configurable: true
  30224. });
  30225. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30226. get: function () {
  30227. if (this._texture) {
  30228. return this._texture._lodTextureHigh;
  30229. }
  30230. return null;
  30231. },
  30232. enumerable: true,
  30233. configurable: true
  30234. });
  30235. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30236. get: function () {
  30237. if (this._texture) {
  30238. return this._texture._lodTextureMid;
  30239. }
  30240. return null;
  30241. },
  30242. enumerable: true,
  30243. configurable: true
  30244. });
  30245. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30246. get: function () {
  30247. if (this._texture) {
  30248. return this._texture._lodTextureLow;
  30249. }
  30250. return null;
  30251. },
  30252. enumerable: true,
  30253. configurable: true
  30254. });
  30255. BaseTexture.prototype.dispose = function () {
  30256. if (!this._scene) {
  30257. return;
  30258. }
  30259. // Animations
  30260. this._scene.stopAnimation(this);
  30261. // Remove from scene
  30262. this._scene._removePendingData(this);
  30263. var index = this._scene.textures.indexOf(this);
  30264. if (index >= 0) {
  30265. this._scene.textures.splice(index, 1);
  30266. }
  30267. if (this._texture === undefined) {
  30268. return;
  30269. }
  30270. // Release
  30271. this.releaseInternalTexture();
  30272. // Callback
  30273. this.onDisposeObservable.notifyObservers(this);
  30274. this.onDisposeObservable.clear();
  30275. };
  30276. BaseTexture.prototype.serialize = function () {
  30277. if (!this.name) {
  30278. return null;
  30279. }
  30280. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30281. // Animations
  30282. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30283. return serializationObject;
  30284. };
  30285. BaseTexture.WhenAllReady = function (textures, callback) {
  30286. var numRemaining = textures.length;
  30287. if (numRemaining === 0) {
  30288. callback();
  30289. return;
  30290. }
  30291. var _loop_1 = function () {
  30292. texture = textures[i];
  30293. if (texture.isReady()) {
  30294. if (--numRemaining === 0) {
  30295. callback();
  30296. }
  30297. }
  30298. else {
  30299. onLoadObservable = texture.onLoadObservable;
  30300. var onLoadCallback_1 = function () {
  30301. onLoadObservable.removeCallback(onLoadCallback_1);
  30302. if (--numRemaining === 0) {
  30303. callback();
  30304. }
  30305. };
  30306. onLoadObservable.add(onLoadCallback_1);
  30307. }
  30308. };
  30309. var texture, onLoadObservable;
  30310. for (var i = 0; i < textures.length; i++) {
  30311. _loop_1();
  30312. }
  30313. };
  30314. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30315. __decorate([
  30316. BABYLON.serialize()
  30317. ], BaseTexture.prototype, "name", void 0);
  30318. __decorate([
  30319. BABYLON.serialize("hasAlpha")
  30320. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30321. __decorate([
  30322. BABYLON.serialize()
  30323. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30324. __decorate([
  30325. BABYLON.serialize()
  30326. ], BaseTexture.prototype, "level", void 0);
  30327. __decorate([
  30328. BABYLON.serialize()
  30329. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30330. __decorate([
  30331. BABYLON.serialize("coordinatesMode")
  30332. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30333. __decorate([
  30334. BABYLON.serialize()
  30335. ], BaseTexture.prototype, "wrapU", void 0);
  30336. __decorate([
  30337. BABYLON.serialize()
  30338. ], BaseTexture.prototype, "wrapV", void 0);
  30339. __decorate([
  30340. BABYLON.serialize()
  30341. ], BaseTexture.prototype, "wrapR", void 0);
  30342. __decorate([
  30343. BABYLON.serialize()
  30344. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30345. __decorate([
  30346. BABYLON.serialize()
  30347. ], BaseTexture.prototype, "isCube", void 0);
  30348. __decorate([
  30349. BABYLON.serialize()
  30350. ], BaseTexture.prototype, "is3D", void 0);
  30351. __decorate([
  30352. BABYLON.serialize()
  30353. ], BaseTexture.prototype, "gammaSpace", void 0);
  30354. __decorate([
  30355. BABYLON.serialize()
  30356. ], BaseTexture.prototype, "invertZ", void 0);
  30357. __decorate([
  30358. BABYLON.serialize()
  30359. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30360. __decorate([
  30361. BABYLON.serialize()
  30362. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30363. __decorate([
  30364. BABYLON.serialize()
  30365. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30366. __decorate([
  30367. BABYLON.serialize()
  30368. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30369. return BaseTexture;
  30370. }());
  30371. BABYLON.BaseTexture = BaseTexture;
  30372. })(BABYLON || (BABYLON = {}));
  30373. //# sourceMappingURL=babylon.baseTexture.js.map
  30374. var BABYLON;
  30375. (function (BABYLON) {
  30376. var Texture = /** @class */ (function (_super) {
  30377. __extends(Texture, _super);
  30378. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30379. if (noMipmap === void 0) { noMipmap = false; }
  30380. if (invertY === void 0) { invertY = true; }
  30381. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30382. if (onLoad === void 0) { onLoad = null; }
  30383. if (onError === void 0) { onError = null; }
  30384. if (buffer === void 0) { buffer = null; }
  30385. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30386. var _this = _super.call(this, scene) || this;
  30387. _this.uOffset = 0;
  30388. _this.vOffset = 0;
  30389. _this.uScale = 1.0;
  30390. _this.vScale = 1.0;
  30391. _this.uAng = 0;
  30392. _this.vAng = 0;
  30393. _this.wAng = 0;
  30394. _this._isBlocking = true;
  30395. _this.name = url || "";
  30396. _this.url = url;
  30397. _this._noMipmap = noMipmap;
  30398. _this._invertY = invertY;
  30399. _this._samplingMode = samplingMode;
  30400. _this._buffer = buffer;
  30401. _this._deleteBuffer = deleteBuffer;
  30402. if (format) {
  30403. _this._format = format;
  30404. }
  30405. scene = _this.getScene();
  30406. if (!scene) {
  30407. return _this;
  30408. }
  30409. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30410. var load = function () {
  30411. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30412. _this.onLoadObservable.notifyObservers(_this);
  30413. }
  30414. if (onLoad) {
  30415. onLoad();
  30416. }
  30417. if (!_this.isBlocking && scene) {
  30418. scene.resetCachedMaterial();
  30419. }
  30420. };
  30421. if (!_this.url) {
  30422. _this._delayedOnLoad = load;
  30423. _this._delayedOnError = onError;
  30424. return _this;
  30425. }
  30426. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30427. if (!_this._texture) {
  30428. if (!scene.useDelayedTextureLoading) {
  30429. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30430. if (deleteBuffer) {
  30431. delete _this._buffer;
  30432. }
  30433. }
  30434. else {
  30435. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30436. _this._delayedOnLoad = load;
  30437. _this._delayedOnError = onError;
  30438. }
  30439. }
  30440. else {
  30441. if (_this._texture.isReady) {
  30442. BABYLON.Tools.SetImmediate(function () { return load(); });
  30443. }
  30444. else {
  30445. _this._texture.onLoadedObservable.add(load);
  30446. }
  30447. }
  30448. return _this;
  30449. }
  30450. Object.defineProperty(Texture.prototype, "noMipmap", {
  30451. get: function () {
  30452. return this._noMipmap;
  30453. },
  30454. enumerable: true,
  30455. configurable: true
  30456. });
  30457. Object.defineProperty(Texture.prototype, "isBlocking", {
  30458. get: function () {
  30459. return this._isBlocking;
  30460. },
  30461. set: function (value) {
  30462. this._isBlocking = value;
  30463. },
  30464. enumerable: true,
  30465. configurable: true
  30466. });
  30467. Object.defineProperty(Texture.prototype, "samplingMode", {
  30468. get: function () {
  30469. return this._samplingMode;
  30470. },
  30471. enumerable: true,
  30472. configurable: true
  30473. });
  30474. Texture.prototype.updateURL = function (url) {
  30475. this.url = url;
  30476. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30477. this.delayLoad();
  30478. };
  30479. Texture.prototype.delayLoad = function () {
  30480. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30481. return;
  30482. }
  30483. var scene = this.getScene();
  30484. if (!scene) {
  30485. return;
  30486. }
  30487. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30488. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30489. if (!this._texture) {
  30490. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30491. if (this._deleteBuffer) {
  30492. delete this._buffer;
  30493. }
  30494. }
  30495. else {
  30496. if (this._delayedOnLoad) {
  30497. if (this._texture.isReady) {
  30498. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30499. }
  30500. else {
  30501. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30502. }
  30503. }
  30504. }
  30505. this._delayedOnLoad = null;
  30506. this._delayedOnError = null;
  30507. };
  30508. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30509. if (!this._texture) {
  30510. return;
  30511. }
  30512. var scene = this.getScene();
  30513. if (!scene) {
  30514. return;
  30515. }
  30516. this._samplingMode = samplingMode;
  30517. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30518. };
  30519. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30520. x *= this.uScale;
  30521. y *= this.vScale;
  30522. x -= 0.5 * this.uScale;
  30523. y -= 0.5 * this.vScale;
  30524. z -= 0.5;
  30525. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30526. t.x += 0.5 * this.uScale + this.uOffset;
  30527. t.y += 0.5 * this.vScale + this.vOffset;
  30528. t.z += 0.5;
  30529. };
  30530. Texture.prototype.getTextureMatrix = function () {
  30531. var _this = this;
  30532. if (this.uOffset === this._cachedUOffset &&
  30533. this.vOffset === this._cachedVOffset &&
  30534. this.uScale === this._cachedUScale &&
  30535. this.vScale === this._cachedVScale &&
  30536. this.uAng === this._cachedUAng &&
  30537. this.vAng === this._cachedVAng &&
  30538. this.wAng === this._cachedWAng) {
  30539. return this._cachedTextureMatrix;
  30540. }
  30541. this._cachedUOffset = this.uOffset;
  30542. this._cachedVOffset = this.vOffset;
  30543. this._cachedUScale = this.uScale;
  30544. this._cachedVScale = this.vScale;
  30545. this._cachedUAng = this.uAng;
  30546. this._cachedVAng = this.vAng;
  30547. this._cachedWAng = this.wAng;
  30548. if (!this._cachedTextureMatrix) {
  30549. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30550. this._rowGenerationMatrix = new BABYLON.Matrix();
  30551. this._t0 = BABYLON.Vector3.Zero();
  30552. this._t1 = BABYLON.Vector3.Zero();
  30553. this._t2 = BABYLON.Vector3.Zero();
  30554. }
  30555. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30556. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30557. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30558. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30559. this._t1.subtractInPlace(this._t0);
  30560. this._t2.subtractInPlace(this._t0);
  30561. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30562. this._cachedTextureMatrix.m[0] = this._t1.x;
  30563. this._cachedTextureMatrix.m[1] = this._t1.y;
  30564. this._cachedTextureMatrix.m[2] = this._t1.z;
  30565. this._cachedTextureMatrix.m[4] = this._t2.x;
  30566. this._cachedTextureMatrix.m[5] = this._t2.y;
  30567. this._cachedTextureMatrix.m[6] = this._t2.z;
  30568. this._cachedTextureMatrix.m[8] = this._t0.x;
  30569. this._cachedTextureMatrix.m[9] = this._t0.y;
  30570. this._cachedTextureMatrix.m[10] = this._t0.z;
  30571. var scene = this.getScene();
  30572. if (!scene) {
  30573. return this._cachedTextureMatrix;
  30574. }
  30575. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30576. return mat.hasTexture(_this);
  30577. });
  30578. return this._cachedTextureMatrix;
  30579. };
  30580. Texture.prototype.getReflectionTextureMatrix = function () {
  30581. var _this = this;
  30582. var scene = this.getScene();
  30583. if (!scene) {
  30584. return this._cachedTextureMatrix;
  30585. }
  30586. if (this.uOffset === this._cachedUOffset &&
  30587. this.vOffset === this._cachedVOffset &&
  30588. this.uScale === this._cachedUScale &&
  30589. this.vScale === this._cachedVScale &&
  30590. this.coordinatesMode === this._cachedCoordinatesMode) {
  30591. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30592. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30593. return this._cachedTextureMatrix;
  30594. }
  30595. }
  30596. else {
  30597. return this._cachedTextureMatrix;
  30598. }
  30599. }
  30600. if (!this._cachedTextureMatrix) {
  30601. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30602. }
  30603. if (!this._projectionModeMatrix) {
  30604. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30605. }
  30606. this._cachedUOffset = this.uOffset;
  30607. this._cachedVOffset = this.vOffset;
  30608. this._cachedUScale = this.uScale;
  30609. this._cachedVScale = this.vScale;
  30610. this._cachedCoordinatesMode = this.coordinatesMode;
  30611. switch (this.coordinatesMode) {
  30612. case Texture.PLANAR_MODE:
  30613. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30614. this._cachedTextureMatrix[0] = this.uScale;
  30615. this._cachedTextureMatrix[5] = this.vScale;
  30616. this._cachedTextureMatrix[12] = this.uOffset;
  30617. this._cachedTextureMatrix[13] = this.vOffset;
  30618. break;
  30619. case Texture.PROJECTION_MODE:
  30620. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30621. this._projectionModeMatrix.m[0] = 0.5;
  30622. this._projectionModeMatrix.m[5] = -0.5;
  30623. this._projectionModeMatrix.m[10] = 0.0;
  30624. this._projectionModeMatrix.m[12] = 0.5;
  30625. this._projectionModeMatrix.m[13] = 0.5;
  30626. this._projectionModeMatrix.m[14] = 1.0;
  30627. this._projectionModeMatrix.m[15] = 1.0;
  30628. var projectionMatrix = scene.getProjectionMatrix();
  30629. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30630. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30631. break;
  30632. default:
  30633. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30634. break;
  30635. }
  30636. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30637. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30638. });
  30639. return this._cachedTextureMatrix;
  30640. };
  30641. Texture.prototype.clone = function () {
  30642. var _this = this;
  30643. return BABYLON.SerializationHelper.Clone(function () {
  30644. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30645. }, this);
  30646. };
  30647. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30648. get: function () {
  30649. if (!this._onLoadObservable) {
  30650. this._onLoadObservable = new BABYLON.Observable();
  30651. }
  30652. return this._onLoadObservable;
  30653. },
  30654. enumerable: true,
  30655. configurable: true
  30656. });
  30657. Texture.prototype.serialize = function () {
  30658. var serializationObject = _super.prototype.serialize.call(this);
  30659. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30660. serializationObject.base64String = this._buffer;
  30661. serializationObject.name = serializationObject.name.replace("data:", "");
  30662. }
  30663. serializationObject.invertY = this._invertY;
  30664. serializationObject.samplingMode = this.samplingMode;
  30665. return serializationObject;
  30666. };
  30667. Texture.prototype.getClassName = function () {
  30668. return "Texture";
  30669. };
  30670. Texture.prototype.dispose = function () {
  30671. _super.prototype.dispose.call(this);
  30672. if (this.onLoadObservable) {
  30673. this.onLoadObservable.clear();
  30674. this._onLoadObservable = null;
  30675. }
  30676. this._delayedOnLoad = null;
  30677. this._delayedOnError = null;
  30678. };
  30679. // Statics
  30680. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30681. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30682. if (onLoad === void 0) { onLoad = null; }
  30683. if (onError === void 0) { onError = null; }
  30684. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30685. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30686. };
  30687. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30688. if (parsedTexture.customType) {
  30689. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30690. // Update Sampling Mode
  30691. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30692. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30693. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30694. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30695. }
  30696. }
  30697. return parsedCustomTexture;
  30698. }
  30699. if (parsedTexture.isCube) {
  30700. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30701. }
  30702. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30703. return null;
  30704. }
  30705. var texture = BABYLON.SerializationHelper.Parse(function () {
  30706. var generateMipMaps = true;
  30707. if (parsedTexture.noMipmap) {
  30708. generateMipMaps = false;
  30709. }
  30710. if (parsedTexture.mirrorPlane) {
  30711. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30712. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30713. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30714. return mirrorTexture;
  30715. }
  30716. else if (parsedTexture.isRenderTarget) {
  30717. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30718. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30719. return renderTargetTexture;
  30720. }
  30721. else {
  30722. var texture;
  30723. if (parsedTexture.base64String) {
  30724. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30725. }
  30726. else {
  30727. var url = rootUrl + parsedTexture.name;
  30728. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30729. url = parsedTexture.url;
  30730. }
  30731. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30732. }
  30733. return texture;
  30734. }
  30735. }, parsedTexture, scene);
  30736. // Update Sampling Mode
  30737. if (parsedTexture.samplingMode) {
  30738. var sampling = parsedTexture.samplingMode;
  30739. if (texture._samplingMode !== sampling) {
  30740. texture.updateSamplingMode(sampling);
  30741. }
  30742. }
  30743. // Animations
  30744. if (parsedTexture.animations) {
  30745. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30746. var parsedAnimation = parsedTexture.animations[animationIndex];
  30747. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30748. }
  30749. }
  30750. return texture;
  30751. };
  30752. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30753. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30754. if (noMipmap === void 0) { noMipmap = false; }
  30755. if (invertY === void 0) { invertY = true; }
  30756. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30757. if (onLoad === void 0) { onLoad = null; }
  30758. if (onError === void 0) { onError = null; }
  30759. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30760. if (name.substr(0, 5) !== "data:") {
  30761. name = "data:" + name;
  30762. }
  30763. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30764. };
  30765. // Constants
  30766. Texture.NEAREST_SAMPLINGMODE = 1;
  30767. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30768. Texture.BILINEAR_SAMPLINGMODE = 2;
  30769. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30770. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30771. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30772. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30773. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30774. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30775. Texture.NEAREST_LINEAR = 7;
  30776. Texture.NEAREST_NEAREST = 8;
  30777. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30778. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30779. Texture.LINEAR_LINEAR = 11;
  30780. Texture.LINEAR_NEAREST = 12;
  30781. Texture.EXPLICIT_MODE = 0;
  30782. Texture.SPHERICAL_MODE = 1;
  30783. Texture.PLANAR_MODE = 2;
  30784. Texture.CUBIC_MODE = 3;
  30785. Texture.PROJECTION_MODE = 4;
  30786. Texture.SKYBOX_MODE = 5;
  30787. Texture.INVCUBIC_MODE = 6;
  30788. Texture.EQUIRECTANGULAR_MODE = 7;
  30789. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30790. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30791. Texture.CLAMP_ADDRESSMODE = 0;
  30792. Texture.WRAP_ADDRESSMODE = 1;
  30793. Texture.MIRROR_ADDRESSMODE = 2;
  30794. /**
  30795. * 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
  30796. */
  30797. Texture.UseSerializedUrlIfAny = false;
  30798. __decorate([
  30799. BABYLON.serialize()
  30800. ], Texture.prototype, "url", void 0);
  30801. __decorate([
  30802. BABYLON.serialize()
  30803. ], Texture.prototype, "uOffset", void 0);
  30804. __decorate([
  30805. BABYLON.serialize()
  30806. ], Texture.prototype, "vOffset", void 0);
  30807. __decorate([
  30808. BABYLON.serialize()
  30809. ], Texture.prototype, "uScale", void 0);
  30810. __decorate([
  30811. BABYLON.serialize()
  30812. ], Texture.prototype, "vScale", void 0);
  30813. __decorate([
  30814. BABYLON.serialize()
  30815. ], Texture.prototype, "uAng", void 0);
  30816. __decorate([
  30817. BABYLON.serialize()
  30818. ], Texture.prototype, "vAng", void 0);
  30819. __decorate([
  30820. BABYLON.serialize()
  30821. ], Texture.prototype, "wAng", void 0);
  30822. __decorate([
  30823. BABYLON.serialize()
  30824. ], Texture.prototype, "isBlocking", null);
  30825. return Texture;
  30826. }(BABYLON.BaseTexture));
  30827. BABYLON.Texture = Texture;
  30828. })(BABYLON || (BABYLON = {}));
  30829. //# sourceMappingURL=babylon.texture.js.map
  30830. var BABYLON;
  30831. (function (BABYLON) {
  30832. /**
  30833. * @hidden
  30834. **/
  30835. var _InstancesBatch = /** @class */ (function () {
  30836. function _InstancesBatch() {
  30837. this.mustReturn = false;
  30838. this.visibleInstances = new Array();
  30839. this.renderSelf = new Array();
  30840. }
  30841. return _InstancesBatch;
  30842. }());
  30843. BABYLON._InstancesBatch = _InstancesBatch;
  30844. var Mesh = /** @class */ (function (_super) {
  30845. __extends(Mesh, _super);
  30846. /**
  30847. * @constructor
  30848. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30849. * @param {Scene} scene The scene to add this mesh to.
  30850. * @param {Node} parent The parent of this mesh, if it has one
  30851. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30852. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30853. * When false, achieved by calling a clone(), also passing False.
  30854. * This will make creation of children, recursive.
  30855. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30856. */
  30857. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30858. if (scene === void 0) { scene = null; }
  30859. if (parent === void 0) { parent = null; }
  30860. if (source === void 0) { source = null; }
  30861. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30862. var _this = _super.call(this, name, scene) || this;
  30863. // Events
  30864. /**
  30865. * An event triggered before rendering the mesh
  30866. */
  30867. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30868. /**
  30869. * An event triggered after rendering the mesh
  30870. */
  30871. _this.onAfterRenderObservable = new BABYLON.Observable();
  30872. /**
  30873. * An event triggered before drawing the mesh
  30874. */
  30875. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30876. // Members
  30877. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30878. _this.instances = new Array();
  30879. _this._LODLevels = new Array();
  30880. _this._visibleInstances = {};
  30881. _this._renderIdForInstances = new Array();
  30882. _this._batchCache = new _InstancesBatch();
  30883. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30884. // Use by builder only to know what orientation were the mesh build in.
  30885. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30886. _this.overrideMaterialSideOrientation = null;
  30887. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30888. // Will be used to save a source mesh reference, If any
  30889. _this._source = null;
  30890. scene = _this.getScene();
  30891. if (source) {
  30892. // Source mesh
  30893. _this._source = source;
  30894. // Geometry
  30895. if (source._geometry) {
  30896. source._geometry.applyToMesh(_this);
  30897. }
  30898. // Deep copy
  30899. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30900. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30901. // Metadata
  30902. if (source.metadata && source.metadata.clone) {
  30903. _this.metadata = source.metadata.clone();
  30904. }
  30905. else {
  30906. _this.metadata = source.metadata;
  30907. }
  30908. // Tags
  30909. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30910. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30911. }
  30912. // Parent
  30913. _this.parent = source.parent;
  30914. // Pivot
  30915. _this.setPivotMatrix(source.getPivotMatrix());
  30916. _this.id = name + "." + source.id;
  30917. // Material
  30918. _this.material = source.material;
  30919. var index;
  30920. if (!doNotCloneChildren) {
  30921. // Children
  30922. var directDescendants = source.getDescendants(true);
  30923. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30924. var child = directDescendants[index_1];
  30925. if (child.clone) {
  30926. child.clone(name + "." + child.name, _this);
  30927. }
  30928. }
  30929. }
  30930. // Physics clone
  30931. var physicsEngine = _this.getScene().getPhysicsEngine();
  30932. if (clonePhysicsImpostor && physicsEngine) {
  30933. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30934. if (impostor) {
  30935. _this.physicsImpostor = impostor.clone(_this);
  30936. }
  30937. }
  30938. // Particles
  30939. for (index = 0; index < scene.particleSystems.length; index++) {
  30940. var system = scene.particleSystems[index];
  30941. if (system.emitter === source) {
  30942. system.clone(system.name, _this);
  30943. }
  30944. }
  30945. _this.computeWorldMatrix(true);
  30946. }
  30947. // Parent
  30948. if (parent !== null) {
  30949. _this.parent = parent;
  30950. }
  30951. return _this;
  30952. }
  30953. Object.defineProperty(Mesh, "FRONTSIDE", {
  30954. /**
  30955. * Mesh side orientation : usually the external or front surface
  30956. */
  30957. get: function () {
  30958. return Mesh._FRONTSIDE;
  30959. },
  30960. enumerable: true,
  30961. configurable: true
  30962. });
  30963. Object.defineProperty(Mesh, "BACKSIDE", {
  30964. /**
  30965. * Mesh side orientation : usually the internal or back surface
  30966. */
  30967. get: function () {
  30968. return Mesh._BACKSIDE;
  30969. },
  30970. enumerable: true,
  30971. configurable: true
  30972. });
  30973. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30974. /**
  30975. * Mesh side orientation : both internal and external or front and back surfaces
  30976. */
  30977. get: function () {
  30978. return Mesh._DOUBLESIDE;
  30979. },
  30980. enumerable: true,
  30981. configurable: true
  30982. });
  30983. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30984. /**
  30985. * Mesh side orientation : by default, `FRONTSIDE`
  30986. */
  30987. get: function () {
  30988. return Mesh._DEFAULTSIDE;
  30989. },
  30990. enumerable: true,
  30991. configurable: true
  30992. });
  30993. Object.defineProperty(Mesh, "NO_CAP", {
  30994. /**
  30995. * Mesh cap setting : no cap
  30996. */
  30997. get: function () {
  30998. return Mesh._NO_CAP;
  30999. },
  31000. enumerable: true,
  31001. configurable: true
  31002. });
  31003. Object.defineProperty(Mesh, "CAP_START", {
  31004. /**
  31005. * Mesh cap setting : one cap at the beginning of the mesh
  31006. */
  31007. get: function () {
  31008. return Mesh._CAP_START;
  31009. },
  31010. enumerable: true,
  31011. configurable: true
  31012. });
  31013. Object.defineProperty(Mesh, "CAP_END", {
  31014. /**
  31015. * Mesh cap setting : one cap at the end of the mesh
  31016. */
  31017. get: function () {
  31018. return Mesh._CAP_END;
  31019. },
  31020. enumerable: true,
  31021. configurable: true
  31022. });
  31023. Object.defineProperty(Mesh, "CAP_ALL", {
  31024. /**
  31025. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31026. */
  31027. get: function () {
  31028. return Mesh._CAP_ALL;
  31029. },
  31030. enumerable: true,
  31031. configurable: true
  31032. });
  31033. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31034. set: function (callback) {
  31035. if (this._onBeforeDrawObserver) {
  31036. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31037. }
  31038. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31039. },
  31040. enumerable: true,
  31041. configurable: true
  31042. });
  31043. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31044. get: function () {
  31045. return this._morphTargetManager;
  31046. },
  31047. set: function (value) {
  31048. if (this._morphTargetManager === value) {
  31049. return;
  31050. }
  31051. this._morphTargetManager = value;
  31052. this._syncGeometryWithMorphTargetManager();
  31053. },
  31054. enumerable: true,
  31055. configurable: true
  31056. });
  31057. Object.defineProperty(Mesh.prototype, "source", {
  31058. get: function () {
  31059. return this._source;
  31060. },
  31061. enumerable: true,
  31062. configurable: true
  31063. });
  31064. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31065. get: function () {
  31066. return this._unIndexed;
  31067. },
  31068. set: function (value) {
  31069. if (this._unIndexed !== value) {
  31070. this._unIndexed = value;
  31071. this._markSubMeshesAsAttributesDirty();
  31072. }
  31073. },
  31074. enumerable: true,
  31075. configurable: true
  31076. });
  31077. // Methods
  31078. /**
  31079. * Returns the string "Mesh".
  31080. */
  31081. Mesh.prototype.getClassName = function () {
  31082. return "Mesh";
  31083. };
  31084. /**
  31085. * Returns a string.
  31086. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31087. */
  31088. Mesh.prototype.toString = function (fullDetails) {
  31089. var ret = _super.prototype.toString.call(this, fullDetails);
  31090. ret += ", n vertices: " + this.getTotalVertices();
  31091. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31092. if (this.animations) {
  31093. for (var i = 0; i < this.animations.length; i++) {
  31094. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31095. }
  31096. }
  31097. if (fullDetails) {
  31098. if (this._geometry) {
  31099. var ib = this.getIndices();
  31100. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31101. if (vb && ib) {
  31102. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31103. }
  31104. }
  31105. else {
  31106. ret += ", flat shading: UNKNOWN";
  31107. }
  31108. }
  31109. return ret;
  31110. };
  31111. Mesh.prototype._unBindEffect = function () {
  31112. _super.prototype._unBindEffect.call(this);
  31113. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31114. var instance = _a[_i];
  31115. instance._unBindEffect();
  31116. }
  31117. };
  31118. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31119. /**
  31120. * True if the mesh has some Levels Of Details (LOD).
  31121. * Returns a boolean.
  31122. */
  31123. get: function () {
  31124. return this._LODLevels.length > 0;
  31125. },
  31126. enumerable: true,
  31127. configurable: true
  31128. });
  31129. /**
  31130. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31131. * @returns an array of {BABYLON.MeshLODLevel}
  31132. */
  31133. Mesh.prototype.getLODLevels = function () {
  31134. return this._LODLevels;
  31135. };
  31136. Mesh.prototype._sortLODLevels = function () {
  31137. this._LODLevels.sort(function (a, b) {
  31138. if (a.distance < b.distance) {
  31139. return 1;
  31140. }
  31141. if (a.distance > b.distance) {
  31142. return -1;
  31143. }
  31144. return 0;
  31145. });
  31146. };
  31147. /**
  31148. * Add a mesh as LOD level triggered at the given distance.
  31149. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31150. * @param {number} distance The distance from the center of the object to show this level
  31151. * @param {Mesh} mesh The mesh to be added as LOD level
  31152. * @return {Mesh} This mesh (for chaining)
  31153. */
  31154. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31155. if (mesh && mesh._masterMesh) {
  31156. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31157. return this;
  31158. }
  31159. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31160. this._LODLevels.push(level);
  31161. if (mesh) {
  31162. mesh._masterMesh = this;
  31163. }
  31164. this._sortLODLevels();
  31165. return this;
  31166. };
  31167. /**
  31168. * Returns the LOD level mesh at the passed distance or null if not found.
  31169. * It is related to the method `addLODLevel(distance, mesh)`.
  31170. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31171. * Returns an object Mesh or `null`.
  31172. */
  31173. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31174. for (var index = 0; index < this._LODLevels.length; index++) {
  31175. var level = this._LODLevels[index];
  31176. if (level.distance === distance) {
  31177. return level.mesh;
  31178. }
  31179. }
  31180. return null;
  31181. };
  31182. /**
  31183. * Remove a mesh from the LOD array
  31184. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31185. * @param {Mesh} mesh The mesh to be removed.
  31186. * @return {Mesh} This mesh (for chaining)
  31187. */
  31188. Mesh.prototype.removeLODLevel = function (mesh) {
  31189. for (var index = 0; index < this._LODLevels.length; index++) {
  31190. if (this._LODLevels[index].mesh === mesh) {
  31191. this._LODLevels.splice(index, 1);
  31192. if (mesh) {
  31193. mesh._masterMesh = null;
  31194. }
  31195. }
  31196. }
  31197. this._sortLODLevels();
  31198. return this;
  31199. };
  31200. /**
  31201. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31202. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31203. */
  31204. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31205. if (!this._LODLevels || this._LODLevels.length === 0) {
  31206. return this;
  31207. }
  31208. var bSphere;
  31209. if (boundingSphere) {
  31210. bSphere = boundingSphere;
  31211. }
  31212. else {
  31213. var boundingInfo = this.getBoundingInfo();
  31214. bSphere = boundingInfo.boundingSphere;
  31215. }
  31216. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31217. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31218. if (this.onLODLevelSelection) {
  31219. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31220. }
  31221. return this;
  31222. }
  31223. for (var index = 0; index < this._LODLevels.length; index++) {
  31224. var level = this._LODLevels[index];
  31225. if (level.distance < distanceToCamera) {
  31226. if (level.mesh) {
  31227. level.mesh._preActivate();
  31228. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31229. }
  31230. if (this.onLODLevelSelection) {
  31231. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31232. }
  31233. return level.mesh;
  31234. }
  31235. }
  31236. if (this.onLODLevelSelection) {
  31237. this.onLODLevelSelection(distanceToCamera, this, this);
  31238. }
  31239. return this;
  31240. };
  31241. Object.defineProperty(Mesh.prototype, "geometry", {
  31242. /**
  31243. * Returns the mesh internal Geometry object.
  31244. */
  31245. get: function () {
  31246. return this._geometry;
  31247. },
  31248. enumerable: true,
  31249. configurable: true
  31250. });
  31251. /**
  31252. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31253. */
  31254. Mesh.prototype.getTotalVertices = function () {
  31255. if (this._geometry === null || this._geometry === undefined) {
  31256. return 0;
  31257. }
  31258. return this._geometry.getTotalVertices();
  31259. };
  31260. /**
  31261. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31262. * 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.
  31263. * You can force the copy with forceCopy === true
  31264. * Returns null if the mesh has no geometry or no vertex buffer.
  31265. * Possible `kind` values :
  31266. * - BABYLON.VertexBuffer.PositionKind
  31267. * - BABYLON.VertexBuffer.UVKind
  31268. * - BABYLON.VertexBuffer.UV2Kind
  31269. * - BABYLON.VertexBuffer.UV3Kind
  31270. * - BABYLON.VertexBuffer.UV4Kind
  31271. * - BABYLON.VertexBuffer.UV5Kind
  31272. * - BABYLON.VertexBuffer.UV6Kind
  31273. * - BABYLON.VertexBuffer.ColorKind
  31274. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31275. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31276. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31277. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31278. */
  31279. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31280. if (!this._geometry) {
  31281. return null;
  31282. }
  31283. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31284. };
  31285. /**
  31286. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31287. * Returns `null` if the mesh has no geometry.
  31288. * Possible `kind` values :
  31289. * - BABYLON.VertexBuffer.PositionKind
  31290. * - BABYLON.VertexBuffer.UVKind
  31291. * - BABYLON.VertexBuffer.UV2Kind
  31292. * - BABYLON.VertexBuffer.UV3Kind
  31293. * - BABYLON.VertexBuffer.UV4Kind
  31294. * - BABYLON.VertexBuffer.UV5Kind
  31295. * - BABYLON.VertexBuffer.UV6Kind
  31296. * - BABYLON.VertexBuffer.ColorKind
  31297. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31298. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31299. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31300. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31301. */
  31302. Mesh.prototype.getVertexBuffer = function (kind) {
  31303. if (!this._geometry) {
  31304. return null;
  31305. }
  31306. return this._geometry.getVertexBuffer(kind);
  31307. };
  31308. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31309. if (!this._geometry) {
  31310. if (this._delayInfo) {
  31311. return this._delayInfo.indexOf(kind) !== -1;
  31312. }
  31313. return false;
  31314. }
  31315. return this._geometry.isVerticesDataPresent(kind);
  31316. };
  31317. /**
  31318. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31319. * Possible `kind` values :
  31320. * - BABYLON.VertexBuffer.PositionKind
  31321. * - BABYLON.VertexBuffer.UVKind
  31322. * - BABYLON.VertexBuffer.UV2Kind
  31323. * - BABYLON.VertexBuffer.UV3Kind
  31324. * - BABYLON.VertexBuffer.UV4Kind
  31325. * - BABYLON.VertexBuffer.UV5Kind
  31326. * - BABYLON.VertexBuffer.UV6Kind
  31327. * - BABYLON.VertexBuffer.ColorKind
  31328. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31329. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31330. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31331. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31332. */
  31333. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31334. if (!this._geometry) {
  31335. if (this._delayInfo) {
  31336. return this._delayInfo.indexOf(kind) !== -1;
  31337. }
  31338. return false;
  31339. }
  31340. return this._geometry.isVertexBufferUpdatable(kind);
  31341. };
  31342. /**
  31343. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31344. * Possible `kind` values :
  31345. * - BABYLON.VertexBuffer.PositionKind
  31346. * - BABYLON.VertexBuffer.UVKind
  31347. * - BABYLON.VertexBuffer.UV2Kind
  31348. * - BABYLON.VertexBuffer.UV3Kind
  31349. * - BABYLON.VertexBuffer.UV4Kind
  31350. * - BABYLON.VertexBuffer.UV5Kind
  31351. * - BABYLON.VertexBuffer.UV6Kind
  31352. * - BABYLON.VertexBuffer.ColorKind
  31353. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31354. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31355. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31356. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31357. */
  31358. Mesh.prototype.getVerticesDataKinds = function () {
  31359. if (!this._geometry) {
  31360. var result = new Array();
  31361. if (this._delayInfo) {
  31362. this._delayInfo.forEach(function (kind, index, array) {
  31363. result.push(kind);
  31364. });
  31365. }
  31366. return result;
  31367. }
  31368. return this._geometry.getVerticesDataKinds();
  31369. };
  31370. /**
  31371. * Returns a positive integer : the total number of indices in this mesh geometry.
  31372. * Returns zero if the mesh has no geometry.
  31373. */
  31374. Mesh.prototype.getTotalIndices = function () {
  31375. if (!this._geometry) {
  31376. return 0;
  31377. }
  31378. return this._geometry.getTotalIndices();
  31379. };
  31380. /**
  31381. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31382. * 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.
  31383. * Returns an empty array if the mesh has no geometry.
  31384. */
  31385. Mesh.prototype.getIndices = function (copyWhenShared) {
  31386. if (!this._geometry) {
  31387. return [];
  31388. }
  31389. return this._geometry.getIndices(copyWhenShared);
  31390. };
  31391. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31392. get: function () {
  31393. return this._masterMesh !== null && this._masterMesh !== undefined;
  31394. },
  31395. enumerable: true,
  31396. configurable: true
  31397. });
  31398. /**
  31399. * Determine if the current mesh is ready to be rendered
  31400. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31401. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31402. * @returns true if all associated assets are ready (material, textures, shaders)
  31403. */
  31404. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31405. if (completeCheck === void 0) { completeCheck = false; }
  31406. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31407. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31408. return false;
  31409. }
  31410. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31411. return false;
  31412. }
  31413. if (!this.subMeshes || this.subMeshes.length === 0) {
  31414. return true;
  31415. }
  31416. if (!completeCheck) {
  31417. return true;
  31418. }
  31419. var engine = this.getEngine();
  31420. var scene = this.getScene();
  31421. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31422. this.computeWorldMatrix();
  31423. var mat = this.material || scene.defaultMaterial;
  31424. if (mat) {
  31425. if (mat.storeEffectOnSubMeshes) {
  31426. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31427. var subMesh = _a[_i];
  31428. var effectiveMaterial = subMesh.getMaterial();
  31429. if (effectiveMaterial) {
  31430. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31431. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31432. return false;
  31433. }
  31434. }
  31435. else {
  31436. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31437. return false;
  31438. }
  31439. }
  31440. }
  31441. }
  31442. }
  31443. else {
  31444. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31445. return false;
  31446. }
  31447. }
  31448. }
  31449. // Shadows
  31450. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31451. var light = _c[_b];
  31452. var generator = light.getShadowGenerator();
  31453. if (generator) {
  31454. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31455. var subMesh = _e[_d];
  31456. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31457. return false;
  31458. }
  31459. }
  31460. }
  31461. }
  31462. // LOD
  31463. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31464. var lod = _g[_f];
  31465. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31466. return false;
  31467. }
  31468. }
  31469. return true;
  31470. };
  31471. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31472. /**
  31473. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31474. * This property is pertinent only for updatable parametric shapes.
  31475. */
  31476. get: function () {
  31477. return this._areNormalsFrozen;
  31478. },
  31479. enumerable: true,
  31480. configurable: true
  31481. });
  31482. /**
  31483. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31484. * It has no effect at all on other shapes.
  31485. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31486. * Returns the Mesh.
  31487. */
  31488. Mesh.prototype.freezeNormals = function () {
  31489. this._areNormalsFrozen = true;
  31490. return this;
  31491. };
  31492. /**
  31493. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31494. * It has no effect at all on other shapes.
  31495. * It reactivates the mesh normals computation if it was previously frozen.
  31496. * Returns the Mesh.
  31497. */
  31498. Mesh.prototype.unfreezeNormals = function () {
  31499. this._areNormalsFrozen = false;
  31500. return this;
  31501. };
  31502. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31503. /**
  31504. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31505. */
  31506. set: function (count) {
  31507. this._overridenInstanceCount = count;
  31508. },
  31509. enumerable: true,
  31510. configurable: true
  31511. });
  31512. // Methods
  31513. Mesh.prototype._preActivate = function () {
  31514. var sceneRenderId = this.getScene().getRenderId();
  31515. if (this._preActivateId === sceneRenderId) {
  31516. return this;
  31517. }
  31518. this._preActivateId = sceneRenderId;
  31519. this._visibleInstances = null;
  31520. return this;
  31521. };
  31522. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31523. if (this._visibleInstances) {
  31524. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31525. }
  31526. return this;
  31527. };
  31528. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31529. if (!this._visibleInstances) {
  31530. this._visibleInstances = {};
  31531. this._visibleInstances.defaultRenderId = renderId;
  31532. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31533. }
  31534. if (!this._visibleInstances[renderId]) {
  31535. this._visibleInstances[renderId] = new Array();
  31536. }
  31537. this._visibleInstances[renderId].push(instance);
  31538. return this;
  31539. };
  31540. /**
  31541. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31542. * This means the mesh underlying bounding box and sphere are recomputed.
  31543. * Returns the Mesh.
  31544. */
  31545. Mesh.prototype.refreshBoundingInfo = function () {
  31546. return this._refreshBoundingInfo(false);
  31547. };
  31548. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31549. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31550. return this;
  31551. }
  31552. var data = this._getPositionData(applySkeleton);
  31553. if (data) {
  31554. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31555. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31556. }
  31557. if (this.subMeshes) {
  31558. for (var index = 0; index < this.subMeshes.length; index++) {
  31559. this.subMeshes[index].refreshBoundingInfo();
  31560. }
  31561. }
  31562. this._updateBoundingInfo();
  31563. return this;
  31564. };
  31565. Mesh.prototype._getPositionData = function (applySkeleton) {
  31566. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31567. if (data && applySkeleton && this.skeleton) {
  31568. data = BABYLON.Tools.Slice(data);
  31569. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31570. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31571. if (matricesWeightsData && matricesIndicesData) {
  31572. var needExtras = this.numBoneInfluencers > 4;
  31573. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31574. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31575. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31576. var tempVector = BABYLON.Tmp.Vector3[0];
  31577. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31578. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31579. var matWeightIdx = 0;
  31580. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31581. finalMatrix.reset();
  31582. var inf;
  31583. var weight;
  31584. for (inf = 0; inf < 4; inf++) {
  31585. weight = matricesWeightsData[matWeightIdx + inf];
  31586. if (weight <= 0)
  31587. break;
  31588. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31589. finalMatrix.addToSelf(tempMatrix);
  31590. }
  31591. if (needExtras) {
  31592. for (inf = 0; inf < 4; inf++) {
  31593. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31594. if (weight <= 0)
  31595. break;
  31596. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31597. finalMatrix.addToSelf(tempMatrix);
  31598. }
  31599. }
  31600. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31601. tempVector.toArray(data, index);
  31602. }
  31603. }
  31604. }
  31605. return data;
  31606. };
  31607. Mesh.prototype._createGlobalSubMesh = function (force) {
  31608. var totalVertices = this.getTotalVertices();
  31609. if (!totalVertices || !this.getIndices()) {
  31610. return null;
  31611. }
  31612. // Check if we need to recreate the submeshes
  31613. if (this.subMeshes && this.subMeshes.length > 0) {
  31614. var ib = this.getIndices();
  31615. if (!ib) {
  31616. return null;
  31617. }
  31618. var totalIndices = ib.length;
  31619. var needToRecreate = false;
  31620. if (force) {
  31621. needToRecreate = true;
  31622. }
  31623. else {
  31624. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31625. var submesh = _a[_i];
  31626. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31627. needToRecreate = true;
  31628. break;
  31629. }
  31630. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31631. needToRecreate = true;
  31632. break;
  31633. }
  31634. }
  31635. }
  31636. if (!needToRecreate) {
  31637. return this.subMeshes[0];
  31638. }
  31639. }
  31640. this.releaseSubMeshes();
  31641. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31642. };
  31643. Mesh.prototype.subdivide = function (count) {
  31644. if (count < 1) {
  31645. return;
  31646. }
  31647. var totalIndices = this.getTotalIndices();
  31648. var subdivisionSize = (totalIndices / count) | 0;
  31649. var offset = 0;
  31650. // Ensure that subdivisionSize is a multiple of 3
  31651. while (subdivisionSize % 3 !== 0) {
  31652. subdivisionSize++;
  31653. }
  31654. this.releaseSubMeshes();
  31655. for (var index = 0; index < count; index++) {
  31656. if (offset >= totalIndices) {
  31657. break;
  31658. }
  31659. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31660. offset += subdivisionSize;
  31661. }
  31662. this.synchronizeInstances();
  31663. };
  31664. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31665. if (updatable === void 0) { updatable = false; }
  31666. if (!this._geometry) {
  31667. var vertexData = new BABYLON.VertexData();
  31668. vertexData.set(data, kind);
  31669. var scene = this.getScene();
  31670. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31671. }
  31672. else {
  31673. this._geometry.setVerticesData(kind, data, updatable, stride);
  31674. }
  31675. return this;
  31676. };
  31677. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31678. if (updatable === void 0) { updatable = true; }
  31679. var vb = this.getVertexBuffer(kind);
  31680. if (!vb || vb.isUpdatable() === updatable) {
  31681. return;
  31682. }
  31683. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31684. };
  31685. /**
  31686. * Sets the mesh VertexBuffer.
  31687. * Returns the Mesh.
  31688. */
  31689. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31690. if (!this._geometry) {
  31691. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31692. }
  31693. this._geometry.setVerticesBuffer(buffer);
  31694. return this;
  31695. };
  31696. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31697. if (!this._geometry) {
  31698. return this;
  31699. }
  31700. if (!makeItUnique) {
  31701. this._geometry.updateVerticesData(kind, data, updateExtends);
  31702. }
  31703. else {
  31704. this.makeGeometryUnique();
  31705. this.updateVerticesData(kind, data, updateExtends, false);
  31706. }
  31707. return this;
  31708. };
  31709. /**
  31710. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31711. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31712. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31713. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31714. * Returns the Mesh.
  31715. */
  31716. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31717. if (computeNormals === void 0) { computeNormals = true; }
  31718. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31719. if (!positions) {
  31720. return this;
  31721. }
  31722. positionFunction(positions);
  31723. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31724. if (computeNormals) {
  31725. var indices = this.getIndices();
  31726. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31727. if (!normals) {
  31728. return this;
  31729. }
  31730. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31731. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31732. }
  31733. return this;
  31734. };
  31735. /**
  31736. * Creates a un-shared specific occurence of the geometry for the mesh.
  31737. * Returns the Mesh.
  31738. */
  31739. Mesh.prototype.makeGeometryUnique = function () {
  31740. if (!this._geometry) {
  31741. return this;
  31742. }
  31743. var oldGeometry = this._geometry;
  31744. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31745. oldGeometry.releaseForMesh(this, true);
  31746. geometry.applyToMesh(this);
  31747. return this;
  31748. };
  31749. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31750. if (totalVertices === void 0) { totalVertices = null; }
  31751. if (updatable === void 0) { updatable = false; }
  31752. if (!this._geometry) {
  31753. var vertexData = new BABYLON.VertexData();
  31754. vertexData.indices = indices;
  31755. var scene = this.getScene();
  31756. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31757. }
  31758. else {
  31759. this._geometry.setIndices(indices, totalVertices, updatable);
  31760. }
  31761. return this;
  31762. };
  31763. /**
  31764. * Update the current index buffer
  31765. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31766. * Returns the Mesh.
  31767. */
  31768. Mesh.prototype.updateIndices = function (indices, offset) {
  31769. if (!this._geometry) {
  31770. return this;
  31771. }
  31772. this._geometry.updateIndices(indices, offset);
  31773. return this;
  31774. };
  31775. /**
  31776. * Invert the geometry to move from a right handed system to a left handed one.
  31777. * Returns the Mesh.
  31778. */
  31779. Mesh.prototype.toLeftHanded = function () {
  31780. if (!this._geometry) {
  31781. return this;
  31782. }
  31783. this._geometry.toLeftHanded();
  31784. return this;
  31785. };
  31786. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31787. if (!this._geometry) {
  31788. return this;
  31789. }
  31790. var engine = this.getScene().getEngine();
  31791. // Wireframe
  31792. var indexToBind;
  31793. if (this._unIndexed) {
  31794. indexToBind = null;
  31795. }
  31796. else {
  31797. switch (fillMode) {
  31798. case BABYLON.Material.PointFillMode:
  31799. indexToBind = null;
  31800. break;
  31801. case BABYLON.Material.WireFrameFillMode:
  31802. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31803. break;
  31804. default:
  31805. case BABYLON.Material.TriangleFillMode:
  31806. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31807. break;
  31808. }
  31809. }
  31810. // VBOs
  31811. this._geometry._bind(effect, indexToBind);
  31812. return this;
  31813. };
  31814. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31815. if (alternate === void 0) { alternate = false; }
  31816. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31817. return this;
  31818. }
  31819. this.onBeforeDrawObservable.notifyObservers(this);
  31820. var scene = this.getScene();
  31821. var engine = scene.getEngine();
  31822. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31823. // or triangles as points
  31824. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31825. }
  31826. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31827. // Triangles as wireframe
  31828. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31829. }
  31830. else {
  31831. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31832. }
  31833. if (scene._isAlternateRenderingEnabled && !alternate) {
  31834. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31835. if (!effect || !scene.activeCamera) {
  31836. return this;
  31837. }
  31838. scene._switchToAlternateCameraConfiguration(true);
  31839. this._effectiveMaterial.bindView(effect);
  31840. this._effectiveMaterial.bindViewProjection(effect);
  31841. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31842. this._draw(subMesh, fillMode, instancesCount, true);
  31843. engine.setViewport(scene.activeCamera.viewport);
  31844. scene._switchToAlternateCameraConfiguration(false);
  31845. this._effectiveMaterial.bindView(effect);
  31846. this._effectiveMaterial.bindViewProjection(effect);
  31847. }
  31848. return this;
  31849. };
  31850. /**
  31851. * Registers for this mesh a javascript function called just before the rendering process.
  31852. * This function is passed the current mesh.
  31853. * Return the Mesh.
  31854. */
  31855. Mesh.prototype.registerBeforeRender = function (func) {
  31856. this.onBeforeRenderObservable.add(func);
  31857. return this;
  31858. };
  31859. /**
  31860. * Disposes a previously registered javascript function called before the rendering.
  31861. * This function is passed the current mesh.
  31862. * Returns the Mesh.
  31863. */
  31864. Mesh.prototype.unregisterBeforeRender = function (func) {
  31865. this.onBeforeRenderObservable.removeCallback(func);
  31866. return this;
  31867. };
  31868. /**
  31869. * Registers for this mesh a javascript function called just after the rendering is complete.
  31870. * This function is passed the current mesh.
  31871. * Returns the Mesh.
  31872. */
  31873. Mesh.prototype.registerAfterRender = function (func) {
  31874. this.onAfterRenderObservable.add(func);
  31875. return this;
  31876. };
  31877. /**
  31878. * Disposes a previously registered javascript function called after the rendering.
  31879. * This function is passed the current mesh.
  31880. * Return the Mesh.
  31881. */
  31882. Mesh.prototype.unregisterAfterRender = function (func) {
  31883. this.onAfterRenderObservable.removeCallback(func);
  31884. return this;
  31885. };
  31886. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31887. var scene = this.getScene();
  31888. this._batchCache.mustReturn = false;
  31889. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31890. this._batchCache.visibleInstances[subMeshId] = null;
  31891. if (this._visibleInstances) {
  31892. var currentRenderId = scene.getRenderId();
  31893. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31894. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31895. var selfRenderId = this._renderId;
  31896. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31897. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31898. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31899. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31900. }
  31901. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31902. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31903. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31904. this._batchCache.mustReturn = true;
  31905. return this._batchCache;
  31906. }
  31907. if (currentRenderId !== selfRenderId) {
  31908. this._batchCache.renderSelf[subMeshId] = false;
  31909. }
  31910. }
  31911. this._renderIdForInstances[subMeshId] = currentRenderId;
  31912. }
  31913. return this._batchCache;
  31914. };
  31915. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31916. var visibleInstances = batch.visibleInstances[subMesh._id];
  31917. if (!visibleInstances) {
  31918. return this;
  31919. }
  31920. var matricesCount = visibleInstances.length + 1;
  31921. var bufferSize = matricesCount * 16 * 4;
  31922. var currentInstancesBufferSize = this._instancesBufferSize;
  31923. var instancesBuffer = this._instancesBuffer;
  31924. while (this._instancesBufferSize < bufferSize) {
  31925. this._instancesBufferSize *= 2;
  31926. }
  31927. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31928. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31929. }
  31930. var offset = 0;
  31931. var instancesCount = 0;
  31932. var world = this.getWorldMatrix();
  31933. if (batch.renderSelf[subMesh._id]) {
  31934. world.copyToArray(this._instancesData, offset);
  31935. offset += 16;
  31936. instancesCount++;
  31937. }
  31938. if (visibleInstances) {
  31939. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31940. var instance = visibleInstances[instanceIndex];
  31941. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31942. offset += 16;
  31943. instancesCount++;
  31944. }
  31945. }
  31946. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31947. if (instancesBuffer) {
  31948. instancesBuffer.dispose();
  31949. }
  31950. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31951. this._instancesBuffer = instancesBuffer;
  31952. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31953. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31954. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31955. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31956. }
  31957. else {
  31958. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31959. }
  31960. this._bind(subMesh, effect, fillMode);
  31961. this._draw(subMesh, fillMode, instancesCount);
  31962. engine.unbindInstanceAttributes();
  31963. return this;
  31964. };
  31965. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31966. var scene = this.getScene();
  31967. var engine = scene.getEngine();
  31968. if (hardwareInstancedRendering) {
  31969. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31970. }
  31971. else {
  31972. if (batch.renderSelf[subMesh._id]) {
  31973. // Draw
  31974. if (onBeforeDraw) {
  31975. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31976. }
  31977. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31978. }
  31979. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31980. if (visibleInstancesForSubMesh) {
  31981. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31982. var instance = visibleInstancesForSubMesh[instanceIndex];
  31983. // World
  31984. var world = instance.getWorldMatrix();
  31985. if (onBeforeDraw) {
  31986. onBeforeDraw(true, world, effectiveMaterial);
  31987. }
  31988. // Draw
  31989. this._draw(subMesh, fillMode);
  31990. }
  31991. }
  31992. }
  31993. return this;
  31994. };
  31995. /**
  31996. * Triggers the draw call for the mesh.
  31997. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  31998. * Returns the Mesh.
  31999. */
  32000. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32001. this._checkOcclusionQuery();
  32002. if (this._isOccluded) {
  32003. return this;
  32004. }
  32005. var scene = this.getScene();
  32006. // Managing instances
  32007. var batch = this._getInstancesRenderList(subMesh._id);
  32008. if (batch.mustReturn) {
  32009. return this;
  32010. }
  32011. // Checking geometry state
  32012. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32013. return this;
  32014. }
  32015. this.onBeforeRenderObservable.notifyObservers(this);
  32016. var engine = scene.getEngine();
  32017. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32018. // Material
  32019. var material = subMesh.getMaterial();
  32020. if (!material) {
  32021. return this;
  32022. }
  32023. this._effectiveMaterial = material;
  32024. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32025. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32026. return this;
  32027. }
  32028. }
  32029. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32030. return this;
  32031. }
  32032. // Alpha mode
  32033. if (enableAlphaMode) {
  32034. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32035. }
  32036. // Outline - step 1
  32037. var savedDepthWrite = engine.getDepthWrite();
  32038. if (this.renderOutline) {
  32039. engine.setDepthWrite(false);
  32040. scene.getOutlineRenderer().render(subMesh, batch);
  32041. engine.setDepthWrite(savedDepthWrite);
  32042. }
  32043. var effect;
  32044. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32045. effect = subMesh.effect;
  32046. }
  32047. else {
  32048. effect = this._effectiveMaterial.getEffect();
  32049. }
  32050. if (!effect) {
  32051. return this;
  32052. }
  32053. var sideOrientation = this.overrideMaterialSideOrientation;
  32054. if (sideOrientation == null) {
  32055. sideOrientation = this._effectiveMaterial.sideOrientation;
  32056. if (this._getWorldMatrixDeterminant() < 0) {
  32057. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32058. }
  32059. }
  32060. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32061. if (this._effectiveMaterial.forceDepthWrite) {
  32062. engine.setDepthWrite(true);
  32063. }
  32064. // Bind
  32065. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32066. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32067. this._bind(subMesh, effect, fillMode);
  32068. }
  32069. var world = this.getWorldMatrix();
  32070. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32071. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32072. }
  32073. else {
  32074. this._effectiveMaterial.bind(world, this);
  32075. }
  32076. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32077. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32078. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32079. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32080. }
  32081. // Draw
  32082. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32083. // Unbind
  32084. this._effectiveMaterial.unbind();
  32085. // Outline - step 2
  32086. if (this.renderOutline && savedDepthWrite) {
  32087. engine.setDepthWrite(true);
  32088. engine.setColorWrite(false);
  32089. scene.getOutlineRenderer().render(subMesh, batch);
  32090. engine.setColorWrite(true);
  32091. }
  32092. // Overlay
  32093. if (this.renderOverlay) {
  32094. var currentMode = engine.getAlphaMode();
  32095. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32096. scene.getOutlineRenderer().render(subMesh, batch, true);
  32097. engine.setAlphaMode(currentMode);
  32098. }
  32099. this.onAfterRenderObservable.notifyObservers(this);
  32100. return this;
  32101. };
  32102. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32103. if (isInstance && effectiveMaterial) {
  32104. effectiveMaterial.bindOnlyWorldMatrix(world);
  32105. }
  32106. };
  32107. /**
  32108. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32109. */
  32110. Mesh.prototype.getEmittedParticleSystems = function () {
  32111. var results = new Array();
  32112. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32113. var particleSystem = this.getScene().particleSystems[index];
  32114. if (particleSystem.emitter === this) {
  32115. results.push(particleSystem);
  32116. }
  32117. }
  32118. return results;
  32119. };
  32120. /**
  32121. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32122. */
  32123. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32124. var results = new Array();
  32125. var descendants = this.getDescendants();
  32126. descendants.push(this);
  32127. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32128. var particleSystem = this.getScene().particleSystems[index];
  32129. var emitter = particleSystem.emitter;
  32130. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32131. results.push(particleSystem);
  32132. }
  32133. }
  32134. return results;
  32135. };
  32136. Mesh.prototype._checkDelayState = function () {
  32137. var scene = this.getScene();
  32138. if (this._geometry) {
  32139. this._geometry.load(scene);
  32140. }
  32141. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32142. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32143. this._queueLoad(scene);
  32144. }
  32145. return this;
  32146. };
  32147. Mesh.prototype._queueLoad = function (scene) {
  32148. var _this = this;
  32149. scene._addPendingData(this);
  32150. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32151. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32152. if (data instanceof ArrayBuffer) {
  32153. _this._delayLoadingFunction(data, _this);
  32154. }
  32155. else {
  32156. _this._delayLoadingFunction(JSON.parse(data), _this);
  32157. }
  32158. _this.instances.forEach(function (instance) {
  32159. instance._syncSubMeshes();
  32160. });
  32161. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32162. scene._removePendingData(_this);
  32163. }, function () { }, scene.database, getBinaryData);
  32164. return this;
  32165. };
  32166. /**
  32167. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32168. */
  32169. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32170. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32171. return false;
  32172. }
  32173. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32174. return false;
  32175. }
  32176. this._checkDelayState();
  32177. return true;
  32178. };
  32179. /**
  32180. * Sets the mesh material by the material or multiMaterial `id` property.
  32181. * The material `id` is a string identifying the material or the multiMaterial.
  32182. * This method returns the Mesh.
  32183. */
  32184. Mesh.prototype.setMaterialByID = function (id) {
  32185. var materials = this.getScene().materials;
  32186. var index;
  32187. for (index = materials.length - 1; index > -1; index--) {
  32188. if (materials[index].id === id) {
  32189. this.material = materials[index];
  32190. return this;
  32191. }
  32192. }
  32193. // Multi
  32194. var multiMaterials = this.getScene().multiMaterials;
  32195. for (index = multiMaterials.length - 1; index > -1; index--) {
  32196. if (multiMaterials[index].id === id) {
  32197. this.material = multiMaterials[index];
  32198. return this;
  32199. }
  32200. }
  32201. return this;
  32202. };
  32203. /**
  32204. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32205. */
  32206. Mesh.prototype.getAnimatables = function () {
  32207. var results = new Array();
  32208. if (this.material) {
  32209. results.push(this.material);
  32210. }
  32211. if (this.skeleton) {
  32212. results.push(this.skeleton);
  32213. }
  32214. return results;
  32215. };
  32216. /**
  32217. * Modifies the mesh geometry according to the passed transformation matrix.
  32218. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32219. * The mesh normals are modified accordingly the same transformation.
  32220. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  32221. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32222. * Returns the Mesh.
  32223. */
  32224. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32225. // Position
  32226. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32227. return this;
  32228. }
  32229. var submeshes = this.subMeshes.splice(0);
  32230. this._resetPointsArrayCache();
  32231. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32232. var temp = new Array();
  32233. var index;
  32234. for (index = 0; index < data.length; index += 3) {
  32235. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32236. }
  32237. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32238. // Normals
  32239. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32240. return this;
  32241. }
  32242. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32243. temp = [];
  32244. for (index = 0; index < data.length; index += 3) {
  32245. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32246. }
  32247. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32248. // flip faces?
  32249. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32250. this.flipFaces();
  32251. }
  32252. // Restore submeshes
  32253. this.releaseSubMeshes();
  32254. this.subMeshes = submeshes;
  32255. return this;
  32256. };
  32257. /**
  32258. * Modifies the mesh geometry according to its own current World Matrix.
  32259. * The mesh World Matrix is then reset.
  32260. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32261. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32262. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32263. * Returns the Mesh.
  32264. */
  32265. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32266. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32267. this.scaling.copyFromFloats(1, 1, 1);
  32268. this.position.copyFromFloats(0, 0, 0);
  32269. this.rotation.copyFromFloats(0, 0, 0);
  32270. //only if quaternion is already set
  32271. if (this.rotationQuaternion) {
  32272. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32273. }
  32274. this._worldMatrix = BABYLON.Matrix.Identity();
  32275. return this;
  32276. };
  32277. Object.defineProperty(Mesh.prototype, "_positions", {
  32278. // Cache
  32279. get: function () {
  32280. if (this._geometry) {
  32281. return this._geometry._positions;
  32282. }
  32283. return null;
  32284. },
  32285. enumerable: true,
  32286. configurable: true
  32287. });
  32288. Mesh.prototype._resetPointsArrayCache = function () {
  32289. if (this._geometry) {
  32290. this._geometry._resetPointsArrayCache();
  32291. }
  32292. return this;
  32293. };
  32294. Mesh.prototype._generatePointsArray = function () {
  32295. if (this._geometry) {
  32296. return this._geometry._generatePointsArray();
  32297. }
  32298. return false;
  32299. };
  32300. /**
  32301. * Returns a new Mesh object generated from the current mesh properties.
  32302. * This method must not get confused with createInstance().
  32303. * The parameter `name` is a string, the name given to the new mesh.
  32304. * The optional parameter `newParent` can be any Node object (default `null`).
  32305. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32306. * 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.
  32307. */
  32308. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32309. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32310. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32311. };
  32312. /**
  32313. * Releases resources associated with this mesh.
  32314. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32315. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32316. */
  32317. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32318. var _this = this;
  32319. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32320. this.morphTargetManager = null;
  32321. if (this._geometry) {
  32322. this._geometry.releaseForMesh(this, true);
  32323. }
  32324. // Sources
  32325. var meshes = this.getScene().meshes;
  32326. meshes.forEach(function (abstractMesh) {
  32327. var mesh = abstractMesh;
  32328. if (mesh._source && mesh._source === _this) {
  32329. mesh._source = null;
  32330. }
  32331. });
  32332. this._source = null;
  32333. // Instances
  32334. if (this._instancesBuffer) {
  32335. this._instancesBuffer.dispose();
  32336. this._instancesBuffer = null;
  32337. }
  32338. while (this.instances.length) {
  32339. this.instances[0].dispose();
  32340. }
  32341. // Effect layers.
  32342. var effectLayers = this.getScene().effectLayers;
  32343. for (var i = 0; i < effectLayers.length; i++) {
  32344. var effectLayer = effectLayers[i];
  32345. if (effectLayer) {
  32346. effectLayer._disposeMesh(this);
  32347. }
  32348. }
  32349. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32350. };
  32351. /**
  32352. * Modifies the mesh geometry according to a displacement map.
  32353. * 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.
  32354. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32355. * This method returns nothing.
  32356. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32357. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32358. * 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.
  32359. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32360. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32361. *
  32362. * Returns the Mesh.
  32363. */
  32364. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32365. var _this = this;
  32366. var scene = this.getScene();
  32367. var onload = function (img) {
  32368. // Getting height map data
  32369. var canvas = document.createElement("canvas");
  32370. var context = canvas.getContext("2d");
  32371. var heightMapWidth = img.width;
  32372. var heightMapHeight = img.height;
  32373. canvas.width = heightMapWidth;
  32374. canvas.height = heightMapHeight;
  32375. context.drawImage(img, 0, 0);
  32376. // Create VertexData from map data
  32377. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32378. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32379. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32380. //execute success callback, if set
  32381. if (onSuccess) {
  32382. onSuccess(_this);
  32383. }
  32384. };
  32385. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32386. return this;
  32387. };
  32388. /**
  32389. * Modifies the mesh geometry according to a displacementMap buffer.
  32390. * 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.
  32391. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32392. * This method returns nothing.
  32393. * 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.
  32394. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32395. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32396. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32397. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32398. *
  32399. * Returns the Mesh.
  32400. */
  32401. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32402. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32403. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32404. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32405. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32406. return this;
  32407. }
  32408. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32409. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32410. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32411. var position = BABYLON.Vector3.Zero();
  32412. var normal = BABYLON.Vector3.Zero();
  32413. var uv = BABYLON.Vector2.Zero();
  32414. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32415. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32416. for (var index = 0; index < positions.length; index += 3) {
  32417. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32418. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32419. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32420. // Compute height
  32421. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32422. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32423. var pos = (u + v * heightMapWidth) * 4;
  32424. var r = buffer[pos] / 255.0;
  32425. var g = buffer[pos + 1] / 255.0;
  32426. var b = buffer[pos + 2] / 255.0;
  32427. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32428. normal.normalize();
  32429. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32430. position = position.add(normal);
  32431. position.toArray(positions, index);
  32432. }
  32433. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32434. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32435. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32436. return this;
  32437. };
  32438. /**
  32439. * Modify the mesh to get a flat shading rendering.
  32440. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32441. * This method returns the Mesh.
  32442. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32443. */
  32444. Mesh.prototype.convertToFlatShadedMesh = function () {
  32445. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32446. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32447. var kinds = this.getVerticesDataKinds();
  32448. var vbs = {};
  32449. var data = {};
  32450. var newdata = {};
  32451. var updatableNormals = false;
  32452. var kindIndex;
  32453. var kind;
  32454. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32455. kind = kinds[kindIndex];
  32456. var vertexBuffer = this.getVertexBuffer(kind);
  32457. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32458. updatableNormals = vertexBuffer.isUpdatable();
  32459. kinds.splice(kindIndex, 1);
  32460. kindIndex--;
  32461. continue;
  32462. }
  32463. vbs[kind] = vertexBuffer;
  32464. data[kind] = vbs[kind].getData();
  32465. newdata[kind] = [];
  32466. }
  32467. // Save previous submeshes
  32468. var previousSubmeshes = this.subMeshes.slice(0);
  32469. var indices = this.getIndices();
  32470. var totalIndices = this.getTotalIndices();
  32471. // Generating unique vertices per face
  32472. var index;
  32473. for (index = 0; index < totalIndices; index++) {
  32474. var vertexIndex = indices[index];
  32475. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32476. kind = kinds[kindIndex];
  32477. var stride = vbs[kind].getStrideSize();
  32478. for (var offset = 0; offset < stride; offset++) {
  32479. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32480. }
  32481. }
  32482. }
  32483. // Updating faces & normal
  32484. var normals = [];
  32485. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32486. for (index = 0; index < totalIndices; index += 3) {
  32487. indices[index] = index;
  32488. indices[index + 1] = index + 1;
  32489. indices[index + 2] = index + 2;
  32490. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32491. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32492. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32493. var p1p2 = p1.subtract(p2);
  32494. var p3p2 = p3.subtract(p2);
  32495. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32496. // Store same normals for every vertex
  32497. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32498. normals.push(normal.x);
  32499. normals.push(normal.y);
  32500. normals.push(normal.z);
  32501. }
  32502. }
  32503. this.setIndices(indices);
  32504. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32505. // Updating vertex buffers
  32506. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32507. kind = kinds[kindIndex];
  32508. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32509. }
  32510. // Updating submeshes
  32511. this.releaseSubMeshes();
  32512. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32513. var previousOne = previousSubmeshes[submeshIndex];
  32514. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32515. }
  32516. this.synchronizeInstances();
  32517. return this;
  32518. };
  32519. /**
  32520. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32521. * In other words, more vertices, no more indices and a single bigger VBO.
  32522. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32523. * Returns the Mesh.
  32524. */
  32525. Mesh.prototype.convertToUnIndexedMesh = function () {
  32526. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32527. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32528. var kinds = this.getVerticesDataKinds();
  32529. var vbs = {};
  32530. var data = {};
  32531. var newdata = {};
  32532. var kindIndex;
  32533. var kind;
  32534. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32535. kind = kinds[kindIndex];
  32536. var vertexBuffer = this.getVertexBuffer(kind);
  32537. vbs[kind] = vertexBuffer;
  32538. data[kind] = vbs[kind].getData();
  32539. newdata[kind] = [];
  32540. }
  32541. // Save previous submeshes
  32542. var previousSubmeshes = this.subMeshes.slice(0);
  32543. var indices = this.getIndices();
  32544. var totalIndices = this.getTotalIndices();
  32545. // Generating unique vertices per face
  32546. var index;
  32547. for (index = 0; index < totalIndices; index++) {
  32548. var vertexIndex = indices[index];
  32549. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32550. kind = kinds[kindIndex];
  32551. var stride = vbs[kind].getStrideSize();
  32552. for (var offset = 0; offset < stride; offset++) {
  32553. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32554. }
  32555. }
  32556. }
  32557. // Updating indices
  32558. for (index = 0; index < totalIndices; index += 3) {
  32559. indices[index] = index;
  32560. indices[index + 1] = index + 1;
  32561. indices[index + 2] = index + 2;
  32562. }
  32563. this.setIndices(indices);
  32564. // Updating vertex buffers
  32565. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32566. kind = kinds[kindIndex];
  32567. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32568. }
  32569. // Updating submeshes
  32570. this.releaseSubMeshes();
  32571. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32572. var previousOne = previousSubmeshes[submeshIndex];
  32573. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32574. }
  32575. this._unIndexed = true;
  32576. this.synchronizeInstances();
  32577. return this;
  32578. };
  32579. /**
  32580. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32581. * This method returns the Mesh.
  32582. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32583. */
  32584. Mesh.prototype.flipFaces = function (flipNormals) {
  32585. if (flipNormals === void 0) { flipNormals = false; }
  32586. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32587. var i;
  32588. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32589. for (i = 0; i < vertex_data.normals.length; i++) {
  32590. vertex_data.normals[i] *= -1;
  32591. }
  32592. }
  32593. if (vertex_data.indices) {
  32594. var temp;
  32595. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32596. // reassign indices
  32597. temp = vertex_data.indices[i + 1];
  32598. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32599. vertex_data.indices[i + 2] = temp;
  32600. }
  32601. }
  32602. vertex_data.applyToMesh(this);
  32603. return this;
  32604. };
  32605. // Instances
  32606. /**
  32607. * Creates a new InstancedMesh object from the mesh model.
  32608. * An instance shares the same properties and the same material than its model.
  32609. * Only these properties of each instance can then be set individually :
  32610. * - position
  32611. * - rotation
  32612. * - rotationQuaternion
  32613. * - setPivotMatrix
  32614. * - scaling
  32615. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32616. * Warning : this method is not supported for Line mesh and LineSystem
  32617. */
  32618. Mesh.prototype.createInstance = function (name) {
  32619. return new BABYLON.InstancedMesh(name, this);
  32620. };
  32621. /**
  32622. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32623. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32624. * This method returns the Mesh.
  32625. */
  32626. Mesh.prototype.synchronizeInstances = function () {
  32627. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32628. var instance = this.instances[instanceIndex];
  32629. instance._syncSubMeshes();
  32630. }
  32631. return this;
  32632. };
  32633. /**
  32634. * Simplify the mesh according to the given array of settings.
  32635. * Function will return immediately and will simplify async. It returns the Mesh.
  32636. * @param settings a collection of simplification settings.
  32637. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32638. * @param type the type of simplification to run.
  32639. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32640. */
  32641. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32642. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32643. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32644. this.getScene().simplificationQueue.addTask({
  32645. settings: settings,
  32646. parallelProcessing: parallelProcessing,
  32647. mesh: this,
  32648. simplificationType: simplificationType,
  32649. successCallback: successCallback
  32650. });
  32651. return this;
  32652. };
  32653. /**
  32654. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32655. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32656. * This should be used together with the simplification to avoid disappearing triangles.
  32657. * Returns the Mesh.
  32658. * @param successCallback an optional success callback to be called after the optimization finished.
  32659. */
  32660. Mesh.prototype.optimizeIndices = function (successCallback) {
  32661. var _this = this;
  32662. var indices = this.getIndices();
  32663. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32664. if (!positions || !indices) {
  32665. return this;
  32666. }
  32667. var vectorPositions = new Array();
  32668. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32669. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32670. }
  32671. var dupes = new Array();
  32672. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32673. var realPos = vectorPositions.length - 1 - iteration;
  32674. var testedPosition = vectorPositions[realPos];
  32675. for (var j = 0; j < realPos; ++j) {
  32676. var againstPosition = vectorPositions[j];
  32677. if (testedPosition.equals(againstPosition)) {
  32678. dupes[realPos] = j;
  32679. break;
  32680. }
  32681. }
  32682. }, function () {
  32683. for (var i = 0; i < indices.length; ++i) {
  32684. indices[i] = dupes[indices[i]] || indices[i];
  32685. }
  32686. //indices are now reordered
  32687. var originalSubMeshes = _this.subMeshes.slice(0);
  32688. _this.setIndices(indices);
  32689. _this.subMeshes = originalSubMeshes;
  32690. if (successCallback) {
  32691. successCallback(_this);
  32692. }
  32693. });
  32694. return this;
  32695. };
  32696. Mesh.prototype.serialize = function (serializationObject) {
  32697. serializationObject.name = this.name;
  32698. serializationObject.id = this.id;
  32699. serializationObject.type = this.getClassName();
  32700. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32701. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32702. }
  32703. serializationObject.position = this.position.asArray();
  32704. if (this.rotationQuaternion) {
  32705. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32706. }
  32707. else if (this.rotation) {
  32708. serializationObject.rotation = this.rotation.asArray();
  32709. }
  32710. serializationObject.scaling = this.scaling.asArray();
  32711. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32712. serializationObject.isEnabled = this.isEnabled(false);
  32713. serializationObject.isVisible = this.isVisible;
  32714. serializationObject.infiniteDistance = this.infiniteDistance;
  32715. serializationObject.pickable = this.isPickable;
  32716. serializationObject.receiveShadows = this.receiveShadows;
  32717. serializationObject.billboardMode = this.billboardMode;
  32718. serializationObject.visibility = this.visibility;
  32719. serializationObject.checkCollisions = this.checkCollisions;
  32720. serializationObject.isBlocker = this.isBlocker;
  32721. // Parent
  32722. if (this.parent) {
  32723. serializationObject.parentId = this.parent.id;
  32724. }
  32725. // Geometry
  32726. serializationObject.isUnIndexed = this.isUnIndexed;
  32727. var geometry = this._geometry;
  32728. if (geometry) {
  32729. var geometryId = geometry.id;
  32730. serializationObject.geometryId = geometryId;
  32731. // SubMeshes
  32732. serializationObject.subMeshes = [];
  32733. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32734. var subMesh = this.subMeshes[subIndex];
  32735. serializationObject.subMeshes.push({
  32736. materialIndex: subMesh.materialIndex,
  32737. verticesStart: subMesh.verticesStart,
  32738. verticesCount: subMesh.verticesCount,
  32739. indexStart: subMesh.indexStart,
  32740. indexCount: subMesh.indexCount
  32741. });
  32742. }
  32743. }
  32744. // Material
  32745. if (this.material) {
  32746. serializationObject.materialId = this.material.id;
  32747. }
  32748. else {
  32749. this.material = null;
  32750. }
  32751. // Morph targets
  32752. if (this.morphTargetManager) {
  32753. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32754. }
  32755. // Skeleton
  32756. if (this.skeleton) {
  32757. serializationObject.skeletonId = this.skeleton.id;
  32758. }
  32759. // Physics
  32760. //TODO implement correct serialization for physics impostors.
  32761. var impostor = this.getPhysicsImpostor();
  32762. if (impostor) {
  32763. serializationObject.physicsMass = impostor.getParam("mass");
  32764. serializationObject.physicsFriction = impostor.getParam("friction");
  32765. serializationObject.physicsRestitution = impostor.getParam("mass");
  32766. serializationObject.physicsImpostor = impostor.type;
  32767. }
  32768. // Metadata
  32769. if (this.metadata) {
  32770. serializationObject.metadata = this.metadata;
  32771. }
  32772. // Instances
  32773. serializationObject.instances = [];
  32774. for (var index = 0; index < this.instances.length; index++) {
  32775. var instance = this.instances[index];
  32776. var serializationInstance = {
  32777. name: instance.name,
  32778. id: instance.id,
  32779. position: instance.position.asArray(),
  32780. scaling: instance.scaling.asArray()
  32781. };
  32782. if (instance.rotationQuaternion) {
  32783. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32784. }
  32785. else if (instance.rotation) {
  32786. serializationInstance.rotation = instance.rotation.asArray();
  32787. }
  32788. serializationObject.instances.push(serializationInstance);
  32789. // Animations
  32790. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32791. serializationInstance.ranges = instance.serializeAnimationRanges();
  32792. }
  32793. //
  32794. // Animations
  32795. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32796. serializationObject.ranges = this.serializeAnimationRanges();
  32797. // Layer mask
  32798. serializationObject.layerMask = this.layerMask;
  32799. // Alpha
  32800. serializationObject.alphaIndex = this.alphaIndex;
  32801. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32802. // Overlay
  32803. serializationObject.overlayAlpha = this.overlayAlpha;
  32804. serializationObject.overlayColor = this.overlayColor.asArray();
  32805. serializationObject.renderOverlay = this.renderOverlay;
  32806. // Fog
  32807. serializationObject.applyFog = this.applyFog;
  32808. // Action Manager
  32809. if (this.actionManager) {
  32810. serializationObject.actions = this.actionManager.serialize(this.name);
  32811. }
  32812. };
  32813. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32814. if (!this.geometry) {
  32815. return;
  32816. }
  32817. this._markSubMeshesAsAttributesDirty();
  32818. var morphTargetManager = this._morphTargetManager;
  32819. if (morphTargetManager && morphTargetManager.vertexCount) {
  32820. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32821. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32822. this.morphTargetManager = null;
  32823. return;
  32824. }
  32825. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32826. var morphTarget = morphTargetManager.getActiveTarget(index);
  32827. var positions = morphTarget.getPositions();
  32828. if (!positions) {
  32829. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32830. return;
  32831. }
  32832. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32833. var normals = morphTarget.getNormals();
  32834. if (normals) {
  32835. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32836. }
  32837. var tangents = morphTarget.getTangents();
  32838. if (tangents) {
  32839. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32840. }
  32841. }
  32842. }
  32843. else {
  32844. var index = 0;
  32845. // Positions
  32846. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32847. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32848. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32849. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32850. }
  32851. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32852. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32853. }
  32854. index++;
  32855. }
  32856. }
  32857. };
  32858. // Statics
  32859. /**
  32860. * Returns a new Mesh object parsed from the source provided.
  32861. * The parameter `parsedMesh` is the source.
  32862. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32863. */
  32864. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32865. var mesh;
  32866. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32867. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32868. }
  32869. else {
  32870. mesh = new Mesh(parsedMesh.name, scene);
  32871. }
  32872. mesh.id = parsedMesh.id;
  32873. if (BABYLON.Tags) {
  32874. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32875. }
  32876. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32877. if (parsedMesh.metadata !== undefined) {
  32878. mesh.metadata = parsedMesh.metadata;
  32879. }
  32880. if (parsedMesh.rotationQuaternion) {
  32881. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32882. }
  32883. else if (parsedMesh.rotation) {
  32884. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32885. }
  32886. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32887. if (parsedMesh.localMatrix) {
  32888. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32889. }
  32890. else if (parsedMesh.pivotMatrix) {
  32891. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32892. }
  32893. mesh.setEnabled(parsedMesh.isEnabled);
  32894. mesh.isVisible = parsedMesh.isVisible;
  32895. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32896. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32897. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32898. if (parsedMesh.applyFog !== undefined) {
  32899. mesh.applyFog = parsedMesh.applyFog;
  32900. }
  32901. if (parsedMesh.pickable !== undefined) {
  32902. mesh.isPickable = parsedMesh.pickable;
  32903. }
  32904. if (parsedMesh.alphaIndex !== undefined) {
  32905. mesh.alphaIndex = parsedMesh.alphaIndex;
  32906. }
  32907. mesh.receiveShadows = parsedMesh.receiveShadows;
  32908. mesh.billboardMode = parsedMesh.billboardMode;
  32909. if (parsedMesh.visibility !== undefined) {
  32910. mesh.visibility = parsedMesh.visibility;
  32911. }
  32912. mesh.checkCollisions = parsedMesh.checkCollisions;
  32913. if (parsedMesh.isBlocker !== undefined) {
  32914. mesh.isBlocker = parsedMesh.isBlocker;
  32915. }
  32916. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32917. // freezeWorldMatrix
  32918. if (parsedMesh.freezeWorldMatrix) {
  32919. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32920. }
  32921. // Parent
  32922. if (parsedMesh.parentId) {
  32923. mesh._waitingParentId = parsedMesh.parentId;
  32924. }
  32925. // Actions
  32926. if (parsedMesh.actions !== undefined) {
  32927. mesh._waitingActions = parsedMesh.actions;
  32928. }
  32929. // Overlay
  32930. if (parsedMesh.overlayAlpha !== undefined) {
  32931. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32932. }
  32933. if (parsedMesh.overlayColor !== undefined) {
  32934. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32935. }
  32936. if (parsedMesh.renderOverlay !== undefined) {
  32937. mesh.renderOverlay = parsedMesh.renderOverlay;
  32938. }
  32939. // Geometry
  32940. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32941. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32942. if (parsedMesh.delayLoadingFile) {
  32943. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32944. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32945. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32946. if (parsedMesh._binaryInfo) {
  32947. mesh._binaryInfo = parsedMesh._binaryInfo;
  32948. }
  32949. mesh._delayInfo = [];
  32950. if (parsedMesh.hasUVs) {
  32951. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32952. }
  32953. if (parsedMesh.hasUVs2) {
  32954. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32955. }
  32956. if (parsedMesh.hasUVs3) {
  32957. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32958. }
  32959. if (parsedMesh.hasUVs4) {
  32960. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32961. }
  32962. if (parsedMesh.hasUVs5) {
  32963. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32964. }
  32965. if (parsedMesh.hasUVs6) {
  32966. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32967. }
  32968. if (parsedMesh.hasColors) {
  32969. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32970. }
  32971. if (parsedMesh.hasMatricesIndices) {
  32972. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32973. }
  32974. if (parsedMesh.hasMatricesWeights) {
  32975. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32976. }
  32977. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32978. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32979. mesh._checkDelayState();
  32980. }
  32981. }
  32982. else {
  32983. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32984. }
  32985. // Material
  32986. if (parsedMesh.materialId) {
  32987. mesh.setMaterialByID(parsedMesh.materialId);
  32988. }
  32989. else {
  32990. mesh.material = null;
  32991. }
  32992. // Morph targets
  32993. if (parsedMesh.morphTargetManagerId > -1) {
  32994. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32995. }
  32996. // Skeleton
  32997. if (parsedMesh.skeletonId > -1) {
  32998. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  32999. if (parsedMesh.numBoneInfluencers) {
  33000. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33001. }
  33002. }
  33003. // Animations
  33004. if (parsedMesh.animations) {
  33005. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33006. var parsedAnimation = parsedMesh.animations[animationIndex];
  33007. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33008. }
  33009. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33010. }
  33011. if (parsedMesh.autoAnimate) {
  33012. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33013. }
  33014. // Layer Mask
  33015. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33016. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33017. }
  33018. else {
  33019. mesh.layerMask = 0x0FFFFFFF;
  33020. }
  33021. // Physics
  33022. if (parsedMesh.physicsImpostor) {
  33023. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33024. mass: parsedMesh.physicsMass,
  33025. friction: parsedMesh.physicsFriction,
  33026. restitution: parsedMesh.physicsRestitution
  33027. }, scene);
  33028. }
  33029. // Instances
  33030. if (parsedMesh.instances) {
  33031. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33032. var parsedInstance = parsedMesh.instances[index];
  33033. var instance = mesh.createInstance(parsedInstance.name);
  33034. if (parsedInstance.id) {
  33035. instance.id = parsedInstance.id;
  33036. }
  33037. if (BABYLON.Tags) {
  33038. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33039. }
  33040. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33041. if (parsedInstance.parentId) {
  33042. instance._waitingParentId = parsedInstance.parentId;
  33043. }
  33044. if (parsedInstance.rotationQuaternion) {
  33045. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33046. }
  33047. else if (parsedInstance.rotation) {
  33048. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33049. }
  33050. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33051. instance.checkCollisions = mesh.checkCollisions;
  33052. if (parsedMesh.animations) {
  33053. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33054. parsedAnimation = parsedMesh.animations[animationIndex];
  33055. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33056. }
  33057. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33058. }
  33059. }
  33060. }
  33061. return mesh;
  33062. };
  33063. /**
  33064. * Creates a ribbon mesh.
  33065. * Please consider using the same method from the MeshBuilder class instead.
  33066. * 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.
  33067. *
  33068. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33069. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33070. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33071. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33072. * 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.
  33073. * 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.
  33074. * 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
  33075. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33076. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33077. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33078. */
  33079. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33080. if (closeArray === void 0) { closeArray = false; }
  33081. if (updatable === void 0) { updatable = false; }
  33082. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33083. pathArray: pathArray,
  33084. closeArray: closeArray,
  33085. closePath: closePath,
  33086. offset: offset,
  33087. updatable: updatable,
  33088. sideOrientation: sideOrientation,
  33089. instance: instance
  33090. }, scene);
  33091. };
  33092. /**
  33093. * Creates a plane polygonal mesh. By default, this is a disc.
  33094. * Please consider using the same method from the MeshBuilder class instead.
  33095. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33096. * 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.
  33097. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33098. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33099. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33100. */
  33101. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33102. if (scene === void 0) { scene = null; }
  33103. var options = {
  33104. radius: radius,
  33105. tessellation: tessellation,
  33106. sideOrientation: sideOrientation,
  33107. updatable: updatable
  33108. };
  33109. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33110. };
  33111. /**
  33112. * Creates a box mesh.
  33113. * Please consider using the same method from the MeshBuilder class instead.
  33114. * The parameter `size` sets the size (float) of each box side (default 1).
  33115. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33116. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33117. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33118. */
  33119. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33120. if (scene === void 0) { scene = null; }
  33121. var options = {
  33122. size: size,
  33123. sideOrientation: sideOrientation,
  33124. updatable: updatable
  33125. };
  33126. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33127. };
  33128. /**
  33129. * Creates a sphere mesh.
  33130. * Please consider using the same method from the MeshBuilder class instead.
  33131. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33132. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33133. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33134. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33135. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33136. */
  33137. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33138. var options = {
  33139. segments: segments,
  33140. diameterX: diameter,
  33141. diameterY: diameter,
  33142. diameterZ: diameter,
  33143. sideOrientation: sideOrientation,
  33144. updatable: updatable
  33145. };
  33146. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33147. };
  33148. /**
  33149. * Creates a cylinder or a cone mesh.
  33150. * Please consider using the same method from the MeshBuilder class instead.
  33151. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33152. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33153. * 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.
  33154. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33155. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33156. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33157. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33158. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33159. */
  33160. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33161. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33162. if (scene !== undefined) {
  33163. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33164. updatable = scene;
  33165. }
  33166. scene = subdivisions;
  33167. subdivisions = 1;
  33168. }
  33169. var options = {
  33170. height: height,
  33171. diameterTop: diameterTop,
  33172. diameterBottom: diameterBottom,
  33173. tessellation: tessellation,
  33174. subdivisions: subdivisions,
  33175. sideOrientation: sideOrientation,
  33176. updatable: updatable
  33177. };
  33178. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33179. };
  33180. // Torus (Code from SharpDX.org)
  33181. /**
  33182. * Creates a torus mesh.
  33183. * Please consider using the same method from the MeshBuilder class instead.
  33184. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33185. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33186. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33187. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33188. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33189. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33190. */
  33191. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33192. var options = {
  33193. diameter: diameter,
  33194. thickness: thickness,
  33195. tessellation: tessellation,
  33196. sideOrientation: sideOrientation,
  33197. updatable: updatable
  33198. };
  33199. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33200. };
  33201. /**
  33202. * Creates a torus knot mesh.
  33203. * Please consider using the same method from the MeshBuilder class instead.
  33204. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33205. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33206. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33207. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33208. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33209. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33210. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33211. */
  33212. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33213. var options = {
  33214. radius: radius,
  33215. tube: tube,
  33216. radialSegments: radialSegments,
  33217. tubularSegments: tubularSegments,
  33218. p: p,
  33219. q: q,
  33220. sideOrientation: sideOrientation,
  33221. updatable: updatable
  33222. };
  33223. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33224. };
  33225. /**
  33226. * Creates a line mesh.
  33227. * Please consider using the same method from the MeshBuilder class instead.
  33228. * 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.
  33229. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33230. * The parameter `points` is an array successive Vector3.
  33231. * 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
  33232. * When updating an instance, remember that only point positions can change, not the number of points.
  33233. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33234. */
  33235. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33236. if (scene === void 0) { scene = null; }
  33237. if (updatable === void 0) { updatable = false; }
  33238. if (instance === void 0) { instance = null; }
  33239. var options = {
  33240. points: points,
  33241. updatable: updatable,
  33242. instance: instance
  33243. };
  33244. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33245. };
  33246. /**
  33247. * Creates a dashed line mesh.
  33248. * Please consider using the same method from the MeshBuilder class instead.
  33249. * 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.
  33250. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33251. * The parameter `points` is an array successive Vector3.
  33252. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33253. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33254. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33255. * 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
  33256. * When updating an instance, remember that only point positions can change, not the number of points.
  33257. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33258. */
  33259. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33260. if (scene === void 0) { scene = null; }
  33261. var options = {
  33262. points: points,
  33263. dashSize: dashSize,
  33264. gapSize: gapSize,
  33265. dashNb: dashNb,
  33266. updatable: updatable,
  33267. instance: instance
  33268. };
  33269. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33270. };
  33271. /**
  33272. * Creates a polygon mesh.
  33273. * Please consider using the same method from the MeshBuilder class instead.
  33274. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33275. * 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.
  33276. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33277. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33278. * Remember you can only change the shape positions, not their number when updating a polygon.
  33279. */
  33280. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33281. var options = {
  33282. shape: shape,
  33283. holes: holes,
  33284. updatable: updatable,
  33285. sideOrientation: sideOrientation
  33286. };
  33287. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33288. };
  33289. /**
  33290. * Creates an extruded polygon mesh, with depth in the Y direction.
  33291. * Please consider using the same method from the MeshBuilder class instead.
  33292. */
  33293. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33294. var options = {
  33295. shape: shape,
  33296. holes: holes,
  33297. depth: depth,
  33298. updatable: updatable,
  33299. sideOrientation: sideOrientation
  33300. };
  33301. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33302. };
  33303. /**
  33304. * Creates an extruded shape mesh.
  33305. * 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.
  33306. * Please consider using the same method from the MeshBuilder class instead.
  33307. *
  33308. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  33309. * 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
  33310. * extruded along the Z axis.
  33311. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33312. * 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.
  33313. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33314. * 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
  33315. * 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
  33316. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33317. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33318. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33319. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33320. */
  33321. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33322. if (scene === void 0) { scene = null; }
  33323. var options = {
  33324. shape: shape,
  33325. path: path,
  33326. scale: scale,
  33327. rotation: rotation,
  33328. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33329. sideOrientation: sideOrientation,
  33330. instance: instance,
  33331. updatable: updatable
  33332. };
  33333. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33334. };
  33335. /**
  33336. * Creates an custom extruded shape mesh.
  33337. * 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.
  33338. * Please consider using the same method from the MeshBuilder class instead.
  33339. *
  33340. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  33341. * 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
  33342. * extruded along the Z axis.
  33343. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33344. * 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
  33345. * and the distance of this point from the begining of the path :
  33346. * ```javascript
  33347. * var rotationFunction = function(i, distance) {
  33348. * // do things
  33349. * return rotationValue; }
  33350. * ```
  33351. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33352. * 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
  33353. * and the distance of this point from the begining of the path :
  33354. * ```javascript
  33355. * var scaleFunction = function(i, distance) {
  33356. * // do things
  33357. * return scaleValue;}
  33358. * ```
  33359. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33360. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33361. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33362. * 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
  33363. * 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
  33364. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33365. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33366. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33367. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33368. */
  33369. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33370. var options = {
  33371. shape: shape,
  33372. path: path,
  33373. scaleFunction: scaleFunction,
  33374. rotationFunction: rotationFunction,
  33375. ribbonCloseArray: ribbonCloseArray,
  33376. ribbonClosePath: ribbonClosePath,
  33377. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33378. sideOrientation: sideOrientation,
  33379. instance: instance,
  33380. updatable: updatable
  33381. };
  33382. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33383. };
  33384. /**
  33385. * Creates lathe mesh.
  33386. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33387. * Please consider using the same method from the MeshBuilder class instead.
  33388. * 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
  33389. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33390. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33391. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33392. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33393. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33394. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33395. */
  33396. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33397. var options = {
  33398. shape: shape,
  33399. radius: radius,
  33400. tessellation: tessellation,
  33401. sideOrientation: sideOrientation,
  33402. updatable: updatable
  33403. };
  33404. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33405. };
  33406. /**
  33407. * Creates a plane mesh.
  33408. * Please consider using the same method from the MeshBuilder class instead.
  33409. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33410. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33411. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33412. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33413. */
  33414. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33415. var options = {
  33416. size: size,
  33417. width: size,
  33418. height: size,
  33419. sideOrientation: sideOrientation,
  33420. updatable: updatable
  33421. };
  33422. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33423. };
  33424. /**
  33425. * Creates a ground mesh.
  33426. * Please consider using the same method from the MeshBuilder class instead.
  33427. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33428. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33429. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33430. */
  33431. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33432. var options = {
  33433. width: width,
  33434. height: height,
  33435. subdivisions: subdivisions,
  33436. updatable: updatable
  33437. };
  33438. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33439. };
  33440. /**
  33441. * Creates a tiled ground mesh.
  33442. * Please consider using the same method from the MeshBuilder class instead.
  33443. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33444. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33445. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33446. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33447. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33448. * numbers of subdivisions on the ground width and height of each tile.
  33449. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33450. */
  33451. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33452. var options = {
  33453. xmin: xmin,
  33454. zmin: zmin,
  33455. xmax: xmax,
  33456. zmax: zmax,
  33457. subdivisions: subdivisions,
  33458. precision: precision,
  33459. updatable: updatable
  33460. };
  33461. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33462. };
  33463. /**
  33464. * Creates a ground mesh from a height map.
  33465. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  33466. * Please consider using the same method from the MeshBuilder class instead.
  33467. * The parameter `url` sets the URL of the height map image resource.
  33468. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33469. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33470. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33471. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33472. * 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).
  33473. * This function is passed the newly built mesh :
  33474. * ```javascript
  33475. * function(mesh) { // do things
  33476. * return; }
  33477. * ```
  33478. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33479. */
  33480. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33481. var options = {
  33482. width: width,
  33483. height: height,
  33484. subdivisions: subdivisions,
  33485. minHeight: minHeight,
  33486. maxHeight: maxHeight,
  33487. updatable: updatable,
  33488. onReady: onReady
  33489. };
  33490. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33491. };
  33492. /**
  33493. * Creates a tube mesh.
  33494. * 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.
  33495. * Please consider using the same method from the MeshBuilder class instead.
  33496. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33497. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33498. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33499. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33500. * 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.
  33501. * It must return a radius value (positive float) :
  33502. * ```javascript
  33503. * var radiusFunction = function(i, distance) {
  33504. * // do things
  33505. * return radius; }
  33506. * ```
  33507. * 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
  33508. * 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
  33509. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33510. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33511. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33512. */
  33513. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33514. var options = {
  33515. path: path,
  33516. radius: radius,
  33517. tessellation: tessellation,
  33518. radiusFunction: radiusFunction,
  33519. arc: 1,
  33520. cap: cap,
  33521. updatable: updatable,
  33522. sideOrientation: sideOrientation,
  33523. instance: instance
  33524. };
  33525. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33526. };
  33527. /**
  33528. * Creates a polyhedron mesh.
  33529. * Please consider using the same method from the MeshBuilder class instead.
  33530. * 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
  33531. * to choose the wanted type.
  33532. * The parameter `size` (positive float, default 1) sets the polygon size.
  33533. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33534. * 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`.
  33535. * 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
  33536. * 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)`).
  33537. * 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
  33538. * 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.
  33539. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33540. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33541. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33542. */
  33543. Mesh.CreatePolyhedron = function (name, options, scene) {
  33544. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33545. };
  33546. /**
  33547. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33548. * Please consider using the same method from the MeshBuilder class instead.
  33549. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33550. * 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`).
  33551. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33552. * 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.
  33553. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33554. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33555. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33556. */
  33557. Mesh.CreateIcoSphere = function (name, options, scene) {
  33558. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33559. };
  33560. /**
  33561. * Creates a decal mesh.
  33562. * Please consider using the same method from the MeshBuilder class instead.
  33563. * 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.
  33564. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33565. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33566. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33567. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33568. */
  33569. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33570. var options = {
  33571. position: position,
  33572. normal: normal,
  33573. size: size,
  33574. angle: angle
  33575. };
  33576. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33577. };
  33578. // Skeletons
  33579. /**
  33580. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33581. */
  33582. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33583. if (!this._sourcePositions) {
  33584. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33585. if (!source) {
  33586. return this._sourcePositions;
  33587. }
  33588. this._sourcePositions = new Float32Array(source);
  33589. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33590. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33591. }
  33592. }
  33593. return this._sourcePositions;
  33594. };
  33595. /**
  33596. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33597. */
  33598. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33599. if (!this._sourceNormals) {
  33600. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33601. if (!source) {
  33602. return this._sourceNormals;
  33603. }
  33604. this._sourceNormals = new Float32Array(source);
  33605. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33606. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33607. }
  33608. }
  33609. return this._sourceNormals;
  33610. };
  33611. /**
  33612. * Updates the vertex buffer by applying transformation from the bones.
  33613. * Returns the Mesh.
  33614. *
  33615. * @param {skeleton} skeleton to apply
  33616. */
  33617. Mesh.prototype.applySkeleton = function (skeleton) {
  33618. if (!this.geometry) {
  33619. return this;
  33620. }
  33621. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33622. return this;
  33623. }
  33624. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33625. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33626. return this;
  33627. }
  33628. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33629. return this;
  33630. }
  33631. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33632. return this;
  33633. }
  33634. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33635. return this;
  33636. }
  33637. if (!this._sourcePositions) {
  33638. var submeshes = this.subMeshes.slice();
  33639. this.setPositionsForCPUSkinning();
  33640. this.subMeshes = submeshes;
  33641. }
  33642. if (!this._sourceNormals) {
  33643. this.setNormalsForCPUSkinning();
  33644. }
  33645. // positionsData checks for not being Float32Array will only pass at most once
  33646. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33647. if (!positionsData) {
  33648. return this;
  33649. }
  33650. if (!(positionsData instanceof Float32Array)) {
  33651. positionsData = new Float32Array(positionsData);
  33652. }
  33653. // normalsData checks for not being Float32Array will only pass at most once
  33654. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33655. if (!normalsData) {
  33656. return this;
  33657. }
  33658. if (!(normalsData instanceof Float32Array)) {
  33659. normalsData = new Float32Array(normalsData);
  33660. }
  33661. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33662. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33663. if (!matricesWeightsData || !matricesIndicesData) {
  33664. return this;
  33665. }
  33666. var needExtras = this.numBoneInfluencers > 4;
  33667. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33668. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33669. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33670. var tempVector3 = BABYLON.Vector3.Zero();
  33671. var finalMatrix = new BABYLON.Matrix();
  33672. var tempMatrix = new BABYLON.Matrix();
  33673. var matWeightIdx = 0;
  33674. var inf;
  33675. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33676. var weight;
  33677. for (inf = 0; inf < 4; inf++) {
  33678. weight = matricesWeightsData[matWeightIdx + inf];
  33679. if (weight > 0) {
  33680. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33681. finalMatrix.addToSelf(tempMatrix);
  33682. }
  33683. else
  33684. break;
  33685. }
  33686. if (needExtras) {
  33687. for (inf = 0; inf < 4; inf++) {
  33688. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33689. if (weight > 0) {
  33690. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33691. finalMatrix.addToSelf(tempMatrix);
  33692. }
  33693. else
  33694. break;
  33695. }
  33696. }
  33697. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33698. tempVector3.toArray(positionsData, index);
  33699. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33700. tempVector3.toArray(normalsData, index);
  33701. finalMatrix.reset();
  33702. }
  33703. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33704. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33705. return this;
  33706. };
  33707. // Tools
  33708. /**
  33709. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33710. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33711. */
  33712. Mesh.MinMax = function (meshes) {
  33713. var minVector = null;
  33714. var maxVector = null;
  33715. meshes.forEach(function (mesh, index, array) {
  33716. var boundingInfo = mesh.getBoundingInfo();
  33717. var boundingBox = boundingInfo.boundingBox;
  33718. if (!minVector || !maxVector) {
  33719. minVector = boundingBox.minimumWorld;
  33720. maxVector = boundingBox.maximumWorld;
  33721. }
  33722. else {
  33723. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33724. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33725. }
  33726. });
  33727. if (!minVector || !maxVector) {
  33728. return {
  33729. min: BABYLON.Vector3.Zero(),
  33730. max: BABYLON.Vector3.Zero()
  33731. };
  33732. }
  33733. return {
  33734. min: minVector,
  33735. max: maxVector
  33736. };
  33737. };
  33738. /**
  33739. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33740. */
  33741. Mesh.Center = function (meshesOrMinMaxVector) {
  33742. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33743. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33744. };
  33745. /**
  33746. * Merge the array of meshes into a single mesh for performance reasons.
  33747. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33748. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33749. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33750. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33751. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33752. */
  33753. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33754. if (disposeSource === void 0) { disposeSource = true; }
  33755. var index;
  33756. if (!allow32BitsIndices) {
  33757. var totalVertices = 0;
  33758. // Counting vertices
  33759. for (index = 0; index < meshes.length; index++) {
  33760. if (meshes[index]) {
  33761. totalVertices += meshes[index].getTotalVertices();
  33762. if (totalVertices > 65536) {
  33763. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33764. return null;
  33765. }
  33766. }
  33767. }
  33768. }
  33769. // Merge
  33770. var vertexData = null;
  33771. var otherVertexData;
  33772. var indiceArray = new Array();
  33773. var source = null;
  33774. for (index = 0; index < meshes.length; index++) {
  33775. if (meshes[index]) {
  33776. meshes[index].computeWorldMatrix(true);
  33777. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33778. otherVertexData.transform(meshes[index].getWorldMatrix());
  33779. if (vertexData) {
  33780. vertexData.merge(otherVertexData);
  33781. }
  33782. else {
  33783. vertexData = otherVertexData;
  33784. source = meshes[index];
  33785. }
  33786. if (subdivideWithSubMeshes) {
  33787. indiceArray.push(meshes[index].getTotalIndices());
  33788. }
  33789. }
  33790. }
  33791. source = source;
  33792. if (!meshSubclass) {
  33793. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33794. }
  33795. vertexData.applyToMesh(meshSubclass);
  33796. // Setting properties
  33797. meshSubclass.material = source.material;
  33798. meshSubclass.checkCollisions = source.checkCollisions;
  33799. // Cleaning
  33800. if (disposeSource) {
  33801. for (index = 0; index < meshes.length; index++) {
  33802. if (meshes[index]) {
  33803. meshes[index].dispose();
  33804. }
  33805. }
  33806. }
  33807. // Subdivide
  33808. if (subdivideWithSubMeshes) {
  33809. //-- Suppresions du submesh global
  33810. meshSubclass.releaseSubMeshes();
  33811. index = 0;
  33812. var offset = 0;
  33813. //-- aplique la subdivision en fonction du tableau d'indices
  33814. while (index < indiceArray.length) {
  33815. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33816. offset += indiceArray[index];
  33817. index++;
  33818. }
  33819. }
  33820. return meshSubclass;
  33821. };
  33822. // Consts
  33823. Mesh._FRONTSIDE = 0;
  33824. Mesh._BACKSIDE = 1;
  33825. Mesh._DOUBLESIDE = 2;
  33826. Mesh._DEFAULTSIDE = 0;
  33827. Mesh._NO_CAP = 0;
  33828. Mesh._CAP_START = 1;
  33829. Mesh._CAP_END = 2;
  33830. Mesh._CAP_ALL = 3;
  33831. return Mesh;
  33832. }(BABYLON.AbstractMesh));
  33833. BABYLON.Mesh = Mesh;
  33834. })(BABYLON || (BABYLON = {}));
  33835. //# sourceMappingURL=babylon.mesh.js.map
  33836. var BABYLON;
  33837. (function (BABYLON) {
  33838. var BaseSubMesh = /** @class */ (function () {
  33839. function BaseSubMesh() {
  33840. }
  33841. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33842. get: function () {
  33843. return this._materialEffect;
  33844. },
  33845. enumerable: true,
  33846. configurable: true
  33847. });
  33848. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33849. if (defines === void 0) { defines = null; }
  33850. if (this._materialEffect === effect) {
  33851. if (!effect) {
  33852. this._materialDefines = null;
  33853. }
  33854. return;
  33855. }
  33856. this._materialDefines = defines;
  33857. this._materialEffect = effect;
  33858. };
  33859. return BaseSubMesh;
  33860. }());
  33861. BABYLON.BaseSubMesh = BaseSubMesh;
  33862. var SubMesh = /** @class */ (function (_super) {
  33863. __extends(SubMesh, _super);
  33864. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33865. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33866. var _this = _super.call(this) || this;
  33867. _this.materialIndex = materialIndex;
  33868. _this.verticesStart = verticesStart;
  33869. _this.verticesCount = verticesCount;
  33870. _this.indexStart = indexStart;
  33871. _this.indexCount = indexCount;
  33872. _this._renderId = 0;
  33873. _this._mesh = mesh;
  33874. _this._renderingMesh = renderingMesh || mesh;
  33875. mesh.subMeshes.push(_this);
  33876. _this._trianglePlanes = [];
  33877. _this._id = mesh.subMeshes.length - 1;
  33878. if (createBoundingBox) {
  33879. _this.refreshBoundingInfo();
  33880. mesh.computeWorldMatrix(true);
  33881. }
  33882. return _this;
  33883. }
  33884. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33885. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33886. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33887. };
  33888. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33889. get: function () {
  33890. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33891. },
  33892. enumerable: true,
  33893. configurable: true
  33894. });
  33895. /**
  33896. * Returns the submesh BoudingInfo object.
  33897. */
  33898. SubMesh.prototype.getBoundingInfo = function () {
  33899. if (this.IsGlobal) {
  33900. return this._mesh.getBoundingInfo();
  33901. }
  33902. return this._boundingInfo;
  33903. };
  33904. /**
  33905. * Sets the submesh BoundingInfo.
  33906. * Return the SubMesh.
  33907. */
  33908. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33909. this._boundingInfo = boundingInfo;
  33910. return this;
  33911. };
  33912. /**
  33913. * Returns the mesh of the current submesh.
  33914. */
  33915. SubMesh.prototype.getMesh = function () {
  33916. return this._mesh;
  33917. };
  33918. /**
  33919. * Returns the rendering mesh of the submesh.
  33920. */
  33921. SubMesh.prototype.getRenderingMesh = function () {
  33922. return this._renderingMesh;
  33923. };
  33924. /**
  33925. * Returns the submesh material.
  33926. */
  33927. SubMesh.prototype.getMaterial = function () {
  33928. var rootMaterial = this._renderingMesh.material;
  33929. if (rootMaterial === null || rootMaterial === undefined) {
  33930. return this._mesh.getScene().defaultMaterial;
  33931. }
  33932. else if (rootMaterial.getSubMaterial) {
  33933. var multiMaterial = rootMaterial;
  33934. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33935. if (this._currentMaterial !== effectiveMaterial) {
  33936. this._currentMaterial = effectiveMaterial;
  33937. this._materialDefines = null;
  33938. }
  33939. return effectiveMaterial;
  33940. }
  33941. return rootMaterial;
  33942. };
  33943. // Methods
  33944. /**
  33945. * Sets a new updated BoundingInfo object to the submesh.
  33946. * Returns the SubMesh.
  33947. */
  33948. SubMesh.prototype.refreshBoundingInfo = function () {
  33949. this._lastColliderWorldVertices = null;
  33950. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33951. return this;
  33952. }
  33953. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33954. if (!data) {
  33955. this._boundingInfo = this._mesh.getBoundingInfo();
  33956. return this;
  33957. }
  33958. var indices = this._renderingMesh.getIndices();
  33959. var extend;
  33960. //is this the only submesh?
  33961. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33962. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33963. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33964. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33965. }
  33966. else {
  33967. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33968. }
  33969. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33970. return this;
  33971. };
  33972. SubMesh.prototype._checkCollision = function (collider) {
  33973. var boundingInfo = this.getBoundingInfo();
  33974. return boundingInfo._checkCollision(collider);
  33975. };
  33976. /**
  33977. * Updates the submesh BoundingInfo.
  33978. * Returns the Submesh.
  33979. */
  33980. SubMesh.prototype.updateBoundingInfo = function (world) {
  33981. var boundingInfo = this.getBoundingInfo();
  33982. if (!boundingInfo) {
  33983. this.refreshBoundingInfo();
  33984. boundingInfo = this.getBoundingInfo();
  33985. }
  33986. boundingInfo.update(world);
  33987. return this;
  33988. };
  33989. /**
  33990. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33991. * Boolean returned.
  33992. */
  33993. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33994. var boundingInfo = this.getBoundingInfo();
  33995. if (!boundingInfo) {
  33996. return false;
  33997. }
  33998. return boundingInfo.isInFrustum(frustumPlanes);
  33999. };
  34000. /**
  34001. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34002. * Boolean returned.
  34003. */
  34004. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34005. var boundingInfo = this.getBoundingInfo();
  34006. if (!boundingInfo) {
  34007. return false;
  34008. }
  34009. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34010. };
  34011. /**
  34012. * Renders the submesh.
  34013. * Returns it.
  34014. */
  34015. SubMesh.prototype.render = function (enableAlphaMode) {
  34016. this._renderingMesh.render(this, enableAlphaMode);
  34017. return this;
  34018. };
  34019. /**
  34020. * Returns a new Index Buffer.
  34021. * Type returned : WebGLBuffer.
  34022. */
  34023. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34024. if (!this._linesIndexBuffer) {
  34025. var linesIndices = [];
  34026. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34027. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34028. }
  34029. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34030. this.linesIndexCount = linesIndices.length;
  34031. }
  34032. return this._linesIndexBuffer;
  34033. };
  34034. /**
  34035. * True is the passed Ray intersects the submesh bounding box.
  34036. * Boolean returned.
  34037. */
  34038. SubMesh.prototype.canIntersects = function (ray) {
  34039. var boundingInfo = this.getBoundingInfo();
  34040. if (!boundingInfo) {
  34041. return false;
  34042. }
  34043. return ray.intersectsBox(boundingInfo.boundingBox);
  34044. };
  34045. /**
  34046. * Returns an object IntersectionInfo.
  34047. */
  34048. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34049. var intersectInfo = null;
  34050. var material = this.getMaterial();
  34051. if (!material) {
  34052. return null;
  34053. }
  34054. switch (material.fillMode) {
  34055. case BABYLON.Material.PointListDrawMode:
  34056. case BABYLON.Material.LineListDrawMode:
  34057. case BABYLON.Material.LineLoopDrawMode:
  34058. case BABYLON.Material.LineStripDrawMode:
  34059. case BABYLON.Material.TriangleFanDrawMode:
  34060. case BABYLON.Material.TriangleStripDrawMode:
  34061. return null;
  34062. }
  34063. // LineMesh first as it's also a Mesh...
  34064. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34065. var lineMesh = this._mesh;
  34066. // Line test
  34067. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34068. var p0 = positions[indices[index]];
  34069. var p1 = positions[indices[index + 1]];
  34070. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34071. if (length < 0) {
  34072. continue;
  34073. }
  34074. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34075. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34076. if (fastCheck) {
  34077. break;
  34078. }
  34079. }
  34080. }
  34081. }
  34082. else {
  34083. // Triangles test
  34084. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34085. var p0 = positions[indices[index]];
  34086. var p1 = positions[indices[index + 1]];
  34087. var p2 = positions[indices[index + 2]];
  34088. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34089. if (currentIntersectInfo) {
  34090. if (currentIntersectInfo.distance < 0) {
  34091. continue;
  34092. }
  34093. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34094. intersectInfo = currentIntersectInfo;
  34095. intersectInfo.faceId = index / 3;
  34096. if (fastCheck) {
  34097. break;
  34098. }
  34099. }
  34100. }
  34101. }
  34102. }
  34103. return intersectInfo;
  34104. };
  34105. SubMesh.prototype._rebuild = function () {
  34106. if (this._linesIndexBuffer) {
  34107. this._linesIndexBuffer = null;
  34108. }
  34109. };
  34110. // Clone
  34111. /**
  34112. * Creates a new Submesh from the passed Mesh.
  34113. */
  34114. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34115. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34116. if (!this.IsGlobal) {
  34117. var boundingInfo = this.getBoundingInfo();
  34118. if (!boundingInfo) {
  34119. return result;
  34120. }
  34121. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34122. }
  34123. return result;
  34124. };
  34125. // Dispose
  34126. /**
  34127. * Disposes the Submesh.
  34128. * Returns nothing.
  34129. */
  34130. SubMesh.prototype.dispose = function () {
  34131. if (this._linesIndexBuffer) {
  34132. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34133. this._linesIndexBuffer = null;
  34134. }
  34135. // Remove from mesh
  34136. var index = this._mesh.subMeshes.indexOf(this);
  34137. this._mesh.subMeshes.splice(index, 1);
  34138. };
  34139. // Statics
  34140. /**
  34141. * Creates a new Submesh from the passed parameters :
  34142. * - materialIndex (integer) : the index of the main mesh material.
  34143. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34144. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34145. * - mesh (Mesh) : the main mesh to create the submesh from.
  34146. * - renderingMesh (optional Mesh) : rendering mesh.
  34147. */
  34148. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34149. var minVertexIndex = Number.MAX_VALUE;
  34150. var maxVertexIndex = -Number.MAX_VALUE;
  34151. renderingMesh = (renderingMesh || mesh);
  34152. var indices = renderingMesh.getIndices();
  34153. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34154. var vertexIndex = indices[index];
  34155. if (vertexIndex < minVertexIndex)
  34156. minVertexIndex = vertexIndex;
  34157. if (vertexIndex > maxVertexIndex)
  34158. maxVertexIndex = vertexIndex;
  34159. }
  34160. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34161. };
  34162. return SubMesh;
  34163. }(BaseSubMesh));
  34164. BABYLON.SubMesh = SubMesh;
  34165. })(BABYLON || (BABYLON = {}));
  34166. //# sourceMappingURL=babylon.subMesh.js.map
  34167. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34168. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34169. s = arguments[i];
  34170. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34171. t[p] = s[p];
  34172. }
  34173. return t;
  34174. };
  34175. var BABYLON;
  34176. (function (BABYLON) {
  34177. /**
  34178. * Manages the defines for the Material
  34179. */
  34180. var MaterialDefines = /** @class */ (function () {
  34181. function MaterialDefines() {
  34182. this._isDirty = true;
  34183. /** @hidden */
  34184. this._areLightsDirty = true;
  34185. /** @hidden */
  34186. this._areAttributesDirty = true;
  34187. /** @hidden */
  34188. this._areTexturesDirty = true;
  34189. /** @hidden */
  34190. this._areFresnelDirty = true;
  34191. /** @hidden */
  34192. this._areMiscDirty = true;
  34193. /** @hidden */
  34194. this._areImageProcessingDirty = true;
  34195. /** @hidden */
  34196. this._normals = false;
  34197. /** @hidden */
  34198. this._uvs = false;
  34199. /** @hidden */
  34200. this._needNormals = false;
  34201. /** @hidden */
  34202. this._needUVs = false;
  34203. }
  34204. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34205. /**
  34206. * Specifies if the material needs to be re-calculated
  34207. */
  34208. get: function () {
  34209. return this._isDirty;
  34210. },
  34211. enumerable: true,
  34212. configurable: true
  34213. });
  34214. /**
  34215. * Marks the material to indicate that it has been re-calculated
  34216. */
  34217. MaterialDefines.prototype.markAsProcessed = function () {
  34218. this._isDirty = false;
  34219. this._areAttributesDirty = false;
  34220. this._areTexturesDirty = false;
  34221. this._areFresnelDirty = false;
  34222. this._areLightsDirty = false;
  34223. this._areMiscDirty = false;
  34224. this._areImageProcessingDirty = false;
  34225. };
  34226. /**
  34227. * Marks the material to indicate that it needs to be re-calculated
  34228. */
  34229. MaterialDefines.prototype.markAsUnprocessed = function () {
  34230. this._isDirty = true;
  34231. };
  34232. /**
  34233. * Marks the material to indicate all of its defines need to be re-calculated
  34234. */
  34235. MaterialDefines.prototype.markAllAsDirty = function () {
  34236. this._areTexturesDirty = true;
  34237. this._areAttributesDirty = true;
  34238. this._areLightsDirty = true;
  34239. this._areFresnelDirty = true;
  34240. this._areMiscDirty = true;
  34241. this._areImageProcessingDirty = true;
  34242. this._isDirty = true;
  34243. };
  34244. /**
  34245. * Marks the material to indicate that image processing needs to be re-calculated
  34246. */
  34247. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34248. this._areImageProcessingDirty = true;
  34249. this._isDirty = true;
  34250. };
  34251. /**
  34252. * Marks the material to indicate the lights need to be re-calculated
  34253. */
  34254. MaterialDefines.prototype.markAsLightDirty = function () {
  34255. this._areLightsDirty = true;
  34256. this._isDirty = true;
  34257. };
  34258. /**
  34259. * Marks the attribute state as changed
  34260. */
  34261. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34262. this._areAttributesDirty = true;
  34263. this._isDirty = true;
  34264. };
  34265. /**
  34266. * Marks the texture state as changed
  34267. */
  34268. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34269. this._areTexturesDirty = true;
  34270. this._isDirty = true;
  34271. };
  34272. /**
  34273. * Marks the fresnel state as changed
  34274. */
  34275. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34276. this._areFresnelDirty = true;
  34277. this._isDirty = true;
  34278. };
  34279. /**
  34280. * Marks the misc state as changed
  34281. */
  34282. MaterialDefines.prototype.markAsMiscDirty = function () {
  34283. this._areMiscDirty = true;
  34284. this._isDirty = true;
  34285. };
  34286. /**
  34287. * Rebuilds the material defines
  34288. */
  34289. MaterialDefines.prototype.rebuild = function () {
  34290. if (this._keys) {
  34291. delete this._keys;
  34292. }
  34293. this._keys = [];
  34294. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34295. var key = _a[_i];
  34296. if (key[0] === "_") {
  34297. continue;
  34298. }
  34299. this._keys.push(key);
  34300. }
  34301. };
  34302. /**
  34303. * Specifies if two material defines are equal
  34304. * @param other - A material define instance to compare to
  34305. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34306. */
  34307. MaterialDefines.prototype.isEqual = function (other) {
  34308. if (this._keys.length !== other._keys.length) {
  34309. return false;
  34310. }
  34311. for (var index = 0; index < this._keys.length; index++) {
  34312. var prop = this._keys[index];
  34313. if (this[prop] !== other[prop]) {
  34314. return false;
  34315. }
  34316. }
  34317. return true;
  34318. };
  34319. /**
  34320. * Clones this instance's defines to another instance
  34321. * @param other - material defines to clone values to
  34322. */
  34323. MaterialDefines.prototype.cloneTo = function (other) {
  34324. if (this._keys.length !== other._keys.length) {
  34325. other._keys = this._keys.slice(0);
  34326. }
  34327. for (var index = 0; index < this._keys.length; index++) {
  34328. var prop = this._keys[index];
  34329. other[prop] = this[prop];
  34330. }
  34331. };
  34332. /**
  34333. * Resets the material define values
  34334. */
  34335. MaterialDefines.prototype.reset = function () {
  34336. for (var index = 0; index < this._keys.length; index++) {
  34337. var prop = this._keys[index];
  34338. var type = typeof this[prop];
  34339. switch (type) {
  34340. case "number":
  34341. this[prop] = 0;
  34342. break;
  34343. case "string":
  34344. this[prop] = "";
  34345. break;
  34346. default:
  34347. this[prop] = false;
  34348. break;
  34349. }
  34350. }
  34351. };
  34352. /**
  34353. * Converts the material define values to a string
  34354. * @returns - String of material define information
  34355. */
  34356. MaterialDefines.prototype.toString = function () {
  34357. var result = "";
  34358. for (var index = 0; index < this._keys.length; index++) {
  34359. var prop = this._keys[index];
  34360. var value = this[prop];
  34361. var type = typeof value;
  34362. switch (type) {
  34363. case "number":
  34364. case "string":
  34365. result += "#define " + prop + " " + value + "\n";
  34366. break;
  34367. default:
  34368. if (value) {
  34369. result += "#define " + prop + "\n";
  34370. }
  34371. break;
  34372. }
  34373. }
  34374. return result;
  34375. };
  34376. return MaterialDefines;
  34377. }());
  34378. BABYLON.MaterialDefines = MaterialDefines;
  34379. /**
  34380. * Base class for the main features of a material in Babylon.js
  34381. */
  34382. var Material = /** @class */ (function () {
  34383. /**
  34384. * Creates a material instance
  34385. * @param name defines the name of the material
  34386. * @param scene defines the scene to reference
  34387. * @param doNotAdd specifies if the material should be added to the scene
  34388. */
  34389. function Material(name, scene, doNotAdd) {
  34390. /**
  34391. * Specifies if the ready state should be checked on each call
  34392. */
  34393. this.checkReadyOnEveryCall = false;
  34394. /**
  34395. * Specifies if the ready state should be checked once
  34396. */
  34397. this.checkReadyOnlyOnce = false;
  34398. /**
  34399. * The state of the material
  34400. */
  34401. this.state = "";
  34402. /**
  34403. * The alpha value of the material
  34404. */
  34405. this._alpha = 1.0;
  34406. /**
  34407. * Specifies if back face culling is enabled
  34408. */
  34409. this._backFaceCulling = true;
  34410. /**
  34411. * Specifies if the material should be serialized
  34412. */
  34413. this.doNotSerialize = false;
  34414. /**
  34415. * Specifies if the effect should be stored on sub meshes
  34416. */
  34417. this.storeEffectOnSubMeshes = false;
  34418. /**
  34419. * An event triggered when the material is disposed
  34420. */
  34421. this.onDisposeObservable = new BABYLON.Observable();
  34422. /**
  34423. * An event triggered when the material is bound
  34424. */
  34425. this.onBindObservable = new BABYLON.Observable();
  34426. /**
  34427. * An event triggered when the material is unbound
  34428. */
  34429. this.onUnBindObservable = new BABYLON.Observable();
  34430. /**
  34431. * Stores the value of the alpha mode
  34432. */
  34433. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34434. /**
  34435. * Stores the state of the need depth pre-pass value
  34436. */
  34437. this._needDepthPrePass = false;
  34438. /**
  34439. * Specifies if depth writing should be disabled
  34440. */
  34441. this.disableDepthWrite = false;
  34442. /**
  34443. * Specifies if depth writing should be forced
  34444. */
  34445. this.forceDepthWrite = false;
  34446. /**
  34447. * Specifies if there should be a separate pass for culling
  34448. */
  34449. this.separateCullingPass = false;
  34450. /**
  34451. * Stores the state specifing if fog should be enabled
  34452. */
  34453. this._fogEnabled = true;
  34454. /**
  34455. * Stores the size of points
  34456. */
  34457. this.pointSize = 1.0;
  34458. /**
  34459. * Stores the z offset value
  34460. */
  34461. this.zOffset = 0;
  34462. /**
  34463. * Specifies if the material was previously ready
  34464. */
  34465. this._wasPreviouslyReady = false;
  34466. /**
  34467. * Stores the fill mode state
  34468. */
  34469. this._fillMode = Material.TriangleFillMode;
  34470. this.name = name;
  34471. this.id = name || BABYLON.Tools.RandomId();
  34472. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34473. if (this._scene.useRightHandedSystem) {
  34474. this.sideOrientation = Material.ClockWiseSideOrientation;
  34475. }
  34476. else {
  34477. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34478. }
  34479. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34480. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34481. if (!doNotAdd) {
  34482. this._scene.materials.push(this);
  34483. }
  34484. }
  34485. Object.defineProperty(Material, "TriangleFillMode", {
  34486. /**
  34487. * Returns the triangle fill mode
  34488. */
  34489. get: function () {
  34490. return Material._TriangleFillMode;
  34491. },
  34492. enumerable: true,
  34493. configurable: true
  34494. });
  34495. Object.defineProperty(Material, "WireFrameFillMode", {
  34496. /**
  34497. * Returns the wireframe mode
  34498. */
  34499. get: function () {
  34500. return Material._WireFrameFillMode;
  34501. },
  34502. enumerable: true,
  34503. configurable: true
  34504. });
  34505. Object.defineProperty(Material, "PointFillMode", {
  34506. /**
  34507. * Returns the point fill mode
  34508. */
  34509. get: function () {
  34510. return Material._PointFillMode;
  34511. },
  34512. enumerable: true,
  34513. configurable: true
  34514. });
  34515. Object.defineProperty(Material, "PointListDrawMode", {
  34516. /**
  34517. * Returns the point list draw mode
  34518. */
  34519. get: function () {
  34520. return Material._PointListDrawMode;
  34521. },
  34522. enumerable: true,
  34523. configurable: true
  34524. });
  34525. Object.defineProperty(Material, "LineListDrawMode", {
  34526. /**
  34527. * Returns the line list draw mode
  34528. */
  34529. get: function () {
  34530. return Material._LineListDrawMode;
  34531. },
  34532. enumerable: true,
  34533. configurable: true
  34534. });
  34535. Object.defineProperty(Material, "LineLoopDrawMode", {
  34536. /**
  34537. * Returns the line loop draw mode
  34538. */
  34539. get: function () {
  34540. return Material._LineLoopDrawMode;
  34541. },
  34542. enumerable: true,
  34543. configurable: true
  34544. });
  34545. Object.defineProperty(Material, "LineStripDrawMode", {
  34546. /**
  34547. * Returns the line strip draw mode
  34548. */
  34549. get: function () {
  34550. return Material._LineStripDrawMode;
  34551. },
  34552. enumerable: true,
  34553. configurable: true
  34554. });
  34555. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34556. /**
  34557. * Returns the triangle strip draw mode
  34558. */
  34559. get: function () {
  34560. return Material._TriangleStripDrawMode;
  34561. },
  34562. enumerable: true,
  34563. configurable: true
  34564. });
  34565. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34566. /**
  34567. * Returns the triangle fan draw mode
  34568. */
  34569. get: function () {
  34570. return Material._TriangleFanDrawMode;
  34571. },
  34572. enumerable: true,
  34573. configurable: true
  34574. });
  34575. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34576. /**
  34577. * Returns the clock-wise side orientation
  34578. */
  34579. get: function () {
  34580. return Material._ClockWiseSideOrientation;
  34581. },
  34582. enumerable: true,
  34583. configurable: true
  34584. });
  34585. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34586. /**
  34587. * Returns the counter clock-wise side orientation
  34588. */
  34589. get: function () {
  34590. return Material._CounterClockWiseSideOrientation;
  34591. },
  34592. enumerable: true,
  34593. configurable: true
  34594. });
  34595. Object.defineProperty(Material, "TextureDirtyFlag", {
  34596. /**
  34597. * Returns the dirty texture flag value
  34598. */
  34599. get: function () {
  34600. return Material._TextureDirtyFlag;
  34601. },
  34602. enumerable: true,
  34603. configurable: true
  34604. });
  34605. Object.defineProperty(Material, "LightDirtyFlag", {
  34606. /**
  34607. * Returns the dirty light flag value
  34608. */
  34609. get: function () {
  34610. return Material._LightDirtyFlag;
  34611. },
  34612. enumerable: true,
  34613. configurable: true
  34614. });
  34615. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34616. /**
  34617. * Returns the dirty fresnel flag value
  34618. */
  34619. get: function () {
  34620. return Material._FresnelDirtyFlag;
  34621. },
  34622. enumerable: true,
  34623. configurable: true
  34624. });
  34625. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34626. /**
  34627. * Returns the dirty attributes flag value
  34628. */
  34629. get: function () {
  34630. return Material._AttributesDirtyFlag;
  34631. },
  34632. enumerable: true,
  34633. configurable: true
  34634. });
  34635. Object.defineProperty(Material, "MiscDirtyFlag", {
  34636. /**
  34637. * Returns the dirty misc flag value
  34638. */
  34639. get: function () {
  34640. return Material._MiscDirtyFlag;
  34641. },
  34642. enumerable: true,
  34643. configurable: true
  34644. });
  34645. Object.defineProperty(Material.prototype, "alpha", {
  34646. /**
  34647. * Gets the alpha value of the material
  34648. */
  34649. get: function () {
  34650. return this._alpha;
  34651. },
  34652. /**
  34653. * Sets the alpha value of the material
  34654. */
  34655. set: function (value) {
  34656. if (this._alpha === value) {
  34657. return;
  34658. }
  34659. this._alpha = value;
  34660. this.markAsDirty(Material.MiscDirtyFlag);
  34661. },
  34662. enumerable: true,
  34663. configurable: true
  34664. });
  34665. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34666. /**
  34667. * Gets the back-face culling state
  34668. */
  34669. get: function () {
  34670. return this._backFaceCulling;
  34671. },
  34672. /**
  34673. * Sets the back-face culling state
  34674. */
  34675. set: function (value) {
  34676. if (this._backFaceCulling === value) {
  34677. return;
  34678. }
  34679. this._backFaceCulling = value;
  34680. this.markAsDirty(Material.TextureDirtyFlag);
  34681. },
  34682. enumerable: true,
  34683. configurable: true
  34684. });
  34685. Object.defineProperty(Material.prototype, "onDispose", {
  34686. /**
  34687. * Called during a dispose event
  34688. */
  34689. set: function (callback) {
  34690. if (this._onDisposeObserver) {
  34691. this.onDisposeObservable.remove(this._onDisposeObserver);
  34692. }
  34693. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34694. },
  34695. enumerable: true,
  34696. configurable: true
  34697. });
  34698. Object.defineProperty(Material.prototype, "onBind", {
  34699. /**
  34700. * Called during a bind event
  34701. */
  34702. set: function (callback) {
  34703. if (this._onBindObserver) {
  34704. this.onBindObservable.remove(this._onBindObserver);
  34705. }
  34706. this._onBindObserver = this.onBindObservable.add(callback);
  34707. },
  34708. enumerable: true,
  34709. configurable: true
  34710. });
  34711. Object.defineProperty(Material.prototype, "alphaMode", {
  34712. /**
  34713. * Gets the value of the alpha mode
  34714. */
  34715. get: function () {
  34716. return this._alphaMode;
  34717. },
  34718. /**
  34719. * Sets the value of the alpha mode.
  34720. *
  34721. * | Value | Type | Description |
  34722. * | --- | --- | --- |
  34723. * | 0 | ALPHA_DISABLE | |
  34724. * | 1 | ALPHA_ADD | |
  34725. * | 2 | ALPHA_COMBINE | |
  34726. * | 3 | ALPHA_SUBTRACT | |
  34727. * | 4 | ALPHA_MULTIPLY | |
  34728. * | 5 | ALPHA_MAXIMIZED | |
  34729. * | 6 | ALPHA_ONEONE | |
  34730. * | 7 | ALPHA_PREMULTIPLIED | |
  34731. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34732. * | 9 | ALPHA_INTERPOLATE | |
  34733. * | 10 | ALPHA_SCREENMODE | |
  34734. *
  34735. */
  34736. set: function (value) {
  34737. if (this._alphaMode === value) {
  34738. return;
  34739. }
  34740. this._alphaMode = value;
  34741. this.markAsDirty(Material.TextureDirtyFlag);
  34742. },
  34743. enumerable: true,
  34744. configurable: true
  34745. });
  34746. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34747. /**
  34748. * Gets the depth pre-pass value
  34749. */
  34750. get: function () {
  34751. return this._needDepthPrePass;
  34752. },
  34753. /**
  34754. * Sets the need depth pre-pass value
  34755. */
  34756. set: function (value) {
  34757. if (this._needDepthPrePass === value) {
  34758. return;
  34759. }
  34760. this._needDepthPrePass = value;
  34761. if (this._needDepthPrePass) {
  34762. this.checkReadyOnEveryCall = true;
  34763. }
  34764. },
  34765. enumerable: true,
  34766. configurable: true
  34767. });
  34768. Object.defineProperty(Material.prototype, "fogEnabled", {
  34769. /**
  34770. * Gets the value of the fog enabled state
  34771. */
  34772. get: function () {
  34773. return this._fogEnabled;
  34774. },
  34775. /**
  34776. * Sets the state for enabling fog
  34777. */
  34778. set: function (value) {
  34779. if (this._fogEnabled === value) {
  34780. return;
  34781. }
  34782. this._fogEnabled = value;
  34783. this.markAsDirty(Material.MiscDirtyFlag);
  34784. },
  34785. enumerable: true,
  34786. configurable: true
  34787. });
  34788. Object.defineProperty(Material.prototype, "wireframe", {
  34789. /**
  34790. * Gets a value specifying if wireframe mode is enabled
  34791. */
  34792. get: function () {
  34793. switch (this._fillMode) {
  34794. case Material.WireFrameFillMode:
  34795. case Material.LineListDrawMode:
  34796. case Material.LineLoopDrawMode:
  34797. case Material.LineStripDrawMode:
  34798. return true;
  34799. }
  34800. return this._scene.forceWireframe;
  34801. },
  34802. /**
  34803. * Sets the state of wireframe mode
  34804. */
  34805. set: function (value) {
  34806. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34807. },
  34808. enumerable: true,
  34809. configurable: true
  34810. });
  34811. Object.defineProperty(Material.prototype, "pointsCloud", {
  34812. /**
  34813. * Gets the value specifying if point clouds are enabled
  34814. */
  34815. get: function () {
  34816. switch (this._fillMode) {
  34817. case Material.PointFillMode:
  34818. case Material.PointListDrawMode:
  34819. return true;
  34820. }
  34821. return this._scene.forcePointsCloud;
  34822. },
  34823. /**
  34824. * Sets the state of point cloud mode
  34825. */
  34826. set: function (value) {
  34827. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34828. },
  34829. enumerable: true,
  34830. configurable: true
  34831. });
  34832. Object.defineProperty(Material.prototype, "fillMode", {
  34833. /**
  34834. * Gets the material fill mode
  34835. */
  34836. get: function () {
  34837. return this._fillMode;
  34838. },
  34839. /**
  34840. * Sets the material fill mode
  34841. */
  34842. set: function (value) {
  34843. if (this._fillMode === value) {
  34844. return;
  34845. }
  34846. this._fillMode = value;
  34847. this.markAsDirty(Material.MiscDirtyFlag);
  34848. },
  34849. enumerable: true,
  34850. configurable: true
  34851. });
  34852. /**
  34853. * Returns a string representation of the current material
  34854. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34855. * @returns a string with material information
  34856. */
  34857. Material.prototype.toString = function (fullDetails) {
  34858. var ret = "Name: " + this.name;
  34859. if (fullDetails) {
  34860. }
  34861. return ret;
  34862. };
  34863. /**
  34864. * Gets the class name of the material
  34865. * @returns a string with the class name of the material
  34866. */
  34867. Material.prototype.getClassName = function () {
  34868. return "Material";
  34869. };
  34870. Object.defineProperty(Material.prototype, "isFrozen", {
  34871. /**
  34872. * Specifies if updates for the material been locked
  34873. */
  34874. get: function () {
  34875. return this.checkReadyOnlyOnce;
  34876. },
  34877. enumerable: true,
  34878. configurable: true
  34879. });
  34880. /**
  34881. * Locks updates for the material
  34882. */
  34883. Material.prototype.freeze = function () {
  34884. this.checkReadyOnlyOnce = true;
  34885. };
  34886. /**
  34887. * Unlocks updates for the material
  34888. */
  34889. Material.prototype.unfreeze = function () {
  34890. this.checkReadyOnlyOnce = false;
  34891. };
  34892. /**
  34893. * Specifies if the material is ready to be used
  34894. * @param mesh defines the mesh to check
  34895. * @param useInstances specifies if instances should be used
  34896. * @returns a boolean indicating if the material is ready to be used
  34897. */
  34898. Material.prototype.isReady = function (mesh, useInstances) {
  34899. return true;
  34900. };
  34901. /**
  34902. * Specifies that the submesh is ready to be used
  34903. * @param mesh defines the mesh to check
  34904. * @param subMesh defines which submesh to check
  34905. * @param useInstances specifies that instances should be used
  34906. * @returns a boolean indicating that the submesh is ready or not
  34907. */
  34908. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34909. return false;
  34910. };
  34911. /**
  34912. * Returns the material effect
  34913. * @returns the effect associated with the material
  34914. */
  34915. Material.prototype.getEffect = function () {
  34916. return this._effect;
  34917. };
  34918. /**
  34919. * Returns the current scene
  34920. * @returns a Scene
  34921. */
  34922. Material.prototype.getScene = function () {
  34923. return this._scene;
  34924. };
  34925. /**
  34926. * Specifies if the material will require alpha blending
  34927. * @returns a boolean specifying if alpha blending is needed
  34928. */
  34929. Material.prototype.needAlphaBlending = function () {
  34930. return (this.alpha < 1.0);
  34931. };
  34932. /**
  34933. * Specifies if the mesh will require alpha blending
  34934. * @param mesh defines the mesh to check
  34935. * @returns a boolean specifying if alpha blending is needed for the mesh
  34936. */
  34937. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34938. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34939. };
  34940. /**
  34941. * Specifies if this material should be rendered in alpha test mode
  34942. * @returns a boolean specifying if an alpha test is needed.
  34943. */
  34944. Material.prototype.needAlphaTesting = function () {
  34945. return false;
  34946. };
  34947. /**
  34948. * Gets the texture used for the alpha test
  34949. * @returns the texture to use for alpha testing
  34950. */
  34951. Material.prototype.getAlphaTestTexture = function () {
  34952. return null;
  34953. };
  34954. /**
  34955. * Marks the material to indicate that it needs to be re-calculated
  34956. */
  34957. Material.prototype.markDirty = function () {
  34958. this._wasPreviouslyReady = false;
  34959. };
  34960. /** @hidden */
  34961. Material.prototype._preBind = function (effect, overrideOrientation) {
  34962. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34963. var engine = this._scene.getEngine();
  34964. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34965. var reverse = orientation === Material.ClockWiseSideOrientation;
  34966. engine.enableEffect(effect ? effect : this._effect);
  34967. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34968. return reverse;
  34969. };
  34970. /**
  34971. * Binds the material to the mesh
  34972. * @param world defines the world transformation matrix
  34973. * @param mesh defines the mesh to bind the material to
  34974. */
  34975. Material.prototype.bind = function (world, mesh) {
  34976. };
  34977. /**
  34978. * Binds the submesh to the material
  34979. * @param world defines the world transformation matrix
  34980. * @param mesh defines the mesh containing the submesh
  34981. * @param subMesh defines the submesh to bind the material to
  34982. */
  34983. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34984. };
  34985. /**
  34986. * Binds the world matrix to the material
  34987. * @param world defines the world transformation matrix
  34988. */
  34989. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34990. };
  34991. /**
  34992. * Binds the scene's uniform buffer to the effect.
  34993. * @param effect defines the effect to bind to the scene uniform buffer
  34994. * @param sceneUbo defines the uniform buffer storing scene data
  34995. */
  34996. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34997. sceneUbo.bindToEffect(effect, "Scene");
  34998. };
  34999. /**
  35000. * Binds the view matrix to the effect
  35001. * @param effect defines the effect to bind the view matrix to
  35002. */
  35003. Material.prototype.bindView = function (effect) {
  35004. if (!this._useUBO) {
  35005. effect.setMatrix("view", this.getScene().getViewMatrix());
  35006. }
  35007. else {
  35008. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35009. }
  35010. };
  35011. /**
  35012. * Binds the view projection matrix to the effect
  35013. * @param effect defines the effect to bind the view projection matrix to
  35014. */
  35015. Material.prototype.bindViewProjection = function (effect) {
  35016. if (!this._useUBO) {
  35017. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35018. }
  35019. else {
  35020. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35021. }
  35022. };
  35023. /**
  35024. * Specifies if material alpha testing should be turned on for the mesh
  35025. * @param mesh defines the mesh to check
  35026. */
  35027. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35028. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35029. };
  35030. /**
  35031. * Processes to execute after binding the material to a mesh
  35032. * @param mesh defines the rendered mesh
  35033. */
  35034. Material.prototype._afterBind = function (mesh) {
  35035. this._scene._cachedMaterial = this;
  35036. if (mesh) {
  35037. this._scene._cachedVisibility = mesh.visibility;
  35038. }
  35039. else {
  35040. this._scene._cachedVisibility = 1;
  35041. }
  35042. if (mesh) {
  35043. this.onBindObservable.notifyObservers(mesh);
  35044. }
  35045. if (this.disableDepthWrite) {
  35046. var engine = this._scene.getEngine();
  35047. this._cachedDepthWriteState = engine.getDepthWrite();
  35048. engine.setDepthWrite(false);
  35049. }
  35050. };
  35051. /**
  35052. * Unbinds the material from the mesh
  35053. */
  35054. Material.prototype.unbind = function () {
  35055. this.onUnBindObservable.notifyObservers(this);
  35056. if (this.disableDepthWrite) {
  35057. var engine = this._scene.getEngine();
  35058. engine.setDepthWrite(this._cachedDepthWriteState);
  35059. }
  35060. };
  35061. /**
  35062. * Gets the active textures from the material
  35063. * @returns an array of textures
  35064. */
  35065. Material.prototype.getActiveTextures = function () {
  35066. return [];
  35067. };
  35068. /**
  35069. * Specifies if the material uses a texture
  35070. * @param texture defines the texture to check against the material
  35071. * @returns a boolean specifying if the material uses the texture
  35072. */
  35073. Material.prototype.hasTexture = function (texture) {
  35074. return false;
  35075. };
  35076. /**
  35077. * Makes a duplicate of the material, and gives it a new name
  35078. * @param name defines the new name for the duplicated material
  35079. * @returns the cloned material
  35080. */
  35081. Material.prototype.clone = function (name) {
  35082. return null;
  35083. };
  35084. /**
  35085. * Gets the meshes bound to the material
  35086. * @returns an array of meshes bound to the material
  35087. */
  35088. Material.prototype.getBindedMeshes = function () {
  35089. var result = new Array();
  35090. for (var index = 0; index < this._scene.meshes.length; index++) {
  35091. var mesh = this._scene.meshes[index];
  35092. if (mesh.material === this) {
  35093. result.push(mesh);
  35094. }
  35095. }
  35096. return result;
  35097. };
  35098. /**
  35099. * Force shader compilation
  35100. * @param mesh defines the mesh associated with this material
  35101. * @param onCompiled defines a function to execute once the material is compiled
  35102. * @param options defines the options to configure the compilation
  35103. */
  35104. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35105. var _this = this;
  35106. var localOptions = __assign({ clipPlane: false }, options);
  35107. var subMesh = new BABYLON.BaseSubMesh();
  35108. var scene = this.getScene();
  35109. var checkReady = function () {
  35110. if (!_this._scene || !_this._scene.getEngine()) {
  35111. return;
  35112. }
  35113. if (subMesh._materialDefines) {
  35114. subMesh._materialDefines._renderId = -1;
  35115. }
  35116. var clipPlaneState = scene.clipPlane;
  35117. if (localOptions.clipPlane) {
  35118. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35119. }
  35120. if (_this.storeEffectOnSubMeshes) {
  35121. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35122. if (onCompiled) {
  35123. onCompiled(_this);
  35124. }
  35125. }
  35126. else {
  35127. setTimeout(checkReady, 16);
  35128. }
  35129. }
  35130. else {
  35131. if (_this.isReady(mesh)) {
  35132. if (onCompiled) {
  35133. onCompiled(_this);
  35134. }
  35135. }
  35136. else {
  35137. setTimeout(checkReady, 16);
  35138. }
  35139. }
  35140. if (localOptions.clipPlane) {
  35141. scene.clipPlane = clipPlaneState;
  35142. }
  35143. };
  35144. checkReady();
  35145. };
  35146. /**
  35147. * Force shader compilation
  35148. * @param mesh defines the mesh that will use this material
  35149. * @param options defines additional options for compiling the shaders
  35150. * @returns a promise that resolves when the compilation completes
  35151. */
  35152. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35153. var _this = this;
  35154. return new Promise(function (resolve) {
  35155. _this.forceCompilation(mesh, function () {
  35156. resolve();
  35157. }, options);
  35158. });
  35159. };
  35160. /**
  35161. * Marks a define in the material to indicate that it needs to be re-computed
  35162. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35163. */
  35164. Material.prototype.markAsDirty = function (flag) {
  35165. if (flag & Material.TextureDirtyFlag) {
  35166. this._markAllSubMeshesAsTexturesDirty();
  35167. }
  35168. if (flag & Material.LightDirtyFlag) {
  35169. this._markAllSubMeshesAsLightsDirty();
  35170. }
  35171. if (flag & Material.FresnelDirtyFlag) {
  35172. this._markAllSubMeshesAsFresnelDirty();
  35173. }
  35174. if (flag & Material.AttributesDirtyFlag) {
  35175. this._markAllSubMeshesAsAttributesDirty();
  35176. }
  35177. if (flag & Material.MiscDirtyFlag) {
  35178. this._markAllSubMeshesAsMiscDirty();
  35179. }
  35180. this.getScene().resetCachedMaterial();
  35181. };
  35182. /**
  35183. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35184. * @param func defines a function which checks material defines against the submeshes
  35185. */
  35186. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35187. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35188. var mesh = _a[_i];
  35189. if (!mesh.subMeshes) {
  35190. continue;
  35191. }
  35192. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35193. var subMesh = _c[_b];
  35194. if (subMesh.getMaterial() !== this) {
  35195. continue;
  35196. }
  35197. if (!subMesh._materialDefines) {
  35198. continue;
  35199. }
  35200. func(subMesh._materialDefines);
  35201. }
  35202. }
  35203. };
  35204. /**
  35205. * Indicates that image processing needs to be re-calculated for all submeshes
  35206. */
  35207. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35208. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35209. };
  35210. /**
  35211. * Indicates that textures need to be re-calculated for all submeshes
  35212. */
  35213. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35214. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35215. };
  35216. /**
  35217. * Indicates that fresnel needs to be re-calculated for all submeshes
  35218. */
  35219. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35220. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35221. };
  35222. /**
  35223. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35224. */
  35225. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35226. this._markAllSubMeshesAsDirty(function (defines) {
  35227. defines.markAsFresnelDirty();
  35228. defines.markAsMiscDirty();
  35229. });
  35230. };
  35231. /**
  35232. * Indicates that lights need to be re-calculated for all submeshes
  35233. */
  35234. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35235. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35236. };
  35237. /**
  35238. * Indicates that attributes need to be re-calculated for all submeshes
  35239. */
  35240. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35241. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35242. };
  35243. /**
  35244. * Indicates that misc needs to be re-calculated for all submeshes
  35245. */
  35246. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35247. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35248. };
  35249. /**
  35250. * Indicates that textures and misc need to be re-calculated for all submeshes
  35251. */
  35252. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35253. this._markAllSubMeshesAsDirty(function (defines) {
  35254. defines.markAsTexturesDirty();
  35255. defines.markAsMiscDirty();
  35256. });
  35257. };
  35258. /**
  35259. * Disposes the material
  35260. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35261. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35262. */
  35263. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35264. // Animations
  35265. this.getScene().stopAnimation(this);
  35266. this.getScene().freeProcessedMaterials();
  35267. // Remove from scene
  35268. var index = this._scene.materials.indexOf(this);
  35269. if (index >= 0) {
  35270. this._scene.materials.splice(index, 1);
  35271. }
  35272. // Remove from meshes
  35273. for (index = 0; index < this._scene.meshes.length; index++) {
  35274. var mesh = this._scene.meshes[index];
  35275. if (mesh.material === this) {
  35276. mesh.material = null;
  35277. if (mesh.geometry) {
  35278. var geometry = (mesh.geometry);
  35279. if (this.storeEffectOnSubMeshes) {
  35280. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35281. var subMesh = _a[_i];
  35282. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35283. if (forceDisposeEffect && subMesh._materialEffect) {
  35284. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35285. }
  35286. }
  35287. }
  35288. else {
  35289. geometry._releaseVertexArrayObject(this._effect);
  35290. }
  35291. }
  35292. }
  35293. }
  35294. this._uniformBuffer.dispose();
  35295. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35296. if (forceDisposeEffect && this._effect) {
  35297. if (!this.storeEffectOnSubMeshes) {
  35298. this._scene.getEngine()._releaseEffect(this._effect);
  35299. }
  35300. this._effect = null;
  35301. }
  35302. // Callback
  35303. this.onDisposeObservable.notifyObservers(this);
  35304. this.onDisposeObservable.clear();
  35305. this.onBindObservable.clear();
  35306. this.onUnBindObservable.clear();
  35307. };
  35308. /**
  35309. * Serializes this material
  35310. * @returns the serialized material object
  35311. */
  35312. Material.prototype.serialize = function () {
  35313. return BABYLON.SerializationHelper.Serialize(this);
  35314. };
  35315. /**
  35316. * Creates a MultiMaterial from parsed MultiMaterial data.
  35317. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35318. * @param scene defines the hosting scene
  35319. * @returns a new MultiMaterial
  35320. */
  35321. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35322. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35323. multiMaterial.id = parsedMultiMaterial.id;
  35324. if (BABYLON.Tags) {
  35325. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35326. }
  35327. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35328. var subMatId = parsedMultiMaterial.materials[matIndex];
  35329. if (subMatId) {
  35330. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35331. }
  35332. else {
  35333. multiMaterial.subMaterials.push(null);
  35334. }
  35335. }
  35336. return multiMaterial;
  35337. };
  35338. /**
  35339. * Creates a material from parsed material data
  35340. * @param parsedMaterial defines parsed material data
  35341. * @param scene defines the hosting scene
  35342. * @param rootUrl defines the root URL to use to load textures
  35343. * @returns a new material
  35344. */
  35345. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35346. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35347. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35348. }
  35349. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35350. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35351. if (!BABYLON.LegacyPBRMaterial) {
  35352. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35353. return;
  35354. }
  35355. }
  35356. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35357. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35358. ;
  35359. };
  35360. // Triangle views
  35361. Material._TriangleFillMode = 0;
  35362. Material._WireFrameFillMode = 1;
  35363. Material._PointFillMode = 2;
  35364. // Draw modes
  35365. Material._PointListDrawMode = 3;
  35366. Material._LineListDrawMode = 4;
  35367. Material._LineLoopDrawMode = 5;
  35368. Material._LineStripDrawMode = 6;
  35369. Material._TriangleStripDrawMode = 7;
  35370. Material._TriangleFanDrawMode = 8;
  35371. /**
  35372. * Stores the clock-wise side orientation
  35373. */
  35374. Material._ClockWiseSideOrientation = 0;
  35375. /**
  35376. * Stores the counter clock-wise side orientation
  35377. */
  35378. Material._CounterClockWiseSideOrientation = 1;
  35379. /**
  35380. * The dirty texture flag value
  35381. */
  35382. Material._TextureDirtyFlag = 1;
  35383. /**
  35384. * The dirty light flag value
  35385. */
  35386. Material._LightDirtyFlag = 2;
  35387. /**
  35388. * The dirty fresnel flag value
  35389. */
  35390. Material._FresnelDirtyFlag = 4;
  35391. /**
  35392. * The dirty attribute flag value
  35393. */
  35394. Material._AttributesDirtyFlag = 8;
  35395. /**
  35396. * The dirty misc flag value
  35397. */
  35398. Material._MiscDirtyFlag = 16;
  35399. __decorate([
  35400. BABYLON.serialize()
  35401. ], Material.prototype, "id", void 0);
  35402. __decorate([
  35403. BABYLON.serialize()
  35404. ], Material.prototype, "name", void 0);
  35405. __decorate([
  35406. BABYLON.serialize()
  35407. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35408. __decorate([
  35409. BABYLON.serialize()
  35410. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35411. __decorate([
  35412. BABYLON.serialize()
  35413. ], Material.prototype, "state", void 0);
  35414. __decorate([
  35415. BABYLON.serialize("alpha")
  35416. ], Material.prototype, "_alpha", void 0);
  35417. __decorate([
  35418. BABYLON.serialize("backFaceCulling")
  35419. ], Material.prototype, "_backFaceCulling", void 0);
  35420. __decorate([
  35421. BABYLON.serialize()
  35422. ], Material.prototype, "sideOrientation", void 0);
  35423. __decorate([
  35424. BABYLON.serialize("alphaMode")
  35425. ], Material.prototype, "_alphaMode", void 0);
  35426. __decorate([
  35427. BABYLON.serialize()
  35428. ], Material.prototype, "_needDepthPrePass", void 0);
  35429. __decorate([
  35430. BABYLON.serialize()
  35431. ], Material.prototype, "disableDepthWrite", void 0);
  35432. __decorate([
  35433. BABYLON.serialize()
  35434. ], Material.prototype, "forceDepthWrite", void 0);
  35435. __decorate([
  35436. BABYLON.serialize()
  35437. ], Material.prototype, "separateCullingPass", void 0);
  35438. __decorate([
  35439. BABYLON.serialize("fogEnabled")
  35440. ], Material.prototype, "_fogEnabled", void 0);
  35441. __decorate([
  35442. BABYLON.serialize()
  35443. ], Material.prototype, "pointSize", void 0);
  35444. __decorate([
  35445. BABYLON.serialize()
  35446. ], Material.prototype, "zOffset", void 0);
  35447. __decorate([
  35448. BABYLON.serialize()
  35449. ], Material.prototype, "wireframe", null);
  35450. __decorate([
  35451. BABYLON.serialize()
  35452. ], Material.prototype, "pointsCloud", null);
  35453. __decorate([
  35454. BABYLON.serialize()
  35455. ], Material.prototype, "fillMode", null);
  35456. return Material;
  35457. }());
  35458. BABYLON.Material = Material;
  35459. })(BABYLON || (BABYLON = {}));
  35460. //# sourceMappingURL=babylon.material.js.map
  35461. var BABYLON;
  35462. (function (BABYLON) {
  35463. var UniformBuffer = /** @class */ (function () {
  35464. /**
  35465. * Uniform buffer objects.
  35466. *
  35467. * Handles blocks of uniform on the GPU.
  35468. *
  35469. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35470. *
  35471. * For more information, please refer to :
  35472. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35473. */
  35474. function UniformBuffer(engine, data, dynamic) {
  35475. this._engine = engine;
  35476. this._noUBO = !engine.supportsUniformBuffers;
  35477. this._dynamic = dynamic;
  35478. this._data = data || [];
  35479. this._uniformLocations = {};
  35480. this._uniformSizes = {};
  35481. this._uniformLocationPointer = 0;
  35482. this._needSync = false;
  35483. if (this._noUBO) {
  35484. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35485. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35486. this.updateFloat = this._updateFloatForEffect;
  35487. this.updateFloat2 = this._updateFloat2ForEffect;
  35488. this.updateFloat3 = this._updateFloat3ForEffect;
  35489. this.updateFloat4 = this._updateFloat4ForEffect;
  35490. this.updateMatrix = this._updateMatrixForEffect;
  35491. this.updateVector3 = this._updateVector3ForEffect;
  35492. this.updateVector4 = this._updateVector4ForEffect;
  35493. this.updateColor3 = this._updateColor3ForEffect;
  35494. this.updateColor4 = this._updateColor4ForEffect;
  35495. }
  35496. else {
  35497. this._engine._uniformBuffers.push(this);
  35498. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35499. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35500. this.updateFloat = this._updateFloatForUniform;
  35501. this.updateFloat2 = this._updateFloat2ForUniform;
  35502. this.updateFloat3 = this._updateFloat3ForUniform;
  35503. this.updateFloat4 = this._updateFloat4ForUniform;
  35504. this.updateMatrix = this._updateMatrixForUniform;
  35505. this.updateVector3 = this._updateVector3ForUniform;
  35506. this.updateVector4 = this._updateVector4ForUniform;
  35507. this.updateColor3 = this._updateColor3ForUniform;
  35508. this.updateColor4 = this._updateColor4ForUniform;
  35509. }
  35510. }
  35511. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35512. // Properties
  35513. /**
  35514. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35515. * or just falling back on setUniformXXX calls.
  35516. */
  35517. get: function () {
  35518. return !this._noUBO;
  35519. },
  35520. enumerable: true,
  35521. configurable: true
  35522. });
  35523. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35524. /**
  35525. * Indicates if the WebGL underlying uniform buffer is in sync
  35526. * with the javascript cache data.
  35527. */
  35528. get: function () {
  35529. return !this._needSync;
  35530. },
  35531. enumerable: true,
  35532. configurable: true
  35533. });
  35534. /**
  35535. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35536. * Also, a dynamic UniformBuffer will disable cache verification and always
  35537. * update the underlying WebGL uniform buffer to the GPU.
  35538. */
  35539. UniformBuffer.prototype.isDynamic = function () {
  35540. return this._dynamic !== undefined;
  35541. };
  35542. /**
  35543. * The data cache on JS side.
  35544. */
  35545. UniformBuffer.prototype.getData = function () {
  35546. return this._bufferData;
  35547. };
  35548. /**
  35549. * The underlying WebGL Uniform buffer.
  35550. */
  35551. UniformBuffer.prototype.getBuffer = function () {
  35552. return this._buffer;
  35553. };
  35554. /**
  35555. * std140 layout specifies how to align data within an UBO structure.
  35556. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35557. * for specs.
  35558. */
  35559. UniformBuffer.prototype._fillAlignment = function (size) {
  35560. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35561. // and 4x4 matrices
  35562. // TODO : change if other types are used
  35563. var alignment;
  35564. if (size <= 2) {
  35565. alignment = size;
  35566. }
  35567. else {
  35568. alignment = 4;
  35569. }
  35570. if ((this._uniformLocationPointer % alignment) !== 0) {
  35571. var oldPointer = this._uniformLocationPointer;
  35572. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35573. var diff = this._uniformLocationPointer - oldPointer;
  35574. for (var i = 0; i < diff; i++) {
  35575. this._data.push(0);
  35576. }
  35577. }
  35578. };
  35579. /**
  35580. * Adds an uniform in the buffer.
  35581. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35582. * for the layout to be correct !
  35583. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35584. * @param {number|number[]} size Data size, or data directly.
  35585. */
  35586. UniformBuffer.prototype.addUniform = function (name, size) {
  35587. if (this._noUBO) {
  35588. return;
  35589. }
  35590. if (this._uniformLocations[name] !== undefined) {
  35591. // Already existing uniform
  35592. return;
  35593. }
  35594. // This function must be called in the order of the shader layout !
  35595. // size can be the size of the uniform, or data directly
  35596. var data;
  35597. if (size instanceof Array) {
  35598. data = size;
  35599. size = data.length;
  35600. }
  35601. else {
  35602. size = size;
  35603. data = [];
  35604. // Fill with zeros
  35605. for (var i = 0; i < size; i++) {
  35606. data.push(0);
  35607. }
  35608. }
  35609. this._fillAlignment(size);
  35610. this._uniformSizes[name] = size;
  35611. this._uniformLocations[name] = this._uniformLocationPointer;
  35612. this._uniformLocationPointer += size;
  35613. for (var i = 0; i < size; i++) {
  35614. this._data.push(data[i]);
  35615. }
  35616. this._needSync = true;
  35617. };
  35618. /**
  35619. * Wrapper for addUniform.
  35620. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35621. * @param {Matrix} mat A 4x4 matrix.
  35622. */
  35623. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35624. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35625. };
  35626. /**
  35627. * Wrapper for addUniform.
  35628. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35629. * @param {number} x
  35630. * @param {number} y
  35631. */
  35632. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35633. var temp = [x, y];
  35634. this.addUniform(name, temp);
  35635. };
  35636. /**
  35637. * Wrapper for addUniform.
  35638. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35639. * @param {number} x
  35640. * @param {number} y
  35641. * @param {number} z
  35642. */
  35643. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35644. var temp = [x, y, z];
  35645. this.addUniform(name, temp);
  35646. };
  35647. /**
  35648. * Wrapper for addUniform.
  35649. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35650. * @param {Color3} color
  35651. */
  35652. UniformBuffer.prototype.addColor3 = function (name, color) {
  35653. var temp = new Array();
  35654. color.toArray(temp);
  35655. this.addUniform(name, temp);
  35656. };
  35657. /**
  35658. * Wrapper for addUniform.
  35659. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35660. * @param {Color3} color
  35661. * @param {number} alpha
  35662. */
  35663. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35664. var temp = new Array();
  35665. color.toArray(temp);
  35666. temp.push(alpha);
  35667. this.addUniform(name, temp);
  35668. };
  35669. /**
  35670. * Wrapper for addUniform.
  35671. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35672. * @param {Vector3} vector
  35673. */
  35674. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35675. var temp = new Array();
  35676. vector.toArray(temp);
  35677. this.addUniform(name, temp);
  35678. };
  35679. /**
  35680. * Wrapper for addUniform.
  35681. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35682. */
  35683. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35684. this.addUniform(name, 12);
  35685. };
  35686. /**
  35687. * Wrapper for addUniform.
  35688. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35689. */
  35690. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35691. this.addUniform(name, 8);
  35692. };
  35693. /**
  35694. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35695. */
  35696. UniformBuffer.prototype.create = function () {
  35697. if (this._noUBO) {
  35698. return;
  35699. }
  35700. if (this._buffer) {
  35701. return; // nothing to do
  35702. }
  35703. // See spec, alignment must be filled as a vec4
  35704. this._fillAlignment(4);
  35705. this._bufferData = new Float32Array(this._data);
  35706. this._rebuild();
  35707. this._needSync = true;
  35708. };
  35709. UniformBuffer.prototype._rebuild = function () {
  35710. if (this._noUBO) {
  35711. return;
  35712. }
  35713. if (this._dynamic) {
  35714. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35715. }
  35716. else {
  35717. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35718. }
  35719. };
  35720. /**
  35721. * Updates the WebGL Uniform Buffer on the GPU.
  35722. * If the `dynamic` flag is set to true, no cache comparison is done.
  35723. * Otherwise, the buffer will be updated only if the cache differs.
  35724. */
  35725. UniformBuffer.prototype.update = function () {
  35726. if (!this._buffer) {
  35727. this.create();
  35728. return;
  35729. }
  35730. if (!this._dynamic && !this._needSync) {
  35731. return;
  35732. }
  35733. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35734. this._needSync = false;
  35735. };
  35736. /**
  35737. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35738. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35739. * @param {number[]|Float32Array} data Flattened data
  35740. * @param {number} size Size of the data.
  35741. */
  35742. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35743. var location = this._uniformLocations[uniformName];
  35744. if (location === undefined) {
  35745. if (this._buffer) {
  35746. // Cannot add an uniform if the buffer is already created
  35747. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35748. return;
  35749. }
  35750. this.addUniform(uniformName, size);
  35751. location = this._uniformLocations[uniformName];
  35752. }
  35753. if (!this._buffer) {
  35754. this.create();
  35755. }
  35756. if (!this._dynamic) {
  35757. // Cache for static uniform buffers
  35758. var changed = false;
  35759. for (var i = 0; i < size; i++) {
  35760. if (this._bufferData[location + i] !== data[i]) {
  35761. changed = true;
  35762. this._bufferData[location + i] = data[i];
  35763. }
  35764. }
  35765. this._needSync = this._needSync || changed;
  35766. }
  35767. else {
  35768. // No cache for dynamic
  35769. for (var i = 0; i < size; i++) {
  35770. this._bufferData[location + i] = data[i];
  35771. }
  35772. }
  35773. };
  35774. // Update methods
  35775. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35776. // To match std140, matrix must be realigned
  35777. for (var i = 0; i < 3; i++) {
  35778. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35779. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35780. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35781. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35782. }
  35783. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35784. };
  35785. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35786. this._currentEffect.setMatrix3x3(name, matrix);
  35787. };
  35788. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35789. this._currentEffect.setMatrix2x2(name, matrix);
  35790. };
  35791. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35792. // To match std140, matrix must be realigned
  35793. for (var i = 0; i < 2; i++) {
  35794. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35795. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35796. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35797. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35798. }
  35799. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35800. };
  35801. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35802. this._currentEffect.setFloat(name, x);
  35803. };
  35804. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35805. UniformBuffer._tempBuffer[0] = x;
  35806. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35807. };
  35808. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35809. if (suffix === void 0) { suffix = ""; }
  35810. this._currentEffect.setFloat2(name + suffix, x, y);
  35811. };
  35812. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35813. if (suffix === void 0) { suffix = ""; }
  35814. UniformBuffer._tempBuffer[0] = x;
  35815. UniformBuffer._tempBuffer[1] = y;
  35816. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35817. };
  35818. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35819. if (suffix === void 0) { suffix = ""; }
  35820. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35821. };
  35822. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35823. if (suffix === void 0) { suffix = ""; }
  35824. UniformBuffer._tempBuffer[0] = x;
  35825. UniformBuffer._tempBuffer[1] = y;
  35826. UniformBuffer._tempBuffer[2] = z;
  35827. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35828. };
  35829. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35830. if (suffix === void 0) { suffix = ""; }
  35831. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35832. };
  35833. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35834. if (suffix === void 0) { suffix = ""; }
  35835. UniformBuffer._tempBuffer[0] = x;
  35836. UniformBuffer._tempBuffer[1] = y;
  35837. UniformBuffer._tempBuffer[2] = z;
  35838. UniformBuffer._tempBuffer[3] = w;
  35839. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35840. };
  35841. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35842. this._currentEffect.setMatrix(name, mat);
  35843. };
  35844. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35845. this.updateUniform(name, mat.toArray(), 16);
  35846. };
  35847. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35848. this._currentEffect.setVector3(name, vector);
  35849. };
  35850. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35851. vector.toArray(UniformBuffer._tempBuffer);
  35852. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35853. };
  35854. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35855. this._currentEffect.setVector4(name, vector);
  35856. };
  35857. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35858. vector.toArray(UniformBuffer._tempBuffer);
  35859. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35860. };
  35861. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35862. if (suffix === void 0) { suffix = ""; }
  35863. this._currentEffect.setColor3(name + suffix, color);
  35864. };
  35865. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35866. if (suffix === void 0) { suffix = ""; }
  35867. color.toArray(UniformBuffer._tempBuffer);
  35868. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35869. };
  35870. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35871. if (suffix === void 0) { suffix = ""; }
  35872. this._currentEffect.setColor4(name + suffix, color, alpha);
  35873. };
  35874. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35875. if (suffix === void 0) { suffix = ""; }
  35876. color.toArray(UniformBuffer._tempBuffer);
  35877. UniformBuffer._tempBuffer[3] = alpha;
  35878. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35879. };
  35880. /**
  35881. * Sets a sampler uniform on the effect.
  35882. * @param {string} name Name of the sampler.
  35883. * @param {Texture} texture
  35884. */
  35885. UniformBuffer.prototype.setTexture = function (name, texture) {
  35886. this._currentEffect.setTexture(name, texture);
  35887. };
  35888. /**
  35889. * Directly updates the value of the uniform in the cache AND on the GPU.
  35890. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35891. * @param {number[]|Float32Array} data Flattened data
  35892. */
  35893. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35894. this.updateUniform(uniformName, data, data.length);
  35895. this.update();
  35896. };
  35897. /**
  35898. * Binds this uniform buffer to an effect.
  35899. * @param {Effect} effect
  35900. * @param {string} name Name of the uniform block in the shader.
  35901. */
  35902. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35903. this._currentEffect = effect;
  35904. if (this._noUBO || !this._buffer) {
  35905. return;
  35906. }
  35907. effect.bindUniformBuffer(this._buffer, name);
  35908. };
  35909. /**
  35910. * Disposes the uniform buffer.
  35911. */
  35912. UniformBuffer.prototype.dispose = function () {
  35913. if (this._noUBO) {
  35914. return;
  35915. }
  35916. var index = this._engine._uniformBuffers.indexOf(this);
  35917. if (index !== -1) {
  35918. this._engine._uniformBuffers.splice(index, 1);
  35919. }
  35920. if (!this._buffer) {
  35921. return;
  35922. }
  35923. if (this._engine._releaseBuffer(this._buffer)) {
  35924. this._buffer = null;
  35925. }
  35926. };
  35927. // Pool for avoiding memory leaks
  35928. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35929. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35930. return UniformBuffer;
  35931. }());
  35932. BABYLON.UniformBuffer = UniformBuffer;
  35933. })(BABYLON || (BABYLON = {}));
  35934. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35935. var BABYLON;
  35936. (function (BABYLON) {
  35937. /**
  35938. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35939. */
  35940. var VertexData = /** @class */ (function () {
  35941. function VertexData() {
  35942. }
  35943. /**
  35944. * Uses the passed data array to set the set the values for the specified kind of data
  35945. * @param data a linear array of floating numbers
  35946. * @param kind the type of data that is being set, eg positions, colors etc
  35947. */
  35948. VertexData.prototype.set = function (data, kind) {
  35949. switch (kind) {
  35950. case BABYLON.VertexBuffer.PositionKind:
  35951. this.positions = data;
  35952. break;
  35953. case BABYLON.VertexBuffer.NormalKind:
  35954. this.normals = data;
  35955. break;
  35956. case BABYLON.VertexBuffer.TangentKind:
  35957. this.tangents = data;
  35958. break;
  35959. case BABYLON.VertexBuffer.UVKind:
  35960. this.uvs = data;
  35961. break;
  35962. case BABYLON.VertexBuffer.UV2Kind:
  35963. this.uvs2 = data;
  35964. break;
  35965. case BABYLON.VertexBuffer.UV3Kind:
  35966. this.uvs3 = data;
  35967. break;
  35968. case BABYLON.VertexBuffer.UV4Kind:
  35969. this.uvs4 = data;
  35970. break;
  35971. case BABYLON.VertexBuffer.UV5Kind:
  35972. this.uvs5 = data;
  35973. break;
  35974. case BABYLON.VertexBuffer.UV6Kind:
  35975. this.uvs6 = data;
  35976. break;
  35977. case BABYLON.VertexBuffer.ColorKind:
  35978. this.colors = data;
  35979. break;
  35980. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35981. this.matricesIndices = data;
  35982. break;
  35983. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35984. this.matricesWeights = data;
  35985. break;
  35986. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35987. this.matricesIndicesExtra = data;
  35988. break;
  35989. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35990. this.matricesWeightsExtra = data;
  35991. break;
  35992. }
  35993. };
  35994. /**
  35995. * Associates the vertexData to the passed Mesh.
  35996. * Sets it as updatable or not (default `false`)
  35997. * @param mesh the mesh the vertexData is applied to
  35998. * @param updatable when used and having the value true allows new data to update the vertexData
  35999. * @returns the VertexData
  36000. */
  36001. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36002. this._applyTo(mesh, updatable);
  36003. return this;
  36004. };
  36005. /**
  36006. * Associates the vertexData to the passed Geometry.
  36007. * Sets it as updatable or not (default `false`)
  36008. * @param geometry the geometry the vertexData is applied to
  36009. * @param updatable when used and having the value true allows new data to update the vertexData
  36010. * @returns VertexData
  36011. */
  36012. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36013. this._applyTo(geometry, updatable);
  36014. return this;
  36015. };
  36016. /**
  36017. * Updates the associated mesh
  36018. * @param mesh the mesh to be updated
  36019. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36020. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36021. * @returns VertexData
  36022. */
  36023. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36024. this._update(mesh);
  36025. return this;
  36026. };
  36027. /**
  36028. * Updates the associated geometry
  36029. * @param geometry the geometry to be updated
  36030. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36031. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36032. * @returns VertexData.
  36033. */
  36034. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36035. this._update(geometry);
  36036. return this;
  36037. };
  36038. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36039. if (updatable === void 0) { updatable = false; }
  36040. if (this.positions) {
  36041. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36042. }
  36043. if (this.normals) {
  36044. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36045. }
  36046. if (this.tangents) {
  36047. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36048. }
  36049. if (this.uvs) {
  36050. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36051. }
  36052. if (this.uvs2) {
  36053. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36054. }
  36055. if (this.uvs3) {
  36056. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36057. }
  36058. if (this.uvs4) {
  36059. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36060. }
  36061. if (this.uvs5) {
  36062. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36063. }
  36064. if (this.uvs6) {
  36065. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36066. }
  36067. if (this.colors) {
  36068. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36069. }
  36070. if (this.matricesIndices) {
  36071. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36072. }
  36073. if (this.matricesWeights) {
  36074. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36075. }
  36076. if (this.matricesIndicesExtra) {
  36077. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36078. }
  36079. if (this.matricesWeightsExtra) {
  36080. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36081. }
  36082. if (this.indices) {
  36083. meshOrGeometry.setIndices(this.indices, null, updatable);
  36084. }
  36085. return this;
  36086. };
  36087. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36088. if (this.positions) {
  36089. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36090. }
  36091. if (this.normals) {
  36092. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36093. }
  36094. if (this.tangents) {
  36095. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36096. }
  36097. if (this.uvs) {
  36098. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36099. }
  36100. if (this.uvs2) {
  36101. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36102. }
  36103. if (this.uvs3) {
  36104. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36105. }
  36106. if (this.uvs4) {
  36107. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36108. }
  36109. if (this.uvs5) {
  36110. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36111. }
  36112. if (this.uvs6) {
  36113. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36114. }
  36115. if (this.colors) {
  36116. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36117. }
  36118. if (this.matricesIndices) {
  36119. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36120. }
  36121. if (this.matricesWeights) {
  36122. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36123. }
  36124. if (this.matricesIndicesExtra) {
  36125. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36126. }
  36127. if (this.matricesWeightsExtra) {
  36128. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36129. }
  36130. if (this.indices) {
  36131. meshOrGeometry.setIndices(this.indices, null);
  36132. }
  36133. return this;
  36134. };
  36135. /**
  36136. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36137. * @param matrix the transforming matrix
  36138. * @returns the VertexData
  36139. */
  36140. VertexData.prototype.transform = function (matrix) {
  36141. var transformed = BABYLON.Vector3.Zero();
  36142. var index;
  36143. if (this.positions) {
  36144. var position = BABYLON.Vector3.Zero();
  36145. for (index = 0; index < this.positions.length; index += 3) {
  36146. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36147. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36148. this.positions[index] = transformed.x;
  36149. this.positions[index + 1] = transformed.y;
  36150. this.positions[index + 2] = transformed.z;
  36151. }
  36152. }
  36153. if (this.normals) {
  36154. var normal = BABYLON.Vector3.Zero();
  36155. for (index = 0; index < this.normals.length; index += 3) {
  36156. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36157. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36158. this.normals[index] = transformed.x;
  36159. this.normals[index + 1] = transformed.y;
  36160. this.normals[index + 2] = transformed.z;
  36161. }
  36162. }
  36163. if (this.tangents) {
  36164. var tangent = BABYLON.Vector4.Zero();
  36165. var tangentTransformed = BABYLON.Vector4.Zero();
  36166. for (index = 0; index < this.tangents.length; index += 4) {
  36167. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36168. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36169. this.tangents[index] = tangentTransformed.x;
  36170. this.tangents[index + 1] = tangentTransformed.y;
  36171. this.tangents[index + 2] = tangentTransformed.z;
  36172. this.tangents[index + 3] = tangentTransformed.w;
  36173. }
  36174. }
  36175. return this;
  36176. };
  36177. /**
  36178. * Merges the passed VertexData into the current one
  36179. * @param other the VertexData to be merged into the current one
  36180. * @returns the modified VertexData
  36181. */
  36182. VertexData.prototype.merge = function (other) {
  36183. this._validate();
  36184. other._validate();
  36185. if (!this.normals !== !other.normals ||
  36186. !this.tangents !== !other.tangents ||
  36187. !this.uvs !== !other.uvs ||
  36188. !this.uvs2 !== !other.uvs2 ||
  36189. !this.uvs3 !== !other.uvs3 ||
  36190. !this.uvs4 !== !other.uvs4 ||
  36191. !this.uvs5 !== !other.uvs5 ||
  36192. !this.uvs6 !== !other.uvs6 ||
  36193. !this.colors !== !other.colors ||
  36194. !this.matricesIndices !== !other.matricesIndices ||
  36195. !this.matricesWeights !== !other.matricesWeights ||
  36196. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36197. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36198. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36199. }
  36200. if (other.indices) {
  36201. if (!this.indices) {
  36202. this.indices = [];
  36203. }
  36204. var offset = this.positions ? this.positions.length / 3 : 0;
  36205. for (var index = 0; index < other.indices.length; index++) {
  36206. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36207. this.indices.push(other.indices[index] + offset);
  36208. }
  36209. }
  36210. this.positions = this._mergeElement(this.positions, other.positions);
  36211. this.normals = this._mergeElement(this.normals, other.normals);
  36212. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36213. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36214. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36215. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36216. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36217. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36218. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36219. this.colors = this._mergeElement(this.colors, other.colors);
  36220. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36221. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36222. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36223. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36224. return this;
  36225. };
  36226. VertexData.prototype._mergeElement = function (source, other) {
  36227. if (!source) {
  36228. return other;
  36229. }
  36230. if (!other) {
  36231. return source;
  36232. }
  36233. var len = other.length + source.length;
  36234. var isSrcTypedArray = source instanceof Float32Array;
  36235. var isOthTypedArray = other instanceof Float32Array;
  36236. // use non-loop method when the source is Float32Array
  36237. if (isSrcTypedArray) {
  36238. var ret32 = new Float32Array(len);
  36239. ret32.set(source);
  36240. ret32.set(other, source.length);
  36241. return ret32;
  36242. // source is number[], when other is also use concat
  36243. }
  36244. else if (!isOthTypedArray) {
  36245. return source.concat(other);
  36246. // source is a number[], but other is a Float32Array, loop required
  36247. }
  36248. else {
  36249. var ret = source.slice(0); // copy source to a separate array
  36250. for (var i = 0, len = other.length; i < len; i++) {
  36251. ret.push(other[i]);
  36252. }
  36253. return ret;
  36254. }
  36255. };
  36256. VertexData.prototype._validate = function () {
  36257. if (!this.positions) {
  36258. throw new Error("Positions are required");
  36259. }
  36260. var getElementCount = function (kind, values) {
  36261. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36262. if ((values.length % stride) !== 0) {
  36263. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36264. }
  36265. return values.length / stride;
  36266. };
  36267. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36268. var validateElementCount = function (kind, values) {
  36269. var elementCount = getElementCount(kind, values);
  36270. if (elementCount !== positionsElementCount) {
  36271. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36272. }
  36273. };
  36274. if (this.normals)
  36275. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36276. if (this.tangents)
  36277. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36278. if (this.uvs)
  36279. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36280. if (this.uvs2)
  36281. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36282. if (this.uvs3)
  36283. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36284. if (this.uvs4)
  36285. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36286. if (this.uvs5)
  36287. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36288. if (this.uvs6)
  36289. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36290. if (this.colors)
  36291. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36292. if (this.matricesIndices)
  36293. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36294. if (this.matricesWeights)
  36295. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36296. if (this.matricesIndicesExtra)
  36297. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36298. if (this.matricesWeightsExtra)
  36299. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36300. };
  36301. /**
  36302. * Serializes the VertexData
  36303. * @returns a serialized object
  36304. */
  36305. VertexData.prototype.serialize = function () {
  36306. var serializationObject = this.serialize();
  36307. if (this.positions) {
  36308. serializationObject.positions = this.positions;
  36309. }
  36310. if (this.normals) {
  36311. serializationObject.normals = this.normals;
  36312. }
  36313. if (this.tangents) {
  36314. serializationObject.tangents = this.tangents;
  36315. }
  36316. if (this.uvs) {
  36317. serializationObject.uvs = this.uvs;
  36318. }
  36319. if (this.uvs2) {
  36320. serializationObject.uvs2 = this.uvs2;
  36321. }
  36322. if (this.uvs3) {
  36323. serializationObject.uvs3 = this.uvs3;
  36324. }
  36325. if (this.uvs4) {
  36326. serializationObject.uvs4 = this.uvs4;
  36327. }
  36328. if (this.uvs5) {
  36329. serializationObject.uvs5 = this.uvs5;
  36330. }
  36331. if (this.uvs6) {
  36332. serializationObject.uvs6 = this.uvs6;
  36333. }
  36334. if (this.colors) {
  36335. serializationObject.colors = this.colors;
  36336. }
  36337. if (this.matricesIndices) {
  36338. serializationObject.matricesIndices = this.matricesIndices;
  36339. serializationObject.matricesIndices._isExpanded = true;
  36340. }
  36341. if (this.matricesWeights) {
  36342. serializationObject.matricesWeights = this.matricesWeights;
  36343. }
  36344. if (this.matricesIndicesExtra) {
  36345. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36346. serializationObject.matricesIndicesExtra._isExpanded = true;
  36347. }
  36348. if (this.matricesWeightsExtra) {
  36349. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36350. }
  36351. serializationObject.indices = this.indices;
  36352. return serializationObject;
  36353. };
  36354. // Statics
  36355. /**
  36356. * Extracts the vertexData from a mesh
  36357. * @param mesh the mesh from which to extract the VertexData
  36358. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36359. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36360. * @returns the object VertexData associated to the passed mesh
  36361. */
  36362. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36363. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36364. };
  36365. /**
  36366. * Extracts the vertexData from the geometry
  36367. * @param geometry the geometry from which to extract the VertexData
  36368. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36369. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36370. * @returns the object VertexData associated to the passed mesh
  36371. */
  36372. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36373. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36374. };
  36375. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36376. var result = new VertexData();
  36377. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36378. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36379. }
  36380. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36381. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36382. }
  36383. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36384. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36385. }
  36386. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36387. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36388. }
  36389. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36390. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36391. }
  36392. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36393. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36394. }
  36395. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36396. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36397. }
  36398. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36399. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36400. }
  36401. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36402. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36403. }
  36404. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36405. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36406. }
  36407. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36408. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36409. }
  36410. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36411. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36412. }
  36413. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36414. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36415. }
  36416. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36417. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36418. }
  36419. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36420. return result;
  36421. };
  36422. /**
  36423. * Creates the VertexData for a Ribbon
  36424. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36425. * * pathArray array of paths, each of which an array of successive Vector3
  36426. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36427. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36428. * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
  36429. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36430. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36431. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36432. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36433. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36434. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36435. * @returns the VertexData of the ribbon
  36436. */
  36437. VertexData.CreateRibbon = function (options) {
  36438. var pathArray = options.pathArray;
  36439. var closeArray = options.closeArray || false;
  36440. var closePath = options.closePath || false;
  36441. var invertUV = options.invertUV || false;
  36442. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36443. var offset = options.offset || defaultOffset;
  36444. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36445. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36446. var customUV = options.uvs;
  36447. var customColors = options.colors;
  36448. var positions = [];
  36449. var indices = [];
  36450. var normals = [];
  36451. var uvs = [];
  36452. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36453. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36454. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36455. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36456. var minlg; // minimal length among all paths from pathArray
  36457. var lg = []; // array of path lengths : nb of vertex per path
  36458. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36459. var p; // path iterator
  36460. var i; // point iterator
  36461. var j; // point iterator
  36462. // if single path in pathArray
  36463. if (pathArray.length < 2) {
  36464. var ar1 = [];
  36465. var ar2 = [];
  36466. for (i = 0; i < pathArray[0].length - offset; i++) {
  36467. ar1.push(pathArray[0][i]);
  36468. ar2.push(pathArray[0][i + offset]);
  36469. }
  36470. pathArray = [ar1, ar2];
  36471. }
  36472. // positions and horizontal distances (u)
  36473. var idc = 0;
  36474. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36475. var path;
  36476. var l;
  36477. minlg = pathArray[0].length;
  36478. var vectlg;
  36479. var dist;
  36480. for (p = 0; p < pathArray.length; p++) {
  36481. uTotalDistance[p] = 0;
  36482. us[p] = [0];
  36483. path = pathArray[p];
  36484. l = path.length;
  36485. minlg = (minlg < l) ? minlg : l;
  36486. j = 0;
  36487. while (j < l) {
  36488. positions.push(path[j].x, path[j].y, path[j].z);
  36489. if (j > 0) {
  36490. vectlg = path[j].subtract(path[j - 1]).length();
  36491. dist = vectlg + uTotalDistance[p];
  36492. us[p].push(dist);
  36493. uTotalDistance[p] = dist;
  36494. }
  36495. j++;
  36496. }
  36497. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36498. j--;
  36499. positions.push(path[0].x, path[0].y, path[0].z);
  36500. vectlg = path[j].subtract(path[0]).length();
  36501. dist = vectlg + uTotalDistance[p];
  36502. us[p].push(dist);
  36503. uTotalDistance[p] = dist;
  36504. }
  36505. lg[p] = l + closePathCorr;
  36506. idx[p] = idc;
  36507. idc += (l + closePathCorr);
  36508. }
  36509. // vertical distances (v)
  36510. var path1;
  36511. var path2;
  36512. var vertex1 = null;
  36513. var vertex2 = null;
  36514. for (i = 0; i < minlg + closePathCorr; i++) {
  36515. vTotalDistance[i] = 0;
  36516. vs[i] = [0];
  36517. for (p = 0; p < pathArray.length - 1; p++) {
  36518. path1 = pathArray[p];
  36519. path2 = pathArray[p + 1];
  36520. if (i === minlg) { // closePath
  36521. vertex1 = path1[0];
  36522. vertex2 = path2[0];
  36523. }
  36524. else {
  36525. vertex1 = path1[i];
  36526. vertex2 = path2[i];
  36527. }
  36528. vectlg = vertex2.subtract(vertex1).length();
  36529. dist = vectlg + vTotalDistance[i];
  36530. vs[i].push(dist);
  36531. vTotalDistance[i] = dist;
  36532. }
  36533. if (closeArray && vertex2 && vertex1) {
  36534. path1 = pathArray[p];
  36535. path2 = pathArray[0];
  36536. if (i === minlg) { // closePath
  36537. vertex2 = path2[0];
  36538. }
  36539. vectlg = vertex2.subtract(vertex1).length();
  36540. dist = vectlg + vTotalDistance[i];
  36541. vTotalDistance[i] = dist;
  36542. }
  36543. }
  36544. // uvs
  36545. var u;
  36546. var v;
  36547. if (customUV) {
  36548. for (p = 0; p < customUV.length; p++) {
  36549. uvs.push(customUV[p].x, customUV[p].y);
  36550. }
  36551. }
  36552. else {
  36553. for (p = 0; p < pathArray.length; p++) {
  36554. for (i = 0; i < minlg + closePathCorr; i++) {
  36555. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36556. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36557. if (invertUV) {
  36558. uvs.push(v, u);
  36559. }
  36560. else {
  36561. uvs.push(u, v);
  36562. }
  36563. }
  36564. }
  36565. }
  36566. // indices
  36567. p = 0; // path index
  36568. var pi = 0; // positions array index
  36569. var l1 = lg[p] - 1; // path1 length
  36570. var l2 = lg[p + 1] - 1; // path2 length
  36571. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36572. var shft = idx[1] - idx[0]; // shift
  36573. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36574. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36575. // 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
  36576. indices.push(pi, pi + shft, pi + 1);
  36577. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36578. pi += 1;
  36579. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36580. p++;
  36581. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36582. shft = idx[0] - idx[p];
  36583. l1 = lg[p] - 1;
  36584. l2 = lg[0] - 1;
  36585. }
  36586. else {
  36587. shft = idx[p + 1] - idx[p];
  36588. l1 = lg[p] - 1;
  36589. l2 = lg[p + 1] - 1;
  36590. }
  36591. pi = idx[p];
  36592. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36593. }
  36594. }
  36595. // normals
  36596. VertexData.ComputeNormals(positions, indices, normals);
  36597. if (closePath) { // update both the first and last vertex normals to their average value
  36598. var indexFirst = 0;
  36599. var indexLast = 0;
  36600. for (p = 0; p < pathArray.length; p++) {
  36601. indexFirst = idx[p] * 3;
  36602. if (p + 1 < pathArray.length) {
  36603. indexLast = (idx[p + 1] - 1) * 3;
  36604. }
  36605. else {
  36606. indexLast = normals.length - 3;
  36607. }
  36608. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36609. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36610. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36611. normals[indexLast] = normals[indexFirst];
  36612. normals[indexLast + 1] = normals[indexFirst + 1];
  36613. normals[indexLast + 2] = normals[indexFirst + 2];
  36614. }
  36615. }
  36616. // sides
  36617. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36618. // Colors
  36619. var colors = null;
  36620. if (customColors) {
  36621. colors = new Float32Array(customColors.length * 4);
  36622. for (var c = 0; c < customColors.length; c++) {
  36623. colors[c * 4] = customColors[c].r;
  36624. colors[c * 4 + 1] = customColors[c].g;
  36625. colors[c * 4 + 2] = customColors[c].b;
  36626. colors[c * 4 + 3] = customColors[c].a;
  36627. }
  36628. }
  36629. // Result
  36630. var vertexData = new VertexData();
  36631. var positions32 = new Float32Array(positions);
  36632. var normals32 = new Float32Array(normals);
  36633. var uvs32 = new Float32Array(uvs);
  36634. vertexData.indices = indices;
  36635. vertexData.positions = positions32;
  36636. vertexData.normals = normals32;
  36637. vertexData.uvs = uvs32;
  36638. if (colors) {
  36639. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36640. }
  36641. if (closePath) {
  36642. vertexData._idx = idx;
  36643. }
  36644. return vertexData;
  36645. };
  36646. /**
  36647. * Creates the VertexData for a box
  36648. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36649. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36650. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36651. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36652. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36653. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36654. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36655. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36656. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36657. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36658. * @returns the VertexData of the box
  36659. */
  36660. VertexData.CreateBox = function (options) {
  36661. var normalsSource = [
  36662. new BABYLON.Vector3(0, 0, 1),
  36663. new BABYLON.Vector3(0, 0, -1),
  36664. new BABYLON.Vector3(1, 0, 0),
  36665. new BABYLON.Vector3(-1, 0, 0),
  36666. new BABYLON.Vector3(0, 1, 0),
  36667. new BABYLON.Vector3(0, -1, 0)
  36668. ];
  36669. var indices = [];
  36670. var positions = [];
  36671. var normals = [];
  36672. var uvs = [];
  36673. var width = options.width || options.size || 1;
  36674. var height = options.height || options.size || 1;
  36675. var depth = options.depth || options.size || 1;
  36676. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36677. var faceUV = options.faceUV || new Array(6);
  36678. var faceColors = options.faceColors;
  36679. var colors = [];
  36680. // default face colors and UV if undefined
  36681. for (var f = 0; f < 6; f++) {
  36682. if (faceUV[f] === undefined) {
  36683. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36684. }
  36685. if (faceColors && faceColors[f] === undefined) {
  36686. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36687. }
  36688. }
  36689. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36690. // Create each face in turn.
  36691. for (var index = 0; index < normalsSource.length; index++) {
  36692. var normal = normalsSource[index];
  36693. // Get two vectors perpendicular to the face normal and to each other.
  36694. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36695. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36696. // Six indices (two triangles) per face.
  36697. var verticesLength = positions.length / 3;
  36698. indices.push(verticesLength);
  36699. indices.push(verticesLength + 1);
  36700. indices.push(verticesLength + 2);
  36701. indices.push(verticesLength);
  36702. indices.push(verticesLength + 2);
  36703. indices.push(verticesLength + 3);
  36704. // Four vertices per face.
  36705. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36706. positions.push(vertex.x, vertex.y, vertex.z);
  36707. normals.push(normal.x, normal.y, normal.z);
  36708. uvs.push(faceUV[index].z, faceUV[index].w);
  36709. if (faceColors) {
  36710. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36711. }
  36712. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36713. positions.push(vertex.x, vertex.y, vertex.z);
  36714. normals.push(normal.x, normal.y, normal.z);
  36715. uvs.push(faceUV[index].x, faceUV[index].w);
  36716. if (faceColors) {
  36717. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36718. }
  36719. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36720. positions.push(vertex.x, vertex.y, vertex.z);
  36721. normals.push(normal.x, normal.y, normal.z);
  36722. uvs.push(faceUV[index].x, faceUV[index].y);
  36723. if (faceColors) {
  36724. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36725. }
  36726. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36727. positions.push(vertex.x, vertex.y, vertex.z);
  36728. normals.push(normal.x, normal.y, normal.z);
  36729. uvs.push(faceUV[index].z, faceUV[index].y);
  36730. if (faceColors) {
  36731. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36732. }
  36733. }
  36734. // sides
  36735. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36736. // Result
  36737. var vertexData = new VertexData();
  36738. vertexData.indices = indices;
  36739. vertexData.positions = positions;
  36740. vertexData.normals = normals;
  36741. vertexData.uvs = uvs;
  36742. if (faceColors) {
  36743. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36744. vertexData.colors = totalColors;
  36745. }
  36746. return vertexData;
  36747. };
  36748. /**
  36749. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36750. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36751. * * segments sets the number of horizontal strips optional, default 32
  36752. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36753. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36754. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36755. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36756. * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
  36757. * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
  36758. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36759. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36760. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36761. * @returns the VertexData of the ellipsoid
  36762. */
  36763. VertexData.CreateSphere = function (options) {
  36764. var segments = options.segments || 32;
  36765. var diameterX = options.diameterX || options.diameter || 1;
  36766. var diameterY = options.diameterY || options.diameter || 1;
  36767. var diameterZ = options.diameterZ || options.diameter || 1;
  36768. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36769. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36770. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36771. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36772. var totalZRotationSteps = 2 + segments;
  36773. var totalYRotationSteps = 2 * totalZRotationSteps;
  36774. var indices = [];
  36775. var positions = [];
  36776. var normals = [];
  36777. var uvs = [];
  36778. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36779. var normalizedZ = zRotationStep / totalZRotationSteps;
  36780. var angleZ = normalizedZ * Math.PI * slice;
  36781. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36782. var normalizedY = yRotationStep / totalYRotationSteps;
  36783. var angleY = normalizedY * Math.PI * 2 * arc;
  36784. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36785. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36786. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36787. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36788. var vertex = complete.multiply(radius);
  36789. var normal = complete.divide(radius).normalize();
  36790. positions.push(vertex.x, vertex.y, vertex.z);
  36791. normals.push(normal.x, normal.y, normal.z);
  36792. uvs.push(normalizedY, normalizedZ);
  36793. }
  36794. if (zRotationStep > 0) {
  36795. var verticesCount = positions.length / 3;
  36796. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36797. indices.push((firstIndex));
  36798. indices.push((firstIndex + 1));
  36799. indices.push(firstIndex + totalYRotationSteps + 1);
  36800. indices.push((firstIndex + totalYRotationSteps + 1));
  36801. indices.push((firstIndex + 1));
  36802. indices.push((firstIndex + totalYRotationSteps + 2));
  36803. }
  36804. }
  36805. }
  36806. // Sides
  36807. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36808. // Result
  36809. var vertexData = new VertexData();
  36810. vertexData.indices = indices;
  36811. vertexData.positions = positions;
  36812. vertexData.normals = normals;
  36813. vertexData.uvs = uvs;
  36814. return vertexData;
  36815. };
  36816. /**
  36817. * Creates the VertexData for a cylinder, cone or prism
  36818. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36819. * * height sets the height (y direction) of the cylinder, optional, default 2
  36820. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36821. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36822. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36823. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36824. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36825. * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
  36826. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36827. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36828. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36829. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36830. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36831. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36832. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36833. * @returns the VertexData of the cylinder, cone or prism
  36834. */
  36835. VertexData.CreateCylinder = function (options) {
  36836. var height = options.height || 2;
  36837. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36838. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36839. var tessellation = options.tessellation || 24;
  36840. var subdivisions = options.subdivisions || 1;
  36841. var hasRings = options.hasRings ? true : false;
  36842. var enclose = options.enclose ? true : false;
  36843. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36844. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36845. var faceUV = options.faceUV || new Array(3);
  36846. var faceColors = options.faceColors;
  36847. // default face colors and UV if undefined
  36848. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36849. var ringNb = (hasRings) ? subdivisions : 1;
  36850. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36851. var f;
  36852. for (f = 0; f < surfaceNb; f++) {
  36853. if (faceColors && faceColors[f] === undefined) {
  36854. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36855. }
  36856. }
  36857. for (f = 0; f < surfaceNb; f++) {
  36858. if (faceUV && faceUV[f] === undefined) {
  36859. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36860. }
  36861. }
  36862. var indices = new Array();
  36863. var positions = new Array();
  36864. var normals = new Array();
  36865. var uvs = new Array();
  36866. var colors = new Array();
  36867. var angle_step = Math.PI * 2 * arc / tessellation;
  36868. var angle;
  36869. var h;
  36870. var radius;
  36871. var tan = (diameterBottom - diameterTop) / 2 / height;
  36872. var ringVertex = BABYLON.Vector3.Zero();
  36873. var ringNormal = BABYLON.Vector3.Zero();
  36874. var ringFirstVertex = BABYLON.Vector3.Zero();
  36875. var ringFirstNormal = BABYLON.Vector3.Zero();
  36876. var quadNormal = BABYLON.Vector3.Zero();
  36877. var Y = BABYLON.Axis.Y;
  36878. // positions, normals, uvs
  36879. var i;
  36880. var j;
  36881. var r;
  36882. var ringIdx = 1;
  36883. var s = 1; // surface index
  36884. var cs = 0;
  36885. var v = 0;
  36886. for (i = 0; i <= subdivisions; i++) {
  36887. h = i / subdivisions;
  36888. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36889. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36890. for (r = 0; r < ringIdx; r++) {
  36891. if (hasRings) {
  36892. s += r;
  36893. }
  36894. if (enclose) {
  36895. s += 2 * r;
  36896. }
  36897. for (j = 0; j <= tessellation; j++) {
  36898. angle = j * angle_step;
  36899. // position
  36900. ringVertex.x = Math.cos(-angle) * radius;
  36901. ringVertex.y = -height / 2 + h * height;
  36902. ringVertex.z = Math.sin(-angle) * radius;
  36903. // normal
  36904. if (diameterTop === 0 && i === subdivisions) {
  36905. // if no top cap, reuse former normals
  36906. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36907. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36908. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36909. }
  36910. else {
  36911. ringNormal.x = ringVertex.x;
  36912. ringNormal.z = ringVertex.z;
  36913. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36914. ringNormal.normalize();
  36915. }
  36916. // keep first ring vertex values for enclose
  36917. if (j === 0) {
  36918. ringFirstVertex.copyFrom(ringVertex);
  36919. ringFirstNormal.copyFrom(ringNormal);
  36920. }
  36921. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36922. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36923. if (hasRings) {
  36924. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36925. }
  36926. else {
  36927. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36928. }
  36929. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36930. if (faceColors) {
  36931. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36932. }
  36933. }
  36934. // if enclose, add four vertices and their dedicated normals
  36935. if (arc !== 1 && enclose) {
  36936. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36937. positions.push(0, ringVertex.y, 0);
  36938. positions.push(0, ringVertex.y, 0);
  36939. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36940. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36941. quadNormal.normalize();
  36942. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36943. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36944. quadNormal.normalize();
  36945. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36946. if (hasRings) {
  36947. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36948. }
  36949. else {
  36950. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36951. }
  36952. uvs.push(faceUV[s + 1].x, v);
  36953. uvs.push(faceUV[s + 1].z, v);
  36954. if (hasRings) {
  36955. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36956. }
  36957. else {
  36958. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36959. }
  36960. uvs.push(faceUV[s + 2].x, v);
  36961. uvs.push(faceUV[s + 2].z, v);
  36962. if (faceColors) {
  36963. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36964. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36965. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36966. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36967. }
  36968. }
  36969. if (cs !== s) {
  36970. cs = s;
  36971. }
  36972. }
  36973. }
  36974. // indices
  36975. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36976. var s;
  36977. i = 0;
  36978. for (s = 0; s < subdivisions; s++) {
  36979. var i0 = 0;
  36980. var i1 = 0;
  36981. var i2 = 0;
  36982. var i3 = 0;
  36983. for (j = 0; j < tessellation; j++) {
  36984. i0 = i * (e + 1) + j;
  36985. i1 = (i + 1) * (e + 1) + j;
  36986. i2 = i * (e + 1) + (j + 1);
  36987. i3 = (i + 1) * (e + 1) + (j + 1);
  36988. indices.push(i0, i1, i2);
  36989. indices.push(i3, i2, i1);
  36990. }
  36991. if (arc !== 1 && enclose) { // if enclose, add two quads
  36992. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36993. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36994. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36995. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36996. }
  36997. i = (hasRings) ? (i + 2) : (i + 1);
  36998. }
  36999. // Caps
  37000. var createCylinderCap = function (isTop) {
  37001. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37002. if (radius === 0) {
  37003. return;
  37004. }
  37005. // Cap positions, normals & uvs
  37006. var angle;
  37007. var circleVector;
  37008. var i;
  37009. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37010. var c = null;
  37011. if (faceColors) {
  37012. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37013. }
  37014. // cap center
  37015. var vbase = positions.length / 3;
  37016. var offset = isTop ? height / 2 : -height / 2;
  37017. var center = new BABYLON.Vector3(0, offset, 0);
  37018. positions.push(center.x, center.y, center.z);
  37019. normals.push(0, isTop ? 1 : -1, 0);
  37020. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37021. if (c) {
  37022. colors.push(c.r, c.g, c.b, c.a);
  37023. }
  37024. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37025. for (i = 0; i <= tessellation; i++) {
  37026. angle = Math.PI * 2 * i * arc / tessellation;
  37027. var cos = Math.cos(-angle);
  37028. var sin = Math.sin(-angle);
  37029. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37030. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37031. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37032. normals.push(0, isTop ? 1 : -1, 0);
  37033. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37034. if (c) {
  37035. colors.push(c.r, c.g, c.b, c.a);
  37036. }
  37037. }
  37038. // Cap indices
  37039. for (i = 0; i < tessellation; i++) {
  37040. if (!isTop) {
  37041. indices.push(vbase);
  37042. indices.push(vbase + (i + 1));
  37043. indices.push(vbase + (i + 2));
  37044. }
  37045. else {
  37046. indices.push(vbase);
  37047. indices.push(vbase + (i + 2));
  37048. indices.push(vbase + (i + 1));
  37049. }
  37050. }
  37051. };
  37052. // add caps to geometry
  37053. createCylinderCap(false);
  37054. createCylinderCap(true);
  37055. // Sides
  37056. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37057. var vertexData = new VertexData();
  37058. vertexData.indices = indices;
  37059. vertexData.positions = positions;
  37060. vertexData.normals = normals;
  37061. vertexData.uvs = uvs;
  37062. if (faceColors) {
  37063. vertexData.colors = colors;
  37064. }
  37065. return vertexData;
  37066. };
  37067. /**
  37068. * Creates the VertexData for a torus
  37069. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37070. * * diameter the diameter of the torus, optional default 1
  37071. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37072. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37073. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37074. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37075. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37076. * @returns the VertexData of the torus
  37077. */
  37078. VertexData.CreateTorus = function (options) {
  37079. var indices = [];
  37080. var positions = [];
  37081. var normals = [];
  37082. var uvs = [];
  37083. var diameter = options.diameter || 1;
  37084. var thickness = options.thickness || 0.5;
  37085. var tessellation = options.tessellation || 16;
  37086. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37087. var stride = tessellation + 1;
  37088. for (var i = 0; i <= tessellation; i++) {
  37089. var u = i / tessellation;
  37090. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37091. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37092. for (var j = 0; j <= tessellation; j++) {
  37093. var v = 1 - j / tessellation;
  37094. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37095. var dx = Math.cos(innerAngle);
  37096. var dy = Math.sin(innerAngle);
  37097. // Create a vertex.
  37098. var normal = new BABYLON.Vector3(dx, dy, 0);
  37099. var position = normal.scale(thickness / 2);
  37100. var textureCoordinate = new BABYLON.Vector2(u, v);
  37101. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37102. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37103. positions.push(position.x, position.y, position.z);
  37104. normals.push(normal.x, normal.y, normal.z);
  37105. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37106. // And create indices for two triangles.
  37107. var nextI = (i + 1) % stride;
  37108. var nextJ = (j + 1) % stride;
  37109. indices.push(i * stride + j);
  37110. indices.push(i * stride + nextJ);
  37111. indices.push(nextI * stride + j);
  37112. indices.push(i * stride + nextJ);
  37113. indices.push(nextI * stride + nextJ);
  37114. indices.push(nextI * stride + j);
  37115. }
  37116. }
  37117. // Sides
  37118. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37119. // Result
  37120. var vertexData = new VertexData();
  37121. vertexData.indices = indices;
  37122. vertexData.positions = positions;
  37123. vertexData.normals = normals;
  37124. vertexData.uvs = uvs;
  37125. return vertexData;
  37126. };
  37127. /**
  37128. * Creates the VertexData of the LineSystem
  37129. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37130. * - lines an array of lines, each line being an array of successive Vector3
  37131. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37132. * @returns the VertexData of the LineSystem
  37133. */
  37134. VertexData.CreateLineSystem = function (options) {
  37135. var indices = [];
  37136. var positions = [];
  37137. var lines = options.lines;
  37138. var colors = options.colors;
  37139. var vertexColors = [];
  37140. var idx = 0;
  37141. for (var l = 0; l < lines.length; l++) {
  37142. var points = lines[l];
  37143. for (var index = 0; index < points.length; index++) {
  37144. positions.push(points[index].x, points[index].y, points[index].z);
  37145. if (colors) {
  37146. var color = colors[l];
  37147. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37148. }
  37149. if (index > 0) {
  37150. indices.push(idx - 1);
  37151. indices.push(idx);
  37152. }
  37153. idx++;
  37154. }
  37155. }
  37156. var vertexData = new VertexData();
  37157. vertexData.indices = indices;
  37158. vertexData.positions = positions;
  37159. if (colors) {
  37160. vertexData.colors = vertexColors;
  37161. }
  37162. return vertexData;
  37163. };
  37164. /**
  37165. * Create the VertexData for a DashedLines
  37166. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37167. * - points an array successive Vector3
  37168. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37169. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37170. * - dashNb the intended total number of dashes, optional, default 200
  37171. * @returns the VertexData for the DashedLines
  37172. */
  37173. VertexData.CreateDashedLines = function (options) {
  37174. var dashSize = options.dashSize || 3;
  37175. var gapSize = options.gapSize || 1;
  37176. var dashNb = options.dashNb || 200;
  37177. var points = options.points;
  37178. var positions = new Array();
  37179. var indices = new Array();
  37180. var curvect = BABYLON.Vector3.Zero();
  37181. var lg = 0;
  37182. var nb = 0;
  37183. var shft = 0;
  37184. var dashshft = 0;
  37185. var curshft = 0;
  37186. var idx = 0;
  37187. var i = 0;
  37188. for (i = 0; i < points.length - 1; i++) {
  37189. points[i + 1].subtractToRef(points[i], curvect);
  37190. lg += curvect.length();
  37191. }
  37192. shft = lg / dashNb;
  37193. dashshft = dashSize * shft / (dashSize + gapSize);
  37194. for (i = 0; i < points.length - 1; i++) {
  37195. points[i + 1].subtractToRef(points[i], curvect);
  37196. nb = Math.floor(curvect.length() / shft);
  37197. curvect.normalize();
  37198. for (var j = 0; j < nb; j++) {
  37199. curshft = shft * j;
  37200. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37201. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37202. indices.push(idx, idx + 1);
  37203. idx += 2;
  37204. }
  37205. }
  37206. // Result
  37207. var vertexData = new VertexData();
  37208. vertexData.positions = positions;
  37209. vertexData.indices = indices;
  37210. return vertexData;
  37211. };
  37212. /**
  37213. * Creates the VertexData for a Ground
  37214. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37215. * - width the width (x direction) of the ground, optional, default 1
  37216. * - height the height (z direction) of the ground, optional, default 1
  37217. * - subdivisions the number of subdivisions per side, optional, default 1
  37218. * @returns the VertexData of the Ground
  37219. */
  37220. VertexData.CreateGround = function (options) {
  37221. var indices = [];
  37222. var positions = [];
  37223. var normals = [];
  37224. var uvs = [];
  37225. var row, col;
  37226. var width = options.width || 1;
  37227. var height = options.height || 1;
  37228. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37229. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37230. for (row = 0; row <= subdivisionsY; row++) {
  37231. for (col = 0; col <= subdivisionsX; col++) {
  37232. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37233. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37234. positions.push(position.x, position.y, position.z);
  37235. normals.push(normal.x, normal.y, normal.z);
  37236. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37237. }
  37238. }
  37239. for (row = 0; row < subdivisionsY; row++) {
  37240. for (col = 0; col < subdivisionsX; col++) {
  37241. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37242. indices.push(col + 1 + row * (subdivisionsX + 1));
  37243. indices.push(col + row * (subdivisionsX + 1));
  37244. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37245. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37246. indices.push(col + row * (subdivisionsX + 1));
  37247. }
  37248. }
  37249. // Result
  37250. var vertexData = new VertexData();
  37251. vertexData.indices = indices;
  37252. vertexData.positions = positions;
  37253. vertexData.normals = normals;
  37254. vertexData.uvs = uvs;
  37255. return vertexData;
  37256. };
  37257. /**
  37258. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37259. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37260. * * xmin the ground minimum X coordinate, optional, default -1
  37261. * * zmin the ground minimum Z coordinate, optional, default -1
  37262. * * xmax the ground maximum X coordinate, optional, default 1
  37263. * * zmax the ground maximum Z coordinate, optional, default 1
  37264. * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
  37265. * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
  37266. * @returns the VertexData of the TiledGround
  37267. */
  37268. VertexData.CreateTiledGround = function (options) {
  37269. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37270. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37271. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37272. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37273. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37274. var precision = options.precision || { w: 1, h: 1 };
  37275. var indices = new Array();
  37276. var positions = new Array();
  37277. var normals = new Array();
  37278. var uvs = new Array();
  37279. var row, col, tileRow, tileCol;
  37280. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37281. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37282. precision.w = (precision.w < 1) ? 1 : precision.w;
  37283. precision.h = (precision.h < 1) ? 1 : precision.h;
  37284. var tileSize = {
  37285. 'w': (xmax - xmin) / subdivisions.w,
  37286. 'h': (zmax - zmin) / subdivisions.h
  37287. };
  37288. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37289. // Indices
  37290. var base = positions.length / 3;
  37291. var rowLength = precision.w + 1;
  37292. for (row = 0; row < precision.h; row++) {
  37293. for (col = 0; col < precision.w; col++) {
  37294. var square = [
  37295. base + col + row * rowLength,
  37296. base + (col + 1) + row * rowLength,
  37297. base + (col + 1) + (row + 1) * rowLength,
  37298. base + col + (row + 1) * rowLength
  37299. ];
  37300. indices.push(square[1]);
  37301. indices.push(square[2]);
  37302. indices.push(square[3]);
  37303. indices.push(square[0]);
  37304. indices.push(square[1]);
  37305. indices.push(square[3]);
  37306. }
  37307. }
  37308. // Position, normals and uvs
  37309. var position = BABYLON.Vector3.Zero();
  37310. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37311. for (row = 0; row <= precision.h; row++) {
  37312. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37313. for (col = 0; col <= precision.w; col++) {
  37314. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37315. position.y = 0;
  37316. positions.push(position.x, position.y, position.z);
  37317. normals.push(normal.x, normal.y, normal.z);
  37318. uvs.push(col / precision.w, row / precision.h);
  37319. }
  37320. }
  37321. }
  37322. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37323. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37324. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37325. }
  37326. }
  37327. // Result
  37328. var vertexData = new VertexData();
  37329. vertexData.indices = indices;
  37330. vertexData.positions = positions;
  37331. vertexData.normals = normals;
  37332. vertexData.uvs = uvs;
  37333. return vertexData;
  37334. };
  37335. /**
  37336. * Creates the VertexData of the Ground designed from a heightmap
  37337. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37338. * * width the width (x direction) of the ground
  37339. * * height the height (z direction) of the ground
  37340. * * subdivisions the number of subdivisions per side
  37341. * * minHeight the minimum altitude on the ground, optional, default 0
  37342. * * maxHeight the maximum altitude on the ground, optional default 1
  37343. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37344. * * buffer the array holding the image color data
  37345. * * bufferWidth the width of image
  37346. * * bufferHeight the height of image
  37347. * @returns the VertexData of the Ground designed from a heightmap
  37348. */
  37349. VertexData.CreateGroundFromHeightMap = function (options) {
  37350. var indices = [];
  37351. var positions = [];
  37352. var normals = [];
  37353. var uvs = [];
  37354. var row, col;
  37355. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37356. // Vertices
  37357. for (row = 0; row <= options.subdivisions; row++) {
  37358. for (col = 0; col <= options.subdivisions; col++) {
  37359. 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));
  37360. // Compute height
  37361. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37362. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37363. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37364. var r = options.buffer[pos] / 255.0;
  37365. var g = options.buffer[pos + 1] / 255.0;
  37366. var b = options.buffer[pos + 2] / 255.0;
  37367. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37368. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37369. // Add vertex
  37370. positions.push(position.x, position.y, position.z);
  37371. normals.push(0, 0, 0);
  37372. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37373. }
  37374. }
  37375. // Indices
  37376. for (row = 0; row < options.subdivisions; row++) {
  37377. for (col = 0; col < options.subdivisions; col++) {
  37378. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37379. indices.push(col + 1 + row * (options.subdivisions + 1));
  37380. indices.push(col + row * (options.subdivisions + 1));
  37381. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37382. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37383. indices.push(col + row * (options.subdivisions + 1));
  37384. }
  37385. }
  37386. // Normals
  37387. VertexData.ComputeNormals(positions, indices, normals);
  37388. // Result
  37389. var vertexData = new VertexData();
  37390. vertexData.indices = indices;
  37391. vertexData.positions = positions;
  37392. vertexData.normals = normals;
  37393. vertexData.uvs = uvs;
  37394. return vertexData;
  37395. };
  37396. /**
  37397. * Creates the VertexData for a Plane
  37398. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37399. * * size sets the width and height of the plane to the value of size, optional default 1
  37400. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37401. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37402. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37403. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37404. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37405. * @returns the VertexData of the box
  37406. */
  37407. VertexData.CreatePlane = function (options) {
  37408. var indices = [];
  37409. var positions = [];
  37410. var normals = [];
  37411. var uvs = [];
  37412. var width = options.width || options.size || 1;
  37413. var height = options.height || options.size || 1;
  37414. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37415. // Vertices
  37416. var halfWidth = width / 2.0;
  37417. var halfHeight = height / 2.0;
  37418. positions.push(-halfWidth, -halfHeight, 0);
  37419. normals.push(0, 0, -1.0);
  37420. uvs.push(0.0, 0.0);
  37421. positions.push(halfWidth, -halfHeight, 0);
  37422. normals.push(0, 0, -1.0);
  37423. uvs.push(1.0, 0.0);
  37424. positions.push(halfWidth, halfHeight, 0);
  37425. normals.push(0, 0, -1.0);
  37426. uvs.push(1.0, 1.0);
  37427. positions.push(-halfWidth, halfHeight, 0);
  37428. normals.push(0, 0, -1.0);
  37429. uvs.push(0.0, 1.0);
  37430. // Indices
  37431. indices.push(0);
  37432. indices.push(1);
  37433. indices.push(2);
  37434. indices.push(0);
  37435. indices.push(2);
  37436. indices.push(3);
  37437. // Sides
  37438. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37439. // Result
  37440. var vertexData = new VertexData();
  37441. vertexData.indices = indices;
  37442. vertexData.positions = positions;
  37443. vertexData.normals = normals;
  37444. vertexData.uvs = uvs;
  37445. return vertexData;
  37446. };
  37447. /**
  37448. * Creates the VertexData of the Disc or regular Polygon
  37449. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37450. * * radius the radius of the disc, optional default 0.5
  37451. * * tessellation the number of polygon sides, optional, default 64
  37452. * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
  37453. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37454. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37455. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37456. * @returns the VertexData of the box
  37457. */
  37458. VertexData.CreateDisc = function (options) {
  37459. var positions = new Array();
  37460. var indices = new Array();
  37461. var normals = new Array();
  37462. var uvs = new Array();
  37463. var radius = options.radius || 0.5;
  37464. var tessellation = options.tessellation || 64;
  37465. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37466. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37467. // positions and uvs
  37468. positions.push(0, 0, 0); // disc center first
  37469. uvs.push(0.5, 0.5);
  37470. var theta = Math.PI * 2 * arc;
  37471. var step = theta / tessellation;
  37472. for (var a = 0; a < theta; a += step) {
  37473. var x = Math.cos(a);
  37474. var y = Math.sin(a);
  37475. var u = (x + 1) / 2;
  37476. var v = (1 - y) / 2;
  37477. positions.push(radius * x, radius * y, 0);
  37478. uvs.push(u, v);
  37479. }
  37480. if (arc === 1) {
  37481. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37482. uvs.push(uvs[2], uvs[3]);
  37483. }
  37484. //indices
  37485. var vertexNb = positions.length / 3;
  37486. for (var i = 1; i < vertexNb - 1; i++) {
  37487. indices.push(i + 1, 0, i);
  37488. }
  37489. // result
  37490. VertexData.ComputeNormals(positions, indices, normals);
  37491. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37492. var vertexData = new VertexData();
  37493. vertexData.indices = indices;
  37494. vertexData.positions = positions;
  37495. vertexData.normals = normals;
  37496. vertexData.uvs = uvs;
  37497. return vertexData;
  37498. };
  37499. /**
  37500. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37501. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37502. * @param polygon a mesh built from polygonTriangulation.build()
  37503. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37504. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37505. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37506. * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37507. * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37508. * @returns the VertexData of the Polygon
  37509. */
  37510. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37511. var faceUV = fUV || new Array(3);
  37512. var faceColors = fColors;
  37513. var colors = [];
  37514. // default face colors and UV if undefined
  37515. for (var f = 0; f < 3; f++) {
  37516. if (faceUV[f] === undefined) {
  37517. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37518. }
  37519. if (faceColors && faceColors[f] === undefined) {
  37520. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37521. }
  37522. }
  37523. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37524. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37525. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37526. var indices = polygon.getIndices();
  37527. // set face colours and textures
  37528. var idx = 0;
  37529. var face = 0;
  37530. for (var index = 0; index < normals.length; index += 3) {
  37531. //Edge Face no. 1
  37532. if (Math.abs(normals[index + 1]) < 0.001) {
  37533. face = 1;
  37534. }
  37535. //Top Face no. 0
  37536. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37537. face = 0;
  37538. }
  37539. //Bottom Face no. 2
  37540. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37541. face = 2;
  37542. }
  37543. idx = index / 3;
  37544. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37545. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37546. if (faceColors) {
  37547. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37548. }
  37549. }
  37550. // sides
  37551. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37552. // Result
  37553. var vertexData = new VertexData();
  37554. vertexData.indices = indices;
  37555. vertexData.positions = positions;
  37556. vertexData.normals = normals;
  37557. vertexData.uvs = uvs;
  37558. if (faceColors) {
  37559. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37560. vertexData.colors = totalColors;
  37561. }
  37562. return vertexData;
  37563. };
  37564. /**
  37565. * Creates the VertexData of the IcoSphere
  37566. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37567. * * radius the radius of the IcoSphere, optional default 1
  37568. * * radiusX allows stretching in the x direction, optional, default radius
  37569. * * radiusY allows stretching in the y direction, optional, default radius
  37570. * * radiusZ allows stretching in the z direction, optional, default radius
  37571. * * flat when true creates a flat shaded mesh, optional, default true
  37572. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37573. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37574. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37575. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37576. * @returns the VertexData of the IcoSphere
  37577. */
  37578. VertexData.CreateIcoSphere = function (options) {
  37579. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37580. var radius = options.radius || 1;
  37581. var flat = (options.flat === undefined) ? true : options.flat;
  37582. var subdivisions = options.subdivisions || 4;
  37583. var radiusX = options.radiusX || radius;
  37584. var radiusY = options.radiusY || radius;
  37585. var radiusZ = options.radiusZ || radius;
  37586. var t = (1 + Math.sqrt(5)) / 2;
  37587. // 12 vertex x,y,z
  37588. var ico_vertices = [
  37589. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37590. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37591. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37592. ];
  37593. // index of 3 vertex makes a face of icopshere
  37594. var ico_indices = [
  37595. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37596. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37597. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37598. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37599. ];
  37600. // vertex for uv have aliased position, not for UV
  37601. var vertices_unalias_id = [
  37602. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37603. // vertex alias
  37604. 0,
  37605. 2,
  37606. 3,
  37607. 3,
  37608. 3,
  37609. 4,
  37610. 7,
  37611. 8,
  37612. 9,
  37613. 9,
  37614. 10,
  37615. 11 // 23: B + 12
  37616. ];
  37617. // uv as integer step (not pixels !)
  37618. var ico_vertexuv = [
  37619. 5, 1, 3, 1, 6, 4, 0, 0,
  37620. 5, 3, 4, 2, 2, 2, 4, 0,
  37621. 2, 0, 1, 1, 6, 0, 6, 2,
  37622. // vertex alias (for same vertex on different faces)
  37623. 0, 4,
  37624. 3, 3,
  37625. 4, 4,
  37626. 3, 1,
  37627. 4, 2,
  37628. 4, 4,
  37629. 0, 2,
  37630. 1, 1,
  37631. 2, 2,
  37632. 3, 3,
  37633. 1, 3,
  37634. 2, 4 // 23: B + 12
  37635. ];
  37636. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37637. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37638. // First island of uv mapping
  37639. // v = 4h 3+ 2
  37640. // v = 3h 9+ 4
  37641. // v = 2h 9+ 5 B
  37642. // v = 1h 9 1 0
  37643. // v = 0h 3 8 7 A
  37644. // u = 0 1 2 3 4 5 6 *a
  37645. // Second island of uv mapping
  37646. // v = 4h 0+ B+ 4+
  37647. // v = 3h A+ 2+
  37648. // v = 2h 7+ 6 3+
  37649. // v = 1h 8+ 3+
  37650. // v = 0h
  37651. // u = 0 1 2 3 4 5 6 *a
  37652. // Face layout on texture UV mapping
  37653. // ============
  37654. // \ 4 /\ 16 / ======
  37655. // \ / \ / /\ 11 /
  37656. // \/ 7 \/ / \ /
  37657. // ======= / 10 \/
  37658. // /\ 17 /\ =======
  37659. // / \ / \ \ 15 /\
  37660. // / 8 \/ 12 \ \ / \
  37661. // ============ \/ 6 \
  37662. // \ 18 /\ ============
  37663. // \ / \ \ 5 /\ 0 /
  37664. // \/ 13 \ \ / \ /
  37665. // ======= \/ 1 \/
  37666. // =============
  37667. // /\ 19 /\ 2 /\
  37668. // / \ / \ / \
  37669. // / 14 \/ 9 \/ 3 \
  37670. // ===================
  37671. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37672. var ustep = 138 / 1024;
  37673. var vstep = 239 / 1024;
  37674. var uoffset = 60 / 1024;
  37675. var voffset = 26 / 1024;
  37676. // Second island should have margin, not to touch the first island
  37677. // avoid any borderline artefact in pixel rounding
  37678. var island_u_offset = -40 / 1024;
  37679. var island_v_offset = +20 / 1024;
  37680. // face is either island 0 or 1 :
  37681. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37682. var island = [
  37683. 0, 0, 0, 0, 1,
  37684. 0, 0, 1, 1, 0,
  37685. 0, 0, 1, 1, 0,
  37686. 0, 1, 1, 1, 0 // 15 - 19
  37687. ];
  37688. var indices = new Array();
  37689. var positions = new Array();
  37690. var normals = new Array();
  37691. var uvs = new Array();
  37692. var current_indice = 0;
  37693. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37694. var face_vertex_pos = new Array(3);
  37695. var face_vertex_uv = new Array(3);
  37696. var v012;
  37697. for (v012 = 0; v012 < 3; v012++) {
  37698. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37699. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37700. }
  37701. // create all with normals
  37702. for (var face = 0; face < 20; face++) {
  37703. // 3 vertex per face
  37704. for (v012 = 0; v012 < 3; v012++) {
  37705. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37706. var v_id = ico_indices[3 * face + v012];
  37707. // vertex have 3D position (x,y,z)
  37708. 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]);
  37709. // Normalize to get normal, then scale to radius
  37710. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37711. // uv Coordinates from vertex ID
  37712. 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);
  37713. }
  37714. // Subdivide the face (interpolate pos, norm, uv)
  37715. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37716. // - norm is linear interpolation of vertex corner normal
  37717. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37718. // - uv is linear interpolation
  37719. //
  37720. // Topology is as below for sub-divide by 2
  37721. // vertex shown as v0,v1,v2
  37722. // interp index is i1 to progress in range [v0,v1[
  37723. // interp index is i2 to progress in range [v0,v2[
  37724. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37725. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37726. //
  37727. //
  37728. // i2 v2
  37729. // ^ ^
  37730. // / / \
  37731. // / / \
  37732. // / / \
  37733. // / / (0,1) \
  37734. // / #---------\
  37735. // / / \ (0,0)'/ \
  37736. // / / \ / \
  37737. // / / \ / \
  37738. // / / (0,0) \ / (1,0) \
  37739. // / #---------#---------\
  37740. // v0 v1
  37741. //
  37742. // --------------------> i1
  37743. //
  37744. // interp of (i1,i2):
  37745. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37746. // along i1 : lerp(x0,x1, i1/(S-i2))
  37747. //
  37748. // centroid of triangle is needed to get help normal computation
  37749. // (c1,c2) are used for centroid location
  37750. var interp_vertex = function (i1, i2, c1, c2) {
  37751. // vertex is interpolated from
  37752. // - face_vertex_pos[0..2]
  37753. // - face_vertex_uv[0..2]
  37754. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37755. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37756. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37757. pos_interp.normalize();
  37758. var vertex_normal;
  37759. if (flat) {
  37760. // in flat mode, recalculate normal as face centroid normal
  37761. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37762. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37763. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37764. }
  37765. else {
  37766. // in smooth mode, recalculate normal from each single vertex position
  37767. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37768. }
  37769. // Vertex normal need correction due to X,Y,Z radius scaling
  37770. vertex_normal.x /= radiusX;
  37771. vertex_normal.y /= radiusY;
  37772. vertex_normal.z /= radiusZ;
  37773. vertex_normal.normalize();
  37774. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37775. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37776. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37777. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37778. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37779. uvs.push(uv_interp.x, uv_interp.y);
  37780. // push each vertex has member of a face
  37781. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37782. indices.push(current_indice);
  37783. current_indice++;
  37784. };
  37785. for (var i2 = 0; i2 < subdivisions; i2++) {
  37786. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37787. // face : (i1,i2) for /\ :
  37788. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37789. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37790. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37791. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37792. if (i1 + i2 + 1 < subdivisions) {
  37793. // face : (i1,i2)' for \/ :
  37794. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37795. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37796. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37797. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37798. }
  37799. }
  37800. }
  37801. }
  37802. // Sides
  37803. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37804. // Result
  37805. var vertexData = new VertexData();
  37806. vertexData.indices = indices;
  37807. vertexData.positions = positions;
  37808. vertexData.normals = normals;
  37809. vertexData.uvs = uvs;
  37810. return vertexData;
  37811. };
  37812. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37813. /**
  37814. * Creates the VertexData for a Polyhedron
  37815. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37816. * * type provided types are:
  37817. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37818. * * 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)
  37819. * * size the size of the IcoSphere, optional default 1
  37820. * * sizeX allows stretching in the x direction, optional, default size
  37821. * * sizeY allows stretching in the y direction, optional, default size
  37822. * * sizeZ allows stretching in the z direction, optional, default size
  37823. * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
  37824. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37825. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37826. * * flat when true creates a flat shaded mesh, optional, default true
  37827. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37828. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37829. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37830. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37831. * @returns the VertexData of the Polyhedron
  37832. */
  37833. VertexData.CreatePolyhedron = function (options) {
  37834. // provided polyhedron types :
  37835. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37836. // 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)
  37837. var polyhedra = [];
  37838. 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]] };
  37839. 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]] };
  37840. polyhedra[2] = {
  37841. 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]],
  37842. 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]]
  37843. };
  37844. polyhedra[3] = {
  37845. 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]],
  37846. 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]]
  37847. };
  37848. polyhedra[4] = {
  37849. 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]],
  37850. 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]]
  37851. };
  37852. 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]] };
  37853. 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]] };
  37854. 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]] };
  37855. 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]] };
  37856. 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]] };
  37857. 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]] };
  37858. 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]] };
  37859. 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]] };
  37860. 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]] };
  37861. polyhedra[14] = {
  37862. 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]],
  37863. 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]]
  37864. };
  37865. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37866. var size = options.size;
  37867. var sizeX = options.sizeX || size || 1;
  37868. var sizeY = options.sizeY || size || 1;
  37869. var sizeZ = options.sizeZ || size || 1;
  37870. var data = options.custom || polyhedra[type];
  37871. var nbfaces = data.face.length;
  37872. var faceUV = options.faceUV || new Array(nbfaces);
  37873. var faceColors = options.faceColors;
  37874. var flat = (options.flat === undefined) ? true : options.flat;
  37875. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37876. var positions = new Array();
  37877. var indices = new Array();
  37878. var normals = new Array();
  37879. var uvs = new Array();
  37880. var colors = new Array();
  37881. var index = 0;
  37882. var faceIdx = 0; // face cursor in the array "indexes"
  37883. var indexes = new Array();
  37884. var i = 0;
  37885. var f = 0;
  37886. var u, v, ang, x, y, tmp;
  37887. // default face colors and UV if undefined
  37888. if (flat) {
  37889. for (f = 0; f < nbfaces; f++) {
  37890. if (faceColors && faceColors[f] === undefined) {
  37891. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37892. }
  37893. if (faceUV && faceUV[f] === undefined) {
  37894. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37895. }
  37896. }
  37897. }
  37898. if (!flat) {
  37899. for (i = 0; i < data.vertex.length; i++) {
  37900. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37901. uvs.push(0, 0);
  37902. }
  37903. for (f = 0; f < nbfaces; f++) {
  37904. for (i = 0; i < data.face[f].length - 2; i++) {
  37905. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37906. }
  37907. }
  37908. }
  37909. else {
  37910. for (f = 0; f < nbfaces; f++) {
  37911. var fl = data.face[f].length; // number of vertices of the current face
  37912. ang = 2 * Math.PI / fl;
  37913. x = 0.5 * Math.tan(ang / 2);
  37914. y = 0.5;
  37915. // positions, uvs, colors
  37916. for (i = 0; i < fl; i++) {
  37917. // positions
  37918. 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);
  37919. indexes.push(index);
  37920. index++;
  37921. // uvs
  37922. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37923. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37924. uvs.push(u, v);
  37925. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37926. y = x * Math.sin(ang) + y * Math.cos(ang);
  37927. x = tmp;
  37928. // colors
  37929. if (faceColors) {
  37930. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37931. }
  37932. }
  37933. // indices from indexes
  37934. for (i = 0; i < fl - 2; i++) {
  37935. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37936. }
  37937. faceIdx += fl;
  37938. }
  37939. }
  37940. VertexData.ComputeNormals(positions, indices, normals);
  37941. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37942. var vertexData = new VertexData();
  37943. vertexData.positions = positions;
  37944. vertexData.indices = indices;
  37945. vertexData.normals = normals;
  37946. vertexData.uvs = uvs;
  37947. if (faceColors && flat) {
  37948. vertexData.colors = colors;
  37949. }
  37950. return vertexData;
  37951. };
  37952. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37953. /**
  37954. * Creates the VertexData for a TorusKnot
  37955. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  37956. * * radius the radius of the torus knot, optional, default 2
  37957. * * tube the thickness of the tube, optional, default 0.5
  37958. * * radialSegments the number of sides on each tube segments, optional, default 32
  37959. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  37960. * * p the number of windings around the z axis, optional, default 2
  37961. * * q the number of windings around the x axis, optional, default 3
  37962. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37963. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37964. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37965. * @returns the VertexData of the Torus Knot
  37966. */
  37967. VertexData.CreateTorusKnot = function (options) {
  37968. var indices = new Array();
  37969. var positions = new Array();
  37970. var normals = new Array();
  37971. var uvs = new Array();
  37972. var radius = options.radius || 2;
  37973. var tube = options.tube || 0.5;
  37974. var radialSegments = options.radialSegments || 32;
  37975. var tubularSegments = options.tubularSegments || 32;
  37976. var p = options.p || 2;
  37977. var q = options.q || 3;
  37978. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37979. // Helper
  37980. var getPos = function (angle) {
  37981. var cu = Math.cos(angle);
  37982. var su = Math.sin(angle);
  37983. var quOverP = q / p * angle;
  37984. var cs = Math.cos(quOverP);
  37985. var tx = radius * (2 + cs) * 0.5 * cu;
  37986. var ty = radius * (2 + cs) * su * 0.5;
  37987. var tz = radius * Math.sin(quOverP) * 0.5;
  37988. return new BABYLON.Vector3(tx, ty, tz);
  37989. };
  37990. // Vertices
  37991. var i;
  37992. var j;
  37993. for (i = 0; i <= radialSegments; i++) {
  37994. var modI = i % radialSegments;
  37995. var u = modI / radialSegments * 2 * p * Math.PI;
  37996. var p1 = getPos(u);
  37997. var p2 = getPos(u + 0.01);
  37998. var tang = p2.subtract(p1);
  37999. var n = p2.add(p1);
  38000. var bitan = BABYLON.Vector3.Cross(tang, n);
  38001. n = BABYLON.Vector3.Cross(bitan, tang);
  38002. bitan.normalize();
  38003. n.normalize();
  38004. for (j = 0; j < tubularSegments; j++) {
  38005. var modJ = j % tubularSegments;
  38006. var v = modJ / tubularSegments * 2 * Math.PI;
  38007. var cx = -tube * Math.cos(v);
  38008. var cy = tube * Math.sin(v);
  38009. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38010. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38011. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38012. uvs.push(i / radialSegments);
  38013. uvs.push(j / tubularSegments);
  38014. }
  38015. }
  38016. for (i = 0; i < radialSegments; i++) {
  38017. for (j = 0; j < tubularSegments; j++) {
  38018. var jNext = (j + 1) % tubularSegments;
  38019. var a = i * tubularSegments + j;
  38020. var b = (i + 1) * tubularSegments + j;
  38021. var c = (i + 1) * tubularSegments + jNext;
  38022. var d = i * tubularSegments + jNext;
  38023. indices.push(d);
  38024. indices.push(b);
  38025. indices.push(a);
  38026. indices.push(d);
  38027. indices.push(c);
  38028. indices.push(b);
  38029. }
  38030. }
  38031. // Normals
  38032. VertexData.ComputeNormals(positions, indices, normals);
  38033. // Sides
  38034. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38035. // Result
  38036. var vertexData = new VertexData();
  38037. vertexData.indices = indices;
  38038. vertexData.positions = positions;
  38039. vertexData.normals = normals;
  38040. vertexData.uvs = uvs;
  38041. return vertexData;
  38042. };
  38043. // Tools
  38044. /**
  38045. * Compute normals for given positions and indices
  38046. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38047. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38048. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38049. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38050. * * facetNormals : optional array of facet normals (vector3)
  38051. * * facetPositions : optional array of facet positions (vector3)
  38052. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38053. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38054. * * bInfo : optional bounding info, required for facetPartitioning computation
  38055. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38056. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38057. * * useRightHandedSystem: optional boolean to for right handed system computation
  38058. * * depthSort : optional boolean to enable the facet depth sort computation
  38059. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38060. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38061. */
  38062. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38063. // temporary scalar variables
  38064. var index = 0; // facet index
  38065. var p1p2x = 0.0; // p1p2 vector x coordinate
  38066. var p1p2y = 0.0; // p1p2 vector y coordinate
  38067. var p1p2z = 0.0; // p1p2 vector z coordinate
  38068. var p3p2x = 0.0; // p3p2 vector x coordinate
  38069. var p3p2y = 0.0; // p3p2 vector y coordinate
  38070. var p3p2z = 0.0; // p3p2 vector z coordinate
  38071. var faceNormalx = 0.0; // facet normal x coordinate
  38072. var faceNormaly = 0.0; // facet normal y coordinate
  38073. var faceNormalz = 0.0; // facet normal z coordinate
  38074. var length = 0.0; // facet normal length before normalization
  38075. var v1x = 0; // vector1 x index in the positions array
  38076. var v1y = 0; // vector1 y index in the positions array
  38077. var v1z = 0; // vector1 z index in the positions array
  38078. var v2x = 0; // vector2 x index in the positions array
  38079. var v2y = 0; // vector2 y index in the positions array
  38080. var v2z = 0; // vector2 z index in the positions array
  38081. var v3x = 0; // vector3 x index in the positions array
  38082. var v3y = 0; // vector3 y index in the positions array
  38083. var v3z = 0; // vector3 z index in the positions array
  38084. var computeFacetNormals = false;
  38085. var computeFacetPositions = false;
  38086. var computeFacetPartitioning = false;
  38087. var computeDepthSort = false;
  38088. var faceNormalSign = 1;
  38089. var ratio = 0;
  38090. var distanceTo = null;
  38091. if (options) {
  38092. computeFacetNormals = (options.facetNormals) ? true : false;
  38093. computeFacetPositions = (options.facetPositions) ? true : false;
  38094. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38095. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38096. ratio = options.ratio || 0;
  38097. computeDepthSort = (options.depthSort) ? true : false;
  38098. distanceTo = (options.distanceTo);
  38099. if (computeDepthSort) {
  38100. if (distanceTo === undefined) {
  38101. distanceTo = BABYLON.Vector3.Zero();
  38102. }
  38103. var depthSortedFacets = options.depthSortedFacets;
  38104. }
  38105. }
  38106. // facetPartitioning reinit if needed
  38107. var xSubRatio = 0;
  38108. var ySubRatio = 0;
  38109. var zSubRatio = 0;
  38110. var subSq = 0;
  38111. if (computeFacetPartitioning && options && options.bbSize) {
  38112. var ox = 0; // X partitioning index for facet position
  38113. var oy = 0; // Y partinioning index for facet position
  38114. var oz = 0; // Z partinioning index for facet position
  38115. var b1x = 0; // X partitioning index for facet v1 vertex
  38116. var b1y = 0; // Y partitioning index for facet v1 vertex
  38117. var b1z = 0; // z partitioning index for facet v1 vertex
  38118. var b2x = 0; // X partitioning index for facet v2 vertex
  38119. var b2y = 0; // Y partitioning index for facet v2 vertex
  38120. var b2z = 0; // Z partitioning index for facet v2 vertex
  38121. var b3x = 0; // X partitioning index for facet v3 vertex
  38122. var b3y = 0; // Y partitioning index for facet v3 vertex
  38123. var b3z = 0; // Z partitioning index for facet v3 vertex
  38124. var block_idx_o = 0; // facet barycenter block index
  38125. var block_idx_v1 = 0; // v1 vertex block index
  38126. var block_idx_v2 = 0; // v2 vertex block index
  38127. var block_idx_v3 = 0; // v3 vertex block index
  38128. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38129. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38130. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38131. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38132. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38133. subSq = options.subDiv.max * options.subDiv.max;
  38134. options.facetPartitioning.length = 0;
  38135. }
  38136. // reset the normals
  38137. for (index = 0; index < positions.length; index++) {
  38138. normals[index] = 0.0;
  38139. }
  38140. // Loop : 1 indice triplet = 1 facet
  38141. var nbFaces = (indices.length / 3) | 0;
  38142. for (index = 0; index < nbFaces; index++) {
  38143. // get the indexes of the coordinates of each vertex of the facet
  38144. v1x = indices[index * 3] * 3;
  38145. v1y = v1x + 1;
  38146. v1z = v1x + 2;
  38147. v2x = indices[index * 3 + 1] * 3;
  38148. v2y = v2x + 1;
  38149. v2z = v2x + 2;
  38150. v3x = indices[index * 3 + 2] * 3;
  38151. v3y = v3x + 1;
  38152. v3z = v3x + 2;
  38153. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38154. p1p2y = positions[v1y] - positions[v2y];
  38155. p1p2z = positions[v1z] - positions[v2z];
  38156. p3p2x = positions[v3x] - positions[v2x];
  38157. p3p2y = positions[v3y] - positions[v2y];
  38158. p3p2z = positions[v3z] - positions[v2z];
  38159. // compute the face normal with the cross product
  38160. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38161. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38162. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38163. // normalize this normal and store it in the array facetData
  38164. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38165. length = (length === 0) ? 1.0 : length;
  38166. faceNormalx /= length;
  38167. faceNormaly /= length;
  38168. faceNormalz /= length;
  38169. if (computeFacetNormals && options) {
  38170. options.facetNormals[index].x = faceNormalx;
  38171. options.facetNormals[index].y = faceNormaly;
  38172. options.facetNormals[index].z = faceNormalz;
  38173. }
  38174. if (computeFacetPositions && options) {
  38175. // compute and the facet barycenter coordinates in the array facetPositions
  38176. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38177. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38178. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38179. }
  38180. if (computeFacetPartitioning && options) {
  38181. // store the facet indexes in arrays in the main facetPartitioning array :
  38182. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38183. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38184. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38185. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38186. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38187. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38188. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38189. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38190. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38191. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38192. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38193. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38194. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38195. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38196. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38197. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38198. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38199. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38200. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38201. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38202. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38203. // push each facet index in each block containing the vertex
  38204. options.facetPartitioning[block_idx_v1].push(index);
  38205. if (block_idx_v2 != block_idx_v1) {
  38206. options.facetPartitioning[block_idx_v2].push(index);
  38207. }
  38208. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38209. options.facetPartitioning[block_idx_v3].push(index);
  38210. }
  38211. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38212. options.facetPartitioning[block_idx_o].push(index);
  38213. }
  38214. }
  38215. if (computeDepthSort && options && options.facetPositions) {
  38216. var dsf = depthSortedFacets[index];
  38217. dsf.ind = index * 3;
  38218. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38219. }
  38220. // compute the normals anyway
  38221. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38222. normals[v1y] += faceNormaly;
  38223. normals[v1z] += faceNormalz;
  38224. normals[v2x] += faceNormalx;
  38225. normals[v2y] += faceNormaly;
  38226. normals[v2z] += faceNormalz;
  38227. normals[v3x] += faceNormalx;
  38228. normals[v3y] += faceNormaly;
  38229. normals[v3z] += faceNormalz;
  38230. }
  38231. // last normalization of each normal
  38232. for (index = 0; index < normals.length / 3; index++) {
  38233. faceNormalx = normals[index * 3];
  38234. faceNormaly = normals[index * 3 + 1];
  38235. faceNormalz = normals[index * 3 + 2];
  38236. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38237. length = (length === 0) ? 1.0 : length;
  38238. faceNormalx /= length;
  38239. faceNormaly /= length;
  38240. faceNormalz /= length;
  38241. normals[index * 3] = faceNormalx;
  38242. normals[index * 3 + 1] = faceNormaly;
  38243. normals[index * 3 + 2] = faceNormalz;
  38244. }
  38245. };
  38246. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38247. var li = indices.length;
  38248. var ln = normals.length;
  38249. var i;
  38250. var n;
  38251. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38252. switch (sideOrientation) {
  38253. case BABYLON.Mesh.FRONTSIDE:
  38254. // nothing changed
  38255. break;
  38256. case BABYLON.Mesh.BACKSIDE:
  38257. var tmp;
  38258. // indices
  38259. for (i = 0; i < li; i += 3) {
  38260. tmp = indices[i];
  38261. indices[i] = indices[i + 2];
  38262. indices[i + 2] = tmp;
  38263. }
  38264. // normals
  38265. for (n = 0; n < ln; n++) {
  38266. normals[n] = -normals[n];
  38267. }
  38268. break;
  38269. case BABYLON.Mesh.DOUBLESIDE:
  38270. // positions
  38271. var lp = positions.length;
  38272. var l = lp / 3;
  38273. for (var p = 0; p < lp; p++) {
  38274. positions[lp + p] = positions[p];
  38275. }
  38276. // indices
  38277. for (i = 0; i < li; i += 3) {
  38278. indices[i + li] = indices[i + 2] + l;
  38279. indices[i + 1 + li] = indices[i + 1] + l;
  38280. indices[i + 2 + li] = indices[i] + l;
  38281. }
  38282. // normals
  38283. for (n = 0; n < ln; n++) {
  38284. normals[ln + n] = -normals[n];
  38285. }
  38286. // uvs
  38287. var lu = uvs.length;
  38288. var u = 0;
  38289. for (u = 0; u < lu; u++) {
  38290. uvs[u + lu] = uvs[u];
  38291. }
  38292. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38293. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38294. u = 0;
  38295. for (i = 0; i < lu / 2; i++) {
  38296. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38297. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38298. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38299. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38300. u += 2;
  38301. }
  38302. break;
  38303. }
  38304. };
  38305. /**
  38306. * Applies VertexData created from the imported parameters to the geometry
  38307. * @param parsedVertexData the parsed data from an imported file
  38308. * @param geometry the geometry to apply the VertexData to
  38309. */
  38310. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38311. var vertexData = new VertexData();
  38312. // positions
  38313. var positions = parsedVertexData.positions;
  38314. if (positions) {
  38315. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38316. }
  38317. // normals
  38318. var normals = parsedVertexData.normals;
  38319. if (normals) {
  38320. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38321. }
  38322. // tangents
  38323. var tangents = parsedVertexData.tangents;
  38324. if (tangents) {
  38325. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38326. }
  38327. // uvs
  38328. var uvs = parsedVertexData.uvs;
  38329. if (uvs) {
  38330. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38331. }
  38332. // uv2s
  38333. var uv2s = parsedVertexData.uv2s;
  38334. if (uv2s) {
  38335. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38336. }
  38337. // uv3s
  38338. var uv3s = parsedVertexData.uv3s;
  38339. if (uv3s) {
  38340. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38341. }
  38342. // uv4s
  38343. var uv4s = parsedVertexData.uv4s;
  38344. if (uv4s) {
  38345. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38346. }
  38347. // uv5s
  38348. var uv5s = parsedVertexData.uv5s;
  38349. if (uv5s) {
  38350. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38351. }
  38352. // uv6s
  38353. var uv6s = parsedVertexData.uv6s;
  38354. if (uv6s) {
  38355. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38356. }
  38357. // colors
  38358. var colors = parsedVertexData.colors;
  38359. if (colors) {
  38360. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38361. }
  38362. // matricesIndices
  38363. var matricesIndices = parsedVertexData.matricesIndices;
  38364. if (matricesIndices) {
  38365. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38366. }
  38367. // matricesWeights
  38368. var matricesWeights = parsedVertexData.matricesWeights;
  38369. if (matricesWeights) {
  38370. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38371. }
  38372. // indices
  38373. var indices = parsedVertexData.indices;
  38374. if (indices) {
  38375. vertexData.indices = indices;
  38376. }
  38377. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38378. };
  38379. return VertexData;
  38380. }());
  38381. BABYLON.VertexData = VertexData;
  38382. })(BABYLON || (BABYLON = {}));
  38383. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38384. var BABYLON;
  38385. (function (BABYLON) {
  38386. /**
  38387. * Class used to store geometry data (vertex buffers + index buffer)
  38388. */
  38389. var Geometry = /** @class */ (function () {
  38390. /**
  38391. * Creates a new geometry
  38392. * @param id defines the unique ID
  38393. * @param scene defines the hosting scene
  38394. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38395. * @param updatable defines if geometry must be updatable (false by default)
  38396. * @param mesh defines the mesh that will be associated with the geometry
  38397. */
  38398. function Geometry(id, scene, vertexData, updatable, mesh) {
  38399. if (updatable === void 0) { updatable = false; }
  38400. if (mesh === void 0) { mesh = null; }
  38401. /**
  38402. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38403. */
  38404. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38405. this._totalVertices = 0;
  38406. this._isDisposed = false;
  38407. this._indexBufferIsUpdatable = false;
  38408. this.id = id;
  38409. this._engine = scene.getEngine();
  38410. this._meshes = [];
  38411. this._scene = scene;
  38412. //Init vertex buffer cache
  38413. this._vertexBuffers = {};
  38414. this._indices = [];
  38415. this._updatable = updatable;
  38416. // vertexData
  38417. if (vertexData) {
  38418. this.setAllVerticesData(vertexData, updatable);
  38419. }
  38420. else {
  38421. this._totalVertices = 0;
  38422. this._indices = [];
  38423. }
  38424. if (this._engine.getCaps().vertexArrayObject) {
  38425. this._vertexArrayObjects = {};
  38426. }
  38427. // applyToMesh
  38428. if (mesh) {
  38429. if (mesh.getClassName() === "LinesMesh") {
  38430. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38431. this._updateExtend();
  38432. }
  38433. this.applyToMesh(mesh);
  38434. mesh.computeWorldMatrix(true);
  38435. }
  38436. }
  38437. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38438. /**
  38439. * 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
  38440. */
  38441. get: function () {
  38442. return this._boundingBias;
  38443. },
  38444. /**
  38445. * 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
  38446. */
  38447. set: function (value) {
  38448. if (this._boundingBias && this._boundingBias.equals(value)) {
  38449. return;
  38450. }
  38451. this._boundingBias = value.clone();
  38452. this._updateBoundingInfo(true, null);
  38453. },
  38454. enumerable: true,
  38455. configurable: true
  38456. });
  38457. /**
  38458. * Static function used to attach a new empty geometry to a mesh
  38459. * @param mesh defines the mesh to attach the geometry to
  38460. * @returns the new {BABYLON.Geometry}
  38461. */
  38462. Geometry.CreateGeometryForMesh = function (mesh) {
  38463. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38464. geometry.applyToMesh(mesh);
  38465. return geometry;
  38466. };
  38467. Object.defineProperty(Geometry.prototype, "extend", {
  38468. /**
  38469. * Gets the current extend of the geometry
  38470. */
  38471. get: function () {
  38472. return this._extend;
  38473. },
  38474. enumerable: true,
  38475. configurable: true
  38476. });
  38477. /**
  38478. * Gets the hosting scene
  38479. * @returns the hosting {BABYLON.Scene}
  38480. */
  38481. Geometry.prototype.getScene = function () {
  38482. return this._scene;
  38483. };
  38484. /**
  38485. * Gets the hosting engine
  38486. * @returns the hosting {BABYLON.Engine}
  38487. */
  38488. Geometry.prototype.getEngine = function () {
  38489. return this._engine;
  38490. };
  38491. /**
  38492. * Defines if the geometry is ready to use
  38493. * @returns true if the geometry is ready to be used
  38494. */
  38495. Geometry.prototype.isReady = function () {
  38496. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38497. };
  38498. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38499. /**
  38500. * Gets a value indicating that the geometry should not be serialized
  38501. */
  38502. get: function () {
  38503. for (var index = 0; index < this._meshes.length; index++) {
  38504. if (!this._meshes[index].doNotSerialize) {
  38505. return false;
  38506. }
  38507. }
  38508. return true;
  38509. },
  38510. enumerable: true,
  38511. configurable: true
  38512. });
  38513. /** @hidden */
  38514. Geometry.prototype._rebuild = function () {
  38515. if (this._vertexArrayObjects) {
  38516. this._vertexArrayObjects = {};
  38517. }
  38518. // Index buffer
  38519. if (this._meshes.length !== 0 && this._indices) {
  38520. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38521. }
  38522. // Vertex buffers
  38523. for (var key in this._vertexBuffers) {
  38524. var vertexBuffer = this._vertexBuffers[key];
  38525. vertexBuffer._rebuild();
  38526. }
  38527. };
  38528. /**
  38529. * Affects all gemetry data in one call
  38530. * @param vertexData defines the geometry data
  38531. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38532. */
  38533. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38534. vertexData.applyToGeometry(this, updatable);
  38535. this.notifyUpdate();
  38536. };
  38537. /**
  38538. * Set specific vertex data
  38539. * @param kind defines the data kind (Position, normal, etc...)
  38540. * @param data defines the vertex data to use
  38541. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38542. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38543. */
  38544. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38545. if (updatable === void 0) { updatable = false; }
  38546. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38547. this.setVerticesBuffer(buffer);
  38548. };
  38549. /**
  38550. * Removes a specific vertex data
  38551. * @param kind defines the data kind (Position, normal, etc...)
  38552. */
  38553. Geometry.prototype.removeVerticesData = function (kind) {
  38554. if (this._vertexBuffers[kind]) {
  38555. this._vertexBuffers[kind].dispose();
  38556. delete this._vertexBuffers[kind];
  38557. }
  38558. };
  38559. /**
  38560. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38561. * @param buffer defines the vertex buffer to use
  38562. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38563. */
  38564. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38565. if (totalVertices === void 0) { totalVertices = null; }
  38566. var kind = buffer.getKind();
  38567. if (this._vertexBuffers[kind]) {
  38568. this._vertexBuffers[kind].dispose();
  38569. }
  38570. this._vertexBuffers[kind] = buffer;
  38571. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38572. var data = buffer.getData();
  38573. if (totalVertices != null) {
  38574. this._totalVertices = totalVertices;
  38575. }
  38576. else {
  38577. if (data != null) {
  38578. this._totalVertices = data.length / (buffer.byteStride / 4);
  38579. }
  38580. }
  38581. this._updateExtend(data);
  38582. this._resetPointsArrayCache();
  38583. var meshes = this._meshes;
  38584. var numOfMeshes = meshes.length;
  38585. for (var index = 0; index < numOfMeshes; index++) {
  38586. var mesh = meshes[index];
  38587. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38588. mesh._createGlobalSubMesh(false);
  38589. mesh.computeWorldMatrix(true);
  38590. }
  38591. }
  38592. this.notifyUpdate(kind);
  38593. if (this._vertexArrayObjects) {
  38594. this._disposeVertexArrayObjects();
  38595. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38596. }
  38597. };
  38598. /**
  38599. * Update a specific vertex buffer
  38600. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38601. * It will do nothing if the buffer is not updatable
  38602. * @param kind defines the data kind (Position, normal, etc...)
  38603. * @param data defines the data to use
  38604. * @param offset defines the offset in the target buffer where to store the data
  38605. * @param useBytes set to true if the offset is in bytes
  38606. */
  38607. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38608. if (useBytes === void 0) { useBytes = false; }
  38609. var vertexBuffer = this.getVertexBuffer(kind);
  38610. if (!vertexBuffer) {
  38611. return;
  38612. }
  38613. vertexBuffer.updateDirectly(data, offset, useBytes);
  38614. this.notifyUpdate(kind);
  38615. };
  38616. /**
  38617. * Update a specific vertex buffer
  38618. * This function will create a new buffer if the current one is not updatable
  38619. * @param kind defines the data kind (Position, normal, etc...)
  38620. * @param data defines the data to use
  38621. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38622. */
  38623. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38624. if (updateExtends === void 0) { updateExtends = false; }
  38625. var vertexBuffer = this.getVertexBuffer(kind);
  38626. if (!vertexBuffer) {
  38627. return;
  38628. }
  38629. vertexBuffer.update(data);
  38630. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38631. this._updateBoundingInfo(updateExtends, data);
  38632. }
  38633. this.notifyUpdate(kind);
  38634. };
  38635. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38636. if (updateExtends) {
  38637. this._updateExtend(data);
  38638. }
  38639. var meshes = this._meshes;
  38640. var numOfMeshes = meshes.length;
  38641. this._resetPointsArrayCache();
  38642. for (var index = 0; index < numOfMeshes; index++) {
  38643. var mesh = meshes[index];
  38644. if (updateExtends) {
  38645. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38646. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38647. var subMesh = mesh.subMeshes[subIndex];
  38648. subMesh.refreshBoundingInfo();
  38649. }
  38650. }
  38651. }
  38652. };
  38653. /** @hidden */
  38654. Geometry.prototype._bind = function (effect, indexToBind) {
  38655. if (!effect) {
  38656. return;
  38657. }
  38658. if (indexToBind === undefined) {
  38659. indexToBind = this._indexBuffer;
  38660. }
  38661. var vbs = this.getVertexBuffers();
  38662. if (!vbs) {
  38663. return;
  38664. }
  38665. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38666. this._engine.bindBuffers(vbs, indexToBind, effect);
  38667. return;
  38668. }
  38669. // Using VAO
  38670. if (!this._vertexArrayObjects[effect.key]) {
  38671. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38672. }
  38673. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38674. };
  38675. /**
  38676. * Gets total number of vertices
  38677. * @returns the total number of vertices
  38678. */
  38679. Geometry.prototype.getTotalVertices = function () {
  38680. if (!this.isReady()) {
  38681. return 0;
  38682. }
  38683. return this._totalVertices;
  38684. };
  38685. /**
  38686. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38687. * @param kind defines the data kind (Position, normal, etc...)
  38688. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38689. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38690. * @returns a float array containing vertex data
  38691. */
  38692. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38693. var vertexBuffer = this.getVertexBuffer(kind);
  38694. if (!vertexBuffer) {
  38695. return null;
  38696. }
  38697. var data = vertexBuffer.getData();
  38698. if (!data) {
  38699. return null;
  38700. }
  38701. var defaultStride = BABYLON.VertexBuffer.DeduceStride(vertexBuffer.getKind());
  38702. var defaultByteStride = defaultStride * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38703. var count = this._totalVertices * defaultStride;
  38704. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== defaultByteStride) {
  38705. var copy_1 = new Array(count);
  38706. vertexBuffer.forEach(count, function (value, index) {
  38707. copy_1[index] = value;
  38708. });
  38709. return copy_1;
  38710. }
  38711. if (!(data instanceof Array || data instanceof Float32Array) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38712. if (data instanceof Array) {
  38713. var offset = vertexBuffer.byteOffset / 4;
  38714. return BABYLON.Tools.Slice(data, offset, offset + count);
  38715. }
  38716. else if (data instanceof ArrayBuffer) {
  38717. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38718. }
  38719. else {
  38720. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38721. }
  38722. }
  38723. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38724. return BABYLON.Tools.Slice(data);
  38725. }
  38726. return data;
  38727. };
  38728. /**
  38729. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38730. * @param kind defines the data kind (Position, normal, etc...)
  38731. * @returns true if the vertex buffer with the specified kind is updatable
  38732. */
  38733. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38734. var vb = this._vertexBuffers[kind];
  38735. if (!vb) {
  38736. return false;
  38737. }
  38738. return vb.isUpdatable();
  38739. };
  38740. /**
  38741. * Gets a specific vertex buffer
  38742. * @param kind defines the data kind (Position, normal, etc...)
  38743. * @returns a {BABYLON.VertexBuffer}
  38744. */
  38745. Geometry.prototype.getVertexBuffer = function (kind) {
  38746. if (!this.isReady()) {
  38747. return null;
  38748. }
  38749. return this._vertexBuffers[kind];
  38750. };
  38751. /**
  38752. * Returns all vertex buffers
  38753. * @return an object holding all vertex buffers indexed by kind
  38754. */
  38755. Geometry.prototype.getVertexBuffers = function () {
  38756. if (!this.isReady()) {
  38757. return null;
  38758. }
  38759. return this._vertexBuffers;
  38760. };
  38761. /**
  38762. * Gets a boolean indicating if specific vertex buffer is present
  38763. * @param kind defines the data kind (Position, normal, etc...)
  38764. * @returns true if data is present
  38765. */
  38766. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38767. if (!this._vertexBuffers) {
  38768. if (this._delayInfo) {
  38769. return this._delayInfo.indexOf(kind) !== -1;
  38770. }
  38771. return false;
  38772. }
  38773. return this._vertexBuffers[kind] !== undefined;
  38774. };
  38775. /**
  38776. * Gets a list of all attached data kinds (Position, normal, etc...)
  38777. * @returns a list of string containing all kinds
  38778. */
  38779. Geometry.prototype.getVerticesDataKinds = function () {
  38780. var result = [];
  38781. var kind;
  38782. if (!this._vertexBuffers && this._delayInfo) {
  38783. for (kind in this._delayInfo) {
  38784. result.push(kind);
  38785. }
  38786. }
  38787. else {
  38788. for (kind in this._vertexBuffers) {
  38789. result.push(kind);
  38790. }
  38791. }
  38792. return result;
  38793. };
  38794. /**
  38795. * Update index buffer
  38796. * @param indices defines the indices to store in the index buffer
  38797. * @param offset defines the offset in the target buffer where to store the data
  38798. */
  38799. Geometry.prototype.updateIndices = function (indices, offset) {
  38800. if (!this._indexBuffer) {
  38801. return;
  38802. }
  38803. if (!this._indexBufferIsUpdatable) {
  38804. this.setIndices(indices, null, true);
  38805. }
  38806. else {
  38807. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38808. }
  38809. };
  38810. /**
  38811. * Creates a new index buffer
  38812. * @param indices defines the indices to store in the index buffer
  38813. * @param totalVertices defines the total number of vertices (could be null)
  38814. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38815. */
  38816. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38817. if (totalVertices === void 0) { totalVertices = null; }
  38818. if (updatable === void 0) { updatable = false; }
  38819. if (this._indexBuffer) {
  38820. this._engine._releaseBuffer(this._indexBuffer);
  38821. }
  38822. this._disposeVertexArrayObjects();
  38823. this._indices = indices;
  38824. this._indexBufferIsUpdatable = updatable;
  38825. if (this._meshes.length !== 0 && this._indices) {
  38826. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38827. }
  38828. if (totalVertices != undefined) { // including null and undefined
  38829. this._totalVertices = totalVertices;
  38830. }
  38831. var meshes = this._meshes;
  38832. var numOfMeshes = meshes.length;
  38833. for (var index = 0; index < numOfMeshes; index++) {
  38834. meshes[index]._createGlobalSubMesh(true);
  38835. }
  38836. this.notifyUpdate();
  38837. };
  38838. /**
  38839. * Return the total number of indices
  38840. * @returns the total number of indices
  38841. */
  38842. Geometry.prototype.getTotalIndices = function () {
  38843. if (!this.isReady()) {
  38844. return 0;
  38845. }
  38846. return this._indices.length;
  38847. };
  38848. /**
  38849. * Gets the index buffer array
  38850. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38851. * @returns the index buffer array
  38852. */
  38853. Geometry.prototype.getIndices = function (copyWhenShared) {
  38854. if (!this.isReady()) {
  38855. return null;
  38856. }
  38857. var orig = this._indices;
  38858. if (!copyWhenShared || this._meshes.length === 1) {
  38859. return orig;
  38860. }
  38861. else {
  38862. var len = orig.length;
  38863. var copy = [];
  38864. for (var i = 0; i < len; i++) {
  38865. copy.push(orig[i]);
  38866. }
  38867. return copy;
  38868. }
  38869. };
  38870. /**
  38871. * Gets the index buffer
  38872. * @return the index buffer
  38873. */
  38874. Geometry.prototype.getIndexBuffer = function () {
  38875. if (!this.isReady()) {
  38876. return null;
  38877. }
  38878. return this._indexBuffer;
  38879. };
  38880. /** @hidden */
  38881. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38882. if (effect === void 0) { effect = null; }
  38883. if (!effect || !this._vertexArrayObjects) {
  38884. return;
  38885. }
  38886. if (this._vertexArrayObjects[effect.key]) {
  38887. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38888. delete this._vertexArrayObjects[effect.key];
  38889. }
  38890. };
  38891. /**
  38892. * Release the associated resources for a specific mesh
  38893. * @param mesh defines the source mesh
  38894. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38895. */
  38896. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38897. var meshes = this._meshes;
  38898. var index = meshes.indexOf(mesh);
  38899. if (index === -1) {
  38900. return;
  38901. }
  38902. meshes.splice(index, 1);
  38903. mesh._geometry = null;
  38904. if (meshes.length === 0 && shouldDispose) {
  38905. this.dispose();
  38906. }
  38907. };
  38908. /**
  38909. * Apply current geometry to a given mesh
  38910. * @param mesh defines the mesh to apply geometry to
  38911. */
  38912. Geometry.prototype.applyToMesh = function (mesh) {
  38913. if (mesh._geometry === this) {
  38914. return;
  38915. }
  38916. var previousGeometry = mesh._geometry;
  38917. if (previousGeometry) {
  38918. previousGeometry.releaseForMesh(mesh);
  38919. }
  38920. var meshes = this._meshes;
  38921. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38922. mesh._geometry = this;
  38923. this._scene.pushGeometry(this);
  38924. meshes.push(mesh);
  38925. if (this.isReady()) {
  38926. this._applyToMesh(mesh);
  38927. }
  38928. else {
  38929. mesh._boundingInfo = this._boundingInfo;
  38930. }
  38931. };
  38932. Geometry.prototype._updateExtend = function (data) {
  38933. if (data === void 0) { data = null; }
  38934. if (!data) {
  38935. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38936. }
  38937. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38938. };
  38939. Geometry.prototype._applyToMesh = function (mesh) {
  38940. var numOfMeshes = this._meshes.length;
  38941. // vertexBuffers
  38942. for (var kind in this._vertexBuffers) {
  38943. if (numOfMeshes === 1) {
  38944. this._vertexBuffers[kind].create();
  38945. }
  38946. var buffer = this._vertexBuffers[kind].getBuffer();
  38947. if (buffer)
  38948. buffer.references = numOfMeshes;
  38949. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38950. if (!this._extend) {
  38951. this._updateExtend();
  38952. }
  38953. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38954. mesh._createGlobalSubMesh(false);
  38955. //bounding info was just created again, world matrix should be applied again.
  38956. mesh._updateBoundingInfo();
  38957. }
  38958. }
  38959. // indexBuffer
  38960. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  38961. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38962. }
  38963. if (this._indexBuffer) {
  38964. this._indexBuffer.references = numOfMeshes;
  38965. }
  38966. };
  38967. Geometry.prototype.notifyUpdate = function (kind) {
  38968. if (this.onGeometryUpdated) {
  38969. this.onGeometryUpdated(this, kind);
  38970. }
  38971. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  38972. var mesh = _a[_i];
  38973. mesh._markSubMeshesAsAttributesDirty();
  38974. }
  38975. };
  38976. /**
  38977. * Load the geometry if it was flagged as delay loaded
  38978. * @param scene defines the hosting scene
  38979. * @param onLoaded defines a callback called when the geometry is loaded
  38980. */
  38981. Geometry.prototype.load = function (scene, onLoaded) {
  38982. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  38983. return;
  38984. }
  38985. if (this.isReady()) {
  38986. if (onLoaded) {
  38987. onLoaded();
  38988. }
  38989. return;
  38990. }
  38991. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  38992. this._queueLoad(scene, onLoaded);
  38993. };
  38994. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  38995. var _this = this;
  38996. if (!this.delayLoadingFile) {
  38997. return;
  38998. }
  38999. scene._addPendingData(this);
  39000. scene._loadFile(this.delayLoadingFile, function (data) {
  39001. if (!_this._delayLoadingFunction) {
  39002. return;
  39003. }
  39004. _this._delayLoadingFunction(JSON.parse(data), _this);
  39005. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39006. _this._delayInfo = [];
  39007. scene._removePendingData(_this);
  39008. var meshes = _this._meshes;
  39009. var numOfMeshes = meshes.length;
  39010. for (var index = 0; index < numOfMeshes; index++) {
  39011. _this._applyToMesh(meshes[index]);
  39012. }
  39013. if (onLoaded) {
  39014. onLoaded();
  39015. }
  39016. }, undefined, true);
  39017. };
  39018. /**
  39019. * Invert the geometry to move from a right handed system to a left handed one.
  39020. */
  39021. Geometry.prototype.toLeftHanded = function () {
  39022. // Flip faces
  39023. var tIndices = this.getIndices(false);
  39024. if (tIndices != null && tIndices.length > 0) {
  39025. for (var i = 0; i < tIndices.length; i += 3) {
  39026. var tTemp = tIndices[i + 0];
  39027. tIndices[i + 0] = tIndices[i + 2];
  39028. tIndices[i + 2] = tTemp;
  39029. }
  39030. this.setIndices(tIndices);
  39031. }
  39032. // Negate position.z
  39033. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39034. if (tPositions != null && tPositions.length > 0) {
  39035. for (var i = 0; i < tPositions.length; i += 3) {
  39036. tPositions[i + 2] = -tPositions[i + 2];
  39037. }
  39038. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39039. }
  39040. // Negate normal.z
  39041. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39042. if (tNormals != null && tNormals.length > 0) {
  39043. for (var i = 0; i < tNormals.length; i += 3) {
  39044. tNormals[i + 2] = -tNormals[i + 2];
  39045. }
  39046. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39047. }
  39048. };
  39049. // Cache
  39050. /** @hidden */
  39051. Geometry.prototype._resetPointsArrayCache = function () {
  39052. this._positions = null;
  39053. };
  39054. /** @hidden */
  39055. Geometry.prototype._generatePointsArray = function () {
  39056. if (this._positions)
  39057. return true;
  39058. this._positions = [];
  39059. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39060. if (!data) {
  39061. return false;
  39062. }
  39063. for (var index = 0; index < data.length; index += 3) {
  39064. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39065. }
  39066. return true;
  39067. };
  39068. /**
  39069. * Gets a value indicating if the geometry is disposed
  39070. * @returns true if the geometry was disposed
  39071. */
  39072. Geometry.prototype.isDisposed = function () {
  39073. return this._isDisposed;
  39074. };
  39075. Geometry.prototype._disposeVertexArrayObjects = function () {
  39076. if (this._vertexArrayObjects) {
  39077. for (var kind in this._vertexArrayObjects) {
  39078. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39079. }
  39080. this._vertexArrayObjects = {};
  39081. }
  39082. };
  39083. /**
  39084. * Free all associated resources
  39085. */
  39086. Geometry.prototype.dispose = function () {
  39087. var meshes = this._meshes;
  39088. var numOfMeshes = meshes.length;
  39089. var index;
  39090. for (index = 0; index < numOfMeshes; index++) {
  39091. this.releaseForMesh(meshes[index]);
  39092. }
  39093. this._meshes = [];
  39094. this._disposeVertexArrayObjects();
  39095. for (var kind in this._vertexBuffers) {
  39096. this._vertexBuffers[kind].dispose();
  39097. }
  39098. this._vertexBuffers = {};
  39099. this._totalVertices = 0;
  39100. if (this._indexBuffer) {
  39101. this._engine._releaseBuffer(this._indexBuffer);
  39102. }
  39103. this._indexBuffer = null;
  39104. this._indices = [];
  39105. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39106. this.delayLoadingFile = null;
  39107. this._delayLoadingFunction = null;
  39108. this._delayInfo = [];
  39109. this._boundingInfo = null;
  39110. this._scene.removeGeometry(this);
  39111. this._isDisposed = true;
  39112. };
  39113. /**
  39114. * Clone the current geometry into a new geometry
  39115. * @param id defines the unique ID of the new geometry
  39116. * @returns a new geometry object
  39117. */
  39118. Geometry.prototype.copy = function (id) {
  39119. var vertexData = new BABYLON.VertexData();
  39120. vertexData.indices = [];
  39121. var indices = this.getIndices();
  39122. if (indices) {
  39123. for (var index = 0; index < indices.length; index++) {
  39124. vertexData.indices.push(indices[index]);
  39125. }
  39126. }
  39127. var updatable = false;
  39128. var stopChecking = false;
  39129. var kind;
  39130. for (kind in this._vertexBuffers) {
  39131. // using slice() to make a copy of the array and not just reference it
  39132. var data = this.getVerticesData(kind);
  39133. if (data instanceof Float32Array) {
  39134. vertexData.set(new Float32Array(data), kind);
  39135. }
  39136. else {
  39137. vertexData.set(data.slice(0), kind);
  39138. }
  39139. if (!stopChecking) {
  39140. var vb = this.getVertexBuffer(kind);
  39141. if (vb) {
  39142. updatable = vb.isUpdatable();
  39143. stopChecking = !updatable;
  39144. }
  39145. }
  39146. }
  39147. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39148. geometry.delayLoadState = this.delayLoadState;
  39149. geometry.delayLoadingFile = this.delayLoadingFile;
  39150. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39151. for (kind in this._delayInfo) {
  39152. geometry._delayInfo = geometry._delayInfo || [];
  39153. geometry._delayInfo.push(kind);
  39154. }
  39155. // Bounding info
  39156. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39157. return geometry;
  39158. };
  39159. /**
  39160. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39161. * @return a JSON representation of the current geometry data (without the vertices data)
  39162. */
  39163. Geometry.prototype.serialize = function () {
  39164. var serializationObject = {};
  39165. serializationObject.id = this.id;
  39166. serializationObject.updatable = this._updatable;
  39167. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39168. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39169. }
  39170. return serializationObject;
  39171. };
  39172. Geometry.prototype.toNumberArray = function (origin) {
  39173. if (Array.isArray(origin)) {
  39174. return origin;
  39175. }
  39176. else {
  39177. return Array.prototype.slice.call(origin);
  39178. }
  39179. };
  39180. /**
  39181. * Serialize all vertices data into a JSON oject
  39182. * @returns a JSON representation of the current geometry data
  39183. */
  39184. Geometry.prototype.serializeVerticeData = function () {
  39185. var serializationObject = this.serialize();
  39186. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39187. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39188. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39189. serializationObject.positions._updatable = true;
  39190. }
  39191. }
  39192. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39193. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39194. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39195. serializationObject.normals._updatable = true;
  39196. }
  39197. }
  39198. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39199. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39200. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39201. serializationObject.tangets._updatable = true;
  39202. }
  39203. }
  39204. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39205. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39206. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39207. serializationObject.uvs._updatable = true;
  39208. }
  39209. }
  39210. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39211. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39212. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39213. serializationObject.uv2s._updatable = true;
  39214. }
  39215. }
  39216. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39217. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39218. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39219. serializationObject.uv3s._updatable = true;
  39220. }
  39221. }
  39222. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39223. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39224. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39225. serializationObject.uv4s._updatable = true;
  39226. }
  39227. }
  39228. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39229. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39230. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39231. serializationObject.uv5s._updatable = true;
  39232. }
  39233. }
  39234. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39235. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39236. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39237. serializationObject.uv6s._updatable = true;
  39238. }
  39239. }
  39240. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39241. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39242. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39243. serializationObject.colors._updatable = true;
  39244. }
  39245. }
  39246. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39247. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39248. serializationObject.matricesIndices._isExpanded = true;
  39249. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39250. serializationObject.matricesIndices._updatable = true;
  39251. }
  39252. }
  39253. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39254. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39255. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39256. serializationObject.matricesWeights._updatable = true;
  39257. }
  39258. }
  39259. serializationObject.indices = this.toNumberArray(this.getIndices());
  39260. return serializationObject;
  39261. };
  39262. // Statics
  39263. /**
  39264. * Extracts a clone of a mesh geometry
  39265. * @param mesh defines the source mesh
  39266. * @param id defines the unique ID of the new geometry object
  39267. * @returns the new geometry object
  39268. */
  39269. Geometry.ExtractFromMesh = function (mesh, id) {
  39270. var geometry = mesh._geometry;
  39271. if (!geometry) {
  39272. return null;
  39273. }
  39274. return geometry.copy(id);
  39275. };
  39276. /**
  39277. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39278. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39279. * Be aware Math.random() could cause collisions, but:
  39280. * "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"
  39281. * @returns a string containing a new GUID
  39282. */
  39283. Geometry.RandomId = function () {
  39284. return BABYLON.Tools.RandomId();
  39285. };
  39286. /** @hidden */
  39287. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39288. var scene = mesh.getScene();
  39289. // Geometry
  39290. var geometryId = parsedGeometry.geometryId;
  39291. if (geometryId) {
  39292. var geometry = scene.getGeometryByID(geometryId);
  39293. if (geometry) {
  39294. geometry.applyToMesh(mesh);
  39295. }
  39296. }
  39297. else if (parsedGeometry instanceof ArrayBuffer) {
  39298. var binaryInfo = mesh._binaryInfo;
  39299. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39300. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39301. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39302. }
  39303. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39304. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39305. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39306. }
  39307. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39308. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39309. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39310. }
  39311. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39312. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39313. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39314. }
  39315. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39316. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39317. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39318. }
  39319. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39320. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39321. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39322. }
  39323. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39324. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39325. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39326. }
  39327. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39328. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39329. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39330. }
  39331. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39332. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39333. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39334. }
  39335. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39336. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39337. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39338. }
  39339. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39340. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39341. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39342. }
  39343. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39344. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39345. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39346. }
  39347. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39348. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39349. mesh.setIndices(indicesData, null);
  39350. }
  39351. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39352. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39353. mesh.subMeshes = [];
  39354. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39355. var materialIndex = subMeshesData[(i * 5) + 0];
  39356. var verticesStart = subMeshesData[(i * 5) + 1];
  39357. var verticesCount = subMeshesData[(i * 5) + 2];
  39358. var indexStart = subMeshesData[(i * 5) + 3];
  39359. var indexCount = subMeshesData[(i * 5) + 4];
  39360. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39361. }
  39362. }
  39363. }
  39364. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39365. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39366. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39367. if (parsedGeometry.tangents) {
  39368. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39369. }
  39370. if (parsedGeometry.uvs) {
  39371. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39372. }
  39373. if (parsedGeometry.uvs2) {
  39374. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39375. }
  39376. if (parsedGeometry.uvs3) {
  39377. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39378. }
  39379. if (parsedGeometry.uvs4) {
  39380. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39381. }
  39382. if (parsedGeometry.uvs5) {
  39383. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39384. }
  39385. if (parsedGeometry.uvs6) {
  39386. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39387. }
  39388. if (parsedGeometry.colors) {
  39389. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39390. }
  39391. if (parsedGeometry.matricesIndices) {
  39392. if (!parsedGeometry.matricesIndices._isExpanded) {
  39393. var floatIndices = [];
  39394. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39395. var matricesIndex = parsedGeometry.matricesIndices[i];
  39396. floatIndices.push(matricesIndex & 0x000000FF);
  39397. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39398. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39399. floatIndices.push(matricesIndex >> 24);
  39400. }
  39401. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39402. }
  39403. else {
  39404. delete parsedGeometry.matricesIndices._isExpanded;
  39405. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39406. }
  39407. }
  39408. if (parsedGeometry.matricesIndicesExtra) {
  39409. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39410. var floatIndices = [];
  39411. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39412. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39413. floatIndices.push(matricesIndex & 0x000000FF);
  39414. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39415. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39416. floatIndices.push(matricesIndex >> 24);
  39417. }
  39418. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39419. }
  39420. else {
  39421. delete parsedGeometry.matricesIndices._isExpanded;
  39422. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39423. }
  39424. }
  39425. if (parsedGeometry.matricesWeights) {
  39426. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39427. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39428. }
  39429. if (parsedGeometry.matricesWeightsExtra) {
  39430. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39431. }
  39432. mesh.setIndices(parsedGeometry.indices, null);
  39433. }
  39434. // SubMeshes
  39435. if (parsedGeometry.subMeshes) {
  39436. mesh.subMeshes = [];
  39437. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39438. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39439. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39440. }
  39441. }
  39442. // Flat shading
  39443. if (mesh._shouldGenerateFlatShading) {
  39444. mesh.convertToFlatShadedMesh();
  39445. delete mesh._shouldGenerateFlatShading;
  39446. }
  39447. // Update
  39448. mesh.computeWorldMatrix(true);
  39449. // Octree
  39450. var sceneOctree = scene.selectionOctree;
  39451. if (sceneOctree !== undefined && sceneOctree !== null) {
  39452. sceneOctree.addMesh(mesh);
  39453. }
  39454. };
  39455. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39456. var epsilon = 1e-3;
  39457. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39458. return;
  39459. }
  39460. var noInfluenceBoneIndex = 0.0;
  39461. if (parsedGeometry.skeletonId > -1) {
  39462. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39463. if (!skeleton) {
  39464. return;
  39465. }
  39466. noInfluenceBoneIndex = skeleton.bones.length;
  39467. }
  39468. else {
  39469. return;
  39470. }
  39471. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39472. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39473. var matricesWeights = parsedGeometry.matricesWeights;
  39474. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39475. var influencers = parsedGeometry.numBoneInfluencer;
  39476. var size = matricesWeights.length;
  39477. for (var i = 0; i < size; i += 4) {
  39478. var weight = 0.0;
  39479. var firstZeroWeight = -1;
  39480. for (var j = 0; j < 4; j++) {
  39481. var w = matricesWeights[i + j];
  39482. weight += w;
  39483. if (w < epsilon && firstZeroWeight < 0) {
  39484. firstZeroWeight = j;
  39485. }
  39486. }
  39487. if (matricesWeightsExtra) {
  39488. for (var j = 0; j < 4; j++) {
  39489. var w = matricesWeightsExtra[i + j];
  39490. weight += w;
  39491. if (w < epsilon && firstZeroWeight < 0) {
  39492. firstZeroWeight = j + 4;
  39493. }
  39494. }
  39495. }
  39496. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39497. firstZeroWeight = influencers - 1;
  39498. }
  39499. if (weight > epsilon) {
  39500. var mweight = 1.0 / weight;
  39501. for (var j = 0; j < 4; j++) {
  39502. matricesWeights[i + j] *= mweight;
  39503. }
  39504. if (matricesWeightsExtra) {
  39505. for (var j = 0; j < 4; j++) {
  39506. matricesWeightsExtra[i + j] *= mweight;
  39507. }
  39508. }
  39509. }
  39510. else {
  39511. if (firstZeroWeight >= 4) {
  39512. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39513. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39514. }
  39515. else {
  39516. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39517. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39518. }
  39519. }
  39520. }
  39521. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39522. if (parsedGeometry.matricesWeightsExtra) {
  39523. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39524. }
  39525. };
  39526. /**
  39527. * Create a new geometry from persisted data (Using .babylon file format)
  39528. * @param parsedVertexData defines the persisted data
  39529. * @param scene defines the hosting scene
  39530. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39531. * @returns the new geometry object
  39532. */
  39533. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39534. if (scene.getGeometryByID(parsedVertexData.id)) {
  39535. return null; // null since geometry could be something else than a box...
  39536. }
  39537. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39538. if (BABYLON.Tags) {
  39539. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39540. }
  39541. if (parsedVertexData.delayLoadingFile) {
  39542. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39543. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39544. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39545. geometry._delayInfo = [];
  39546. if (parsedVertexData.hasUVs) {
  39547. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39548. }
  39549. if (parsedVertexData.hasUVs2) {
  39550. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39551. }
  39552. if (parsedVertexData.hasUVs3) {
  39553. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39554. }
  39555. if (parsedVertexData.hasUVs4) {
  39556. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39557. }
  39558. if (parsedVertexData.hasUVs5) {
  39559. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39560. }
  39561. if (parsedVertexData.hasUVs6) {
  39562. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39563. }
  39564. if (parsedVertexData.hasColors) {
  39565. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39566. }
  39567. if (parsedVertexData.hasMatricesIndices) {
  39568. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39569. }
  39570. if (parsedVertexData.hasMatricesWeights) {
  39571. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39572. }
  39573. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39574. }
  39575. else {
  39576. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39577. }
  39578. scene.pushGeometry(geometry, true);
  39579. return geometry;
  39580. };
  39581. return Geometry;
  39582. }());
  39583. BABYLON.Geometry = Geometry;
  39584. // Primitives
  39585. /// Abstract class
  39586. /**
  39587. * Abstract class used to provide common services for all typed geometries
  39588. * @hidden
  39589. */
  39590. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39591. __extends(_PrimitiveGeometry, _super);
  39592. /**
  39593. * Creates a new typed geometry
  39594. * @param id defines the unique ID of the geometry
  39595. * @param scene defines the hosting scene
  39596. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39597. * @param mesh defines the hosting mesh (can be null)
  39598. */
  39599. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39600. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39601. if (mesh === void 0) { mesh = null; }
  39602. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39603. _this._canBeRegenerated = _canBeRegenerated;
  39604. _this._beingRegenerated = true;
  39605. _this.regenerate();
  39606. _this._beingRegenerated = false;
  39607. return _this;
  39608. }
  39609. /**
  39610. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39611. * @returns true if the geometry can be regenerated
  39612. */
  39613. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39614. return this._canBeRegenerated;
  39615. };
  39616. /**
  39617. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39618. */
  39619. _PrimitiveGeometry.prototype.regenerate = function () {
  39620. if (!this._canBeRegenerated) {
  39621. return;
  39622. }
  39623. this._beingRegenerated = true;
  39624. this.setAllVerticesData(this._regenerateVertexData(), false);
  39625. this._beingRegenerated = false;
  39626. };
  39627. /**
  39628. * Clone the geometry
  39629. * @param id defines the unique ID of the new geometry
  39630. * @returns the new geometry
  39631. */
  39632. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39633. return _super.prototype.copy.call(this, id);
  39634. };
  39635. // overrides
  39636. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39637. if (!this._beingRegenerated) {
  39638. return;
  39639. }
  39640. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39641. };
  39642. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39643. if (!this._beingRegenerated) {
  39644. return;
  39645. }
  39646. _super.prototype.setVerticesData.call(this, kind, data, false);
  39647. };
  39648. // to override
  39649. /** @hidden */
  39650. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39651. throw new Error("Abstract method");
  39652. };
  39653. _PrimitiveGeometry.prototype.copy = function (id) {
  39654. throw new Error("Must be overriden in sub-classes.");
  39655. };
  39656. _PrimitiveGeometry.prototype.serialize = function () {
  39657. var serializationObject = _super.prototype.serialize.call(this);
  39658. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39659. return serializationObject;
  39660. };
  39661. return _PrimitiveGeometry;
  39662. }(Geometry));
  39663. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39664. /**
  39665. * Creates a ribbon geometry
  39666. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39667. */
  39668. var RibbonGeometry = /** @class */ (function (_super) {
  39669. __extends(RibbonGeometry, _super);
  39670. /**
  39671. * Creates a ribbon geometry
  39672. * @param id defines the unique ID of the geometry
  39673. * @param scene defines the hosting scene
  39674. * @param pathArray defines the array of paths to use
  39675. * @param closeArray defines if the last path and the first path must be joined
  39676. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39677. * @param offset defines the offset between points
  39678. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39679. * @param mesh defines the hosting mesh (can be null)
  39680. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39681. */
  39682. function RibbonGeometry(id, scene,
  39683. /**
  39684. * Defines the array of paths to use
  39685. */
  39686. pathArray,
  39687. /**
  39688. * Defines if the last and first points of each path in your pathArray must be joined
  39689. */
  39690. closeArray,
  39691. /**
  39692. * Defines if the last and first points of each path in your pathArray must be joined
  39693. */
  39694. closePath,
  39695. /**
  39696. * Defines the offset between points
  39697. */
  39698. offset, canBeRegenerated, mesh,
  39699. /**
  39700. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39701. */
  39702. side) {
  39703. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39704. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39705. _this.pathArray = pathArray;
  39706. _this.closeArray = closeArray;
  39707. _this.closePath = closePath;
  39708. _this.offset = offset;
  39709. _this.side = side;
  39710. return _this;
  39711. }
  39712. /** @hidden */
  39713. RibbonGeometry.prototype._regenerateVertexData = function () {
  39714. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39715. };
  39716. RibbonGeometry.prototype.copy = function (id) {
  39717. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39718. };
  39719. return RibbonGeometry;
  39720. }(_PrimitiveGeometry));
  39721. BABYLON.RibbonGeometry = RibbonGeometry;
  39722. /**
  39723. * Creates a box geometry
  39724. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39725. */
  39726. var BoxGeometry = /** @class */ (function (_super) {
  39727. __extends(BoxGeometry, _super);
  39728. /**
  39729. * Creates a box geometry
  39730. * @param id defines the unique ID of the geometry
  39731. * @param scene defines the hosting scene
  39732. * @param size defines the zise of the box (width, height and depth are the same)
  39733. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39734. * @param mesh defines the hosting mesh (can be null)
  39735. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39736. */
  39737. function BoxGeometry(id, scene,
  39738. /**
  39739. * Defines the zise of the box (width, height and depth are the same)
  39740. */
  39741. size, canBeRegenerated, mesh,
  39742. /**
  39743. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39744. */
  39745. side) {
  39746. if (mesh === void 0) { mesh = null; }
  39747. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39748. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39749. _this.size = size;
  39750. _this.side = side;
  39751. return _this;
  39752. }
  39753. BoxGeometry.prototype._regenerateVertexData = function () {
  39754. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39755. };
  39756. BoxGeometry.prototype.copy = function (id) {
  39757. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39758. };
  39759. BoxGeometry.prototype.serialize = function () {
  39760. var serializationObject = _super.prototype.serialize.call(this);
  39761. serializationObject.size = this.size;
  39762. return serializationObject;
  39763. };
  39764. BoxGeometry.Parse = function (parsedBox, scene) {
  39765. if (scene.getGeometryByID(parsedBox.id)) {
  39766. return null; // null since geometry could be something else than a box...
  39767. }
  39768. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39769. if (BABYLON.Tags) {
  39770. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39771. }
  39772. scene.pushGeometry(box, true);
  39773. return box;
  39774. };
  39775. return BoxGeometry;
  39776. }(_PrimitiveGeometry));
  39777. BABYLON.BoxGeometry = BoxGeometry;
  39778. /**
  39779. * Creates a sphere geometry
  39780. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39781. */
  39782. var SphereGeometry = /** @class */ (function (_super) {
  39783. __extends(SphereGeometry, _super);
  39784. /**
  39785. * Create a new sphere geometry
  39786. * @param id defines the unique ID of the geometry
  39787. * @param scene defines the hosting scene
  39788. * @param segments defines the number of segments to use to create the sphere
  39789. * @param diameter defines the diameter of the sphere
  39790. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39791. * @param mesh defines the hosting mesh (can be null)
  39792. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39793. */
  39794. function SphereGeometry(id, scene,
  39795. /**
  39796. * Defines the number of segments to use to create the sphere
  39797. */
  39798. segments,
  39799. /**
  39800. * Defines the diameter of the sphere
  39801. */
  39802. diameter, canBeRegenerated, mesh,
  39803. /**
  39804. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39805. */
  39806. side) {
  39807. if (mesh === void 0) { mesh = null; }
  39808. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39809. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39810. _this.segments = segments;
  39811. _this.diameter = diameter;
  39812. _this.side = side;
  39813. return _this;
  39814. }
  39815. SphereGeometry.prototype._regenerateVertexData = function () {
  39816. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39817. };
  39818. SphereGeometry.prototype.copy = function (id) {
  39819. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39820. };
  39821. SphereGeometry.prototype.serialize = function () {
  39822. var serializationObject = _super.prototype.serialize.call(this);
  39823. serializationObject.segments = this.segments;
  39824. serializationObject.diameter = this.diameter;
  39825. return serializationObject;
  39826. };
  39827. SphereGeometry.Parse = function (parsedSphere, scene) {
  39828. if (scene.getGeometryByID(parsedSphere.id)) {
  39829. return null; // null since geometry could be something else than a sphere...
  39830. }
  39831. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39832. if (BABYLON.Tags) {
  39833. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39834. }
  39835. scene.pushGeometry(sphere, true);
  39836. return sphere;
  39837. };
  39838. return SphereGeometry;
  39839. }(_PrimitiveGeometry));
  39840. BABYLON.SphereGeometry = SphereGeometry;
  39841. /**
  39842. * Creates a disc geometry
  39843. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39844. */
  39845. var DiscGeometry = /** @class */ (function (_super) {
  39846. __extends(DiscGeometry, _super);
  39847. /**
  39848. * Creates a new disc geometry
  39849. * @param id defines the unique ID of the geometry
  39850. * @param scene defines the hosting scene
  39851. * @param radius defines the radius of the disc
  39852. * @param tessellation defines the tesselation factor to apply to the disc
  39853. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39854. * @param mesh defines the hosting mesh (can be null)
  39855. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39856. */
  39857. function DiscGeometry(id, scene,
  39858. /**
  39859. * Defines the radius of the disc
  39860. */
  39861. radius,
  39862. /**
  39863. * Defines the tesselation factor to apply to the disc
  39864. */
  39865. tessellation, canBeRegenerated, mesh,
  39866. /**
  39867. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39868. */
  39869. side) {
  39870. if (mesh === void 0) { mesh = null; }
  39871. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39872. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39873. _this.radius = radius;
  39874. _this.tessellation = tessellation;
  39875. _this.side = side;
  39876. return _this;
  39877. }
  39878. DiscGeometry.prototype._regenerateVertexData = function () {
  39879. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39880. };
  39881. DiscGeometry.prototype.copy = function (id) {
  39882. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39883. };
  39884. return DiscGeometry;
  39885. }(_PrimitiveGeometry));
  39886. BABYLON.DiscGeometry = DiscGeometry;
  39887. /**
  39888. * Creates a new cylinder geometry
  39889. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39890. */
  39891. var CylinderGeometry = /** @class */ (function (_super) {
  39892. __extends(CylinderGeometry, _super);
  39893. /**
  39894. * Creates a new cylinder geometry
  39895. * @param id defines the unique ID of the geometry
  39896. * @param scene defines the hosting scene
  39897. * @param height defines the height of the cylinder
  39898. * @param diameterTop defines the diameter of the cylinder's top cap
  39899. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39900. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39901. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39902. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39903. * @param mesh defines the hosting mesh (can be null)
  39904. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39905. */
  39906. function CylinderGeometry(id, scene,
  39907. /**
  39908. * Defines the height of the cylinder
  39909. */
  39910. height,
  39911. /**
  39912. * Defines the diameter of the cylinder's top cap
  39913. */
  39914. diameterTop,
  39915. /**
  39916. * Defines the diameter of the cylinder's bottom cap
  39917. */
  39918. diameterBottom,
  39919. /**
  39920. * Defines the tessellation factor to apply to the cylinder
  39921. */
  39922. tessellation,
  39923. /**
  39924. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39925. */
  39926. subdivisions, canBeRegenerated, mesh,
  39927. /**
  39928. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39929. */
  39930. side) {
  39931. if (subdivisions === void 0) { subdivisions = 1; }
  39932. if (mesh === void 0) { mesh = null; }
  39933. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39934. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39935. _this.height = height;
  39936. _this.diameterTop = diameterTop;
  39937. _this.diameterBottom = diameterBottom;
  39938. _this.tessellation = tessellation;
  39939. _this.subdivisions = subdivisions;
  39940. _this.side = side;
  39941. return _this;
  39942. }
  39943. CylinderGeometry.prototype._regenerateVertexData = function () {
  39944. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39945. };
  39946. CylinderGeometry.prototype.copy = function (id) {
  39947. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39948. };
  39949. CylinderGeometry.prototype.serialize = function () {
  39950. var serializationObject = _super.prototype.serialize.call(this);
  39951. serializationObject.height = this.height;
  39952. serializationObject.diameterTop = this.diameterTop;
  39953. serializationObject.diameterBottom = this.diameterBottom;
  39954. serializationObject.tessellation = this.tessellation;
  39955. return serializationObject;
  39956. };
  39957. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  39958. if (scene.getGeometryByID(parsedCylinder.id)) {
  39959. return null; // null since geometry could be something else than a cylinder...
  39960. }
  39961. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  39962. if (BABYLON.Tags) {
  39963. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  39964. }
  39965. scene.pushGeometry(cylinder, true);
  39966. return cylinder;
  39967. };
  39968. return CylinderGeometry;
  39969. }(_PrimitiveGeometry));
  39970. BABYLON.CylinderGeometry = CylinderGeometry;
  39971. /**
  39972. * Creates a new torus geometry
  39973. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  39974. */
  39975. var TorusGeometry = /** @class */ (function (_super) {
  39976. __extends(TorusGeometry, _super);
  39977. /**
  39978. * Creates a new torus geometry
  39979. * @param id defines the unique ID of the geometry
  39980. * @param scene defines the hosting scene
  39981. * @param diameter defines the diameter of the torus
  39982. * @param thickness defines the thickness of the torus (ie. internal diameter)
  39983. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  39984. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39985. * @param mesh defines the hosting mesh (can be null)
  39986. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39987. */
  39988. function TorusGeometry(id, scene,
  39989. /**
  39990. * Defines the diameter of the torus
  39991. */
  39992. diameter,
  39993. /**
  39994. * Defines the thickness of the torus (ie. internal diameter)
  39995. */
  39996. thickness,
  39997. /**
  39998. * Defines the tesselation factor to apply to the torus
  39999. */
  40000. tessellation, canBeRegenerated, mesh,
  40001. /**
  40002. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40003. */
  40004. side) {
  40005. if (mesh === void 0) { mesh = null; }
  40006. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40007. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40008. _this.diameter = diameter;
  40009. _this.thickness = thickness;
  40010. _this.tessellation = tessellation;
  40011. _this.side = side;
  40012. return _this;
  40013. }
  40014. TorusGeometry.prototype._regenerateVertexData = function () {
  40015. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40016. };
  40017. TorusGeometry.prototype.copy = function (id) {
  40018. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40019. };
  40020. TorusGeometry.prototype.serialize = function () {
  40021. var serializationObject = _super.prototype.serialize.call(this);
  40022. serializationObject.diameter = this.diameter;
  40023. serializationObject.thickness = this.thickness;
  40024. serializationObject.tessellation = this.tessellation;
  40025. return serializationObject;
  40026. };
  40027. TorusGeometry.Parse = function (parsedTorus, scene) {
  40028. if (scene.getGeometryByID(parsedTorus.id)) {
  40029. return null; // null since geometry could be something else than a torus...
  40030. }
  40031. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40032. if (BABYLON.Tags) {
  40033. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40034. }
  40035. scene.pushGeometry(torus, true);
  40036. return torus;
  40037. };
  40038. return TorusGeometry;
  40039. }(_PrimitiveGeometry));
  40040. BABYLON.TorusGeometry = TorusGeometry;
  40041. /**
  40042. * Creates a new ground geometry
  40043. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40044. */
  40045. var GroundGeometry = /** @class */ (function (_super) {
  40046. __extends(GroundGeometry, _super);
  40047. /**
  40048. * Creates a new ground geometry
  40049. * @param id defines the unique ID of the geometry
  40050. * @param scene defines the hosting scene
  40051. * @param width defines the width of the ground
  40052. * @param height defines the height of the ground
  40053. * @param subdivisions defines the subdivisions to apply to the ground
  40054. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40055. * @param mesh defines the hosting mesh (can be null)
  40056. */
  40057. function GroundGeometry(id, scene,
  40058. /**
  40059. * Defines the width of the ground
  40060. */
  40061. width,
  40062. /**
  40063. * Defines the height of the ground
  40064. */
  40065. height,
  40066. /**
  40067. * Defines the subdivisions to apply to the ground
  40068. */
  40069. subdivisions, canBeRegenerated, mesh) {
  40070. if (mesh === void 0) { mesh = null; }
  40071. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40072. _this.width = width;
  40073. _this.height = height;
  40074. _this.subdivisions = subdivisions;
  40075. return _this;
  40076. }
  40077. GroundGeometry.prototype._regenerateVertexData = function () {
  40078. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40079. };
  40080. GroundGeometry.prototype.copy = function (id) {
  40081. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40082. };
  40083. GroundGeometry.prototype.serialize = function () {
  40084. var serializationObject = _super.prototype.serialize.call(this);
  40085. serializationObject.width = this.width;
  40086. serializationObject.height = this.height;
  40087. serializationObject.subdivisions = this.subdivisions;
  40088. return serializationObject;
  40089. };
  40090. GroundGeometry.Parse = function (parsedGround, scene) {
  40091. if (scene.getGeometryByID(parsedGround.id)) {
  40092. return null; // null since geometry could be something else than a ground...
  40093. }
  40094. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40095. if (BABYLON.Tags) {
  40096. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40097. }
  40098. scene.pushGeometry(ground, true);
  40099. return ground;
  40100. };
  40101. return GroundGeometry;
  40102. }(_PrimitiveGeometry));
  40103. BABYLON.GroundGeometry = GroundGeometry;
  40104. /**
  40105. * Creates a tiled ground geometry
  40106. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40107. */
  40108. var TiledGroundGeometry = /** @class */ (function (_super) {
  40109. __extends(TiledGroundGeometry, _super);
  40110. /**
  40111. * Creates a tiled ground geometry
  40112. * @param id defines the unique ID of the geometry
  40113. * @param scene defines the hosting scene
  40114. * @param xmin defines the minimum value on X axis
  40115. * @param zmin defines the minimum value on Z axis
  40116. * @param xmax defines the maximum value on X axis
  40117. * @param zmax defines the maximum value on Z axis
  40118. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40119. * @param precision defines the precision to use when computing the tiles
  40120. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40121. * @param mesh defines the hosting mesh (can be null)
  40122. */
  40123. function TiledGroundGeometry(id, scene,
  40124. /**
  40125. * Defines the minimum value on X axis
  40126. */
  40127. xmin,
  40128. /**
  40129. * Defines the minimum value on Z axis
  40130. */
  40131. zmin,
  40132. /**
  40133. * Defines the maximum value on X axis
  40134. */
  40135. xmax,
  40136. /**
  40137. * Defines the maximum value on Z axis
  40138. */
  40139. zmax,
  40140. /**
  40141. * Defines the subdivisions to apply to the ground
  40142. */
  40143. subdivisions,
  40144. /**
  40145. * Defines the precision to use when computing the tiles
  40146. */
  40147. precision, canBeRegenerated, mesh) {
  40148. if (mesh === void 0) { mesh = null; }
  40149. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40150. _this.xmin = xmin;
  40151. _this.zmin = zmin;
  40152. _this.xmax = xmax;
  40153. _this.zmax = zmax;
  40154. _this.subdivisions = subdivisions;
  40155. _this.precision = precision;
  40156. return _this;
  40157. }
  40158. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40159. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40160. };
  40161. TiledGroundGeometry.prototype.copy = function (id) {
  40162. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40163. };
  40164. return TiledGroundGeometry;
  40165. }(_PrimitiveGeometry));
  40166. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40167. /**
  40168. * Creates a plane geometry
  40169. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40170. */
  40171. var PlaneGeometry = /** @class */ (function (_super) {
  40172. __extends(PlaneGeometry, _super);
  40173. /**
  40174. * Creates a plane geometry
  40175. * @param id defines the unique ID of the geometry
  40176. * @param scene defines the hosting scene
  40177. * @param size defines the size of the plane (width === height)
  40178. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40179. * @param mesh defines the hosting mesh (can be null)
  40180. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40181. */
  40182. function PlaneGeometry(id, scene,
  40183. /**
  40184. * Defines the size of the plane (width === height)
  40185. */
  40186. size, canBeRegenerated, mesh,
  40187. /**
  40188. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40189. */
  40190. side) {
  40191. if (mesh === void 0) { mesh = null; }
  40192. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40193. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40194. _this.size = size;
  40195. _this.side = side;
  40196. return _this;
  40197. }
  40198. PlaneGeometry.prototype._regenerateVertexData = function () {
  40199. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40200. };
  40201. PlaneGeometry.prototype.copy = function (id) {
  40202. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40203. };
  40204. PlaneGeometry.prototype.serialize = function () {
  40205. var serializationObject = _super.prototype.serialize.call(this);
  40206. serializationObject.size = this.size;
  40207. return serializationObject;
  40208. };
  40209. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40210. if (scene.getGeometryByID(parsedPlane.id)) {
  40211. return null; // null since geometry could be something else than a ground...
  40212. }
  40213. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40214. if (BABYLON.Tags) {
  40215. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40216. }
  40217. scene.pushGeometry(plane, true);
  40218. return plane;
  40219. };
  40220. return PlaneGeometry;
  40221. }(_PrimitiveGeometry));
  40222. BABYLON.PlaneGeometry = PlaneGeometry;
  40223. /**
  40224. * Creates a torus knot geometry
  40225. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40226. */
  40227. var TorusKnotGeometry = /** @class */ (function (_super) {
  40228. __extends(TorusKnotGeometry, _super);
  40229. /**
  40230. * Creates a torus knot geometry
  40231. * @param id defines the unique ID of the geometry
  40232. * @param scene defines the hosting scene
  40233. * @param radius defines the radius of the torus knot
  40234. * @param tube defines the thickness of the torus knot tube
  40235. * @param radialSegments defines the number of radial segments
  40236. * @param tubularSegments defines the number of tubular segments
  40237. * @param p defines the first number of windings
  40238. * @param q defines the second number of windings
  40239. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40240. * @param mesh defines the hosting mesh (can be null)
  40241. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40242. */
  40243. function TorusKnotGeometry(id, scene,
  40244. /**
  40245. * Defines the radius of the torus knot
  40246. */
  40247. radius,
  40248. /**
  40249. * Defines the thickness of the torus knot tube
  40250. */
  40251. tube,
  40252. /**
  40253. * Defines the number of radial segments
  40254. */
  40255. radialSegments,
  40256. /**
  40257. * Defines the number of tubular segments
  40258. */
  40259. tubularSegments,
  40260. /**
  40261. * Defines the first number of windings
  40262. */
  40263. p,
  40264. /**
  40265. * Defines the second number of windings
  40266. */
  40267. q, canBeRegenerated, mesh,
  40268. /**
  40269. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40270. */
  40271. side) {
  40272. if (mesh === void 0) { mesh = null; }
  40273. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40274. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40275. _this.radius = radius;
  40276. _this.tube = tube;
  40277. _this.radialSegments = radialSegments;
  40278. _this.tubularSegments = tubularSegments;
  40279. _this.p = p;
  40280. _this.q = q;
  40281. _this.side = side;
  40282. return _this;
  40283. }
  40284. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40285. 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 });
  40286. };
  40287. TorusKnotGeometry.prototype.copy = function (id) {
  40288. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40289. };
  40290. TorusKnotGeometry.prototype.serialize = function () {
  40291. var serializationObject = _super.prototype.serialize.call(this);
  40292. serializationObject.radius = this.radius;
  40293. serializationObject.tube = this.tube;
  40294. serializationObject.radialSegments = this.radialSegments;
  40295. serializationObject.tubularSegments = this.tubularSegments;
  40296. serializationObject.p = this.p;
  40297. serializationObject.q = this.q;
  40298. return serializationObject;
  40299. };
  40300. ;
  40301. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40302. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40303. return null; // null since geometry could be something else than a ground...
  40304. }
  40305. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40306. if (BABYLON.Tags) {
  40307. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40308. }
  40309. scene.pushGeometry(torusKnot, true);
  40310. return torusKnot;
  40311. };
  40312. return TorusKnotGeometry;
  40313. }(_PrimitiveGeometry));
  40314. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40315. //}
  40316. })(BABYLON || (BABYLON = {}));
  40317. //# sourceMappingURL=babylon.geometry.js.map
  40318. var BABYLON;
  40319. (function (BABYLON) {
  40320. /**
  40321. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40322. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40323. */
  40324. var PostProcessManager = /** @class */ (function () {
  40325. /**
  40326. * Creates a new instance PostProcess
  40327. * @param scene The scene that the post process is associated with.
  40328. */
  40329. function PostProcessManager(scene) {
  40330. this._vertexBuffers = {};
  40331. this._scene = scene;
  40332. }
  40333. PostProcessManager.prototype._prepareBuffers = function () {
  40334. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40335. return;
  40336. }
  40337. // VBO
  40338. var vertices = [];
  40339. vertices.push(1, 1);
  40340. vertices.push(-1, 1);
  40341. vertices.push(-1, -1);
  40342. vertices.push(1, -1);
  40343. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40344. this._buildIndexBuffer();
  40345. };
  40346. PostProcessManager.prototype._buildIndexBuffer = function () {
  40347. // Indices
  40348. var indices = [];
  40349. indices.push(0);
  40350. indices.push(1);
  40351. indices.push(2);
  40352. indices.push(0);
  40353. indices.push(2);
  40354. indices.push(3);
  40355. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40356. };
  40357. /**
  40358. * Rebuilds the vertex buffers of the manager.
  40359. */
  40360. PostProcessManager.prototype._rebuild = function () {
  40361. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40362. if (!vb) {
  40363. return;
  40364. }
  40365. vb._rebuild();
  40366. this._buildIndexBuffer();
  40367. };
  40368. // Methods
  40369. /**
  40370. * Prepares a frame to be run through a post process.
  40371. * @param sourceTexture The input texture to the post procesess. (default: null)
  40372. * @param postProcesses An array of post processes to be run. (default: null)
  40373. * @returns True if the post processes were able to be run.
  40374. */
  40375. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40376. if (sourceTexture === void 0) { sourceTexture = null; }
  40377. if (postProcesses === void 0) { postProcesses = null; }
  40378. var camera = this._scene.activeCamera;
  40379. if (!camera) {
  40380. return false;
  40381. }
  40382. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40383. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40384. return false;
  40385. }
  40386. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40387. return true;
  40388. };
  40389. /**
  40390. * Manually render a set of post processes to a texture.
  40391. * @param postProcesses An array of post processes to be run.
  40392. * @param targetTexture The target texture to render to.
  40393. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40394. */
  40395. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40396. if (targetTexture === void 0) { targetTexture = null; }
  40397. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40398. var engine = this._scene.getEngine();
  40399. for (var index = 0; index < postProcesses.length; index++) {
  40400. if (index < postProcesses.length - 1) {
  40401. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40402. }
  40403. else {
  40404. if (targetTexture) {
  40405. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40406. }
  40407. else {
  40408. engine.restoreDefaultFramebuffer();
  40409. }
  40410. }
  40411. var pp = postProcesses[index];
  40412. var effect = pp.apply();
  40413. if (effect) {
  40414. pp.onBeforeRenderObservable.notifyObservers(effect);
  40415. // VBOs
  40416. this._prepareBuffers();
  40417. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40418. // Draw order
  40419. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40420. pp.onAfterRenderObservable.notifyObservers(effect);
  40421. }
  40422. }
  40423. // Restore depth buffer
  40424. engine.setDepthBuffer(true);
  40425. engine.setDepthWrite(true);
  40426. };
  40427. /**
  40428. * Finalize the result of the output of the postprocesses.
  40429. * @param doNotPresent If true the result will not be displayed to the screen.
  40430. * @param targetTexture The target texture to render to.
  40431. * @param faceIndex The index of the face to bind the target texture to.
  40432. * @param postProcesses The array of post processes to render.
  40433. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40434. */
  40435. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40436. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40437. var camera = this._scene.activeCamera;
  40438. if (!camera) {
  40439. return;
  40440. }
  40441. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40442. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40443. return;
  40444. }
  40445. var engine = this._scene.getEngine();
  40446. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40447. var pp = postProcesses[index];
  40448. if (index < len - 1) {
  40449. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40450. }
  40451. else {
  40452. if (targetTexture) {
  40453. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40454. pp._outputTexture = targetTexture;
  40455. }
  40456. else {
  40457. engine.restoreDefaultFramebuffer();
  40458. pp._outputTexture = null;
  40459. }
  40460. }
  40461. if (doNotPresent) {
  40462. break;
  40463. }
  40464. var effect = pp.apply();
  40465. if (effect) {
  40466. pp.onBeforeRenderObservable.notifyObservers(effect);
  40467. // VBOs
  40468. this._prepareBuffers();
  40469. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40470. // Draw order
  40471. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40472. pp.onAfterRenderObservable.notifyObservers(effect);
  40473. }
  40474. }
  40475. // Restore states
  40476. engine.setDepthBuffer(true);
  40477. engine.setDepthWrite(true);
  40478. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40479. };
  40480. /**
  40481. * Disposes of the post process manager.
  40482. */
  40483. PostProcessManager.prototype.dispose = function () {
  40484. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40485. if (buffer) {
  40486. buffer.dispose();
  40487. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40488. }
  40489. if (this._indexBuffer) {
  40490. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40491. this._indexBuffer = null;
  40492. }
  40493. };
  40494. return PostProcessManager;
  40495. }());
  40496. BABYLON.PostProcessManager = PostProcessManager;
  40497. })(BABYLON || (BABYLON = {}));
  40498. //# sourceMappingURL=babylon.postProcessManager.js.map
  40499. var BABYLON;
  40500. (function (BABYLON) {
  40501. /**
  40502. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40503. */
  40504. var PerformanceMonitor = /** @class */ (function () {
  40505. /**
  40506. * constructor
  40507. * @param frameSampleSize The number of samples required to saturate the sliding window
  40508. */
  40509. function PerformanceMonitor(frameSampleSize) {
  40510. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40511. this._enabled = true;
  40512. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40513. }
  40514. /**
  40515. * Samples current frame
  40516. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40517. */
  40518. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40519. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40520. if (!this._enabled)
  40521. return;
  40522. if (this._lastFrameTimeMs != null) {
  40523. var dt = timeMs - this._lastFrameTimeMs;
  40524. this._rollingFrameTime.add(dt);
  40525. }
  40526. this._lastFrameTimeMs = timeMs;
  40527. };
  40528. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40529. /**
  40530. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40531. * @return Average frame time in milliseconds
  40532. */
  40533. get: function () {
  40534. return this._rollingFrameTime.average;
  40535. },
  40536. enumerable: true,
  40537. configurable: true
  40538. });
  40539. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40540. /**
  40541. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40542. * @return Frame time variance in milliseconds squared
  40543. */
  40544. get: function () {
  40545. return this._rollingFrameTime.variance;
  40546. },
  40547. enumerable: true,
  40548. configurable: true
  40549. });
  40550. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40551. /**
  40552. * Returns the frame time of the most recent frame
  40553. * @return Frame time in milliseconds
  40554. */
  40555. get: function () {
  40556. return this._rollingFrameTime.history(0);
  40557. },
  40558. enumerable: true,
  40559. configurable: true
  40560. });
  40561. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40562. /**
  40563. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40564. * @return Framerate in frames per second
  40565. */
  40566. get: function () {
  40567. return 1000.0 / this._rollingFrameTime.average;
  40568. },
  40569. enumerable: true,
  40570. configurable: true
  40571. });
  40572. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40573. /**
  40574. * Returns the average framerate in frames per second using the most recent frame time
  40575. * @return Framerate in frames per second
  40576. */
  40577. get: function () {
  40578. var history = this._rollingFrameTime.history(0);
  40579. if (history === 0) {
  40580. return 0;
  40581. }
  40582. return 1000.0 / history;
  40583. },
  40584. enumerable: true,
  40585. configurable: true
  40586. });
  40587. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40588. /**
  40589. * Returns true if enough samples have been taken to completely fill the sliding window
  40590. * @return true if saturated
  40591. */
  40592. get: function () {
  40593. return this._rollingFrameTime.isSaturated();
  40594. },
  40595. enumerable: true,
  40596. configurable: true
  40597. });
  40598. /**
  40599. * Enables contributions to the sliding window sample set
  40600. */
  40601. PerformanceMonitor.prototype.enable = function () {
  40602. this._enabled = true;
  40603. };
  40604. /**
  40605. * Disables contributions to the sliding window sample set
  40606. * Samples will not be interpolated over the disabled period
  40607. */
  40608. PerformanceMonitor.prototype.disable = function () {
  40609. this._enabled = false;
  40610. //clear last sample to avoid interpolating over the disabled period when next enabled
  40611. this._lastFrameTimeMs = null;
  40612. };
  40613. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40614. /**
  40615. * Returns true if sampling is enabled
  40616. * @return true if enabled
  40617. */
  40618. get: function () {
  40619. return this._enabled;
  40620. },
  40621. enumerable: true,
  40622. configurable: true
  40623. });
  40624. /**
  40625. * Resets performance monitor
  40626. */
  40627. PerformanceMonitor.prototype.reset = function () {
  40628. //clear last sample to avoid interpolating over the disabled period when next enabled
  40629. this._lastFrameTimeMs = null;
  40630. //wipe record
  40631. this._rollingFrameTime.reset();
  40632. };
  40633. return PerformanceMonitor;
  40634. }());
  40635. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40636. /**
  40637. * RollingAverage
  40638. *
  40639. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40640. */
  40641. var RollingAverage = /** @class */ (function () {
  40642. /**
  40643. * constructor
  40644. * @param length The number of samples required to saturate the sliding window
  40645. */
  40646. function RollingAverage(length) {
  40647. this._samples = new Array(length);
  40648. this.reset();
  40649. }
  40650. /**
  40651. * Adds a sample to the sample set
  40652. * @param v The sample value
  40653. */
  40654. RollingAverage.prototype.add = function (v) {
  40655. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40656. var delta;
  40657. //we need to check if we've already wrapped round
  40658. if (this.isSaturated()) {
  40659. //remove bottom of stack from mean
  40660. var bottomValue = this._samples[this._pos];
  40661. delta = bottomValue - this.average;
  40662. this.average -= delta / (this._sampleCount - 1);
  40663. this._m2 -= delta * (bottomValue - this.average);
  40664. }
  40665. else {
  40666. this._sampleCount++;
  40667. }
  40668. //add new value to mean
  40669. delta = v - this.average;
  40670. this.average += delta / (this._sampleCount);
  40671. this._m2 += delta * (v - this.average);
  40672. //set the new variance
  40673. this.variance = this._m2 / (this._sampleCount - 1);
  40674. this._samples[this._pos] = v;
  40675. this._pos++;
  40676. this._pos %= this._samples.length; //positive wrap around
  40677. };
  40678. /**
  40679. * Returns previously added values or null if outside of history or outside the sliding window domain
  40680. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40681. * @return Value previously recorded with add() or null if outside of range
  40682. */
  40683. RollingAverage.prototype.history = function (i) {
  40684. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40685. return 0;
  40686. }
  40687. var i0 = this._wrapPosition(this._pos - 1.0);
  40688. return this._samples[this._wrapPosition(i0 - i)];
  40689. };
  40690. /**
  40691. * Returns true if enough samples have been taken to completely fill the sliding window
  40692. * @return true if sample-set saturated
  40693. */
  40694. RollingAverage.prototype.isSaturated = function () {
  40695. return this._sampleCount >= this._samples.length;
  40696. };
  40697. /**
  40698. * Resets the rolling average (equivalent to 0 samples taken so far)
  40699. */
  40700. RollingAverage.prototype.reset = function () {
  40701. this.average = 0;
  40702. this.variance = 0;
  40703. this._sampleCount = 0;
  40704. this._pos = 0;
  40705. this._m2 = 0;
  40706. };
  40707. /**
  40708. * Wraps a value around the sample range boundaries
  40709. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40710. * @return Wrapped position in sample range
  40711. */
  40712. RollingAverage.prototype._wrapPosition = function (i) {
  40713. var max = this._samples.length;
  40714. return ((i % max) + max) % max;
  40715. };
  40716. return RollingAverage;
  40717. }());
  40718. BABYLON.RollingAverage = RollingAverage;
  40719. })(BABYLON || (BABYLON = {}));
  40720. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40721. var BABYLON;
  40722. (function (BABYLON) {
  40723. /**
  40724. * This groups together the common properties used for image processing either in direct forward pass
  40725. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40726. * or not.
  40727. */
  40728. var ImageProcessingConfiguration = /** @class */ (function () {
  40729. function ImageProcessingConfiguration() {
  40730. /**
  40731. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40732. */
  40733. this.colorCurves = new BABYLON.ColorCurves();
  40734. this._colorCurvesEnabled = false;
  40735. this._colorGradingEnabled = false;
  40736. this._colorGradingWithGreenDepth = true;
  40737. this._colorGradingBGR = true;
  40738. this._exposure = 1.0;
  40739. this._toneMappingEnabled = false;
  40740. this._contrast = 1.0;
  40741. /**
  40742. * Vignette stretch size.
  40743. */
  40744. this.vignetteStretch = 0;
  40745. /**
  40746. * Vignette centre X Offset.
  40747. */
  40748. this.vignetteCentreX = 0;
  40749. /**
  40750. * Vignette centre Y Offset.
  40751. */
  40752. this.vignetteCentreY = 0;
  40753. /**
  40754. * Vignette weight or intensity of the vignette effect.
  40755. */
  40756. this.vignetteWeight = 1.5;
  40757. /**
  40758. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40759. * if vignetteEnabled is set to true.
  40760. */
  40761. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40762. /**
  40763. * Camera field of view used by the Vignette effect.
  40764. */
  40765. this.vignetteCameraFov = 0.5;
  40766. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40767. this._vignetteEnabled = false;
  40768. this._applyByPostProcess = false;
  40769. this._isEnabled = true;
  40770. /**
  40771. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40772. */
  40773. this.onUpdateParameters = new BABYLON.Observable();
  40774. }
  40775. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40776. /**
  40777. * Gets wether the color curves effect is enabled.
  40778. */
  40779. get: function () {
  40780. return this._colorCurvesEnabled;
  40781. },
  40782. /**
  40783. * Sets wether the color curves effect is enabled.
  40784. */
  40785. set: function (value) {
  40786. if (this._colorCurvesEnabled === value) {
  40787. return;
  40788. }
  40789. this._colorCurvesEnabled = value;
  40790. this._updateParameters();
  40791. },
  40792. enumerable: true,
  40793. configurable: true
  40794. });
  40795. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40796. /**
  40797. * Gets wether the color grading effect is enabled.
  40798. */
  40799. get: function () {
  40800. return this._colorGradingEnabled;
  40801. },
  40802. /**
  40803. * Sets wether the color grading effect is enabled.
  40804. */
  40805. set: function (value) {
  40806. if (this._colorGradingEnabled === value) {
  40807. return;
  40808. }
  40809. this._colorGradingEnabled = value;
  40810. this._updateParameters();
  40811. },
  40812. enumerable: true,
  40813. configurable: true
  40814. });
  40815. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40816. /**
  40817. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40818. */
  40819. get: function () {
  40820. return this._colorGradingWithGreenDepth;
  40821. },
  40822. /**
  40823. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40824. */
  40825. set: function (value) {
  40826. if (this._colorGradingWithGreenDepth === value) {
  40827. return;
  40828. }
  40829. this._colorGradingWithGreenDepth = value;
  40830. this._updateParameters();
  40831. },
  40832. enumerable: true,
  40833. configurable: true
  40834. });
  40835. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40836. /**
  40837. * Gets wether the color grading texture contains BGR values.
  40838. */
  40839. get: function () {
  40840. return this._colorGradingBGR;
  40841. },
  40842. /**
  40843. * Sets wether the color grading texture contains BGR values.
  40844. */
  40845. set: function (value) {
  40846. if (this._colorGradingBGR === value) {
  40847. return;
  40848. }
  40849. this._colorGradingBGR = value;
  40850. this._updateParameters();
  40851. },
  40852. enumerable: true,
  40853. configurable: true
  40854. });
  40855. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40856. /**
  40857. * Gets the Exposure used in the effect.
  40858. */
  40859. get: function () {
  40860. return this._exposure;
  40861. },
  40862. /**
  40863. * Sets the Exposure used in the effect.
  40864. */
  40865. set: function (value) {
  40866. if (this._exposure === value) {
  40867. return;
  40868. }
  40869. this._exposure = value;
  40870. this._updateParameters();
  40871. },
  40872. enumerable: true,
  40873. configurable: true
  40874. });
  40875. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40876. /**
  40877. * Gets wether the tone mapping effect is enabled.
  40878. */
  40879. get: function () {
  40880. return this._toneMappingEnabled;
  40881. },
  40882. /**
  40883. * Sets wether the tone mapping effect is enabled.
  40884. */
  40885. set: function (value) {
  40886. if (this._toneMappingEnabled === value) {
  40887. return;
  40888. }
  40889. this._toneMappingEnabled = value;
  40890. this._updateParameters();
  40891. },
  40892. enumerable: true,
  40893. configurable: true
  40894. });
  40895. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40896. /**
  40897. * Gets the contrast used in the effect.
  40898. */
  40899. get: function () {
  40900. return this._contrast;
  40901. },
  40902. /**
  40903. * Sets the contrast used in the effect.
  40904. */
  40905. set: function (value) {
  40906. if (this._contrast === value) {
  40907. return;
  40908. }
  40909. this._contrast = value;
  40910. this._updateParameters();
  40911. },
  40912. enumerable: true,
  40913. configurable: true
  40914. });
  40915. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40916. /**
  40917. * Gets the vignette blend mode allowing different kind of effect.
  40918. */
  40919. get: function () {
  40920. return this._vignetteBlendMode;
  40921. },
  40922. /**
  40923. * Sets the vignette blend mode allowing different kind of effect.
  40924. */
  40925. set: function (value) {
  40926. if (this._vignetteBlendMode === value) {
  40927. return;
  40928. }
  40929. this._vignetteBlendMode = value;
  40930. this._updateParameters();
  40931. },
  40932. enumerable: true,
  40933. configurable: true
  40934. });
  40935. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  40936. /**
  40937. * Gets wether the vignette effect is enabled.
  40938. */
  40939. get: function () {
  40940. return this._vignetteEnabled;
  40941. },
  40942. /**
  40943. * Sets wether the vignette effect is enabled.
  40944. */
  40945. set: function (value) {
  40946. if (this._vignetteEnabled === value) {
  40947. return;
  40948. }
  40949. this._vignetteEnabled = value;
  40950. this._updateParameters();
  40951. },
  40952. enumerable: true,
  40953. configurable: true
  40954. });
  40955. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  40956. /**
  40957. * Gets wether the image processing is applied through a post process or not.
  40958. */
  40959. get: function () {
  40960. return this._applyByPostProcess;
  40961. },
  40962. /**
  40963. * Sets wether the image processing is applied through a post process or not.
  40964. */
  40965. set: function (value) {
  40966. if (this._applyByPostProcess === value) {
  40967. return;
  40968. }
  40969. this._applyByPostProcess = value;
  40970. this._updateParameters();
  40971. },
  40972. enumerable: true,
  40973. configurable: true
  40974. });
  40975. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  40976. /**
  40977. * Gets wether the image processing is enabled or not.
  40978. */
  40979. get: function () {
  40980. return this._isEnabled;
  40981. },
  40982. /**
  40983. * Sets wether the image processing is enabled or not.
  40984. */
  40985. set: function (value) {
  40986. if (this._isEnabled === value) {
  40987. return;
  40988. }
  40989. this._isEnabled = value;
  40990. this._updateParameters();
  40991. },
  40992. enumerable: true,
  40993. configurable: true
  40994. });
  40995. /**
  40996. * Method called each time the image processing information changes requires to recompile the effect.
  40997. */
  40998. ImageProcessingConfiguration.prototype._updateParameters = function () {
  40999. this.onUpdateParameters.notifyObservers(this);
  41000. };
  41001. ImageProcessingConfiguration.prototype.getClassName = function () {
  41002. return "ImageProcessingConfiguration";
  41003. };
  41004. /**
  41005. * Prepare the list of uniforms associated with the Image Processing effects.
  41006. * @param uniformsList The list of uniforms used in the effect
  41007. * @param defines the list of defines currently in use
  41008. */
  41009. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41010. if (defines.EXPOSURE) {
  41011. uniforms.push("exposureLinear");
  41012. }
  41013. if (defines.CONTRAST) {
  41014. uniforms.push("contrast");
  41015. }
  41016. if (defines.COLORGRADING) {
  41017. uniforms.push("colorTransformSettings");
  41018. }
  41019. if (defines.VIGNETTE) {
  41020. uniforms.push("vInverseScreenSize");
  41021. uniforms.push("vignetteSettings1");
  41022. uniforms.push("vignetteSettings2");
  41023. }
  41024. if (defines.COLORCURVES) {
  41025. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41026. }
  41027. };
  41028. /**
  41029. * Prepare the list of samplers associated with the Image Processing effects.
  41030. * @param uniformsList The list of uniforms used in the effect
  41031. * @param defines the list of defines currently in use
  41032. */
  41033. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41034. if (defines.COLORGRADING) {
  41035. samplersList.push("txColorTransform");
  41036. }
  41037. };
  41038. /**
  41039. * Prepare the list of defines associated to the shader.
  41040. * @param defines the list of defines to complete
  41041. */
  41042. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41043. if (forPostProcess === void 0) { forPostProcess = false; }
  41044. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41045. defines.VIGNETTE = false;
  41046. defines.TONEMAPPING = false;
  41047. defines.CONTRAST = false;
  41048. defines.EXPOSURE = false;
  41049. defines.COLORCURVES = false;
  41050. defines.COLORGRADING = false;
  41051. defines.COLORGRADING3D = false;
  41052. defines.IMAGEPROCESSING = false;
  41053. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41054. return;
  41055. }
  41056. defines.VIGNETTE = this.vignetteEnabled;
  41057. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41058. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41059. defines.TONEMAPPING = this.toneMappingEnabled;
  41060. defines.CONTRAST = (this.contrast !== 1.0);
  41061. defines.EXPOSURE = (this.exposure !== 1.0);
  41062. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41063. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41064. if (defines.COLORGRADING) {
  41065. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41066. }
  41067. else {
  41068. defines.COLORGRADING3D = false;
  41069. }
  41070. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41071. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41072. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41073. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41074. };
  41075. /**
  41076. * Returns true if all the image processing information are ready.
  41077. */
  41078. ImageProcessingConfiguration.prototype.isReady = function () {
  41079. // Color Grading texure can not be none blocking.
  41080. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41081. };
  41082. /**
  41083. * Binds the image processing to the shader.
  41084. * @param effect The effect to bind to
  41085. */
  41086. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41087. if (aspectRatio === void 0) { aspectRatio = 1; }
  41088. // Color Curves
  41089. if (this._colorCurvesEnabled && this.colorCurves) {
  41090. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41091. }
  41092. // Vignette
  41093. if (this._vignetteEnabled) {
  41094. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41095. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41096. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41097. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41098. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41099. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41100. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41101. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41102. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41103. var vignettePower = -2.0 * this.vignetteWeight;
  41104. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41105. }
  41106. // Exposure
  41107. effect.setFloat("exposureLinear", this.exposure);
  41108. // Contrast
  41109. effect.setFloat("contrast", this.contrast);
  41110. // Color transform settings
  41111. if (this.colorGradingTexture) {
  41112. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41113. var textureSize = this.colorGradingTexture.getSize().height;
  41114. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41115. 0.5 / textureSize, // textureOffset
  41116. textureSize, // textureSize
  41117. this.colorGradingTexture.level // weight
  41118. );
  41119. }
  41120. };
  41121. /**
  41122. * Clones the current image processing instance.
  41123. * @return The cloned image processing
  41124. */
  41125. ImageProcessingConfiguration.prototype.clone = function () {
  41126. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41127. };
  41128. /**
  41129. * Serializes the current image processing instance to a json representation.
  41130. * @return a JSON representation
  41131. */
  41132. ImageProcessingConfiguration.prototype.serialize = function () {
  41133. return BABYLON.SerializationHelper.Serialize(this);
  41134. };
  41135. /**
  41136. * Parses the image processing from a json representation.
  41137. * @param source the JSON source to parse
  41138. * @return The parsed image processing
  41139. */
  41140. ImageProcessingConfiguration.Parse = function (source) {
  41141. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41142. };
  41143. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41144. /**
  41145. * Used to apply the vignette as a mix with the pixel color.
  41146. */
  41147. get: function () {
  41148. return this._VIGNETTEMODE_MULTIPLY;
  41149. },
  41150. enumerable: true,
  41151. configurable: true
  41152. });
  41153. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41154. /**
  41155. * Used to apply the vignette as a replacement of the pixel color.
  41156. */
  41157. get: function () {
  41158. return this._VIGNETTEMODE_OPAQUE;
  41159. },
  41160. enumerable: true,
  41161. configurable: true
  41162. });
  41163. // Static constants associated to the image processing.
  41164. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41165. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41166. __decorate([
  41167. BABYLON.serializeAsColorCurves()
  41168. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41169. __decorate([
  41170. BABYLON.serialize()
  41171. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41172. __decorate([
  41173. BABYLON.serializeAsTexture()
  41174. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41175. __decorate([
  41176. BABYLON.serialize()
  41177. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41178. __decorate([
  41179. BABYLON.serialize()
  41180. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41181. __decorate([
  41182. BABYLON.serialize()
  41183. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41184. __decorate([
  41185. BABYLON.serialize()
  41186. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41187. __decorate([
  41188. BABYLON.serialize()
  41189. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41190. __decorate([
  41191. BABYLON.serialize()
  41192. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41193. __decorate([
  41194. BABYLON.serialize()
  41195. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41196. __decorate([
  41197. BABYLON.serialize()
  41198. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41199. __decorate([
  41200. BABYLON.serialize()
  41201. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41202. __decorate([
  41203. BABYLON.serialize()
  41204. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41205. __decorate([
  41206. BABYLON.serializeAsColor4()
  41207. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41208. __decorate([
  41209. BABYLON.serialize()
  41210. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41211. __decorate([
  41212. BABYLON.serialize()
  41213. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41214. __decorate([
  41215. BABYLON.serialize()
  41216. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41217. __decorate([
  41218. BABYLON.serialize()
  41219. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41220. __decorate([
  41221. BABYLON.serialize()
  41222. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41223. return ImageProcessingConfiguration;
  41224. }());
  41225. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41226. })(BABYLON || (BABYLON = {}));
  41227. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41228. var BABYLON;
  41229. (function (BABYLON) {
  41230. /**
  41231. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41232. * It can help converting any input color in a desired output one. This can then be used to create effects
  41233. * from sepia, black and white to sixties or futuristic rendering...
  41234. *
  41235. * The only supported format is currently 3dl.
  41236. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41237. */
  41238. var ColorGradingTexture = /** @class */ (function (_super) {
  41239. __extends(ColorGradingTexture, _super);
  41240. /**
  41241. * Instantiates a ColorGradingTexture from the following parameters.
  41242. *
  41243. * @param url The location of the color gradind data (currently only supporting 3dl)
  41244. * @param scene The scene the texture will be used in
  41245. */
  41246. function ColorGradingTexture(url, scene) {
  41247. var _this = _super.call(this, scene) || this;
  41248. if (!url) {
  41249. return _this;
  41250. }
  41251. _this._engine = scene.getEngine();
  41252. _this._textureMatrix = BABYLON.Matrix.Identity();
  41253. _this.name = url;
  41254. _this.url = url;
  41255. _this.hasAlpha = false;
  41256. _this.isCube = false;
  41257. _this.is3D = _this._engine.webGLVersion > 1;
  41258. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41259. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41260. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41261. _this.anisotropicFilteringLevel = 1;
  41262. _this._texture = _this._getFromCache(url, true);
  41263. if (!_this._texture) {
  41264. if (!scene.useDelayedTextureLoading) {
  41265. _this.loadTexture();
  41266. }
  41267. else {
  41268. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41269. }
  41270. }
  41271. return _this;
  41272. }
  41273. /**
  41274. * Returns the texture matrix used in most of the material.
  41275. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41276. */
  41277. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41278. return this._textureMatrix;
  41279. };
  41280. /**
  41281. * Occurs when the file being loaded is a .3dl LUT file.
  41282. */
  41283. ColorGradingTexture.prototype.load3dlTexture = function () {
  41284. var engine = this._engine;
  41285. var texture;
  41286. if (engine.webGLVersion === 1) {
  41287. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41288. }
  41289. else {
  41290. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41291. }
  41292. this._texture = texture;
  41293. var callback = function (text) {
  41294. if (typeof text !== "string") {
  41295. return;
  41296. }
  41297. var data = null;
  41298. var tempData = null;
  41299. var line;
  41300. var lines = text.split('\n');
  41301. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41302. var maxColor = 0;
  41303. for (var i = 0; i < lines.length; i++) {
  41304. line = lines[i];
  41305. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41306. continue;
  41307. if (line.indexOf('#') === 0)
  41308. continue;
  41309. var words = line.split(" ");
  41310. if (size === 0) {
  41311. // Number of space + one
  41312. size = words.length;
  41313. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41314. tempData = new Float32Array(size * size * size * 4);
  41315. continue;
  41316. }
  41317. if (size != 0) {
  41318. var r = Math.max(parseInt(words[0]), 0);
  41319. var g = Math.max(parseInt(words[1]), 0);
  41320. var b = Math.max(parseInt(words[2]), 0);
  41321. maxColor = Math.max(r, maxColor);
  41322. maxColor = Math.max(g, maxColor);
  41323. maxColor = Math.max(b, maxColor);
  41324. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41325. if (tempData) {
  41326. tempData[pixelStorageIndex + 0] = r;
  41327. tempData[pixelStorageIndex + 1] = g;
  41328. tempData[pixelStorageIndex + 2] = b;
  41329. }
  41330. pixelIndexSlice++;
  41331. if (pixelIndexSlice % size == 0) {
  41332. pixelIndexH++;
  41333. pixelIndexSlice = 0;
  41334. if (pixelIndexH % size == 0) {
  41335. pixelIndexW++;
  41336. pixelIndexH = 0;
  41337. }
  41338. }
  41339. }
  41340. }
  41341. if (tempData && data) {
  41342. for (var i = 0; i < tempData.length; i++) {
  41343. if (i > 0 && (i + 1) % 4 === 0) {
  41344. data[i] = 255;
  41345. }
  41346. else {
  41347. var value = tempData[i];
  41348. data[i] = (value / maxColor * 255);
  41349. }
  41350. }
  41351. }
  41352. if (texture.is3D) {
  41353. texture.updateSize(size, size, size);
  41354. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41355. }
  41356. else {
  41357. texture.updateSize(size * size, size);
  41358. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41359. }
  41360. };
  41361. var scene = this.getScene();
  41362. if (scene) {
  41363. scene._loadFile(this.url, callback);
  41364. }
  41365. else {
  41366. this._engine._loadFile(this.url, callback);
  41367. }
  41368. return this._texture;
  41369. };
  41370. /**
  41371. * Starts the loading process of the texture.
  41372. */
  41373. ColorGradingTexture.prototype.loadTexture = function () {
  41374. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41375. this.load3dlTexture();
  41376. }
  41377. };
  41378. /**
  41379. * Clones the color gradind texture.
  41380. */
  41381. ColorGradingTexture.prototype.clone = function () {
  41382. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41383. // Base texture
  41384. newTexture.level = this.level;
  41385. return newTexture;
  41386. };
  41387. /**
  41388. * Called during delayed load for textures.
  41389. */
  41390. ColorGradingTexture.prototype.delayLoad = function () {
  41391. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41392. return;
  41393. }
  41394. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41395. this._texture = this._getFromCache(this.url, true);
  41396. if (!this._texture) {
  41397. this.loadTexture();
  41398. }
  41399. };
  41400. /**
  41401. * Parses a color grading texture serialized by Babylon.
  41402. * @param parsedTexture The texture information being parsedTexture
  41403. * @param scene The scene to load the texture in
  41404. * @param rootUrl The root url of the data assets to load
  41405. * @return A color gradind texture
  41406. */
  41407. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41408. var texture = null;
  41409. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41410. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41411. texture.name = parsedTexture.name;
  41412. texture.level = parsedTexture.level;
  41413. }
  41414. return texture;
  41415. };
  41416. /**
  41417. * Serializes the LUT texture to json format.
  41418. */
  41419. ColorGradingTexture.prototype.serialize = function () {
  41420. if (!this.name) {
  41421. return null;
  41422. }
  41423. var serializationObject = {};
  41424. serializationObject.name = this.name;
  41425. serializationObject.level = this.level;
  41426. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41427. return serializationObject;
  41428. };
  41429. /**
  41430. * Empty line regex stored for GC.
  41431. */
  41432. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41433. return ColorGradingTexture;
  41434. }(BABYLON.BaseTexture));
  41435. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41436. })(BABYLON || (BABYLON = {}));
  41437. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41438. var BABYLON;
  41439. (function (BABYLON) {
  41440. /**
  41441. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41442. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41443. * 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;
  41444. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41445. */
  41446. var ColorCurves = /** @class */ (function () {
  41447. function ColorCurves() {
  41448. this._dirty = true;
  41449. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41450. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41451. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41452. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41453. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41454. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41455. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41456. this._globalHue = 30;
  41457. this._globalDensity = 0;
  41458. this._globalSaturation = 0;
  41459. this._globalExposure = 0;
  41460. this._highlightsHue = 30;
  41461. this._highlightsDensity = 0;
  41462. this._highlightsSaturation = 0;
  41463. this._highlightsExposure = 0;
  41464. this._midtonesHue = 30;
  41465. this._midtonesDensity = 0;
  41466. this._midtonesSaturation = 0;
  41467. this._midtonesExposure = 0;
  41468. this._shadowsHue = 30;
  41469. this._shadowsDensity = 0;
  41470. this._shadowsSaturation = 0;
  41471. this._shadowsExposure = 0;
  41472. }
  41473. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41474. /**
  41475. * Gets the global Hue value.
  41476. * 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).
  41477. */
  41478. get: function () {
  41479. return this._globalHue;
  41480. },
  41481. /**
  41482. * Sets the global Hue value.
  41483. * 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).
  41484. */
  41485. set: function (value) {
  41486. this._globalHue = value;
  41487. this._dirty = true;
  41488. },
  41489. enumerable: true,
  41490. configurable: true
  41491. });
  41492. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41493. /**
  41494. * Gets the global Density value.
  41495. * 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.
  41496. * Values less than zero provide a filter of opposite hue.
  41497. */
  41498. get: function () {
  41499. return this._globalDensity;
  41500. },
  41501. /**
  41502. * Sets the global Density value.
  41503. * 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.
  41504. * Values less than zero provide a filter of opposite hue.
  41505. */
  41506. set: function (value) {
  41507. this._globalDensity = value;
  41508. this._dirty = true;
  41509. },
  41510. enumerable: true,
  41511. configurable: true
  41512. });
  41513. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41514. /**
  41515. * Gets the global Saturation value.
  41516. * 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.
  41517. */
  41518. get: function () {
  41519. return this._globalSaturation;
  41520. },
  41521. /**
  41522. * Sets the global Saturation value.
  41523. * 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.
  41524. */
  41525. set: function (value) {
  41526. this._globalSaturation = value;
  41527. this._dirty = true;
  41528. },
  41529. enumerable: true,
  41530. configurable: true
  41531. });
  41532. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41533. /**
  41534. * Gets the highlights Hue value.
  41535. * 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).
  41536. */
  41537. get: function () {
  41538. return this._highlightsHue;
  41539. },
  41540. /**
  41541. * Sets the highlights Hue value.
  41542. * 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).
  41543. */
  41544. set: function (value) {
  41545. this._highlightsHue = value;
  41546. this._dirty = true;
  41547. },
  41548. enumerable: true,
  41549. configurable: true
  41550. });
  41551. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41552. /**
  41553. * Gets the highlights Density value.
  41554. * 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.
  41555. * Values less than zero provide a filter of opposite hue.
  41556. */
  41557. get: function () {
  41558. return this._highlightsDensity;
  41559. },
  41560. /**
  41561. * Sets the highlights Density value.
  41562. * 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.
  41563. * Values less than zero provide a filter of opposite hue.
  41564. */
  41565. set: function (value) {
  41566. this._highlightsDensity = value;
  41567. this._dirty = true;
  41568. },
  41569. enumerable: true,
  41570. configurable: true
  41571. });
  41572. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41573. /**
  41574. * Gets the highlights Saturation value.
  41575. * 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.
  41576. */
  41577. get: function () {
  41578. return this._highlightsSaturation;
  41579. },
  41580. /**
  41581. * Sets the highlights Saturation value.
  41582. * 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.
  41583. */
  41584. set: function (value) {
  41585. this._highlightsSaturation = value;
  41586. this._dirty = true;
  41587. },
  41588. enumerable: true,
  41589. configurable: true
  41590. });
  41591. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41592. /**
  41593. * Gets the highlights Exposure value.
  41594. * 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.
  41595. */
  41596. get: function () {
  41597. return this._highlightsExposure;
  41598. },
  41599. /**
  41600. * Sets the highlights Exposure value.
  41601. * 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.
  41602. */
  41603. set: function (value) {
  41604. this._highlightsExposure = value;
  41605. this._dirty = true;
  41606. },
  41607. enumerable: true,
  41608. configurable: true
  41609. });
  41610. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41611. /**
  41612. * Gets the midtones Hue value.
  41613. * 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).
  41614. */
  41615. get: function () {
  41616. return this._midtonesHue;
  41617. },
  41618. /**
  41619. * Sets the midtones Hue value.
  41620. * 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).
  41621. */
  41622. set: function (value) {
  41623. this._midtonesHue = value;
  41624. this._dirty = true;
  41625. },
  41626. enumerable: true,
  41627. configurable: true
  41628. });
  41629. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41630. /**
  41631. * Gets the midtones Density value.
  41632. * 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.
  41633. * Values less than zero provide a filter of opposite hue.
  41634. */
  41635. get: function () {
  41636. return this._midtonesDensity;
  41637. },
  41638. /**
  41639. * Sets the midtones Density value.
  41640. * 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.
  41641. * Values less than zero provide a filter of opposite hue.
  41642. */
  41643. set: function (value) {
  41644. this._midtonesDensity = value;
  41645. this._dirty = true;
  41646. },
  41647. enumerable: true,
  41648. configurable: true
  41649. });
  41650. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41651. /**
  41652. * Gets the midtones Saturation value.
  41653. * 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.
  41654. */
  41655. get: function () {
  41656. return this._midtonesSaturation;
  41657. },
  41658. /**
  41659. * Sets the midtones Saturation value.
  41660. * 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.
  41661. */
  41662. set: function (value) {
  41663. this._midtonesSaturation = value;
  41664. this._dirty = true;
  41665. },
  41666. enumerable: true,
  41667. configurable: true
  41668. });
  41669. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41670. /**
  41671. * Gets the midtones Exposure value.
  41672. * 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.
  41673. */
  41674. get: function () {
  41675. return this._midtonesExposure;
  41676. },
  41677. /**
  41678. * Sets the midtones Exposure value.
  41679. * 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.
  41680. */
  41681. set: function (value) {
  41682. this._midtonesExposure = value;
  41683. this._dirty = true;
  41684. },
  41685. enumerable: true,
  41686. configurable: true
  41687. });
  41688. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41689. /**
  41690. * Gets the shadows Hue value.
  41691. * 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).
  41692. */
  41693. get: function () {
  41694. return this._shadowsHue;
  41695. },
  41696. /**
  41697. * Sets the shadows Hue value.
  41698. * 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).
  41699. */
  41700. set: function (value) {
  41701. this._shadowsHue = value;
  41702. this._dirty = true;
  41703. },
  41704. enumerable: true,
  41705. configurable: true
  41706. });
  41707. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41708. /**
  41709. * Gets the shadows Density value.
  41710. * 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.
  41711. * Values less than zero provide a filter of opposite hue.
  41712. */
  41713. get: function () {
  41714. return this._shadowsDensity;
  41715. },
  41716. /**
  41717. * Sets the shadows Density value.
  41718. * 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.
  41719. * Values less than zero provide a filter of opposite hue.
  41720. */
  41721. set: function (value) {
  41722. this._shadowsDensity = value;
  41723. this._dirty = true;
  41724. },
  41725. enumerable: true,
  41726. configurable: true
  41727. });
  41728. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41729. /**
  41730. * Gets the shadows Saturation value.
  41731. * 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.
  41732. */
  41733. get: function () {
  41734. return this._shadowsSaturation;
  41735. },
  41736. /**
  41737. * Sets the shadows Saturation value.
  41738. * 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.
  41739. */
  41740. set: function (value) {
  41741. this._shadowsSaturation = value;
  41742. this._dirty = true;
  41743. },
  41744. enumerable: true,
  41745. configurable: true
  41746. });
  41747. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41748. /**
  41749. * Gets the shadows Exposure value.
  41750. * 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.
  41751. */
  41752. get: function () {
  41753. return this._shadowsExposure;
  41754. },
  41755. /**
  41756. * Sets the shadows Exposure value.
  41757. * 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.
  41758. */
  41759. set: function (value) {
  41760. this._shadowsExposure = value;
  41761. this._dirty = true;
  41762. },
  41763. enumerable: true,
  41764. configurable: true
  41765. });
  41766. ColorCurves.prototype.getClassName = function () {
  41767. return "ColorCurves";
  41768. };
  41769. /**
  41770. * Binds the color curves to the shader.
  41771. * @param colorCurves The color curve to bind
  41772. * @param effect The effect to bind to
  41773. */
  41774. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41775. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41776. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41777. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41778. if (colorCurves._dirty) {
  41779. colorCurves._dirty = false;
  41780. // Fill in global info.
  41781. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41782. // Compute highlights info.
  41783. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41784. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41785. // Compute midtones info.
  41786. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41787. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41788. // Compute shadows info.
  41789. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41790. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41791. // Compute deltas (neutral is midtones).
  41792. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41793. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41794. }
  41795. if (effect) {
  41796. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41797. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41798. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41799. }
  41800. };
  41801. /**
  41802. * Prepare the list of uniforms associated with the ColorCurves effects.
  41803. * @param uniformsList The list of uniforms used in the effect
  41804. */
  41805. ColorCurves.PrepareUniforms = function (uniformsList) {
  41806. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41807. };
  41808. /**
  41809. * Returns color grading data based on a hue, density, saturation and exposure value.
  41810. * @param filterHue The hue of the color filter.
  41811. * @param filterDensity The density of the color filter.
  41812. * @param saturation The saturation.
  41813. * @param exposure The exposure.
  41814. * @param result The result data container.
  41815. */
  41816. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41817. if (hue == null) {
  41818. return;
  41819. }
  41820. hue = ColorCurves.clamp(hue, 0, 360);
  41821. density = ColorCurves.clamp(density, -100, 100);
  41822. saturation = ColorCurves.clamp(saturation, -100, 100);
  41823. exposure = ColorCurves.clamp(exposure, -100, 100);
  41824. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41825. // so that the maximum filter density is only 50% control. This provides fine control
  41826. // for small values and reasonable range.
  41827. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41828. density *= 0.5;
  41829. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41830. if (density < 0) {
  41831. density *= -1;
  41832. hue = (hue + 180) % 360;
  41833. }
  41834. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41835. result.scaleToRef(2, result);
  41836. result.a = 1 + 0.01 * saturation;
  41837. };
  41838. /**
  41839. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41840. * @param value The input slider value in range [-100,100].
  41841. * @returns Adjusted value.
  41842. */
  41843. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41844. value /= 100;
  41845. var x = Math.abs(value);
  41846. x = Math.pow(x, 2);
  41847. if (value < 0) {
  41848. x *= -1;
  41849. }
  41850. x *= 100;
  41851. return x;
  41852. };
  41853. /**
  41854. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41855. * @param hue The hue (H) input.
  41856. * @param saturation The saturation (S) input.
  41857. * @param brightness The brightness (B) input.
  41858. * @result An RGBA color represented as Vector4.
  41859. */
  41860. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41861. var h = ColorCurves.clamp(hue, 0, 360);
  41862. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41863. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41864. if (s === 0) {
  41865. result.r = v;
  41866. result.g = v;
  41867. result.b = v;
  41868. }
  41869. else {
  41870. // sector 0 to 5
  41871. h /= 60;
  41872. var i = Math.floor(h);
  41873. // fractional part of h
  41874. var f = h - i;
  41875. var p = v * (1 - s);
  41876. var q = v * (1 - s * f);
  41877. var t = v * (1 - s * (1 - f));
  41878. switch (i) {
  41879. case 0:
  41880. result.r = v;
  41881. result.g = t;
  41882. result.b = p;
  41883. break;
  41884. case 1:
  41885. result.r = q;
  41886. result.g = v;
  41887. result.b = p;
  41888. break;
  41889. case 2:
  41890. result.r = p;
  41891. result.g = v;
  41892. result.b = t;
  41893. break;
  41894. case 3:
  41895. result.r = p;
  41896. result.g = q;
  41897. result.b = v;
  41898. break;
  41899. case 4:
  41900. result.r = t;
  41901. result.g = p;
  41902. result.b = v;
  41903. break;
  41904. default: // case 5:
  41905. result.r = v;
  41906. result.g = p;
  41907. result.b = q;
  41908. break;
  41909. }
  41910. }
  41911. result.a = 1;
  41912. };
  41913. /**
  41914. * Returns a value clamped between min and max
  41915. * @param value The value to clamp
  41916. * @param min The minimum of value
  41917. * @param max The maximum of value
  41918. * @returns The clamped value.
  41919. */
  41920. ColorCurves.clamp = function (value, min, max) {
  41921. return Math.min(Math.max(value, min), max);
  41922. };
  41923. /**
  41924. * Clones the current color curve instance.
  41925. * @return The cloned curves
  41926. */
  41927. ColorCurves.prototype.clone = function () {
  41928. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  41929. };
  41930. /**
  41931. * Serializes the current color curve instance to a json representation.
  41932. * @return a JSON representation
  41933. */
  41934. ColorCurves.prototype.serialize = function () {
  41935. return BABYLON.SerializationHelper.Serialize(this);
  41936. };
  41937. /**
  41938. * Parses the color curve from a json representation.
  41939. * @param source the JSON source to parse
  41940. * @return The parsed curves
  41941. */
  41942. ColorCurves.Parse = function (source) {
  41943. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  41944. };
  41945. __decorate([
  41946. BABYLON.serialize()
  41947. ], ColorCurves.prototype, "_globalHue", void 0);
  41948. __decorate([
  41949. BABYLON.serialize()
  41950. ], ColorCurves.prototype, "_globalDensity", void 0);
  41951. __decorate([
  41952. BABYLON.serialize()
  41953. ], ColorCurves.prototype, "_globalSaturation", void 0);
  41954. __decorate([
  41955. BABYLON.serialize()
  41956. ], ColorCurves.prototype, "_globalExposure", void 0);
  41957. __decorate([
  41958. BABYLON.serialize()
  41959. ], ColorCurves.prototype, "_highlightsHue", void 0);
  41960. __decorate([
  41961. BABYLON.serialize()
  41962. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  41963. __decorate([
  41964. BABYLON.serialize()
  41965. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  41966. __decorate([
  41967. BABYLON.serialize()
  41968. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  41969. __decorate([
  41970. BABYLON.serialize()
  41971. ], ColorCurves.prototype, "_midtonesHue", void 0);
  41972. __decorate([
  41973. BABYLON.serialize()
  41974. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  41975. __decorate([
  41976. BABYLON.serialize()
  41977. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  41978. __decorate([
  41979. BABYLON.serialize()
  41980. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  41981. return ColorCurves;
  41982. }());
  41983. BABYLON.ColorCurves = ColorCurves;
  41984. })(BABYLON || (BABYLON = {}));
  41985. //# sourceMappingURL=babylon.colorCurves.js.map
  41986. //# sourceMappingURL=babylon.behavior.js.map
  41987. var BABYLON;
  41988. (function (BABYLON) {
  41989. /**
  41990. * "Static Class" containing the most commonly used helper while dealing with material for
  41991. * rendering purpose.
  41992. *
  41993. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41994. *
  41995. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41996. */
  41997. var MaterialHelper = /** @class */ (function () {
  41998. function MaterialHelper() {
  41999. }
  42000. /**
  42001. * Bind the current view position to an effect.
  42002. * @param effect The effect to be bound
  42003. * @param scene The scene the eyes position is used from
  42004. */
  42005. MaterialHelper.BindEyePosition = function (effect, scene) {
  42006. if (scene._forcedViewPosition) {
  42007. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42008. return;
  42009. }
  42010. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42011. };
  42012. /**
  42013. * Helps preparing the defines values about the UVs in used in the effect.
  42014. * UVs are shared as much as we can accross chanels in the shaders.
  42015. * @param texture The texture we are preparing the UVs for
  42016. * @param defines The defines to update
  42017. * @param key The chanel key "diffuse", "specular"... used in the shader
  42018. */
  42019. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42020. defines._needUVs = true;
  42021. defines[key] = true;
  42022. if (texture.getTextureMatrix().isIdentity(true)) {
  42023. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42024. if (texture.coordinatesIndex === 0) {
  42025. defines["MAINUV1"] = true;
  42026. }
  42027. else {
  42028. defines["MAINUV2"] = true;
  42029. }
  42030. }
  42031. else {
  42032. defines[key + "DIRECTUV"] = 0;
  42033. }
  42034. };
  42035. /**
  42036. * Binds a texture matrix value to its corrsponding uniform
  42037. * @param texture The texture to bind the matrix for
  42038. * @param uniformBuffer The uniform buffer receivin the data
  42039. * @param key The chanel key "diffuse", "specular"... used in the shader
  42040. */
  42041. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42042. var matrix = texture.getTextureMatrix();
  42043. if (!matrix.isIdentity(true)) {
  42044. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42045. }
  42046. };
  42047. /**
  42048. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42049. * @param mesh defines the current mesh
  42050. * @param scene defines the current scene
  42051. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42052. * @param pointsCloud defines if point cloud rendering has to be turned on
  42053. * @param fogEnabled defines if fog has to be turned on
  42054. * @param alphaTest defines if alpha testing has to be turned on
  42055. * @param defines defines the current list of defines
  42056. */
  42057. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42058. if (defines._areMiscDirty) {
  42059. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42060. defines["POINTSIZE"] = pointsCloud;
  42061. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42062. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42063. defines["ALPHATEST"] = alphaTest;
  42064. }
  42065. };
  42066. /**
  42067. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42068. * @param scene defines the current scene
  42069. * @param engine defines the current engine
  42070. * @param defines specifies the list of active defines
  42071. * @param useInstances defines if instances have to be turned on
  42072. * @param useClipPlane defines if clip plane have to be turned on
  42073. */
  42074. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42075. if (useClipPlane === void 0) { useClipPlane = null; }
  42076. var changed = false;
  42077. if (useClipPlane == null) {
  42078. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42079. }
  42080. if (defines["CLIPPLANE"] !== useClipPlane) {
  42081. defines["CLIPPLANE"] = useClipPlane;
  42082. changed = true;
  42083. }
  42084. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42085. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42086. changed = true;
  42087. }
  42088. if (defines["INSTANCES"] !== useInstances) {
  42089. defines["INSTANCES"] = useInstances;
  42090. changed = true;
  42091. }
  42092. if (changed) {
  42093. defines.markAsUnprocessed();
  42094. }
  42095. };
  42096. /**
  42097. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42098. * @param mesh The mesh containing the geometry data we will draw
  42099. * @param defines The defines to update
  42100. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42101. * @param useBones Precise whether bones should be used or not (override mesh info)
  42102. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42103. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42104. * @returns false if defines are considered not dirty and have not been checked
  42105. */
  42106. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42107. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42108. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42109. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42110. return false;
  42111. }
  42112. defines._normals = defines._needNormals;
  42113. defines._uvs = defines._needUVs;
  42114. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42115. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42116. defines["TANGENT"] = true;
  42117. }
  42118. if (defines._needUVs) {
  42119. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42120. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42121. }
  42122. else {
  42123. defines["UV1"] = false;
  42124. defines["UV2"] = false;
  42125. }
  42126. if (useVertexColor) {
  42127. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42128. defines["VERTEXCOLOR"] = hasVertexColors;
  42129. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42130. }
  42131. if (useBones) {
  42132. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42133. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42134. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42135. }
  42136. else {
  42137. defines["NUM_BONE_INFLUENCERS"] = 0;
  42138. defines["BonesPerMesh"] = 0;
  42139. }
  42140. }
  42141. if (useMorphTargets) {
  42142. var manager = mesh.morphTargetManager;
  42143. if (manager) {
  42144. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42145. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42146. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42147. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42148. }
  42149. else {
  42150. defines["MORPHTARGETS_TANGENT"] = false;
  42151. defines["MORPHTARGETS_NORMAL"] = false;
  42152. defines["MORPHTARGETS"] = false;
  42153. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42154. }
  42155. }
  42156. return true;
  42157. };
  42158. /**
  42159. * Prepares the defines related to the light information passed in parameter
  42160. * @param scene The scene we are intending to draw
  42161. * @param mesh The mesh the effect is compiling for
  42162. * @param defines The defines to update
  42163. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42164. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42165. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42166. * @returns true if normals will be required for the rest of the effect
  42167. */
  42168. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42169. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42170. if (disableLighting === void 0) { disableLighting = false; }
  42171. if (!defines._areLightsDirty) {
  42172. return defines._needNormals;
  42173. }
  42174. var lightIndex = 0;
  42175. var needNormals = false;
  42176. var needRebuild = false;
  42177. var lightmapMode = false;
  42178. var shadowEnabled = false;
  42179. var specularEnabled = false;
  42180. if (scene.lightsEnabled && !disableLighting) {
  42181. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42182. var light = _a[_i];
  42183. needNormals = true;
  42184. if (defines["LIGHT" + lightIndex] === undefined) {
  42185. needRebuild = true;
  42186. }
  42187. defines["LIGHT" + lightIndex] = true;
  42188. defines["SPOTLIGHT" + lightIndex] = false;
  42189. defines["HEMILIGHT" + lightIndex] = false;
  42190. defines["POINTLIGHT" + lightIndex] = false;
  42191. defines["DIRLIGHT" + lightIndex] = false;
  42192. var type;
  42193. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42194. type = "SPOTLIGHT" + lightIndex;
  42195. var spotLight = light;
  42196. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42197. }
  42198. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42199. type = "HEMILIGHT" + lightIndex;
  42200. }
  42201. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42202. type = "POINTLIGHT" + lightIndex;
  42203. }
  42204. else {
  42205. type = "DIRLIGHT" + lightIndex;
  42206. }
  42207. defines[type] = true;
  42208. // Specular
  42209. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42210. specularEnabled = true;
  42211. }
  42212. // Shadows
  42213. defines["SHADOW" + lightIndex] = false;
  42214. defines["SHADOWPCF" + lightIndex] = false;
  42215. defines["SHADOWPCSS" + lightIndex] = false;
  42216. defines["SHADOWPOISSON" + lightIndex] = false;
  42217. defines["SHADOWESM" + lightIndex] = false;
  42218. defines["SHADOWCUBE" + lightIndex] = false;
  42219. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42220. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42221. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42222. var shadowGenerator = light.getShadowGenerator();
  42223. if (shadowGenerator) {
  42224. shadowEnabled = true;
  42225. shadowGenerator.prepareDefines(defines, lightIndex);
  42226. }
  42227. }
  42228. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42229. lightmapMode = true;
  42230. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42231. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42232. }
  42233. else {
  42234. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42235. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42236. }
  42237. lightIndex++;
  42238. if (lightIndex === maxSimultaneousLights)
  42239. break;
  42240. }
  42241. }
  42242. defines["SPECULARTERM"] = specularEnabled;
  42243. defines["SHADOWS"] = shadowEnabled;
  42244. // Resetting all other lights if any
  42245. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42246. if (defines["LIGHT" + index] !== undefined) {
  42247. defines["LIGHT" + index] = false;
  42248. defines["HEMILIGHT" + lightIndex] = false;
  42249. defines["POINTLIGHT" + lightIndex] = false;
  42250. defines["DIRLIGHT" + lightIndex] = false;
  42251. defines["SPOTLIGHT" + lightIndex] = false;
  42252. defines["SHADOW" + lightIndex] = false;
  42253. }
  42254. }
  42255. var caps = scene.getEngine().getCaps();
  42256. if (defines["SHADOWFLOAT"] === undefined) {
  42257. needRebuild = true;
  42258. }
  42259. defines["SHADOWFLOAT"] = shadowEnabled &&
  42260. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42261. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42262. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42263. if (needRebuild) {
  42264. defines.rebuild();
  42265. }
  42266. return needNormals;
  42267. };
  42268. /**
  42269. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42270. * that won t be acctive due to defines being turned off.
  42271. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42272. * @param samplersList The samplers list
  42273. * @param defines The defines helping in the list generation
  42274. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42275. */
  42276. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42277. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42278. var uniformsList;
  42279. var uniformBuffersList = null;
  42280. if (uniformsListOrOptions.uniformsNames) {
  42281. var options = uniformsListOrOptions;
  42282. uniformsList = options.uniformsNames;
  42283. uniformBuffersList = options.uniformBuffersNames;
  42284. samplersList = options.samplers;
  42285. defines = options.defines;
  42286. maxSimultaneousLights = options.maxSimultaneousLights;
  42287. }
  42288. else {
  42289. uniformsList = uniformsListOrOptions;
  42290. if (!samplersList) {
  42291. samplersList = [];
  42292. }
  42293. }
  42294. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42295. if (!defines["LIGHT" + lightIndex]) {
  42296. break;
  42297. }
  42298. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42299. if (uniformBuffersList) {
  42300. uniformBuffersList.push("Light" + lightIndex);
  42301. }
  42302. samplersList.push("shadowSampler" + lightIndex);
  42303. samplersList.push("depthSampler" + lightIndex);
  42304. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42305. samplersList.push("projectionLightSampler" + lightIndex);
  42306. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42307. }
  42308. }
  42309. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42310. uniformsList.push("morphTargetInfluences");
  42311. }
  42312. };
  42313. /**
  42314. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42315. * @param defines The defines to update while falling back
  42316. * @param fallbacks The authorized effect fallbacks
  42317. * @param maxSimultaneousLights The maximum number of lights allowed
  42318. * @param rank the current rank of the Effect
  42319. * @returns The newly affected rank
  42320. */
  42321. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42322. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42323. if (rank === void 0) { rank = 0; }
  42324. var lightFallbackRank = 0;
  42325. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42326. if (!defines["LIGHT" + lightIndex]) {
  42327. break;
  42328. }
  42329. if (lightIndex > 0) {
  42330. lightFallbackRank = rank + lightIndex;
  42331. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42332. }
  42333. if (!defines["SHADOWS"]) {
  42334. if (defines["SHADOW" + lightIndex]) {
  42335. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42336. }
  42337. if (defines["SHADOWPCF" + lightIndex]) {
  42338. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42339. }
  42340. if (defines["SHADOWPCSS" + lightIndex]) {
  42341. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42342. }
  42343. if (defines["SHADOWPOISSON" + lightIndex]) {
  42344. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42345. }
  42346. if (defines["SHADOWESM" + lightIndex]) {
  42347. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42348. }
  42349. }
  42350. }
  42351. return lightFallbackRank++;
  42352. };
  42353. /**
  42354. * Prepares the list of attributes required for morph targets according to the effect defines.
  42355. * @param attribs The current list of supported attribs
  42356. * @param mesh The mesh to prepare the morph targets attributes for
  42357. * @param defines The current Defines of the effect
  42358. */
  42359. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42360. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42361. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42362. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42363. var manager = mesh.morphTargetManager;
  42364. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42365. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42366. for (var index = 0; index < influencers; index++) {
  42367. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42368. if (normal) {
  42369. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42370. }
  42371. if (tangent) {
  42372. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42373. }
  42374. if (attribs.length > maxAttributesCount) {
  42375. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42376. }
  42377. }
  42378. }
  42379. };
  42380. /**
  42381. * Prepares the list of attributes required for bones according to the effect defines.
  42382. * @param attribs The current list of supported attribs
  42383. * @param mesh The mesh to prepare the bones attributes for
  42384. * @param defines The current Defines of the effect
  42385. * @param fallbacks The current efffect fallback strategy
  42386. */
  42387. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42388. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42389. fallbacks.addCPUSkinningFallback(0, mesh);
  42390. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42391. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42392. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42393. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42394. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42395. }
  42396. }
  42397. };
  42398. /**
  42399. * Prepares the list of attributes required for instances according to the effect defines.
  42400. * @param attribs The current list of supported attribs
  42401. * @param defines The current Defines of the effect
  42402. */
  42403. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42404. if (defines["INSTANCES"]) {
  42405. attribs.push("world0");
  42406. attribs.push("world1");
  42407. attribs.push("world2");
  42408. attribs.push("world3");
  42409. }
  42410. };
  42411. /**
  42412. * Binds the light shadow information to the effect for the given mesh.
  42413. * @param light The light containing the generator
  42414. * @param scene The scene the lights belongs to
  42415. * @param mesh The mesh we are binding the information to render
  42416. * @param lightIndex The light index in the effect used to render the mesh
  42417. * @param effect The effect we are binding the data to
  42418. */
  42419. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42420. if (light.shadowEnabled && mesh.receiveShadows) {
  42421. var shadowGenerator = light.getShadowGenerator();
  42422. if (shadowGenerator) {
  42423. shadowGenerator.bindShadowLight(lightIndex, effect);
  42424. }
  42425. }
  42426. };
  42427. /**
  42428. * Binds the light information to the effect.
  42429. * @param light The light containing the generator
  42430. * @param effect The effect we are binding the data to
  42431. * @param lightIndex The light index in the effect used to render
  42432. */
  42433. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42434. light.transferToEffect(effect, lightIndex + "");
  42435. };
  42436. /**
  42437. * Binds the lights information from the scene to the effect for the given mesh.
  42438. * @param scene The scene the lights belongs to
  42439. * @param mesh The mesh we are binding the information to render
  42440. * @param effect The effect we are binding the data to
  42441. * @param defines The generated defines for the effect
  42442. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42443. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42444. */
  42445. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42446. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42447. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42448. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42449. for (var i = 0; i < len; i++) {
  42450. var light = mesh._lightSources[i];
  42451. var iAsString = i.toString();
  42452. var scaledIntensity = light.getScaledIntensity();
  42453. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42454. MaterialHelper.BindLightProperties(light, effect, i);
  42455. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42456. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42457. if (defines["SPECULARTERM"]) {
  42458. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42459. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42460. }
  42461. // Shadows
  42462. if (scene.shadowsEnabled) {
  42463. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42464. }
  42465. light._uniformBuffer.update();
  42466. }
  42467. };
  42468. /**
  42469. * Binds the fog information from the scene to the effect for the given mesh.
  42470. * @param scene The scene the lights belongs to
  42471. * @param mesh The mesh we are binding the information to render
  42472. * @param effect The effect we are binding the data to
  42473. */
  42474. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42475. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42476. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42477. effect.setColor3("vFogColor", scene.fogColor);
  42478. }
  42479. };
  42480. /**
  42481. * Binds the bones information from the mesh to the effect.
  42482. * @param mesh The mesh we are binding the information to render
  42483. * @param effect The effect we are binding the data to
  42484. */
  42485. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42486. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42487. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42488. if (matrices && effect) {
  42489. effect.setMatrices("mBones", matrices);
  42490. }
  42491. }
  42492. };
  42493. /**
  42494. * Binds the morph targets information from the mesh to the effect.
  42495. * @param abstractMesh The mesh we are binding the information to render
  42496. * @param effect The effect we are binding the data to
  42497. */
  42498. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42499. var manager = abstractMesh.morphTargetManager;
  42500. if (!abstractMesh || !manager) {
  42501. return;
  42502. }
  42503. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42504. };
  42505. /**
  42506. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42507. * @param defines The generated defines used in the effect
  42508. * @param effect The effect we are binding the data to
  42509. * @param scene The scene we are willing to render with logarithmic scale for
  42510. */
  42511. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42512. if (defines["LOGARITHMICDEPTH"]) {
  42513. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42514. }
  42515. };
  42516. /**
  42517. * Binds the clip plane information from the scene to the effect.
  42518. * @param scene The scene the clip plane information are extracted from
  42519. * @param effect The effect we are binding the data to
  42520. */
  42521. MaterialHelper.BindClipPlane = function (effect, scene) {
  42522. if (scene.clipPlane) {
  42523. var clipPlane = scene.clipPlane;
  42524. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42525. }
  42526. };
  42527. return MaterialHelper;
  42528. }());
  42529. BABYLON.MaterialHelper = MaterialHelper;
  42530. })(BABYLON || (BABYLON = {}));
  42531. //# sourceMappingURL=babylon.materialHelper.js.map
  42532. var BABYLON;
  42533. (function (BABYLON) {
  42534. var PushMaterial = /** @class */ (function (_super) {
  42535. __extends(PushMaterial, _super);
  42536. function PushMaterial(name, scene) {
  42537. var _this = _super.call(this, name, scene) || this;
  42538. _this._normalMatrix = new BABYLON.Matrix();
  42539. _this.storeEffectOnSubMeshes = true;
  42540. return _this;
  42541. }
  42542. PushMaterial.prototype.getEffect = function () {
  42543. return this._activeEffect;
  42544. };
  42545. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42546. if (!mesh) {
  42547. return false;
  42548. }
  42549. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42550. return true;
  42551. }
  42552. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42553. };
  42554. /**
  42555. * Binds the given world matrix to the active effect
  42556. *
  42557. * @param world the matrix to bind
  42558. */
  42559. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42560. this._activeEffect.setMatrix("world", world);
  42561. };
  42562. /**
  42563. * Binds the given normal matrix to the active effect
  42564. *
  42565. * @param normalMatrix the matrix to bind
  42566. */
  42567. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42568. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42569. };
  42570. PushMaterial.prototype.bind = function (world, mesh) {
  42571. if (!mesh) {
  42572. return;
  42573. }
  42574. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42575. };
  42576. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42577. if (effect === void 0) { effect = null; }
  42578. _super.prototype._afterBind.call(this, mesh);
  42579. this.getScene()._cachedEffect = effect;
  42580. };
  42581. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42582. if (visibility === void 0) { visibility = 1; }
  42583. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42584. };
  42585. return PushMaterial;
  42586. }(BABYLON.Material));
  42587. BABYLON.PushMaterial = PushMaterial;
  42588. })(BABYLON || (BABYLON = {}));
  42589. //# sourceMappingURL=babylon.pushMaterial.js.map
  42590. var BABYLON;
  42591. (function (BABYLON) {
  42592. /** @hidden */
  42593. var StandardMaterialDefines = /** @class */ (function (_super) {
  42594. __extends(StandardMaterialDefines, _super);
  42595. function StandardMaterialDefines() {
  42596. var _this = _super.call(this) || this;
  42597. _this.MAINUV1 = false;
  42598. _this.MAINUV2 = false;
  42599. _this.DIFFUSE = false;
  42600. _this.DIFFUSEDIRECTUV = 0;
  42601. _this.AMBIENT = false;
  42602. _this.AMBIENTDIRECTUV = 0;
  42603. _this.OPACITY = false;
  42604. _this.OPACITYDIRECTUV = 0;
  42605. _this.OPACITYRGB = false;
  42606. _this.REFLECTION = false;
  42607. _this.EMISSIVE = false;
  42608. _this.EMISSIVEDIRECTUV = 0;
  42609. _this.SPECULAR = false;
  42610. _this.SPECULARDIRECTUV = 0;
  42611. _this.BUMP = false;
  42612. _this.BUMPDIRECTUV = 0;
  42613. _this.PARALLAX = false;
  42614. _this.PARALLAXOCCLUSION = false;
  42615. _this.SPECULAROVERALPHA = false;
  42616. _this.CLIPPLANE = false;
  42617. _this.ALPHATEST = false;
  42618. _this.DEPTHPREPASS = false;
  42619. _this.ALPHAFROMDIFFUSE = false;
  42620. _this.POINTSIZE = false;
  42621. _this.FOG = false;
  42622. _this.SPECULARTERM = false;
  42623. _this.DIFFUSEFRESNEL = false;
  42624. _this.OPACITYFRESNEL = false;
  42625. _this.REFLECTIONFRESNEL = false;
  42626. _this.REFRACTIONFRESNEL = false;
  42627. _this.EMISSIVEFRESNEL = false;
  42628. _this.FRESNEL = false;
  42629. _this.NORMAL = false;
  42630. _this.UV1 = false;
  42631. _this.UV2 = false;
  42632. _this.VERTEXCOLOR = false;
  42633. _this.VERTEXALPHA = false;
  42634. _this.NUM_BONE_INFLUENCERS = 0;
  42635. _this.BonesPerMesh = 0;
  42636. _this.INSTANCES = false;
  42637. _this.GLOSSINESS = false;
  42638. _this.ROUGHNESS = false;
  42639. _this.EMISSIVEASILLUMINATION = false;
  42640. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42641. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42642. _this.LIGHTMAP = false;
  42643. _this.LIGHTMAPDIRECTUV = 0;
  42644. _this.OBJECTSPACE_NORMALMAP = false;
  42645. _this.USELIGHTMAPASSHADOWMAP = false;
  42646. _this.REFLECTIONMAP_3D = false;
  42647. _this.REFLECTIONMAP_SPHERICAL = false;
  42648. _this.REFLECTIONMAP_PLANAR = false;
  42649. _this.REFLECTIONMAP_CUBIC = false;
  42650. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42651. _this.REFLECTIONMAP_PROJECTION = false;
  42652. _this.REFLECTIONMAP_SKYBOX = false;
  42653. _this.REFLECTIONMAP_EXPLICIT = false;
  42654. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42655. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42656. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42657. _this.INVERTCUBICMAP = false;
  42658. _this.LOGARITHMICDEPTH = false;
  42659. _this.REFRACTION = false;
  42660. _this.REFRACTIONMAP_3D = false;
  42661. _this.REFLECTIONOVERALPHA = false;
  42662. _this.TWOSIDEDLIGHTING = false;
  42663. _this.SHADOWFLOAT = false;
  42664. _this.MORPHTARGETS = false;
  42665. _this.MORPHTARGETS_NORMAL = false;
  42666. _this.MORPHTARGETS_TANGENT = false;
  42667. _this.NUM_MORPH_INFLUENCERS = 0;
  42668. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42669. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42670. _this.IMAGEPROCESSING = false;
  42671. _this.VIGNETTE = false;
  42672. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42673. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42674. _this.TONEMAPPING = false;
  42675. _this.CONTRAST = false;
  42676. _this.COLORCURVES = false;
  42677. _this.COLORGRADING = false;
  42678. _this.COLORGRADING3D = false;
  42679. _this.SAMPLER3DGREENDEPTH = false;
  42680. _this.SAMPLER3DBGRMAP = false;
  42681. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42682. /**
  42683. * If the reflection texture on this material is in linear color space
  42684. * @hidden
  42685. */
  42686. _this.IS_REFLECTION_LINEAR = false;
  42687. /**
  42688. * If the refraction texture on this material is in linear color space
  42689. * @hidden
  42690. */
  42691. _this.IS_REFRACTION_LINEAR = false;
  42692. _this.EXPOSURE = false;
  42693. _this.rebuild();
  42694. return _this;
  42695. }
  42696. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42697. var modes = [
  42698. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42699. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42700. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42701. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42702. ];
  42703. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42704. var mode = modes_1[_i];
  42705. this[mode] = (mode === modeToEnable);
  42706. }
  42707. };
  42708. return StandardMaterialDefines;
  42709. }(BABYLON.MaterialDefines));
  42710. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42711. var StandardMaterial = /** @class */ (function (_super) {
  42712. __extends(StandardMaterial, _super);
  42713. function StandardMaterial(name, scene) {
  42714. var _this = _super.call(this, name, scene) || this;
  42715. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42716. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42717. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42718. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42719. _this.specularPower = 64;
  42720. _this._useAlphaFromDiffuseTexture = false;
  42721. _this._useEmissiveAsIllumination = false;
  42722. _this._linkEmissiveWithDiffuse = false;
  42723. _this._useSpecularOverAlpha = false;
  42724. _this._useReflectionOverAlpha = false;
  42725. _this._disableLighting = false;
  42726. _this._useObjectSpaceNormalMap = false;
  42727. _this._useParallax = false;
  42728. _this._useParallaxOcclusion = false;
  42729. _this.parallaxScaleBias = 0.05;
  42730. _this._roughness = 0;
  42731. _this.indexOfRefraction = 0.98;
  42732. _this.invertRefractionY = true;
  42733. /**
  42734. * Defines the alpha limits in alpha test mode
  42735. */
  42736. _this.alphaCutOff = 0.4;
  42737. _this._useLightmapAsShadowmap = false;
  42738. _this._useReflectionFresnelFromSpecular = false;
  42739. _this._useGlossinessFromSpecularMapAlpha = false;
  42740. _this._maxSimultaneousLights = 4;
  42741. /**
  42742. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42743. */
  42744. _this._invertNormalMapX = false;
  42745. /**
  42746. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42747. */
  42748. _this._invertNormalMapY = false;
  42749. /**
  42750. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42751. */
  42752. _this._twoSidedLighting = false;
  42753. _this._renderTargets = new BABYLON.SmartArray(16);
  42754. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42755. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42756. // Setup the default processing configuration to the scene.
  42757. _this._attachImageProcessingConfiguration(null);
  42758. _this.getRenderTargetTextures = function () {
  42759. _this._renderTargets.reset();
  42760. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42761. _this._renderTargets.push(_this._reflectionTexture);
  42762. }
  42763. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42764. _this._renderTargets.push(_this._refractionTexture);
  42765. }
  42766. return _this._renderTargets;
  42767. };
  42768. return _this;
  42769. }
  42770. ;
  42771. ;
  42772. ;
  42773. ;
  42774. ;
  42775. ;
  42776. ;
  42777. ;
  42778. ;
  42779. ;
  42780. ;
  42781. ;
  42782. ;
  42783. ;
  42784. ;
  42785. ;
  42786. ;
  42787. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42788. /**
  42789. * Gets the image processing configuration used either in this material.
  42790. */
  42791. get: function () {
  42792. return this._imageProcessingConfiguration;
  42793. },
  42794. /**
  42795. * Sets the Default image processing configuration used either in the this material.
  42796. *
  42797. * If sets to null, the scene one is in use.
  42798. */
  42799. set: function (value) {
  42800. this._attachImageProcessingConfiguration(value);
  42801. // Ensure the effect will be rebuilt.
  42802. this._markAllSubMeshesAsTexturesDirty();
  42803. },
  42804. enumerable: true,
  42805. configurable: true
  42806. });
  42807. /**
  42808. * Attaches a new image processing configuration to the Standard Material.
  42809. * @param configuration
  42810. */
  42811. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42812. var _this = this;
  42813. if (configuration === this._imageProcessingConfiguration) {
  42814. return;
  42815. }
  42816. // Detaches observer.
  42817. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42818. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42819. }
  42820. // Pick the scene configuration if needed.
  42821. if (!configuration) {
  42822. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42823. }
  42824. else {
  42825. this._imageProcessingConfiguration = configuration;
  42826. }
  42827. // Attaches observer.
  42828. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42829. _this._markAllSubMeshesAsImageProcessingDirty();
  42830. });
  42831. };
  42832. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42833. /**
  42834. * Gets wether the color curves effect is enabled.
  42835. */
  42836. get: function () {
  42837. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42838. },
  42839. /**
  42840. * Sets wether the color curves effect is enabled.
  42841. */
  42842. set: function (value) {
  42843. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42844. },
  42845. enumerable: true,
  42846. configurable: true
  42847. });
  42848. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42849. /**
  42850. * Gets wether the color grading effect is enabled.
  42851. */
  42852. get: function () {
  42853. return this.imageProcessingConfiguration.colorGradingEnabled;
  42854. },
  42855. /**
  42856. * Gets wether the color grading effect is enabled.
  42857. */
  42858. set: function (value) {
  42859. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42860. },
  42861. enumerable: true,
  42862. configurable: true
  42863. });
  42864. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42865. /**
  42866. * Gets wether tonemapping is enabled or not.
  42867. */
  42868. get: function () {
  42869. return this._imageProcessingConfiguration.toneMappingEnabled;
  42870. },
  42871. /**
  42872. * Sets wether tonemapping is enabled or not
  42873. */
  42874. set: function (value) {
  42875. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42876. },
  42877. enumerable: true,
  42878. configurable: true
  42879. });
  42880. ;
  42881. ;
  42882. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42883. /**
  42884. * The camera exposure used on this material.
  42885. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42886. * This corresponds to a photographic exposure.
  42887. */
  42888. get: function () {
  42889. return this._imageProcessingConfiguration.exposure;
  42890. },
  42891. /**
  42892. * The camera exposure used on this material.
  42893. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42894. * This corresponds to a photographic exposure.
  42895. */
  42896. set: function (value) {
  42897. this._imageProcessingConfiguration.exposure = value;
  42898. },
  42899. enumerable: true,
  42900. configurable: true
  42901. });
  42902. ;
  42903. ;
  42904. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42905. /**
  42906. * Gets The camera contrast used on this material.
  42907. */
  42908. get: function () {
  42909. return this._imageProcessingConfiguration.contrast;
  42910. },
  42911. /**
  42912. * Sets The camera contrast used on this material.
  42913. */
  42914. set: function (value) {
  42915. this._imageProcessingConfiguration.contrast = value;
  42916. },
  42917. enumerable: true,
  42918. configurable: true
  42919. });
  42920. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42921. /**
  42922. * Gets the Color Grading 2D Lookup Texture.
  42923. */
  42924. get: function () {
  42925. return this._imageProcessingConfiguration.colorGradingTexture;
  42926. },
  42927. /**
  42928. * Sets the Color Grading 2D Lookup Texture.
  42929. */
  42930. set: function (value) {
  42931. this._imageProcessingConfiguration.colorGradingTexture = value;
  42932. },
  42933. enumerable: true,
  42934. configurable: true
  42935. });
  42936. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42937. /**
  42938. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42939. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42940. * 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;
  42941. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42942. */
  42943. get: function () {
  42944. return this._imageProcessingConfiguration.colorCurves;
  42945. },
  42946. /**
  42947. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42948. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42949. * 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;
  42950. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42951. */
  42952. set: function (value) {
  42953. this._imageProcessingConfiguration.colorCurves = value;
  42954. },
  42955. enumerable: true,
  42956. configurable: true
  42957. });
  42958. StandardMaterial.prototype.getClassName = function () {
  42959. return "StandardMaterial";
  42960. };
  42961. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42962. get: function () {
  42963. return this._useLogarithmicDepth;
  42964. },
  42965. set: function (value) {
  42966. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42967. this._markAllSubMeshesAsMiscDirty();
  42968. },
  42969. enumerable: true,
  42970. configurable: true
  42971. });
  42972. StandardMaterial.prototype.needAlphaBlending = function () {
  42973. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42974. };
  42975. StandardMaterial.prototype.needAlphaTesting = function () {
  42976. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42977. };
  42978. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42979. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42980. };
  42981. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42982. return this._diffuseTexture;
  42983. };
  42984. /**
  42985. * Child classes can use it to update shaders
  42986. */
  42987. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42988. if (useInstances === void 0) { useInstances = false; }
  42989. if (subMesh.effect && this.isFrozen) {
  42990. if (this._wasPreviouslyReady && subMesh.effect) {
  42991. return true;
  42992. }
  42993. }
  42994. if (!subMesh._materialDefines) {
  42995. subMesh._materialDefines = new StandardMaterialDefines();
  42996. }
  42997. var scene = this.getScene();
  42998. var defines = subMesh._materialDefines;
  42999. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43000. if (defines._renderId === scene.getRenderId()) {
  43001. return true;
  43002. }
  43003. }
  43004. var engine = scene.getEngine();
  43005. // Lights
  43006. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43007. // Textures
  43008. if (defines._areTexturesDirty) {
  43009. defines._needUVs = false;
  43010. defines.MAINUV1 = false;
  43011. defines.MAINUV2 = false;
  43012. if (scene.texturesEnabled) {
  43013. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43014. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43015. return false;
  43016. }
  43017. else {
  43018. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43019. }
  43020. }
  43021. else {
  43022. defines.DIFFUSE = false;
  43023. }
  43024. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43025. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43026. return false;
  43027. }
  43028. else {
  43029. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43030. }
  43031. }
  43032. else {
  43033. defines.AMBIENT = false;
  43034. }
  43035. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43036. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43037. return false;
  43038. }
  43039. else {
  43040. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43041. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43042. }
  43043. }
  43044. else {
  43045. defines.OPACITY = false;
  43046. }
  43047. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43048. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43049. return false;
  43050. }
  43051. else {
  43052. defines._needNormals = true;
  43053. defines.REFLECTION = true;
  43054. defines.ROUGHNESS = (this._roughness > 0);
  43055. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43056. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43057. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43058. switch (this._reflectionTexture.coordinatesMode) {
  43059. case BABYLON.Texture.CUBIC_MODE:
  43060. case BABYLON.Texture.INVCUBIC_MODE:
  43061. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43062. break;
  43063. case BABYLON.Texture.EXPLICIT_MODE:
  43064. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43065. break;
  43066. case BABYLON.Texture.PLANAR_MODE:
  43067. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43068. break;
  43069. case BABYLON.Texture.PROJECTION_MODE:
  43070. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43071. break;
  43072. case BABYLON.Texture.SKYBOX_MODE:
  43073. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43074. break;
  43075. case BABYLON.Texture.SPHERICAL_MODE:
  43076. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43077. break;
  43078. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43079. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43080. break;
  43081. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43082. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43083. break;
  43084. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43085. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43086. break;
  43087. }
  43088. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43089. }
  43090. }
  43091. else {
  43092. defines.REFLECTION = false;
  43093. }
  43094. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43095. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43096. return false;
  43097. }
  43098. else {
  43099. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43100. }
  43101. }
  43102. else {
  43103. defines.EMISSIVE = false;
  43104. }
  43105. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43106. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43107. return false;
  43108. }
  43109. else {
  43110. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43111. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43112. }
  43113. }
  43114. else {
  43115. defines.LIGHTMAP = false;
  43116. }
  43117. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43118. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43119. return false;
  43120. }
  43121. else {
  43122. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43123. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43124. }
  43125. }
  43126. else {
  43127. defines.SPECULAR = false;
  43128. }
  43129. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43130. // Bump texure can not be not blocking.
  43131. if (!this._bumpTexture.isReady()) {
  43132. return false;
  43133. }
  43134. else {
  43135. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43136. defines.PARALLAX = this._useParallax;
  43137. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43138. }
  43139. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43140. }
  43141. else {
  43142. defines.BUMP = false;
  43143. }
  43144. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43145. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43146. return false;
  43147. }
  43148. else {
  43149. defines._needUVs = true;
  43150. defines.REFRACTION = true;
  43151. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43152. }
  43153. }
  43154. else {
  43155. defines.REFRACTION = false;
  43156. }
  43157. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43158. }
  43159. else {
  43160. defines.DIFFUSE = false;
  43161. defines.AMBIENT = false;
  43162. defines.OPACITY = false;
  43163. defines.REFLECTION = false;
  43164. defines.EMISSIVE = false;
  43165. defines.LIGHTMAP = false;
  43166. defines.BUMP = false;
  43167. defines.REFRACTION = false;
  43168. }
  43169. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43170. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43171. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43172. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43173. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43174. }
  43175. if (defines._areImageProcessingDirty) {
  43176. if (!this._imageProcessingConfiguration.isReady()) {
  43177. return false;
  43178. }
  43179. this._imageProcessingConfiguration.prepareDefines(defines);
  43180. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43181. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43182. }
  43183. if (defines._areFresnelDirty) {
  43184. if (StandardMaterial.FresnelEnabled) {
  43185. // Fresnel
  43186. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43187. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43188. this._reflectionFresnelParameters) {
  43189. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43190. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43191. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43192. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43193. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43194. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43195. defines._needNormals = true;
  43196. defines.FRESNEL = true;
  43197. }
  43198. }
  43199. else {
  43200. defines.FRESNEL = false;
  43201. }
  43202. }
  43203. // Misc.
  43204. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43205. // Attribs
  43206. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43207. // Values that need to be evaluated on every frame
  43208. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43209. // Get correct effect
  43210. if (defines.isDirty) {
  43211. defines.markAsProcessed();
  43212. scene.resetCachedMaterial();
  43213. // Fallbacks
  43214. var fallbacks = new BABYLON.EffectFallbacks();
  43215. if (defines.REFLECTION) {
  43216. fallbacks.addFallback(0, "REFLECTION");
  43217. }
  43218. if (defines.SPECULAR) {
  43219. fallbacks.addFallback(0, "SPECULAR");
  43220. }
  43221. if (defines.BUMP) {
  43222. fallbacks.addFallback(0, "BUMP");
  43223. }
  43224. if (defines.PARALLAX) {
  43225. fallbacks.addFallback(1, "PARALLAX");
  43226. }
  43227. if (defines.PARALLAXOCCLUSION) {
  43228. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43229. }
  43230. if (defines.SPECULAROVERALPHA) {
  43231. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43232. }
  43233. if (defines.FOG) {
  43234. fallbacks.addFallback(1, "FOG");
  43235. }
  43236. if (defines.POINTSIZE) {
  43237. fallbacks.addFallback(0, "POINTSIZE");
  43238. }
  43239. if (defines.LOGARITHMICDEPTH) {
  43240. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43241. }
  43242. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43243. if (defines.SPECULARTERM) {
  43244. fallbacks.addFallback(0, "SPECULARTERM");
  43245. }
  43246. if (defines.DIFFUSEFRESNEL) {
  43247. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43248. }
  43249. if (defines.OPACITYFRESNEL) {
  43250. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43251. }
  43252. if (defines.REFLECTIONFRESNEL) {
  43253. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43254. }
  43255. if (defines.EMISSIVEFRESNEL) {
  43256. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43257. }
  43258. if (defines.FRESNEL) {
  43259. fallbacks.addFallback(4, "FRESNEL");
  43260. }
  43261. //Attributes
  43262. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43263. if (defines.NORMAL) {
  43264. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43265. }
  43266. if (defines.UV1) {
  43267. attribs.push(BABYLON.VertexBuffer.UVKind);
  43268. }
  43269. if (defines.UV2) {
  43270. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43271. }
  43272. if (defines.VERTEXCOLOR) {
  43273. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43274. }
  43275. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43276. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43277. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43278. var shaderName = "default";
  43279. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43280. "vFogInfos", "vFogColor", "pointSize",
  43281. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43282. "mBones",
  43283. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43284. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43285. "vReflectionPosition", "vReflectionSize",
  43286. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43287. ];
  43288. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43289. var uniformBuffers = ["Material", "Scene"];
  43290. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43291. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43292. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43293. uniformsNames: uniforms,
  43294. uniformBuffersNames: uniformBuffers,
  43295. samplers: samplers,
  43296. defines: defines,
  43297. maxSimultaneousLights: this._maxSimultaneousLights
  43298. });
  43299. if (this.customShaderNameResolve) {
  43300. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43301. }
  43302. var join = defines.toString();
  43303. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43304. attributes: attribs,
  43305. uniformsNames: uniforms,
  43306. uniformBuffersNames: uniformBuffers,
  43307. samplers: samplers,
  43308. defines: join,
  43309. fallbacks: fallbacks,
  43310. onCompiled: this.onCompiled,
  43311. onError: this.onError,
  43312. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43313. }, engine), defines);
  43314. this.buildUniformLayout();
  43315. }
  43316. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43317. return false;
  43318. }
  43319. defines._renderId = scene.getRenderId();
  43320. this._wasPreviouslyReady = true;
  43321. return true;
  43322. };
  43323. StandardMaterial.prototype.buildUniformLayout = function () {
  43324. // Order is important !
  43325. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43326. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43327. this._uniformBuffer.addUniform("opacityParts", 4);
  43328. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43329. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43330. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43331. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43332. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43333. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43334. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43335. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43336. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43337. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43338. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43339. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43340. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43341. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43342. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43343. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43344. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43345. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43346. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43347. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43348. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43349. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43350. this._uniformBuffer.addUniform("specularMatrix", 16);
  43351. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43352. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43353. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43354. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43355. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43356. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43357. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43358. this._uniformBuffer.addUniform("pointSize", 1);
  43359. this._uniformBuffer.create();
  43360. };
  43361. StandardMaterial.prototype.unbind = function () {
  43362. if (this._activeEffect) {
  43363. var needFlag = false;
  43364. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43365. this._activeEffect.setTexture("reflection2DSampler", null);
  43366. needFlag = true;
  43367. }
  43368. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43369. this._activeEffect.setTexture("refraction2DSampler", null);
  43370. needFlag = true;
  43371. }
  43372. if (needFlag) {
  43373. this._markAllSubMeshesAsTexturesDirty();
  43374. }
  43375. }
  43376. _super.prototype.unbind.call(this);
  43377. };
  43378. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43379. var scene = this.getScene();
  43380. var defines = subMesh._materialDefines;
  43381. if (!defines) {
  43382. return;
  43383. }
  43384. var effect = subMesh.effect;
  43385. if (!effect) {
  43386. return;
  43387. }
  43388. this._activeEffect = effect;
  43389. // Matrices
  43390. this.bindOnlyWorldMatrix(world);
  43391. // Normal Matrix
  43392. if (defines.OBJECTSPACE_NORMALMAP) {
  43393. world.toNormalMatrix(this._normalMatrix);
  43394. this.bindOnlyNormalMatrix(this._normalMatrix);
  43395. }
  43396. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43397. // Bones
  43398. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43399. if (mustRebind) {
  43400. this._uniformBuffer.bindToEffect(effect, "Material");
  43401. this.bindViewProjection(effect);
  43402. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43403. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43404. // Fresnel
  43405. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43406. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43407. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43408. }
  43409. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43410. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43411. }
  43412. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43413. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43414. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43415. }
  43416. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43417. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43418. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43419. }
  43420. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43421. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43422. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43423. }
  43424. }
  43425. // Textures
  43426. if (scene.texturesEnabled) {
  43427. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43428. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43429. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43430. if (this._diffuseTexture.hasAlpha) {
  43431. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43432. }
  43433. }
  43434. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43435. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43436. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43437. }
  43438. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43439. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43440. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43441. }
  43442. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43443. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43444. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43445. if (this._reflectionTexture.boundingBoxSize) {
  43446. var cubeTexture = this._reflectionTexture;
  43447. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43448. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43449. }
  43450. }
  43451. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43452. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43453. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43454. }
  43455. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43456. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43457. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43458. }
  43459. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43460. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43461. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43462. }
  43463. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43464. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43465. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43466. if (scene._mirroredCameraPosition) {
  43467. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43468. }
  43469. else {
  43470. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43471. }
  43472. }
  43473. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43474. var depth = 1.0;
  43475. if (!this._refractionTexture.isCube) {
  43476. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43477. if (this._refractionTexture.depth) {
  43478. depth = this._refractionTexture.depth;
  43479. }
  43480. }
  43481. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43482. }
  43483. }
  43484. // Point size
  43485. if (this.pointsCloud) {
  43486. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43487. }
  43488. if (defines.SPECULARTERM) {
  43489. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43490. }
  43491. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43492. // Diffuse
  43493. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43494. }
  43495. // Textures
  43496. if (scene.texturesEnabled) {
  43497. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43498. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43499. }
  43500. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43501. effect.setTexture("ambientSampler", this._ambientTexture);
  43502. }
  43503. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43504. effect.setTexture("opacitySampler", this._opacityTexture);
  43505. }
  43506. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43507. if (this._reflectionTexture.isCube) {
  43508. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43509. }
  43510. else {
  43511. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43512. }
  43513. }
  43514. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43515. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43516. }
  43517. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43518. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43519. }
  43520. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43521. effect.setTexture("specularSampler", this._specularTexture);
  43522. }
  43523. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43524. effect.setTexture("bumpSampler", this._bumpTexture);
  43525. }
  43526. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43527. var depth = 1.0;
  43528. if (this._refractionTexture.isCube) {
  43529. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43530. }
  43531. else {
  43532. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43533. }
  43534. }
  43535. }
  43536. // Clip plane
  43537. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43538. // Colors
  43539. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43540. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43541. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43542. }
  43543. if (mustRebind || !this.isFrozen) {
  43544. // Lights
  43545. if (scene.lightsEnabled && !this._disableLighting) {
  43546. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43547. }
  43548. // View
  43549. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43550. this.bindView(effect);
  43551. }
  43552. // Fog
  43553. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43554. // Morph targets
  43555. if (defines.NUM_MORPH_INFLUENCERS) {
  43556. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43557. }
  43558. // Log. depth
  43559. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43560. // image processing
  43561. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43562. this._imageProcessingConfiguration.bind(this._activeEffect);
  43563. }
  43564. }
  43565. this._uniformBuffer.update();
  43566. this._afterBind(mesh, this._activeEffect);
  43567. };
  43568. StandardMaterial.prototype.getAnimatables = function () {
  43569. var results = [];
  43570. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43571. results.push(this._diffuseTexture);
  43572. }
  43573. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43574. results.push(this._ambientTexture);
  43575. }
  43576. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43577. results.push(this._opacityTexture);
  43578. }
  43579. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43580. results.push(this._reflectionTexture);
  43581. }
  43582. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43583. results.push(this._emissiveTexture);
  43584. }
  43585. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43586. results.push(this._specularTexture);
  43587. }
  43588. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43589. results.push(this._bumpTexture);
  43590. }
  43591. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43592. results.push(this._lightmapTexture);
  43593. }
  43594. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43595. results.push(this._refractionTexture);
  43596. }
  43597. return results;
  43598. };
  43599. StandardMaterial.prototype.getActiveTextures = function () {
  43600. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43601. if (this._diffuseTexture) {
  43602. activeTextures.push(this._diffuseTexture);
  43603. }
  43604. if (this._ambientTexture) {
  43605. activeTextures.push(this._ambientTexture);
  43606. }
  43607. if (this._opacityTexture) {
  43608. activeTextures.push(this._opacityTexture);
  43609. }
  43610. if (this._reflectionTexture) {
  43611. activeTextures.push(this._reflectionTexture);
  43612. }
  43613. if (this._emissiveTexture) {
  43614. activeTextures.push(this._emissiveTexture);
  43615. }
  43616. if (this._specularTexture) {
  43617. activeTextures.push(this._specularTexture);
  43618. }
  43619. if (this._bumpTexture) {
  43620. activeTextures.push(this._bumpTexture);
  43621. }
  43622. if (this._lightmapTexture) {
  43623. activeTextures.push(this._lightmapTexture);
  43624. }
  43625. if (this._refractionTexture) {
  43626. activeTextures.push(this._refractionTexture);
  43627. }
  43628. return activeTextures;
  43629. };
  43630. StandardMaterial.prototype.hasTexture = function (texture) {
  43631. if (_super.prototype.hasTexture.call(this, texture)) {
  43632. return true;
  43633. }
  43634. if (this._diffuseTexture === texture) {
  43635. return true;
  43636. }
  43637. if (this._ambientTexture === texture) {
  43638. return true;
  43639. }
  43640. if (this._opacityTexture === texture) {
  43641. return true;
  43642. }
  43643. if (this._reflectionTexture === texture) {
  43644. return true;
  43645. }
  43646. if (this._emissiveTexture === texture) {
  43647. return true;
  43648. }
  43649. if (this._specularTexture === texture) {
  43650. return true;
  43651. }
  43652. if (this._bumpTexture === texture) {
  43653. return true;
  43654. }
  43655. if (this._lightmapTexture === texture) {
  43656. return true;
  43657. }
  43658. if (this._refractionTexture === texture) {
  43659. return true;
  43660. }
  43661. return false;
  43662. };
  43663. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43664. if (forceDisposeTextures) {
  43665. if (this._diffuseTexture) {
  43666. this._diffuseTexture.dispose();
  43667. }
  43668. if (this._ambientTexture) {
  43669. this._ambientTexture.dispose();
  43670. }
  43671. if (this._opacityTexture) {
  43672. this._opacityTexture.dispose();
  43673. }
  43674. if (this._reflectionTexture) {
  43675. this._reflectionTexture.dispose();
  43676. }
  43677. if (this._emissiveTexture) {
  43678. this._emissiveTexture.dispose();
  43679. }
  43680. if (this._specularTexture) {
  43681. this._specularTexture.dispose();
  43682. }
  43683. if (this._bumpTexture) {
  43684. this._bumpTexture.dispose();
  43685. }
  43686. if (this._lightmapTexture) {
  43687. this._lightmapTexture.dispose();
  43688. }
  43689. if (this._refractionTexture) {
  43690. this._refractionTexture.dispose();
  43691. }
  43692. }
  43693. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43694. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43695. }
  43696. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43697. };
  43698. StandardMaterial.prototype.clone = function (name) {
  43699. var _this = this;
  43700. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43701. result.name = name;
  43702. result.id = name;
  43703. return result;
  43704. };
  43705. StandardMaterial.prototype.serialize = function () {
  43706. return BABYLON.SerializationHelper.Serialize(this);
  43707. };
  43708. // Statics
  43709. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43710. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43711. };
  43712. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43713. get: function () {
  43714. return StandardMaterial._DiffuseTextureEnabled;
  43715. },
  43716. set: function (value) {
  43717. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43718. return;
  43719. }
  43720. StandardMaterial._DiffuseTextureEnabled = value;
  43721. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43722. },
  43723. enumerable: true,
  43724. configurable: true
  43725. });
  43726. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43727. get: function () {
  43728. return StandardMaterial._AmbientTextureEnabled;
  43729. },
  43730. set: function (value) {
  43731. if (StandardMaterial._AmbientTextureEnabled === value) {
  43732. return;
  43733. }
  43734. StandardMaterial._AmbientTextureEnabled = value;
  43735. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43736. },
  43737. enumerable: true,
  43738. configurable: true
  43739. });
  43740. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43741. get: function () {
  43742. return StandardMaterial._OpacityTextureEnabled;
  43743. },
  43744. set: function (value) {
  43745. if (StandardMaterial._OpacityTextureEnabled === value) {
  43746. return;
  43747. }
  43748. StandardMaterial._OpacityTextureEnabled = value;
  43749. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43750. },
  43751. enumerable: true,
  43752. configurable: true
  43753. });
  43754. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43755. get: function () {
  43756. return StandardMaterial._ReflectionTextureEnabled;
  43757. },
  43758. set: function (value) {
  43759. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43760. return;
  43761. }
  43762. StandardMaterial._ReflectionTextureEnabled = value;
  43763. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43764. },
  43765. enumerable: true,
  43766. configurable: true
  43767. });
  43768. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43769. get: function () {
  43770. return StandardMaterial._EmissiveTextureEnabled;
  43771. },
  43772. set: function (value) {
  43773. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43774. return;
  43775. }
  43776. StandardMaterial._EmissiveTextureEnabled = value;
  43777. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43778. },
  43779. enumerable: true,
  43780. configurable: true
  43781. });
  43782. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43783. get: function () {
  43784. return StandardMaterial._SpecularTextureEnabled;
  43785. },
  43786. set: function (value) {
  43787. if (StandardMaterial._SpecularTextureEnabled === value) {
  43788. return;
  43789. }
  43790. StandardMaterial._SpecularTextureEnabled = value;
  43791. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43792. },
  43793. enumerable: true,
  43794. configurable: true
  43795. });
  43796. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43797. get: function () {
  43798. return StandardMaterial._BumpTextureEnabled;
  43799. },
  43800. set: function (value) {
  43801. if (StandardMaterial._BumpTextureEnabled === value) {
  43802. return;
  43803. }
  43804. StandardMaterial._BumpTextureEnabled = value;
  43805. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43806. },
  43807. enumerable: true,
  43808. configurable: true
  43809. });
  43810. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43811. get: function () {
  43812. return StandardMaterial._LightmapTextureEnabled;
  43813. },
  43814. set: function (value) {
  43815. if (StandardMaterial._LightmapTextureEnabled === value) {
  43816. return;
  43817. }
  43818. StandardMaterial._LightmapTextureEnabled = value;
  43819. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43820. },
  43821. enumerable: true,
  43822. configurable: true
  43823. });
  43824. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43825. get: function () {
  43826. return StandardMaterial._RefractionTextureEnabled;
  43827. },
  43828. set: function (value) {
  43829. if (StandardMaterial._RefractionTextureEnabled === value) {
  43830. return;
  43831. }
  43832. StandardMaterial._RefractionTextureEnabled = value;
  43833. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43834. },
  43835. enumerable: true,
  43836. configurable: true
  43837. });
  43838. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43839. get: function () {
  43840. return StandardMaterial._ColorGradingTextureEnabled;
  43841. },
  43842. set: function (value) {
  43843. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43844. return;
  43845. }
  43846. StandardMaterial._ColorGradingTextureEnabled = value;
  43847. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43848. },
  43849. enumerable: true,
  43850. configurable: true
  43851. });
  43852. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43853. get: function () {
  43854. return StandardMaterial._FresnelEnabled;
  43855. },
  43856. set: function (value) {
  43857. if (StandardMaterial._FresnelEnabled === value) {
  43858. return;
  43859. }
  43860. StandardMaterial._FresnelEnabled = value;
  43861. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43862. },
  43863. enumerable: true,
  43864. configurable: true
  43865. });
  43866. // Flags used to enable or disable a type of texture for all Standard Materials
  43867. StandardMaterial._DiffuseTextureEnabled = true;
  43868. StandardMaterial._AmbientTextureEnabled = true;
  43869. StandardMaterial._OpacityTextureEnabled = true;
  43870. StandardMaterial._ReflectionTextureEnabled = true;
  43871. StandardMaterial._EmissiveTextureEnabled = true;
  43872. StandardMaterial._SpecularTextureEnabled = true;
  43873. StandardMaterial._BumpTextureEnabled = true;
  43874. StandardMaterial._LightmapTextureEnabled = true;
  43875. StandardMaterial._RefractionTextureEnabled = true;
  43876. StandardMaterial._ColorGradingTextureEnabled = true;
  43877. StandardMaterial._FresnelEnabled = true;
  43878. __decorate([
  43879. BABYLON.serializeAsTexture("diffuseTexture")
  43880. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43881. __decorate([
  43882. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43883. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43884. __decorate([
  43885. BABYLON.serializeAsTexture("ambientTexture")
  43886. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43887. __decorate([
  43888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43889. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43890. __decorate([
  43891. BABYLON.serializeAsTexture("opacityTexture")
  43892. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43893. __decorate([
  43894. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43895. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43896. __decorate([
  43897. BABYLON.serializeAsTexture("reflectionTexture")
  43898. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43899. __decorate([
  43900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43901. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43902. __decorate([
  43903. BABYLON.serializeAsTexture("emissiveTexture")
  43904. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43905. __decorate([
  43906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43907. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43908. __decorate([
  43909. BABYLON.serializeAsTexture("specularTexture")
  43910. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43911. __decorate([
  43912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43913. ], StandardMaterial.prototype, "specularTexture", void 0);
  43914. __decorate([
  43915. BABYLON.serializeAsTexture("bumpTexture")
  43916. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43917. __decorate([
  43918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43919. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43920. __decorate([
  43921. BABYLON.serializeAsTexture("lightmapTexture")
  43922. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43923. __decorate([
  43924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43925. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43926. __decorate([
  43927. BABYLON.serializeAsTexture("refractionTexture")
  43928. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43929. __decorate([
  43930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43931. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43932. __decorate([
  43933. BABYLON.serializeAsColor3("ambient")
  43934. ], StandardMaterial.prototype, "ambientColor", void 0);
  43935. __decorate([
  43936. BABYLON.serializeAsColor3("diffuse")
  43937. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43938. __decorate([
  43939. BABYLON.serializeAsColor3("specular")
  43940. ], StandardMaterial.prototype, "specularColor", void 0);
  43941. __decorate([
  43942. BABYLON.serializeAsColor3("emissive")
  43943. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43944. __decorate([
  43945. BABYLON.serialize()
  43946. ], StandardMaterial.prototype, "specularPower", void 0);
  43947. __decorate([
  43948. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43949. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43950. __decorate([
  43951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43952. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43953. __decorate([
  43954. BABYLON.serialize("useEmissiveAsIllumination")
  43955. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43956. __decorate([
  43957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43958. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43959. __decorate([
  43960. BABYLON.serialize("linkEmissiveWithDiffuse")
  43961. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43962. __decorate([
  43963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43964. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43965. __decorate([
  43966. BABYLON.serialize("useSpecularOverAlpha")
  43967. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43968. __decorate([
  43969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43970. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43971. __decorate([
  43972. BABYLON.serialize("useReflectionOverAlpha")
  43973. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43974. __decorate([
  43975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43976. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43977. __decorate([
  43978. BABYLON.serialize("disableLighting")
  43979. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43980. __decorate([
  43981. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43982. ], StandardMaterial.prototype, "disableLighting", void 0);
  43983. __decorate([
  43984. BABYLON.serialize("useObjectSpaceNormalMap")
  43985. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43986. __decorate([
  43987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43988. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43989. __decorate([
  43990. BABYLON.serialize("useParallax")
  43991. ], StandardMaterial.prototype, "_useParallax", void 0);
  43992. __decorate([
  43993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43994. ], StandardMaterial.prototype, "useParallax", void 0);
  43995. __decorate([
  43996. BABYLON.serialize("useParallaxOcclusion")
  43997. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43998. __decorate([
  43999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44000. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44001. __decorate([
  44002. BABYLON.serialize()
  44003. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44004. __decorate([
  44005. BABYLON.serialize("roughness")
  44006. ], StandardMaterial.prototype, "_roughness", void 0);
  44007. __decorate([
  44008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44009. ], StandardMaterial.prototype, "roughness", void 0);
  44010. __decorate([
  44011. BABYLON.serialize()
  44012. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44013. __decorate([
  44014. BABYLON.serialize()
  44015. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44016. __decorate([
  44017. BABYLON.serialize()
  44018. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44019. __decorate([
  44020. BABYLON.serialize("useLightmapAsShadowmap")
  44021. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44022. __decorate([
  44023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44024. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44025. __decorate([
  44026. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44027. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44028. __decorate([
  44029. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44030. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44031. __decorate([
  44032. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44033. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44034. __decorate([
  44035. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44036. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44037. __decorate([
  44038. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44039. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44040. __decorate([
  44041. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44042. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44043. __decorate([
  44044. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44045. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44046. __decorate([
  44047. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44048. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44049. __decorate([
  44050. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44051. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44052. __decorate([
  44053. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44054. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44055. __decorate([
  44056. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44057. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44058. __decorate([
  44059. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44060. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44061. __decorate([
  44062. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44063. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44064. __decorate([
  44065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44066. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44067. __decorate([
  44068. BABYLON.serialize("maxSimultaneousLights")
  44069. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44070. __decorate([
  44071. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44072. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44073. __decorate([
  44074. BABYLON.serialize("invertNormalMapX")
  44075. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44076. __decorate([
  44077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44078. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44079. __decorate([
  44080. BABYLON.serialize("invertNormalMapY")
  44081. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44082. __decorate([
  44083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44084. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44085. __decorate([
  44086. BABYLON.serialize("twoSidedLighting")
  44087. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44088. __decorate([
  44089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44090. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44091. __decorate([
  44092. BABYLON.serialize()
  44093. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44094. return StandardMaterial;
  44095. }(BABYLON.PushMaterial));
  44096. BABYLON.StandardMaterial = StandardMaterial;
  44097. })(BABYLON || (BABYLON = {}));
  44098. //# sourceMappingURL=babylon.standardMaterial.js.map
  44099. var BABYLON;
  44100. (function (BABYLON) {
  44101. /**
  44102. * Manages the defines for the PBR Material.
  44103. * @hiddenChildren
  44104. */
  44105. var PBRMaterialDefines = /** @class */ (function (_super) {
  44106. __extends(PBRMaterialDefines, _super);
  44107. /**
  44108. * Initializes the PBR Material defines.
  44109. */
  44110. function PBRMaterialDefines() {
  44111. var _this = _super.call(this) || this;
  44112. _this.PBR = true;
  44113. _this.MAINUV1 = false;
  44114. _this.MAINUV2 = false;
  44115. _this.UV1 = false;
  44116. _this.UV2 = false;
  44117. _this.ALBEDO = false;
  44118. _this.ALBEDODIRECTUV = 0;
  44119. _this.VERTEXCOLOR = false;
  44120. _this.AMBIENT = false;
  44121. _this.AMBIENTDIRECTUV = 0;
  44122. _this.AMBIENTINGRAYSCALE = false;
  44123. _this.OPACITY = false;
  44124. _this.VERTEXALPHA = false;
  44125. _this.OPACITYDIRECTUV = 0;
  44126. _this.OPACITYRGB = false;
  44127. _this.ALPHATEST = false;
  44128. _this.DEPTHPREPASS = false;
  44129. _this.ALPHABLEND = false;
  44130. _this.ALPHAFROMALBEDO = false;
  44131. _this.ALPHATESTVALUE = "0.5";
  44132. _this.SPECULAROVERALPHA = false;
  44133. _this.RADIANCEOVERALPHA = false;
  44134. _this.ALPHAFRESNEL = false;
  44135. _this.LINEARALPHAFRESNEL = false;
  44136. _this.PREMULTIPLYALPHA = false;
  44137. _this.EMISSIVE = false;
  44138. _this.EMISSIVEDIRECTUV = 0;
  44139. _this.REFLECTIVITY = false;
  44140. _this.REFLECTIVITYDIRECTUV = 0;
  44141. _this.SPECULARTERM = false;
  44142. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44143. _this.MICROSURFACEAUTOMATIC = false;
  44144. _this.LODBASEDMICROSFURACE = false;
  44145. _this.MICROSURFACEMAP = false;
  44146. _this.MICROSURFACEMAPDIRECTUV = 0;
  44147. _this.METALLICWORKFLOW = false;
  44148. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44149. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44150. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44151. _this.AOSTOREINMETALMAPRED = false;
  44152. _this.ENVIRONMENTBRDF = false;
  44153. _this.NORMAL = false;
  44154. _this.TANGENT = false;
  44155. _this.BUMP = false;
  44156. _this.BUMPDIRECTUV = 0;
  44157. _this.OBJECTSPACE_NORMALMAP = false;
  44158. _this.PARALLAX = false;
  44159. _this.PARALLAXOCCLUSION = false;
  44160. _this.NORMALXYSCALE = true;
  44161. _this.LIGHTMAP = false;
  44162. _this.LIGHTMAPDIRECTUV = 0;
  44163. _this.USELIGHTMAPASSHADOWMAP = false;
  44164. _this.GAMMALIGHTMAP = false;
  44165. _this.REFLECTION = false;
  44166. _this.REFLECTIONMAP_3D = false;
  44167. _this.REFLECTIONMAP_SPHERICAL = false;
  44168. _this.REFLECTIONMAP_PLANAR = false;
  44169. _this.REFLECTIONMAP_CUBIC = false;
  44170. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44171. _this.REFLECTIONMAP_PROJECTION = false;
  44172. _this.REFLECTIONMAP_SKYBOX = false;
  44173. _this.REFLECTIONMAP_EXPLICIT = false;
  44174. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44175. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44176. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44177. _this.INVERTCUBICMAP = false;
  44178. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44179. _this.USESPHERICALINVERTEX = false;
  44180. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44181. _this.LODINREFLECTIONALPHA = false;
  44182. _this.GAMMAREFLECTION = false;
  44183. _this.RADIANCEOCCLUSION = false;
  44184. _this.HORIZONOCCLUSION = false;
  44185. _this.REFRACTION = false;
  44186. _this.REFRACTIONMAP_3D = false;
  44187. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44188. _this.LODINREFRACTIONALPHA = false;
  44189. _this.GAMMAREFRACTION = false;
  44190. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44191. _this.INSTANCES = false;
  44192. _this.NUM_BONE_INFLUENCERS = 0;
  44193. _this.BonesPerMesh = 0;
  44194. _this.NONUNIFORMSCALING = false;
  44195. _this.MORPHTARGETS = false;
  44196. _this.MORPHTARGETS_NORMAL = false;
  44197. _this.MORPHTARGETS_TANGENT = false;
  44198. _this.NUM_MORPH_INFLUENCERS = 0;
  44199. _this.IMAGEPROCESSING = false;
  44200. _this.VIGNETTE = false;
  44201. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44202. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44203. _this.TONEMAPPING = false;
  44204. _this.CONTRAST = false;
  44205. _this.COLORCURVES = false;
  44206. _this.COLORGRADING = false;
  44207. _this.COLORGRADING3D = false;
  44208. _this.SAMPLER3DGREENDEPTH = false;
  44209. _this.SAMPLER3DBGRMAP = false;
  44210. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44211. _this.EXPOSURE = false;
  44212. _this.USEPHYSICALLIGHTFALLOFF = false;
  44213. _this.TWOSIDEDLIGHTING = false;
  44214. _this.SHADOWFLOAT = false;
  44215. _this.CLIPPLANE = false;
  44216. _this.POINTSIZE = false;
  44217. _this.FOG = false;
  44218. _this.LOGARITHMICDEPTH = false;
  44219. _this.FORCENORMALFORWARD = false;
  44220. _this.SPECULARAA = false;
  44221. _this.UNLIT = false;
  44222. _this.rebuild();
  44223. return _this;
  44224. }
  44225. /**
  44226. * Resets the PBR Material defines.
  44227. */
  44228. PBRMaterialDefines.prototype.reset = function () {
  44229. _super.prototype.reset.call(this);
  44230. this.ALPHATESTVALUE = "0.5";
  44231. this.PBR = true;
  44232. };
  44233. return PBRMaterialDefines;
  44234. }(BABYLON.MaterialDefines));
  44235. /**
  44236. * The Physically based material base class of BJS.
  44237. *
  44238. * This offers the main features of a standard PBR material.
  44239. * For more information, please refer to the documentation :
  44240. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44241. */
  44242. var PBRBaseMaterial = /** @class */ (function (_super) {
  44243. __extends(PBRBaseMaterial, _super);
  44244. /**
  44245. * Instantiates a new PBRMaterial instance.
  44246. *
  44247. * @param name The material name
  44248. * @param scene The scene the material will be use in.
  44249. */
  44250. function PBRBaseMaterial(name, scene) {
  44251. var _this = _super.call(this, name, scene) || this;
  44252. /**
  44253. * Intensity of the direct lights e.g. the four lights available in your scene.
  44254. * This impacts both the direct diffuse and specular highlights.
  44255. */
  44256. _this._directIntensity = 1.0;
  44257. /**
  44258. * Intensity of the emissive part of the material.
  44259. * This helps controlling the emissive effect without modifying the emissive color.
  44260. */
  44261. _this._emissiveIntensity = 1.0;
  44262. /**
  44263. * Intensity of the environment e.g. how much the environment will light the object
  44264. * either through harmonics for rough material or through the refelction for shiny ones.
  44265. */
  44266. _this._environmentIntensity = 1.0;
  44267. /**
  44268. * This is a special control allowing the reduction of the specular highlights coming from the
  44269. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44270. */
  44271. _this._specularIntensity = 1.0;
  44272. /**
  44273. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44274. */
  44275. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44276. /**
  44277. * Debug Control allowing disabling the bump map on this material.
  44278. */
  44279. _this._disableBumpMap = false;
  44280. /**
  44281. * AKA Occlusion Texture Intensity in other nomenclature.
  44282. */
  44283. _this._ambientTextureStrength = 1.0;
  44284. /**
  44285. * The color of a material in ambient lighting.
  44286. */
  44287. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44288. /**
  44289. * AKA Diffuse Color in other nomenclature.
  44290. */
  44291. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44292. /**
  44293. * AKA Specular Color in other nomenclature.
  44294. */
  44295. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44296. /**
  44297. * The color applied when light is reflected from a material.
  44298. */
  44299. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44300. /**
  44301. * The color applied when light is emitted from a material.
  44302. */
  44303. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44304. /**
  44305. * AKA Glossiness in other nomenclature.
  44306. */
  44307. _this._microSurface = 0.9;
  44308. /**
  44309. * source material index of refraction (IOR)' / 'destination material IOR.
  44310. */
  44311. _this._indexOfRefraction = 0.66;
  44312. /**
  44313. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44314. */
  44315. _this._invertRefractionY = false;
  44316. /**
  44317. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44318. * Materials half opaque for instance using refraction could benefit from this control.
  44319. */
  44320. _this._linkRefractionWithTransparency = false;
  44321. /**
  44322. * Specifies that the material will use the light map as a show map.
  44323. */
  44324. _this._useLightmapAsShadowmap = false;
  44325. /**
  44326. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44327. * makes the reflect vector face the model (under horizon).
  44328. */
  44329. _this._useHorizonOcclusion = true;
  44330. /**
  44331. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44332. * too much the area relying on ambient texture to define their ambient occlusion.
  44333. */
  44334. _this._useRadianceOcclusion = true;
  44335. /**
  44336. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44337. */
  44338. _this._useAlphaFromAlbedoTexture = false;
  44339. /**
  44340. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44341. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44342. */
  44343. _this._useSpecularOverAlpha = true;
  44344. /**
  44345. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44346. */
  44347. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44348. /**
  44349. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44350. */
  44351. _this._useRoughnessFromMetallicTextureAlpha = true;
  44352. /**
  44353. * Specifies if the metallic texture contains the roughness information in its green channel.
  44354. */
  44355. _this._useRoughnessFromMetallicTextureGreen = false;
  44356. /**
  44357. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44358. */
  44359. _this._useMetallnessFromMetallicTextureBlue = false;
  44360. /**
  44361. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44362. */
  44363. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44364. /**
  44365. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44366. */
  44367. _this._useAmbientInGrayScale = false;
  44368. /**
  44369. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44370. * The material will try to infer what glossiness each pixel should be.
  44371. */
  44372. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44373. /**
  44374. * BJS is using an harcoded light falloff based on a manually sets up range.
  44375. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44376. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44377. */
  44378. _this._usePhysicalLightFalloff = true;
  44379. /**
  44380. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44381. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44382. */
  44383. _this._useRadianceOverAlpha = true;
  44384. /**
  44385. * Allows using an object space normal map (instead of tangent space).
  44386. */
  44387. _this._useObjectSpaceNormalMap = false;
  44388. /**
  44389. * Allows using the bump map in parallax mode.
  44390. */
  44391. _this._useParallax = false;
  44392. /**
  44393. * Allows using the bump map in parallax occlusion mode.
  44394. */
  44395. _this._useParallaxOcclusion = false;
  44396. /**
  44397. * Controls the scale bias of the parallax mode.
  44398. */
  44399. _this._parallaxScaleBias = 0.05;
  44400. /**
  44401. * If sets to true, disables all the lights affecting the material.
  44402. */
  44403. _this._disableLighting = false;
  44404. /**
  44405. * Number of Simultaneous lights allowed on the material.
  44406. */
  44407. _this._maxSimultaneousLights = 4;
  44408. /**
  44409. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44410. */
  44411. _this._invertNormalMapX = false;
  44412. /**
  44413. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44414. */
  44415. _this._invertNormalMapY = false;
  44416. /**
  44417. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44418. */
  44419. _this._twoSidedLighting = false;
  44420. /**
  44421. * Defines the alpha limits in alpha test mode.
  44422. */
  44423. _this._alphaCutOff = 0.4;
  44424. /**
  44425. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44426. */
  44427. _this._forceAlphaTest = false;
  44428. /**
  44429. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44430. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44431. */
  44432. _this._useAlphaFresnel = false;
  44433. /**
  44434. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44435. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44436. */
  44437. _this._useLinearAlphaFresnel = false;
  44438. /**
  44439. * The transparency mode of the material.
  44440. */
  44441. _this._transparencyMode = null;
  44442. /**
  44443. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44444. * from cos thetav and roughness:
  44445. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44446. */
  44447. _this._environmentBRDFTexture = null;
  44448. /**
  44449. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44450. */
  44451. _this._forceIrradianceInFragment = false;
  44452. /**
  44453. * Force normal to face away from face.
  44454. */
  44455. _this._forceNormalForward = false;
  44456. /**
  44457. * Enables specular anti aliasing in the PBR shader.
  44458. * It will both interacts on the Geometry for analytical and IBL lighting.
  44459. * It also prefilter the roughness map based on the bump values.
  44460. */
  44461. _this._enableSpecularAntiAliasing = false;
  44462. /**
  44463. * Stores the available render targets.
  44464. */
  44465. _this._renderTargets = new BABYLON.SmartArray(16);
  44466. /**
  44467. * Sets the global ambient color for the material used in lighting calculations.
  44468. */
  44469. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44470. /**
  44471. * If set to true, no lighting calculations will be applied.
  44472. */
  44473. _this._unlit = false;
  44474. // Setup the default processing configuration to the scene.
  44475. _this._attachImageProcessingConfiguration(null);
  44476. _this.getRenderTargetTextures = function () {
  44477. _this._renderTargets.reset();
  44478. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44479. _this._renderTargets.push(_this._reflectionTexture);
  44480. }
  44481. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44482. _this._renderTargets.push(_this._refractionTexture);
  44483. }
  44484. return _this._renderTargets;
  44485. };
  44486. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44487. return _this;
  44488. }
  44489. /**
  44490. * Attaches a new image processing configuration to the PBR Material.
  44491. * @param configuration
  44492. */
  44493. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44494. var _this = this;
  44495. if (configuration === this._imageProcessingConfiguration) {
  44496. return;
  44497. }
  44498. // Detaches observer.
  44499. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44500. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44501. }
  44502. // Pick the scene configuration if needed.
  44503. if (!configuration) {
  44504. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44505. }
  44506. else {
  44507. this._imageProcessingConfiguration = configuration;
  44508. }
  44509. // Attaches observer.
  44510. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44511. _this._markAllSubMeshesAsImageProcessingDirty();
  44512. });
  44513. };
  44514. /**
  44515. * Gets the name of the material class.
  44516. */
  44517. PBRBaseMaterial.prototype.getClassName = function () {
  44518. return "PBRBaseMaterial";
  44519. };
  44520. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44521. /**
  44522. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44523. */
  44524. get: function () {
  44525. return this._useLogarithmicDepth;
  44526. },
  44527. /**
  44528. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44529. */
  44530. set: function (value) {
  44531. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44532. },
  44533. enumerable: true,
  44534. configurable: true
  44535. });
  44536. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44537. /**
  44538. * Gets the current transparency mode.
  44539. */
  44540. get: function () {
  44541. return this._transparencyMode;
  44542. },
  44543. /**
  44544. * Sets the transparency mode of the material.
  44545. */
  44546. set: function (value) {
  44547. if (this._transparencyMode === value) {
  44548. return;
  44549. }
  44550. this._transparencyMode = value;
  44551. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44552. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44553. },
  44554. enumerable: true,
  44555. configurable: true
  44556. });
  44557. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44558. /**
  44559. * Returns true if alpha blending should be disabled.
  44560. */
  44561. get: function () {
  44562. return (this._linkRefractionWithTransparency ||
  44563. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44564. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44565. },
  44566. enumerable: true,
  44567. configurable: true
  44568. });
  44569. /**
  44570. * Specifies whether or not this material should be rendered in alpha blend mode.
  44571. */
  44572. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44573. if (this._disableAlphaBlending) {
  44574. return false;
  44575. }
  44576. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44577. };
  44578. /**
  44579. * Specifies if the mesh will require alpha blending.
  44580. * @param mesh - BJS mesh.
  44581. */
  44582. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44583. if (this._disableAlphaBlending) {
  44584. return false;
  44585. }
  44586. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44587. };
  44588. /**
  44589. * Specifies whether or not this material should be rendered in alpha test mode.
  44590. */
  44591. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44592. if (this._forceAlphaTest) {
  44593. return true;
  44594. }
  44595. if (this._linkRefractionWithTransparency) {
  44596. return false;
  44597. }
  44598. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44599. };
  44600. /**
  44601. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44602. */
  44603. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44604. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44605. };
  44606. /**
  44607. * Gets the texture used for the alpha test.
  44608. */
  44609. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44610. return this._albedoTexture;
  44611. };
  44612. /**
  44613. * Specifies that the submesh is ready to be used.
  44614. * @param mesh - BJS mesh.
  44615. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44616. * @param useInstances - Specifies that instances should be used.
  44617. * @returns - boolean indicating that the submesh is ready or not.
  44618. */
  44619. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44620. if (subMesh.effect && this.isFrozen) {
  44621. if (this._wasPreviouslyReady) {
  44622. return true;
  44623. }
  44624. }
  44625. if (!subMesh._materialDefines) {
  44626. subMesh._materialDefines = new PBRMaterialDefines();
  44627. }
  44628. var defines = subMesh._materialDefines;
  44629. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44630. if (defines._renderId === this.getScene().getRenderId()) {
  44631. return true;
  44632. }
  44633. }
  44634. var scene = this.getScene();
  44635. var engine = scene.getEngine();
  44636. if (defines._areTexturesDirty) {
  44637. if (scene.texturesEnabled) {
  44638. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44639. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44640. return false;
  44641. }
  44642. }
  44643. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44644. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44645. return false;
  44646. }
  44647. }
  44648. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44649. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44650. return false;
  44651. }
  44652. }
  44653. var reflectionTexture = this._getReflectionTexture();
  44654. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44655. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44656. return false;
  44657. }
  44658. }
  44659. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44660. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44661. return false;
  44662. }
  44663. }
  44664. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44665. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44666. return false;
  44667. }
  44668. }
  44669. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44670. if (this._metallicTexture) {
  44671. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44672. return false;
  44673. }
  44674. }
  44675. else if (this._reflectivityTexture) {
  44676. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44677. return false;
  44678. }
  44679. }
  44680. if (this._microSurfaceTexture) {
  44681. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44682. return false;
  44683. }
  44684. }
  44685. }
  44686. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44687. // Bump texture cannot be not blocking.
  44688. if (!this._bumpTexture.isReady()) {
  44689. return false;
  44690. }
  44691. }
  44692. var refractionTexture = this._getRefractionTexture();
  44693. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44694. if (!refractionTexture.isReadyOrNotBlocking()) {
  44695. return false;
  44696. }
  44697. }
  44698. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44699. // This is blocking.
  44700. if (!this._environmentBRDFTexture.isReady()) {
  44701. return false;
  44702. }
  44703. }
  44704. }
  44705. }
  44706. if (defines._areImageProcessingDirty) {
  44707. if (!this._imageProcessingConfiguration.isReady()) {
  44708. return false;
  44709. }
  44710. }
  44711. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44712. mesh.createNormals(true);
  44713. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44714. }
  44715. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44716. if (effect) {
  44717. scene.resetCachedMaterial();
  44718. subMesh.setEffect(effect, defines);
  44719. this.buildUniformLayout();
  44720. }
  44721. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44722. return false;
  44723. }
  44724. defines._renderId = scene.getRenderId();
  44725. this._wasPreviouslyReady = true;
  44726. return true;
  44727. };
  44728. /**
  44729. * Specifies if the material uses metallic roughness workflow.
  44730. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44731. */
  44732. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44733. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44734. return true;
  44735. }
  44736. return false;
  44737. };
  44738. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44739. if (onCompiled === void 0) { onCompiled = null; }
  44740. if (onError === void 0) { onError = null; }
  44741. if (useInstances === void 0) { useInstances = null; }
  44742. if (useClipPlane === void 0) { useClipPlane = null; }
  44743. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44744. if (!defines.isDirty) {
  44745. return null;
  44746. }
  44747. defines.markAsProcessed();
  44748. var scene = this.getScene();
  44749. var engine = scene.getEngine();
  44750. // Fallbacks
  44751. var fallbacks = new BABYLON.EffectFallbacks();
  44752. var fallbackRank = 0;
  44753. if (defines.USESPHERICALINVERTEX) {
  44754. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44755. }
  44756. if (defines.FOG) {
  44757. fallbacks.addFallback(fallbackRank, "FOG");
  44758. }
  44759. if (defines.POINTSIZE) {
  44760. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44761. }
  44762. if (defines.LOGARITHMICDEPTH) {
  44763. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44764. }
  44765. if (defines.PARALLAX) {
  44766. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44767. }
  44768. if (defines.PARALLAXOCCLUSION) {
  44769. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44770. }
  44771. if (defines.ENVIRONMENTBRDF) {
  44772. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44773. }
  44774. if (defines.TANGENT) {
  44775. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44776. }
  44777. if (defines.BUMP) {
  44778. fallbacks.addFallback(fallbackRank++, "BUMP");
  44779. }
  44780. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44781. if (defines.SPECULARTERM) {
  44782. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44783. }
  44784. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44785. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44786. }
  44787. if (defines.LIGHTMAP) {
  44788. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44789. }
  44790. if (defines.NORMAL) {
  44791. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44792. }
  44793. if (defines.AMBIENT) {
  44794. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44795. }
  44796. if (defines.EMISSIVE) {
  44797. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44798. }
  44799. if (defines.VERTEXCOLOR) {
  44800. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44801. }
  44802. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44803. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44804. }
  44805. if (defines.MORPHTARGETS) {
  44806. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44807. }
  44808. //Attributes
  44809. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44810. if (defines.NORMAL) {
  44811. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44812. }
  44813. if (defines.TANGENT) {
  44814. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44815. }
  44816. if (defines.UV1) {
  44817. attribs.push(BABYLON.VertexBuffer.UVKind);
  44818. }
  44819. if (defines.UV2) {
  44820. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44821. }
  44822. if (defines.VERTEXCOLOR) {
  44823. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44824. }
  44825. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44826. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44827. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44828. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44829. "vFogInfos", "vFogColor", "pointSize",
  44830. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44831. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44832. "mBones",
  44833. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44834. "vLightingIntensity",
  44835. "logarithmicDepthConstant",
  44836. "vSphericalX", "vSphericalY", "vSphericalZ",
  44837. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44838. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44839. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44840. "vTangentSpaceParams"
  44841. ];
  44842. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44843. "bumpSampler", "lightmapSampler", "opacitySampler",
  44844. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44845. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44846. "microSurfaceSampler", "environmentBrdfSampler"];
  44847. var uniformBuffers = ["Material", "Scene"];
  44848. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44849. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44850. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44851. uniformsNames: uniforms,
  44852. uniformBuffersNames: uniformBuffers,
  44853. samplers: samplers,
  44854. defines: defines,
  44855. maxSimultaneousLights: this._maxSimultaneousLights
  44856. });
  44857. var join = defines.toString();
  44858. return engine.createEffect("pbr", {
  44859. attributes: attribs,
  44860. uniformsNames: uniforms,
  44861. uniformBuffersNames: uniformBuffers,
  44862. samplers: samplers,
  44863. defines: join,
  44864. fallbacks: fallbacks,
  44865. onCompiled: onCompiled,
  44866. onError: onError,
  44867. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44868. }, engine);
  44869. };
  44870. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44871. if (useInstances === void 0) { useInstances = null; }
  44872. if (useClipPlane === void 0) { useClipPlane = null; }
  44873. var scene = this.getScene();
  44874. var engine = scene.getEngine();
  44875. // Lights
  44876. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44877. defines._needNormals = true;
  44878. // Textures
  44879. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44880. if (defines._areTexturesDirty) {
  44881. defines._needUVs = false;
  44882. if (scene.texturesEnabled) {
  44883. if (scene.getEngine().getCaps().textureLOD) {
  44884. defines.LODBASEDMICROSFURACE = true;
  44885. }
  44886. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44887. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44888. }
  44889. else {
  44890. defines.ALBEDO = false;
  44891. }
  44892. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44893. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44894. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44895. }
  44896. else {
  44897. defines.AMBIENT = false;
  44898. }
  44899. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44900. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44901. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44902. }
  44903. else {
  44904. defines.OPACITY = false;
  44905. }
  44906. var reflectionTexture = this._getReflectionTexture();
  44907. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44908. defines.REFLECTION = true;
  44909. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44910. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44911. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44912. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44913. defines.INVERTCUBICMAP = true;
  44914. }
  44915. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44916. switch (reflectionTexture.coordinatesMode) {
  44917. case BABYLON.Texture.CUBIC_MODE:
  44918. case BABYLON.Texture.INVCUBIC_MODE:
  44919. defines.REFLECTIONMAP_CUBIC = true;
  44920. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44921. break;
  44922. case BABYLON.Texture.EXPLICIT_MODE:
  44923. defines.REFLECTIONMAP_EXPLICIT = true;
  44924. break;
  44925. case BABYLON.Texture.PLANAR_MODE:
  44926. defines.REFLECTIONMAP_PLANAR = true;
  44927. break;
  44928. case BABYLON.Texture.PROJECTION_MODE:
  44929. defines.REFLECTIONMAP_PROJECTION = true;
  44930. break;
  44931. case BABYLON.Texture.SKYBOX_MODE:
  44932. defines.REFLECTIONMAP_SKYBOX = true;
  44933. break;
  44934. case BABYLON.Texture.SPHERICAL_MODE:
  44935. defines.REFLECTIONMAP_SPHERICAL = true;
  44936. break;
  44937. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44938. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44939. break;
  44940. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44941. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44942. break;
  44943. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44944. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44945. break;
  44946. }
  44947. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44948. if (reflectionTexture.sphericalPolynomial) {
  44949. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44950. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44951. defines.USESPHERICALINVERTEX = false;
  44952. }
  44953. else {
  44954. defines.USESPHERICALINVERTEX = true;
  44955. }
  44956. }
  44957. }
  44958. }
  44959. else {
  44960. defines.REFLECTION = false;
  44961. defines.REFLECTIONMAP_3D = false;
  44962. defines.REFLECTIONMAP_SPHERICAL = false;
  44963. defines.REFLECTIONMAP_PLANAR = false;
  44964. defines.REFLECTIONMAP_CUBIC = false;
  44965. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44966. defines.REFLECTIONMAP_PROJECTION = false;
  44967. defines.REFLECTIONMAP_SKYBOX = false;
  44968. defines.REFLECTIONMAP_EXPLICIT = false;
  44969. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44970. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44971. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44972. defines.INVERTCUBICMAP = false;
  44973. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44974. defines.USESPHERICALINVERTEX = false;
  44975. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44976. defines.LODINREFLECTIONALPHA = false;
  44977. defines.GAMMAREFLECTION = false;
  44978. }
  44979. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44980. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44981. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44982. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44983. }
  44984. else {
  44985. defines.LIGHTMAP = false;
  44986. }
  44987. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44988. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44989. }
  44990. else {
  44991. defines.EMISSIVE = false;
  44992. }
  44993. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44994. if (this._metallicTexture) {
  44995. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44996. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44997. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44998. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44999. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45000. }
  45001. else if (this._reflectivityTexture) {
  45002. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45003. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45004. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45005. }
  45006. else {
  45007. defines.REFLECTIVITY = false;
  45008. }
  45009. if (this._microSurfaceTexture) {
  45010. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45011. }
  45012. else {
  45013. defines.MICROSURFACEMAP = false;
  45014. }
  45015. }
  45016. else {
  45017. defines.REFLECTIVITY = false;
  45018. defines.MICROSURFACEMAP = false;
  45019. }
  45020. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45021. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45022. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45023. defines.PARALLAX = true;
  45024. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45025. }
  45026. else {
  45027. defines.PARALLAX = false;
  45028. }
  45029. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45030. }
  45031. else {
  45032. defines.BUMP = false;
  45033. }
  45034. var refractionTexture = this._getRefractionTexture();
  45035. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45036. defines.REFRACTION = true;
  45037. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45038. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45039. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45040. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45041. if (this._linkRefractionWithTransparency) {
  45042. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45043. }
  45044. }
  45045. else {
  45046. defines.REFRACTION = false;
  45047. }
  45048. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45049. defines.ENVIRONMENTBRDF = true;
  45050. }
  45051. else {
  45052. defines.ENVIRONMENTBRDF = false;
  45053. }
  45054. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45055. defines.ALPHAFROMALBEDO = true;
  45056. }
  45057. else {
  45058. defines.ALPHAFROMALBEDO = false;
  45059. }
  45060. }
  45061. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45062. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45063. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45064. if (!this.backFaceCulling && this._twoSidedLighting) {
  45065. defines.TWOSIDEDLIGHTING = true;
  45066. }
  45067. else {
  45068. defines.TWOSIDEDLIGHTING = false;
  45069. }
  45070. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45071. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45072. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45073. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45074. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45075. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45076. }
  45077. if (defines._areImageProcessingDirty) {
  45078. this._imageProcessingConfiguration.prepareDefines(defines);
  45079. }
  45080. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45081. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45082. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45083. // Misc.
  45084. if (defines._areMiscDirty) {
  45085. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45086. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45087. }
  45088. // Values that need to be evaluated on every frame
  45089. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45090. // Attribs
  45091. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45092. };
  45093. /**
  45094. * Force shader compilation
  45095. */
  45096. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45097. var _this = this;
  45098. var localOptions = __assign({ clipPlane: false }, options);
  45099. var defines = new PBRMaterialDefines();
  45100. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45101. if (effect.isReady()) {
  45102. if (onCompiled) {
  45103. onCompiled(this);
  45104. }
  45105. }
  45106. else {
  45107. effect.onCompileObservable.add(function () {
  45108. if (onCompiled) {
  45109. onCompiled(_this);
  45110. }
  45111. });
  45112. }
  45113. };
  45114. /**
  45115. * Initializes the uniform buffer layout for the shader.
  45116. */
  45117. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45118. // Order is important !
  45119. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45120. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45121. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45122. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45123. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45124. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45125. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45126. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45127. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45128. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45129. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45130. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45131. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45132. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45133. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45134. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45135. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45136. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45137. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45138. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45139. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45140. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45141. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45142. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45143. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45144. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45145. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45146. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45147. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45148. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45149. this._uniformBuffer.addUniform("pointSize", 1);
  45150. this._uniformBuffer.create();
  45151. };
  45152. /**
  45153. * Unbinds the textures.
  45154. */
  45155. PBRBaseMaterial.prototype.unbind = function () {
  45156. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45157. this._uniformBuffer.setTexture("reflectionSampler", null);
  45158. }
  45159. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45160. this._uniformBuffer.setTexture("refractionSampler", null);
  45161. }
  45162. _super.prototype.unbind.call(this);
  45163. };
  45164. /**
  45165. * Binds the submesh data.
  45166. * @param world - The world matrix.
  45167. * @param mesh - The BJS mesh.
  45168. * @param subMesh - A submesh of the BJS mesh.
  45169. */
  45170. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45171. var scene = this.getScene();
  45172. var defines = subMesh._materialDefines;
  45173. if (!defines) {
  45174. return;
  45175. }
  45176. var effect = subMesh.effect;
  45177. if (!effect) {
  45178. return;
  45179. }
  45180. this._activeEffect = effect;
  45181. // Matrices
  45182. this.bindOnlyWorldMatrix(world);
  45183. // Normal Matrix
  45184. if (defines.OBJECTSPACE_NORMALMAP) {
  45185. world.toNormalMatrix(this._normalMatrix);
  45186. this.bindOnlyNormalMatrix(this._normalMatrix);
  45187. }
  45188. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45189. // Bones
  45190. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45191. var reflectionTexture = null;
  45192. if (mustRebind) {
  45193. this._uniformBuffer.bindToEffect(effect, "Material");
  45194. this.bindViewProjection(effect);
  45195. reflectionTexture = this._getReflectionTexture();
  45196. var refractionTexture = this._getRefractionTexture();
  45197. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45198. // Texture uniforms
  45199. if (scene.texturesEnabled) {
  45200. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45201. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45202. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45203. }
  45204. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45205. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45206. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45207. }
  45208. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45209. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45210. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45211. }
  45212. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45213. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45214. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45215. if (reflectionTexture.boundingBoxSize) {
  45216. var cubeTexture = reflectionTexture;
  45217. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45218. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45219. }
  45220. var polynomials = reflectionTexture.sphericalPolynomial;
  45221. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45222. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45223. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45224. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45225. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45226. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45227. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45228. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45229. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45230. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45231. }
  45232. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45233. }
  45234. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45235. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45236. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45237. }
  45238. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45239. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45240. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45241. }
  45242. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45243. if (this._metallicTexture) {
  45244. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45245. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45246. }
  45247. else if (this._reflectivityTexture) {
  45248. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45249. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45250. }
  45251. if (this._microSurfaceTexture) {
  45252. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45253. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45254. }
  45255. }
  45256. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45257. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45258. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45259. if (scene._mirroredCameraPosition) {
  45260. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45261. }
  45262. else {
  45263. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45264. }
  45265. }
  45266. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45267. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45268. var depth = 1.0;
  45269. if (!refractionTexture.isCube) {
  45270. if (refractionTexture.depth) {
  45271. depth = refractionTexture.depth;
  45272. }
  45273. }
  45274. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45275. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45276. }
  45277. }
  45278. // Point size
  45279. if (this.pointsCloud) {
  45280. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45281. }
  45282. // Colors
  45283. if (defines.METALLICWORKFLOW) {
  45284. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45285. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45286. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45287. }
  45288. else {
  45289. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45290. }
  45291. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45292. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45293. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45294. // Misc
  45295. this._lightingInfos.x = this._directIntensity;
  45296. this._lightingInfos.y = this._emissiveIntensity;
  45297. this._lightingInfos.z = this._environmentIntensity;
  45298. this._lightingInfos.w = this._specularIntensity;
  45299. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45300. }
  45301. // Textures
  45302. if (scene.texturesEnabled) {
  45303. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45304. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45305. }
  45306. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45307. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45308. }
  45309. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45310. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45311. }
  45312. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45313. if (defines.LODBASEDMICROSFURACE) {
  45314. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45315. }
  45316. else {
  45317. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45318. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45319. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45320. }
  45321. }
  45322. if (defines.ENVIRONMENTBRDF) {
  45323. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45324. }
  45325. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45326. if (defines.LODBASEDMICROSFURACE) {
  45327. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45328. }
  45329. else {
  45330. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45331. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45332. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45333. }
  45334. }
  45335. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45336. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45337. }
  45338. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45339. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45340. }
  45341. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45342. if (this._metallicTexture) {
  45343. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45344. }
  45345. else if (this._reflectivityTexture) {
  45346. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45347. }
  45348. if (this._microSurfaceTexture) {
  45349. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45350. }
  45351. }
  45352. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45353. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45354. }
  45355. }
  45356. // Clip plane
  45357. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45358. // Colors
  45359. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45360. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45361. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45362. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45363. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45364. }
  45365. if (mustRebind || !this.isFrozen) {
  45366. // Lights
  45367. if (scene.lightsEnabled && !this._disableLighting) {
  45368. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45369. }
  45370. // View
  45371. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45372. this.bindView(effect);
  45373. }
  45374. // Fog
  45375. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45376. // Morph targets
  45377. if (defines.NUM_MORPH_INFLUENCERS) {
  45378. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45379. }
  45380. // image processing
  45381. this._imageProcessingConfiguration.bind(this._activeEffect);
  45382. // Log. depth
  45383. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45384. }
  45385. this._uniformBuffer.update();
  45386. this._afterBind(mesh);
  45387. };
  45388. /**
  45389. * Returns the animatable textures.
  45390. * @returns - Array of animatable textures.
  45391. */
  45392. PBRBaseMaterial.prototype.getAnimatables = function () {
  45393. var results = [];
  45394. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45395. results.push(this._albedoTexture);
  45396. }
  45397. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45398. results.push(this._ambientTexture);
  45399. }
  45400. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45401. results.push(this._opacityTexture);
  45402. }
  45403. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45404. results.push(this._reflectionTexture);
  45405. }
  45406. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45407. results.push(this._emissiveTexture);
  45408. }
  45409. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45410. results.push(this._metallicTexture);
  45411. }
  45412. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45413. results.push(this._reflectivityTexture);
  45414. }
  45415. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45416. results.push(this._bumpTexture);
  45417. }
  45418. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45419. results.push(this._lightmapTexture);
  45420. }
  45421. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45422. results.push(this._refractionTexture);
  45423. }
  45424. return results;
  45425. };
  45426. /**
  45427. * Returns the texture used for reflections.
  45428. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45429. */
  45430. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45431. if (this._reflectionTexture) {
  45432. return this._reflectionTexture;
  45433. }
  45434. return this.getScene().environmentTexture;
  45435. };
  45436. /**
  45437. * Returns the texture used for refraction or null if none is used.
  45438. * @returns - Refection texture if present. If no refraction texture and refraction
  45439. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45440. */
  45441. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45442. if (this._refractionTexture) {
  45443. return this._refractionTexture;
  45444. }
  45445. if (this._linkRefractionWithTransparency) {
  45446. return this.getScene().environmentTexture;
  45447. }
  45448. return null;
  45449. };
  45450. /**
  45451. * Disposes the resources of the material.
  45452. * @param forceDisposeEffect - Forces the disposal of effects.
  45453. * @param forceDisposeTextures - Forces the disposal of all textures.
  45454. */
  45455. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45456. if (forceDisposeTextures) {
  45457. if (this._albedoTexture) {
  45458. this._albedoTexture.dispose();
  45459. }
  45460. if (this._ambientTexture) {
  45461. this._ambientTexture.dispose();
  45462. }
  45463. if (this._opacityTexture) {
  45464. this._opacityTexture.dispose();
  45465. }
  45466. if (this._reflectionTexture) {
  45467. this._reflectionTexture.dispose();
  45468. }
  45469. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45470. this._environmentBRDFTexture.dispose();
  45471. }
  45472. if (this._emissiveTexture) {
  45473. this._emissiveTexture.dispose();
  45474. }
  45475. if (this._metallicTexture) {
  45476. this._metallicTexture.dispose();
  45477. }
  45478. if (this._reflectivityTexture) {
  45479. this._reflectivityTexture.dispose();
  45480. }
  45481. if (this._bumpTexture) {
  45482. this._bumpTexture.dispose();
  45483. }
  45484. if (this._lightmapTexture) {
  45485. this._lightmapTexture.dispose();
  45486. }
  45487. if (this._refractionTexture) {
  45488. this._refractionTexture.dispose();
  45489. }
  45490. }
  45491. this._renderTargets.dispose();
  45492. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45493. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45494. }
  45495. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45496. };
  45497. /**
  45498. * Stores the reflectivity values based on metallic roughness workflow.
  45499. */
  45500. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45501. __decorate([
  45502. BABYLON.serializeAsImageProcessingConfiguration()
  45503. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45504. __decorate([
  45505. BABYLON.serialize()
  45506. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45507. __decorate([
  45508. BABYLON.serialize()
  45509. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45510. return PBRBaseMaterial;
  45511. }(BABYLON.PushMaterial));
  45512. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45513. })(BABYLON || (BABYLON = {}));
  45514. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45515. var BABYLON;
  45516. (function (BABYLON) {
  45517. /**
  45518. * The Physically based simple base material of BJS.
  45519. *
  45520. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45521. * It is used as the base class for both the specGloss and metalRough conventions.
  45522. */
  45523. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45524. __extends(PBRBaseSimpleMaterial, _super);
  45525. /**
  45526. * Instantiates a new PBRMaterial instance.
  45527. *
  45528. * @param name The material name
  45529. * @param scene The scene the material will be use in.
  45530. */
  45531. function PBRBaseSimpleMaterial(name, scene) {
  45532. var _this = _super.call(this, name, scene) || this;
  45533. /**
  45534. * Number of Simultaneous lights allowed on the material.
  45535. */
  45536. _this.maxSimultaneousLights = 4;
  45537. /**
  45538. * If sets to true, disables all the lights affecting the material.
  45539. */
  45540. _this.disableLighting = false;
  45541. /**
  45542. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45543. */
  45544. _this.invertNormalMapX = false;
  45545. /**
  45546. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45547. */
  45548. _this.invertNormalMapY = false;
  45549. /**
  45550. * Emissivie color used to self-illuminate the model.
  45551. */
  45552. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45553. /**
  45554. * Occlusion Channel Strenght.
  45555. */
  45556. _this.occlusionStrength = 1.0;
  45557. _this.useLightmapAsShadowmap = false;
  45558. _this._useAlphaFromAlbedoTexture = true;
  45559. _this._useAmbientInGrayScale = true;
  45560. return _this;
  45561. }
  45562. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45563. /**
  45564. * Gets the current double sided mode.
  45565. */
  45566. get: function () {
  45567. return this._twoSidedLighting;
  45568. },
  45569. /**
  45570. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45571. */
  45572. set: function (value) {
  45573. if (this._twoSidedLighting === value) {
  45574. return;
  45575. }
  45576. this._twoSidedLighting = value;
  45577. this.backFaceCulling = !value;
  45578. this._markAllSubMeshesAsTexturesDirty();
  45579. },
  45580. enumerable: true,
  45581. configurable: true
  45582. });
  45583. /**
  45584. * Return the active textures of the material.
  45585. */
  45586. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45587. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45588. if (this.environmentTexture) {
  45589. activeTextures.push(this.environmentTexture);
  45590. }
  45591. if (this.normalTexture) {
  45592. activeTextures.push(this.normalTexture);
  45593. }
  45594. if (this.emissiveTexture) {
  45595. activeTextures.push(this.emissiveTexture);
  45596. }
  45597. if (this.occlusionTexture) {
  45598. activeTextures.push(this.occlusionTexture);
  45599. }
  45600. if (this.lightmapTexture) {
  45601. activeTextures.push(this.lightmapTexture);
  45602. }
  45603. return activeTextures;
  45604. };
  45605. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45606. if (_super.prototype.hasTexture.call(this, texture)) {
  45607. return true;
  45608. }
  45609. if (this.lightmapTexture === texture) {
  45610. return true;
  45611. }
  45612. return false;
  45613. };
  45614. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45615. return "PBRBaseSimpleMaterial";
  45616. };
  45617. __decorate([
  45618. BABYLON.serialize(),
  45619. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45620. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45621. __decorate([
  45622. BABYLON.serialize(),
  45623. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45624. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45625. __decorate([
  45626. BABYLON.serializeAsTexture(),
  45627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45628. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45629. __decorate([
  45630. BABYLON.serialize(),
  45631. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45632. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45633. __decorate([
  45634. BABYLON.serialize(),
  45635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45636. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45637. __decorate([
  45638. BABYLON.serializeAsTexture(),
  45639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45640. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45641. __decorate([
  45642. BABYLON.serializeAsColor3("emissive"),
  45643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45644. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45645. __decorate([
  45646. BABYLON.serializeAsTexture(),
  45647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45648. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45649. __decorate([
  45650. BABYLON.serialize(),
  45651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45652. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45653. __decorate([
  45654. BABYLON.serializeAsTexture(),
  45655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45656. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45657. __decorate([
  45658. BABYLON.serialize(),
  45659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45660. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45661. __decorate([
  45662. BABYLON.serialize()
  45663. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45664. __decorate([
  45665. BABYLON.serializeAsTexture(),
  45666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45667. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45668. __decorate([
  45669. BABYLON.serialize(),
  45670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45671. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45672. return PBRBaseSimpleMaterial;
  45673. }(BABYLON.PBRBaseMaterial));
  45674. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45675. })(BABYLON || (BABYLON = {}));
  45676. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45677. var BABYLON;
  45678. (function (BABYLON) {
  45679. /**
  45680. * The Physically based material of BJS.
  45681. *
  45682. * This offers the main features of a standard PBR material.
  45683. * For more information, please refer to the documentation :
  45684. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45685. */
  45686. var PBRMaterial = /** @class */ (function (_super) {
  45687. __extends(PBRMaterial, _super);
  45688. /**
  45689. * Instantiates a new PBRMaterial instance.
  45690. *
  45691. * @param name The material name
  45692. * @param scene The scene the material will be use in.
  45693. */
  45694. function PBRMaterial(name, scene) {
  45695. var _this = _super.call(this, name, scene) || this;
  45696. /**
  45697. * Intensity of the direct lights e.g. the four lights available in your scene.
  45698. * This impacts both the direct diffuse and specular highlights.
  45699. */
  45700. _this.directIntensity = 1.0;
  45701. /**
  45702. * Intensity of the emissive part of the material.
  45703. * This helps controlling the emissive effect without modifying the emissive color.
  45704. */
  45705. _this.emissiveIntensity = 1.0;
  45706. /**
  45707. * Intensity of the environment e.g. how much the environment will light the object
  45708. * either through harmonics for rough material or through the refelction for shiny ones.
  45709. */
  45710. _this.environmentIntensity = 1.0;
  45711. /**
  45712. * This is a special control allowing the reduction of the specular highlights coming from the
  45713. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45714. */
  45715. _this.specularIntensity = 1.0;
  45716. /**
  45717. * Debug Control allowing disabling the bump map on this material.
  45718. */
  45719. _this.disableBumpMap = false;
  45720. /**
  45721. * AKA Occlusion Texture Intensity in other nomenclature.
  45722. */
  45723. _this.ambientTextureStrength = 1.0;
  45724. /**
  45725. * The color of a material in ambient lighting.
  45726. */
  45727. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45728. /**
  45729. * AKA Diffuse Color in other nomenclature.
  45730. */
  45731. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45732. /**
  45733. * AKA Specular Color in other nomenclature.
  45734. */
  45735. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45736. /**
  45737. * The color reflected from the material.
  45738. */
  45739. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45740. /**
  45741. * The color emitted from the material.
  45742. */
  45743. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45744. /**
  45745. * AKA Glossiness in other nomenclature.
  45746. */
  45747. _this.microSurface = 1.0;
  45748. /**
  45749. * source material index of refraction (IOR)' / 'destination material IOR.
  45750. */
  45751. _this.indexOfRefraction = 0.66;
  45752. /**
  45753. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45754. */
  45755. _this.invertRefractionY = false;
  45756. /**
  45757. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45758. * Materials half opaque for instance using refraction could benefit from this control.
  45759. */
  45760. _this.linkRefractionWithTransparency = false;
  45761. _this.useLightmapAsShadowmap = false;
  45762. /**
  45763. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45764. */
  45765. _this.useAlphaFromAlbedoTexture = false;
  45766. /**
  45767. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45768. */
  45769. _this.forceAlphaTest = false;
  45770. /**
  45771. * Defines the alpha limits in alpha test mode.
  45772. */
  45773. _this.alphaCutOff = 0.4;
  45774. /**
  45775. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45776. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45777. */
  45778. _this.useSpecularOverAlpha = true;
  45779. /**
  45780. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45781. */
  45782. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45783. /**
  45784. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45785. */
  45786. _this.useRoughnessFromMetallicTextureAlpha = true;
  45787. /**
  45788. * Specifies if the metallic texture contains the roughness information in its green channel.
  45789. */
  45790. _this.useRoughnessFromMetallicTextureGreen = false;
  45791. /**
  45792. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45793. */
  45794. _this.useMetallnessFromMetallicTextureBlue = false;
  45795. /**
  45796. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45797. */
  45798. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45799. /**
  45800. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45801. */
  45802. _this.useAmbientInGrayScale = false;
  45803. /**
  45804. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45805. * The material will try to infer what glossiness each pixel should be.
  45806. */
  45807. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45808. /**
  45809. * BJS is using an harcoded light falloff based on a manually sets up range.
  45810. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45811. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45812. */
  45813. _this.usePhysicalLightFalloff = true;
  45814. /**
  45815. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45816. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45817. */
  45818. _this.useRadianceOverAlpha = true;
  45819. /**
  45820. * Allows using an object space normal map (instead of tangent space).
  45821. */
  45822. _this.useObjectSpaceNormalMap = false;
  45823. /**
  45824. * Allows using the bump map in parallax mode.
  45825. */
  45826. _this.useParallax = false;
  45827. /**
  45828. * Allows using the bump map in parallax occlusion mode.
  45829. */
  45830. _this.useParallaxOcclusion = false;
  45831. /**
  45832. * Controls the scale bias of the parallax mode.
  45833. */
  45834. _this.parallaxScaleBias = 0.05;
  45835. /**
  45836. * If sets to true, disables all the lights affecting the material.
  45837. */
  45838. _this.disableLighting = false;
  45839. /**
  45840. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45841. */
  45842. _this.forceIrradianceInFragment = false;
  45843. /**
  45844. * Number of Simultaneous lights allowed on the material.
  45845. */
  45846. _this.maxSimultaneousLights = 4;
  45847. /**
  45848. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45849. */
  45850. _this.invertNormalMapX = false;
  45851. /**
  45852. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45853. */
  45854. _this.invertNormalMapY = false;
  45855. /**
  45856. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45857. */
  45858. _this.twoSidedLighting = false;
  45859. /**
  45860. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45861. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45862. */
  45863. _this.useAlphaFresnel = false;
  45864. /**
  45865. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45866. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45867. */
  45868. _this.useLinearAlphaFresnel = false;
  45869. /**
  45870. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45871. * And/Or occlude the blended part.
  45872. */
  45873. _this.environmentBRDFTexture = null;
  45874. /**
  45875. * Force normal to face away from face.
  45876. */
  45877. _this.forceNormalForward = false;
  45878. /**
  45879. * Enables specular anti aliasing in the PBR shader.
  45880. * It will both interacts on the Geometry for analytical and IBL lighting.
  45881. * It also prefilter the roughness map based on the bump values.
  45882. */
  45883. _this.enableSpecularAntiAliasing = false;
  45884. /**
  45885. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45886. * makes the reflect vector face the model (under horizon).
  45887. */
  45888. _this.useHorizonOcclusion = true;
  45889. /**
  45890. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45891. * too much the area relying on ambient texture to define their ambient occlusion.
  45892. */
  45893. _this.useRadianceOcclusion = true;
  45894. /**
  45895. * If set to true, no lighting calculations will be applied.
  45896. */
  45897. _this.unlit = false;
  45898. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45899. return _this;
  45900. }
  45901. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45902. /**
  45903. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45904. */
  45905. get: function () {
  45906. return this._PBRMATERIAL_OPAQUE;
  45907. },
  45908. enumerable: true,
  45909. configurable: true
  45910. });
  45911. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45912. /**
  45913. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45914. */
  45915. get: function () {
  45916. return this._PBRMATERIAL_ALPHATEST;
  45917. },
  45918. enumerable: true,
  45919. configurable: true
  45920. });
  45921. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45922. /**
  45923. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45924. */
  45925. get: function () {
  45926. return this._PBRMATERIAL_ALPHABLEND;
  45927. },
  45928. enumerable: true,
  45929. configurable: true
  45930. });
  45931. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45932. /**
  45933. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45934. * They are also discarded below the alpha cutoff threshold to improve performances.
  45935. */
  45936. get: function () {
  45937. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45938. },
  45939. enumerable: true,
  45940. configurable: true
  45941. });
  45942. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45943. /**
  45944. * Gets the image processing configuration used either in this material.
  45945. */
  45946. get: function () {
  45947. return this._imageProcessingConfiguration;
  45948. },
  45949. /**
  45950. * Sets the Default image processing configuration used either in the this material.
  45951. *
  45952. * If sets to null, the scene one is in use.
  45953. */
  45954. set: function (value) {
  45955. this._attachImageProcessingConfiguration(value);
  45956. // Ensure the effect will be rebuilt.
  45957. this._markAllSubMeshesAsTexturesDirty();
  45958. },
  45959. enumerable: true,
  45960. configurable: true
  45961. });
  45962. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45963. /**
  45964. * Gets wether the color curves effect is enabled.
  45965. */
  45966. get: function () {
  45967. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45968. },
  45969. /**
  45970. * Sets wether the color curves effect is enabled.
  45971. */
  45972. set: function (value) {
  45973. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45974. },
  45975. enumerable: true,
  45976. configurable: true
  45977. });
  45978. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45979. /**
  45980. * Gets wether the color grading effect is enabled.
  45981. */
  45982. get: function () {
  45983. return this.imageProcessingConfiguration.colorGradingEnabled;
  45984. },
  45985. /**
  45986. * Gets wether the color grading effect is enabled.
  45987. */
  45988. set: function (value) {
  45989. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45990. },
  45991. enumerable: true,
  45992. configurable: true
  45993. });
  45994. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45995. /**
  45996. * Gets wether tonemapping is enabled or not.
  45997. */
  45998. get: function () {
  45999. return this._imageProcessingConfiguration.toneMappingEnabled;
  46000. },
  46001. /**
  46002. * Sets wether tonemapping is enabled or not
  46003. */
  46004. set: function (value) {
  46005. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46006. },
  46007. enumerable: true,
  46008. configurable: true
  46009. });
  46010. ;
  46011. ;
  46012. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46013. /**
  46014. * The camera exposure used on this material.
  46015. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46016. * This corresponds to a photographic exposure.
  46017. */
  46018. get: function () {
  46019. return this._imageProcessingConfiguration.exposure;
  46020. },
  46021. /**
  46022. * The camera exposure used on this material.
  46023. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46024. * This corresponds to a photographic exposure.
  46025. */
  46026. set: function (value) {
  46027. this._imageProcessingConfiguration.exposure = value;
  46028. },
  46029. enumerable: true,
  46030. configurable: true
  46031. });
  46032. ;
  46033. ;
  46034. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46035. /**
  46036. * Gets The camera contrast used on this material.
  46037. */
  46038. get: function () {
  46039. return this._imageProcessingConfiguration.contrast;
  46040. },
  46041. /**
  46042. * Sets The camera contrast used on this material.
  46043. */
  46044. set: function (value) {
  46045. this._imageProcessingConfiguration.contrast = value;
  46046. },
  46047. enumerable: true,
  46048. configurable: true
  46049. });
  46050. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46051. /**
  46052. * Gets the Color Grading 2D Lookup Texture.
  46053. */
  46054. get: function () {
  46055. return this._imageProcessingConfiguration.colorGradingTexture;
  46056. },
  46057. /**
  46058. * Sets the Color Grading 2D Lookup Texture.
  46059. */
  46060. set: function (value) {
  46061. this._imageProcessingConfiguration.colorGradingTexture = value;
  46062. },
  46063. enumerable: true,
  46064. configurable: true
  46065. });
  46066. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46067. /**
  46068. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46069. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46070. * 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;
  46071. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46072. */
  46073. get: function () {
  46074. return this._imageProcessingConfiguration.colorCurves;
  46075. },
  46076. /**
  46077. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46078. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46079. * 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;
  46080. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46081. */
  46082. set: function (value) {
  46083. this._imageProcessingConfiguration.colorCurves = value;
  46084. },
  46085. enumerable: true,
  46086. configurable: true
  46087. });
  46088. /**
  46089. * Returns the name of this material class.
  46090. */
  46091. PBRMaterial.prototype.getClassName = function () {
  46092. return "PBRMaterial";
  46093. };
  46094. /**
  46095. * Returns an array of the actively used textures.
  46096. * @returns - Array of BaseTextures
  46097. */
  46098. PBRMaterial.prototype.getActiveTextures = function () {
  46099. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46100. if (this._albedoTexture) {
  46101. activeTextures.push(this._albedoTexture);
  46102. }
  46103. if (this._ambientTexture) {
  46104. activeTextures.push(this._ambientTexture);
  46105. }
  46106. if (this._opacityTexture) {
  46107. activeTextures.push(this._opacityTexture);
  46108. }
  46109. if (this._reflectionTexture) {
  46110. activeTextures.push(this._reflectionTexture);
  46111. }
  46112. if (this._emissiveTexture) {
  46113. activeTextures.push(this._emissiveTexture);
  46114. }
  46115. if (this._reflectivityTexture) {
  46116. activeTextures.push(this._reflectivityTexture);
  46117. }
  46118. if (this._metallicTexture) {
  46119. activeTextures.push(this._metallicTexture);
  46120. }
  46121. if (this._microSurfaceTexture) {
  46122. activeTextures.push(this._microSurfaceTexture);
  46123. }
  46124. if (this._bumpTexture) {
  46125. activeTextures.push(this._bumpTexture);
  46126. }
  46127. if (this._lightmapTexture) {
  46128. activeTextures.push(this._lightmapTexture);
  46129. }
  46130. if (this._refractionTexture) {
  46131. activeTextures.push(this._refractionTexture);
  46132. }
  46133. return activeTextures;
  46134. };
  46135. /**
  46136. * Checks to see if a texture is used in the material.
  46137. * @param texture - Base texture to use.
  46138. * @returns - Boolean specifying if a texture is used in the material.
  46139. */
  46140. PBRMaterial.prototype.hasTexture = function (texture) {
  46141. if (_super.prototype.hasTexture.call(this, texture)) {
  46142. return true;
  46143. }
  46144. if (this._albedoTexture === texture) {
  46145. return true;
  46146. }
  46147. if (this._ambientTexture === texture) {
  46148. return true;
  46149. }
  46150. if (this._opacityTexture === texture) {
  46151. return true;
  46152. }
  46153. if (this._reflectionTexture === texture) {
  46154. return true;
  46155. }
  46156. if (this._reflectivityTexture === texture) {
  46157. return true;
  46158. }
  46159. if (this._metallicTexture === texture) {
  46160. return true;
  46161. }
  46162. if (this._microSurfaceTexture === texture) {
  46163. return true;
  46164. }
  46165. if (this._bumpTexture === texture) {
  46166. return true;
  46167. }
  46168. if (this._lightmapTexture === texture) {
  46169. return true;
  46170. }
  46171. if (this._refractionTexture === texture) {
  46172. return true;
  46173. }
  46174. return false;
  46175. };
  46176. /**
  46177. * Makes a duplicate of the current material.
  46178. * @param name - name to use for the new material.
  46179. */
  46180. PBRMaterial.prototype.clone = function (name) {
  46181. var _this = this;
  46182. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46183. clone.id = name;
  46184. clone.name = name;
  46185. return clone;
  46186. };
  46187. /**
  46188. * Serializes this PBR Material.
  46189. * @returns - An object with the serialized material.
  46190. */
  46191. PBRMaterial.prototype.serialize = function () {
  46192. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46193. serializationObject.customType = "BABYLON.PBRMaterial";
  46194. return serializationObject;
  46195. };
  46196. // Statics
  46197. /**
  46198. * Parses a PBR Material from a serialized object.
  46199. * @param source - Serialized object.
  46200. * @param scene - BJS scene instance.
  46201. * @param rootUrl - url for the scene object
  46202. * @returns - PBRMaterial
  46203. */
  46204. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46205. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46206. };
  46207. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46208. /**
  46209. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46210. */
  46211. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46212. /**
  46213. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46214. */
  46215. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46216. /**
  46217. * 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.
  46218. * They are also discarded below the alpha cutoff threshold to improve performances.
  46219. */
  46220. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46221. __decorate([
  46222. BABYLON.serialize(),
  46223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46224. ], PBRMaterial.prototype, "directIntensity", void 0);
  46225. __decorate([
  46226. BABYLON.serialize(),
  46227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46228. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46229. __decorate([
  46230. BABYLON.serialize(),
  46231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46232. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46233. __decorate([
  46234. BABYLON.serialize(),
  46235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46236. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46237. __decorate([
  46238. BABYLON.serialize(),
  46239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46240. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46241. __decorate([
  46242. BABYLON.serializeAsTexture(),
  46243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46244. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46245. __decorate([
  46246. BABYLON.serializeAsTexture(),
  46247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46248. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46249. __decorate([
  46250. BABYLON.serialize(),
  46251. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46252. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46253. __decorate([
  46254. BABYLON.serializeAsTexture(),
  46255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46256. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46257. __decorate([
  46258. BABYLON.serializeAsTexture(),
  46259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46260. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46261. __decorate([
  46262. BABYLON.serializeAsTexture(),
  46263. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46264. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46265. __decorate([
  46266. BABYLON.serializeAsTexture(),
  46267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46268. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46269. __decorate([
  46270. BABYLON.serializeAsTexture(),
  46271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46272. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46273. __decorate([
  46274. BABYLON.serialize(),
  46275. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46276. ], PBRMaterial.prototype, "metallic", void 0);
  46277. __decorate([
  46278. BABYLON.serialize(),
  46279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46280. ], PBRMaterial.prototype, "roughness", void 0);
  46281. __decorate([
  46282. BABYLON.serializeAsTexture(),
  46283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46284. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46285. __decorate([
  46286. BABYLON.serializeAsTexture(),
  46287. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46288. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46289. __decorate([
  46290. BABYLON.serializeAsTexture(),
  46291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46292. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46293. __decorate([
  46294. BABYLON.serializeAsTexture(),
  46295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46296. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46297. __decorate([
  46298. BABYLON.serializeAsColor3("ambient"),
  46299. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46300. ], PBRMaterial.prototype, "ambientColor", void 0);
  46301. __decorate([
  46302. BABYLON.serializeAsColor3("albedo"),
  46303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46304. ], PBRMaterial.prototype, "albedoColor", void 0);
  46305. __decorate([
  46306. BABYLON.serializeAsColor3("reflectivity"),
  46307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46308. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46309. __decorate([
  46310. BABYLON.serializeAsColor3("reflection"),
  46311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46312. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46313. __decorate([
  46314. BABYLON.serializeAsColor3("emissive"),
  46315. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46316. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46317. __decorate([
  46318. BABYLON.serialize(),
  46319. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46320. ], PBRMaterial.prototype, "microSurface", void 0);
  46321. __decorate([
  46322. BABYLON.serialize(),
  46323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46324. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46325. __decorate([
  46326. BABYLON.serialize(),
  46327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46328. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46329. __decorate([
  46330. BABYLON.serialize(),
  46331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46332. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46333. __decorate([
  46334. BABYLON.serialize(),
  46335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46336. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46337. __decorate([
  46338. BABYLON.serialize(),
  46339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46340. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46341. __decorate([
  46342. BABYLON.serialize(),
  46343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46344. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46345. __decorate([
  46346. BABYLON.serialize(),
  46347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46348. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46349. __decorate([
  46350. BABYLON.serialize(),
  46351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46352. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46353. __decorate([
  46354. BABYLON.serialize(),
  46355. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46356. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46357. __decorate([
  46358. BABYLON.serialize(),
  46359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46360. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46361. __decorate([
  46362. BABYLON.serialize(),
  46363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46364. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46365. __decorate([
  46366. BABYLON.serialize(),
  46367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46368. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46369. __decorate([
  46370. BABYLON.serialize(),
  46371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46372. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46373. __decorate([
  46374. BABYLON.serialize(),
  46375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46376. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46377. __decorate([
  46378. BABYLON.serialize(),
  46379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46380. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46381. __decorate([
  46382. BABYLON.serialize(),
  46383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46384. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46385. __decorate([
  46386. BABYLON.serialize(),
  46387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46388. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46389. __decorate([
  46390. BABYLON.serialize(),
  46391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46392. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46393. __decorate([
  46394. BABYLON.serialize(),
  46395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46396. ], PBRMaterial.prototype, "useParallax", void 0);
  46397. __decorate([
  46398. BABYLON.serialize(),
  46399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46400. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46401. __decorate([
  46402. BABYLON.serialize(),
  46403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46404. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46405. __decorate([
  46406. BABYLON.serialize(),
  46407. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46408. ], PBRMaterial.prototype, "disableLighting", void 0);
  46409. __decorate([
  46410. BABYLON.serialize(),
  46411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46412. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46413. __decorate([
  46414. BABYLON.serialize(),
  46415. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46416. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46417. __decorate([
  46418. BABYLON.serialize(),
  46419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46420. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46421. __decorate([
  46422. BABYLON.serialize(),
  46423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46424. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46425. __decorate([
  46426. BABYLON.serialize(),
  46427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46428. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46429. __decorate([
  46430. BABYLON.serialize(),
  46431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46432. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46433. __decorate([
  46434. BABYLON.serialize(),
  46435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46436. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46437. __decorate([
  46438. BABYLON.serializeAsTexture(),
  46439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46440. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46441. __decorate([
  46442. BABYLON.serialize(),
  46443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46444. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46445. __decorate([
  46446. BABYLON.serialize(),
  46447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46448. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46449. __decorate([
  46450. BABYLON.serialize(),
  46451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46452. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46453. __decorate([
  46454. BABYLON.serialize(),
  46455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46456. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46457. __decorate([
  46458. BABYLON.serialize(),
  46459. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46460. ], PBRMaterial.prototype, "unlit", void 0);
  46461. return PBRMaterial;
  46462. }(BABYLON.PBRBaseMaterial));
  46463. BABYLON.PBRMaterial = PBRMaterial;
  46464. })(BABYLON || (BABYLON = {}));
  46465. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46466. var BABYLON;
  46467. (function (BABYLON) {
  46468. /**
  46469. * The PBR material of BJS following the metal roughness convention.
  46470. *
  46471. * This fits to the PBR convention in the GLTF definition:
  46472. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46473. */
  46474. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46475. __extends(PBRMetallicRoughnessMaterial, _super);
  46476. /**
  46477. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46478. *
  46479. * @param name The material name
  46480. * @param scene The scene the material will be use in.
  46481. */
  46482. function PBRMetallicRoughnessMaterial(name, scene) {
  46483. var _this = _super.call(this, name, scene) || this;
  46484. _this._useRoughnessFromMetallicTextureAlpha = false;
  46485. _this._useRoughnessFromMetallicTextureGreen = true;
  46486. _this._useMetallnessFromMetallicTextureBlue = true;
  46487. _this.metallic = 1.0;
  46488. _this.roughness = 1.0;
  46489. return _this;
  46490. }
  46491. /**
  46492. * Return the currrent class name of the material.
  46493. */
  46494. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46495. return "PBRMetallicRoughnessMaterial";
  46496. };
  46497. /**
  46498. * Return the active textures of the material.
  46499. */
  46500. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46501. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46502. if (this.baseTexture) {
  46503. activeTextures.push(this.baseTexture);
  46504. }
  46505. if (this.metallicRoughnessTexture) {
  46506. activeTextures.push(this.metallicRoughnessTexture);
  46507. }
  46508. return activeTextures;
  46509. };
  46510. /**
  46511. * Checks to see if a texture is used in the material.
  46512. * @param texture - Base texture to use.
  46513. * @returns - Boolean specifying if a texture is used in the material.
  46514. */
  46515. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46516. if (_super.prototype.hasTexture.call(this, texture)) {
  46517. return true;
  46518. }
  46519. if (this.baseTexture === texture) {
  46520. return true;
  46521. }
  46522. if (this.metallicRoughnessTexture === texture) {
  46523. return true;
  46524. }
  46525. return false;
  46526. };
  46527. /**
  46528. * Makes a duplicate of the current material.
  46529. * @param name - name to use for the new material.
  46530. */
  46531. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46532. var _this = this;
  46533. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46534. clone.id = name;
  46535. clone.name = name;
  46536. return clone;
  46537. };
  46538. /**
  46539. * Serialize the material to a parsable JSON object.
  46540. */
  46541. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46542. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46543. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46544. return serializationObject;
  46545. };
  46546. /**
  46547. * Parses a JSON object correponding to the serialize function.
  46548. */
  46549. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46550. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46551. };
  46552. __decorate([
  46553. BABYLON.serializeAsColor3(),
  46554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46555. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46556. __decorate([
  46557. BABYLON.serializeAsTexture(),
  46558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46559. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46560. __decorate([
  46561. BABYLON.serialize(),
  46562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46563. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46564. __decorate([
  46565. BABYLON.serialize(),
  46566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46567. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46568. __decorate([
  46569. BABYLON.serializeAsTexture(),
  46570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46571. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46572. return PBRMetallicRoughnessMaterial;
  46573. }(BABYLON.PBRBaseSimpleMaterial));
  46574. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46575. })(BABYLON || (BABYLON = {}));
  46576. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46577. var BABYLON;
  46578. (function (BABYLON) {
  46579. /**
  46580. * The PBR material of BJS following the specular glossiness convention.
  46581. *
  46582. * This fits to the PBR convention in the GLTF definition:
  46583. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46584. */
  46585. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46586. __extends(PBRSpecularGlossinessMaterial, _super);
  46587. /**
  46588. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46589. *
  46590. * @param name The material name
  46591. * @param scene The scene the material will be use in.
  46592. */
  46593. function PBRSpecularGlossinessMaterial(name, scene) {
  46594. var _this = _super.call(this, name, scene) || this;
  46595. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46596. return _this;
  46597. }
  46598. /**
  46599. * Return the currrent class name of the material.
  46600. */
  46601. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46602. return "PBRSpecularGlossinessMaterial";
  46603. };
  46604. /**
  46605. * Return the active textures of the material.
  46606. */
  46607. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46608. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46609. if (this.diffuseTexture) {
  46610. activeTextures.push(this.diffuseTexture);
  46611. }
  46612. if (this.specularGlossinessTexture) {
  46613. activeTextures.push(this.specularGlossinessTexture);
  46614. }
  46615. return activeTextures;
  46616. };
  46617. /**
  46618. * Checks to see if a texture is used in the material.
  46619. * @param texture - Base texture to use.
  46620. * @returns - Boolean specifying if a texture is used in the material.
  46621. */
  46622. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46623. if (_super.prototype.hasTexture.call(this, texture)) {
  46624. return true;
  46625. }
  46626. if (this.diffuseTexture === texture) {
  46627. return true;
  46628. }
  46629. if (this.specularGlossinessTexture === texture) {
  46630. return true;
  46631. }
  46632. return false;
  46633. };
  46634. /**
  46635. * Makes a duplicate of the current material.
  46636. * @param name - name to use for the new material.
  46637. */
  46638. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46639. var _this = this;
  46640. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46641. clone.id = name;
  46642. clone.name = name;
  46643. return clone;
  46644. };
  46645. /**
  46646. * Serialize the material to a parsable JSON object.
  46647. */
  46648. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46649. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46650. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46651. return serializationObject;
  46652. };
  46653. /**
  46654. * Parses a JSON object correponding to the serialize function.
  46655. */
  46656. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46657. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46658. };
  46659. __decorate([
  46660. BABYLON.serializeAsColor3("diffuse"),
  46661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46662. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46663. __decorate([
  46664. BABYLON.serializeAsTexture(),
  46665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46666. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46667. __decorate([
  46668. BABYLON.serializeAsColor3("specular"),
  46669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46670. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46671. __decorate([
  46672. BABYLON.serialize(),
  46673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46674. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46675. __decorate([
  46676. BABYLON.serializeAsTexture(),
  46677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46678. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46679. return PBRSpecularGlossinessMaterial;
  46680. }(BABYLON.PBRBaseSimpleMaterial));
  46681. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46682. })(BABYLON || (BABYLON = {}));
  46683. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46684. var BABYLON;
  46685. (function (BABYLON) {
  46686. BABYLON.CameraInputTypes = {};
  46687. var CameraInputsManager = /** @class */ (function () {
  46688. function CameraInputsManager(camera) {
  46689. this.attached = {};
  46690. this.camera = camera;
  46691. this.checkInputs = function () { };
  46692. }
  46693. /**
  46694. * Add an input method to a camera.
  46695. * builtin inputs example: camera.inputs.addGamepad();
  46696. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46697. * @param input camera input method
  46698. */
  46699. CameraInputsManager.prototype.add = function (input) {
  46700. var type = input.getSimpleName();
  46701. if (this.attached[type]) {
  46702. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46703. return;
  46704. }
  46705. this.attached[type] = input;
  46706. input.camera = this.camera;
  46707. //for checkInputs, we are dynamically creating a function
  46708. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46709. if (input.checkInputs) {
  46710. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46711. }
  46712. if (this.attachedElement) {
  46713. input.attachControl(this.attachedElement);
  46714. }
  46715. };
  46716. /**
  46717. * Remove a specific input method from a camera
  46718. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46719. * @param inputToRemove camera input method
  46720. */
  46721. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46722. for (var cam in this.attached) {
  46723. var input = this.attached[cam];
  46724. if (input === inputToRemove) {
  46725. input.detachControl(this.attachedElement);
  46726. input.camera = null;
  46727. delete this.attached[cam];
  46728. this.rebuildInputCheck();
  46729. }
  46730. }
  46731. };
  46732. CameraInputsManager.prototype.removeByType = function (inputType) {
  46733. for (var cam in this.attached) {
  46734. var input = this.attached[cam];
  46735. if (input.getClassName() === inputType) {
  46736. input.detachControl(this.attachedElement);
  46737. input.camera = null;
  46738. delete this.attached[cam];
  46739. this.rebuildInputCheck();
  46740. }
  46741. }
  46742. };
  46743. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46744. var current = this.checkInputs;
  46745. return function () {
  46746. current();
  46747. fn();
  46748. };
  46749. };
  46750. CameraInputsManager.prototype.attachInput = function (input) {
  46751. if (this.attachedElement) {
  46752. input.attachControl(this.attachedElement, this.noPreventDefault);
  46753. }
  46754. };
  46755. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46756. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46757. if (this.attachedElement) {
  46758. return;
  46759. }
  46760. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46761. this.attachedElement = element;
  46762. this.noPreventDefault = noPreventDefault;
  46763. for (var cam in this.attached) {
  46764. this.attached[cam].attachControl(element, noPreventDefault);
  46765. }
  46766. };
  46767. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46768. if (disconnect === void 0) { disconnect = false; }
  46769. if (this.attachedElement !== element) {
  46770. return;
  46771. }
  46772. for (var cam in this.attached) {
  46773. this.attached[cam].detachControl(element);
  46774. if (disconnect) {
  46775. this.attached[cam].camera = null;
  46776. }
  46777. }
  46778. this.attachedElement = null;
  46779. };
  46780. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46781. this.checkInputs = function () { };
  46782. for (var cam in this.attached) {
  46783. var input = this.attached[cam];
  46784. if (input.checkInputs) {
  46785. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46786. }
  46787. }
  46788. };
  46789. /**
  46790. * Remove all attached input methods from a camera
  46791. */
  46792. CameraInputsManager.prototype.clear = function () {
  46793. if (this.attachedElement) {
  46794. this.detachElement(this.attachedElement, true);
  46795. }
  46796. this.attached = {};
  46797. this.attachedElement = null;
  46798. this.checkInputs = function () { };
  46799. };
  46800. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46801. var inputs = {};
  46802. for (var cam in this.attached) {
  46803. var input = this.attached[cam];
  46804. var res = BABYLON.SerializationHelper.Serialize(input);
  46805. inputs[input.getClassName()] = res;
  46806. }
  46807. serializedCamera.inputsmgr = inputs;
  46808. };
  46809. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46810. var parsedInputs = parsedCamera.inputsmgr;
  46811. if (parsedInputs) {
  46812. this.clear();
  46813. for (var n in parsedInputs) {
  46814. var construct = BABYLON.CameraInputTypes[n];
  46815. if (construct) {
  46816. var parsedinput = parsedInputs[n];
  46817. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46818. this.add(input);
  46819. }
  46820. }
  46821. }
  46822. else {
  46823. //2016-03-08 this part is for managing backward compatibility
  46824. for (var n in this.attached) {
  46825. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46826. if (construct) {
  46827. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46828. this.remove(this.attached[n]);
  46829. this.add(input);
  46830. }
  46831. }
  46832. }
  46833. };
  46834. return CameraInputsManager;
  46835. }());
  46836. BABYLON.CameraInputsManager = CameraInputsManager;
  46837. })(BABYLON || (BABYLON = {}));
  46838. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46839. var BABYLON;
  46840. (function (BABYLON) {
  46841. var TargetCamera = /** @class */ (function (_super) {
  46842. __extends(TargetCamera, _super);
  46843. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46844. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46845. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46846. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46847. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46848. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46849. _this.speed = 2.0;
  46850. _this.noRotationConstraint = false;
  46851. _this.lockedTarget = null;
  46852. _this._currentTarget = BABYLON.Vector3.Zero();
  46853. _this._viewMatrix = BABYLON.Matrix.Zero();
  46854. _this._camMatrix = BABYLON.Matrix.Zero();
  46855. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46856. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46857. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46858. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46859. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46860. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46861. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46862. return _this;
  46863. }
  46864. TargetCamera.prototype.getFrontPosition = function (distance) {
  46865. this.getWorldMatrix();
  46866. var direction = this.getTarget().subtract(this.position);
  46867. direction.normalize();
  46868. direction.scaleInPlace(distance);
  46869. return this.globalPosition.add(direction);
  46870. };
  46871. TargetCamera.prototype._getLockedTargetPosition = function () {
  46872. if (!this.lockedTarget) {
  46873. return null;
  46874. }
  46875. if (this.lockedTarget.absolutePosition) {
  46876. this.lockedTarget.computeWorldMatrix();
  46877. }
  46878. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46879. };
  46880. TargetCamera.prototype.storeState = function () {
  46881. this._storedPosition = this.position.clone();
  46882. this._storedRotation = this.rotation.clone();
  46883. if (this.rotationQuaternion) {
  46884. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46885. }
  46886. return _super.prototype.storeState.call(this);
  46887. };
  46888. /**
  46889. * Restored camera state. You must call storeState() first
  46890. */
  46891. TargetCamera.prototype._restoreStateValues = function () {
  46892. if (!_super.prototype._restoreStateValues.call(this)) {
  46893. return false;
  46894. }
  46895. this.position = this._storedPosition.clone();
  46896. this.rotation = this._storedRotation.clone();
  46897. if (this.rotationQuaternion) {
  46898. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46899. }
  46900. this.cameraDirection.copyFromFloats(0, 0, 0);
  46901. this.cameraRotation.copyFromFloats(0, 0);
  46902. return true;
  46903. };
  46904. // Cache
  46905. TargetCamera.prototype._initCache = function () {
  46906. _super.prototype._initCache.call(this);
  46907. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46908. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46909. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46910. };
  46911. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46912. if (!ignoreParentClass) {
  46913. _super.prototype._updateCache.call(this);
  46914. }
  46915. var lockedTargetPosition = this._getLockedTargetPosition();
  46916. if (!lockedTargetPosition) {
  46917. this._cache.lockedTarget = null;
  46918. }
  46919. else {
  46920. if (!this._cache.lockedTarget) {
  46921. this._cache.lockedTarget = lockedTargetPosition.clone();
  46922. }
  46923. else {
  46924. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46925. }
  46926. }
  46927. this._cache.rotation.copyFrom(this.rotation);
  46928. if (this.rotationQuaternion)
  46929. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46930. };
  46931. // Synchronized
  46932. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46933. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46934. return false;
  46935. }
  46936. var lockedTargetPosition = this._getLockedTargetPosition();
  46937. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46938. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46939. };
  46940. // Methods
  46941. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46942. var engine = this.getEngine();
  46943. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46944. };
  46945. // Target
  46946. TargetCamera.prototype.setTarget = function (target) {
  46947. this.upVector.normalize();
  46948. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46949. this._camMatrix.invert();
  46950. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46951. var vDir = target.subtract(this.position);
  46952. if (vDir.x >= 0.0) {
  46953. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46954. }
  46955. else {
  46956. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46957. }
  46958. this.rotation.z = 0;
  46959. if (isNaN(this.rotation.x)) {
  46960. this.rotation.x = 0;
  46961. }
  46962. if (isNaN(this.rotation.y)) {
  46963. this.rotation.y = 0;
  46964. }
  46965. if (isNaN(this.rotation.z)) {
  46966. this.rotation.z = 0;
  46967. }
  46968. if (this.rotationQuaternion) {
  46969. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46970. }
  46971. };
  46972. /**
  46973. * Return the current target position of the camera. This value is expressed in local space.
  46974. */
  46975. TargetCamera.prototype.getTarget = function () {
  46976. return this._currentTarget;
  46977. };
  46978. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46979. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46980. };
  46981. TargetCamera.prototype._updatePosition = function () {
  46982. if (this.parent) {
  46983. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46984. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46985. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46986. return;
  46987. }
  46988. this.position.addInPlace(this.cameraDirection);
  46989. };
  46990. TargetCamera.prototype._checkInputs = function () {
  46991. var needToMove = this._decideIfNeedsToMove();
  46992. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46993. // Move
  46994. if (needToMove) {
  46995. this._updatePosition();
  46996. }
  46997. // Rotate
  46998. if (needToRotate) {
  46999. this.rotation.x += this.cameraRotation.x;
  47000. this.rotation.y += this.cameraRotation.y;
  47001. //rotate, if quaternion is set and rotation was used
  47002. if (this.rotationQuaternion) {
  47003. var len = this.rotation.lengthSquared();
  47004. if (len) {
  47005. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47006. }
  47007. }
  47008. if (!this.noRotationConstraint) {
  47009. var limit = (Math.PI / 2) * 0.95;
  47010. if (this.rotation.x > limit)
  47011. this.rotation.x = limit;
  47012. if (this.rotation.x < -limit)
  47013. this.rotation.x = -limit;
  47014. }
  47015. }
  47016. // Inertia
  47017. if (needToMove) {
  47018. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47019. this.cameraDirection.x = 0;
  47020. }
  47021. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47022. this.cameraDirection.y = 0;
  47023. }
  47024. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47025. this.cameraDirection.z = 0;
  47026. }
  47027. this.cameraDirection.scaleInPlace(this.inertia);
  47028. }
  47029. if (needToRotate) {
  47030. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47031. this.cameraRotation.x = 0;
  47032. }
  47033. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47034. this.cameraRotation.y = 0;
  47035. }
  47036. this.cameraRotation.scaleInPlace(this.inertia);
  47037. }
  47038. _super.prototype._checkInputs.call(this);
  47039. };
  47040. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47041. if (this.rotationQuaternion) {
  47042. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47043. }
  47044. else {
  47045. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47046. }
  47047. //update the up vector!
  47048. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47049. };
  47050. TargetCamera.prototype._getViewMatrix = function () {
  47051. if (this.lockedTarget) {
  47052. this.setTarget(this._getLockedTargetPosition());
  47053. }
  47054. // Compute
  47055. this._updateCameraRotationMatrix();
  47056. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47057. // Computing target and final matrix
  47058. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47059. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47060. return this._viewMatrix;
  47061. };
  47062. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47063. if (this.parent) {
  47064. var parentWorldMatrix = this.parent.getWorldMatrix();
  47065. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47066. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47067. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47068. this._markSyncedWithParent();
  47069. }
  47070. else {
  47071. this._globalPosition.copyFrom(this.position);
  47072. this._globalCurrentTarget.copyFrom(target);
  47073. this._globalCurrentUpVector.copyFrom(up);
  47074. }
  47075. if (this.getScene().useRightHandedSystem) {
  47076. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47077. }
  47078. else {
  47079. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47080. }
  47081. };
  47082. /**
  47083. * @override
  47084. * Override Camera.createRigCamera
  47085. */
  47086. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47087. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47088. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47089. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47090. if (!this.rotationQuaternion) {
  47091. this.rotationQuaternion = new BABYLON.Quaternion();
  47092. }
  47093. rigCamera._cameraRigParams = {};
  47094. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47095. }
  47096. return rigCamera;
  47097. }
  47098. return null;
  47099. };
  47100. /**
  47101. * @override
  47102. * Override Camera._updateRigCameras
  47103. */
  47104. TargetCamera.prototype._updateRigCameras = function () {
  47105. var camLeft = this._rigCameras[0];
  47106. var camRight = this._rigCameras[1];
  47107. switch (this.cameraRigMode) {
  47108. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47109. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47110. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47111. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47112. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47113. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47114. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47115. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47116. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47117. camLeft.setTarget(this.getTarget());
  47118. camRight.setTarget(this.getTarget());
  47119. break;
  47120. case BABYLON.Camera.RIG_MODE_VR:
  47121. if (camLeft.rotationQuaternion) {
  47122. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47123. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47124. }
  47125. else {
  47126. camLeft.rotation.copyFrom(this.rotation);
  47127. camRight.rotation.copyFrom(this.rotation);
  47128. }
  47129. camLeft.position.copyFrom(this.position);
  47130. camRight.position.copyFrom(this.position);
  47131. break;
  47132. }
  47133. _super.prototype._updateRigCameras.call(this);
  47134. };
  47135. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47136. if (!this._rigCamTransformMatrix) {
  47137. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47138. }
  47139. var target = this.getTarget();
  47140. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47141. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47142. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47143. };
  47144. TargetCamera.prototype.getClassName = function () {
  47145. return "TargetCamera";
  47146. };
  47147. __decorate([
  47148. BABYLON.serializeAsVector3()
  47149. ], TargetCamera.prototype, "rotation", void 0);
  47150. __decorate([
  47151. BABYLON.serialize()
  47152. ], TargetCamera.prototype, "speed", void 0);
  47153. __decorate([
  47154. BABYLON.serializeAsMeshReference("lockedTargetId")
  47155. ], TargetCamera.prototype, "lockedTarget", void 0);
  47156. return TargetCamera;
  47157. }(BABYLON.Camera));
  47158. BABYLON.TargetCamera = TargetCamera;
  47159. })(BABYLON || (BABYLON = {}));
  47160. //# sourceMappingURL=babylon.targetCamera.js.map
  47161. var BABYLON;
  47162. (function (BABYLON) {
  47163. var FreeCameraMouseInput = /** @class */ (function () {
  47164. function FreeCameraMouseInput(touchEnabled) {
  47165. if (touchEnabled === void 0) { touchEnabled = true; }
  47166. this.touchEnabled = touchEnabled;
  47167. this.buttons = [0, 1, 2];
  47168. this.angularSensibility = 2000.0;
  47169. this.previousPosition = null;
  47170. }
  47171. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47172. var _this = this;
  47173. var engine = this.camera.getEngine();
  47174. if (!this._pointerInput) {
  47175. this._pointerInput = function (p, s) {
  47176. var evt = p.event;
  47177. if (engine.isInVRExclusivePointerMode) {
  47178. return;
  47179. }
  47180. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47181. return;
  47182. }
  47183. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47184. return;
  47185. }
  47186. var srcElement = (evt.srcElement || evt.target);
  47187. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47188. try {
  47189. srcElement.setPointerCapture(evt.pointerId);
  47190. }
  47191. catch (e) {
  47192. //Nothing to do with the error. Execution will continue.
  47193. }
  47194. _this.previousPosition = {
  47195. x: evt.clientX,
  47196. y: evt.clientY
  47197. };
  47198. if (!noPreventDefault) {
  47199. evt.preventDefault();
  47200. element.focus();
  47201. }
  47202. }
  47203. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47204. try {
  47205. srcElement.releasePointerCapture(evt.pointerId);
  47206. }
  47207. catch (e) {
  47208. //Nothing to do with the error.
  47209. }
  47210. _this.previousPosition = null;
  47211. if (!noPreventDefault) {
  47212. evt.preventDefault();
  47213. }
  47214. }
  47215. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47216. if (!_this.previousPosition || engine.isPointerLock) {
  47217. return;
  47218. }
  47219. var offsetX = evt.clientX - _this.previousPosition.x;
  47220. if (_this.camera.getScene().useRightHandedSystem)
  47221. offsetX *= -1;
  47222. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47223. offsetX *= -1;
  47224. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47225. var offsetY = evt.clientY - _this.previousPosition.y;
  47226. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47227. _this.previousPosition = {
  47228. x: evt.clientX,
  47229. y: evt.clientY
  47230. };
  47231. if (!noPreventDefault) {
  47232. evt.preventDefault();
  47233. }
  47234. }
  47235. };
  47236. }
  47237. this._onMouseMove = function (evt) {
  47238. if (!engine.isPointerLock) {
  47239. return;
  47240. }
  47241. if (engine.isInVRExclusivePointerMode) {
  47242. return;
  47243. }
  47244. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47245. if (_this.camera.getScene().useRightHandedSystem)
  47246. offsetX *= -1;
  47247. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47248. offsetX *= -1;
  47249. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47250. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47251. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47252. _this.previousPosition = null;
  47253. if (!noPreventDefault) {
  47254. evt.preventDefault();
  47255. }
  47256. };
  47257. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47258. element.addEventListener("mousemove", this._onMouseMove, false);
  47259. };
  47260. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47261. if (this._observer && element) {
  47262. this.camera.getScene().onPointerObservable.remove(this._observer);
  47263. if (this._onMouseMove) {
  47264. element.removeEventListener("mousemove", this._onMouseMove);
  47265. }
  47266. this._observer = null;
  47267. this._onMouseMove = null;
  47268. this.previousPosition = null;
  47269. }
  47270. };
  47271. FreeCameraMouseInput.prototype.getClassName = function () {
  47272. return "FreeCameraMouseInput";
  47273. };
  47274. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47275. return "mouse";
  47276. };
  47277. __decorate([
  47278. BABYLON.serialize()
  47279. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47280. __decorate([
  47281. BABYLON.serialize()
  47282. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47283. return FreeCameraMouseInput;
  47284. }());
  47285. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47286. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47287. })(BABYLON || (BABYLON = {}));
  47288. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47289. var BABYLON;
  47290. (function (BABYLON) {
  47291. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47292. function FreeCameraKeyboardMoveInput() {
  47293. this._keys = new Array();
  47294. this.keysUp = [38];
  47295. this.keysDown = [40];
  47296. this.keysLeft = [37];
  47297. this.keysRight = [39];
  47298. }
  47299. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47300. var _this = this;
  47301. if (this._onCanvasBlurObserver) {
  47302. return;
  47303. }
  47304. this._scene = this.camera.getScene();
  47305. this._engine = this._scene.getEngine();
  47306. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47307. _this._keys = [];
  47308. });
  47309. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47310. var evt = info.event;
  47311. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47312. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47313. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47314. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47315. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47316. var index = _this._keys.indexOf(evt.keyCode);
  47317. if (index === -1) {
  47318. _this._keys.push(evt.keyCode);
  47319. }
  47320. if (!noPreventDefault) {
  47321. evt.preventDefault();
  47322. }
  47323. }
  47324. }
  47325. else {
  47326. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47327. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47328. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47329. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47330. var index = _this._keys.indexOf(evt.keyCode);
  47331. if (index >= 0) {
  47332. _this._keys.splice(index, 1);
  47333. }
  47334. if (!noPreventDefault) {
  47335. evt.preventDefault();
  47336. }
  47337. }
  47338. }
  47339. });
  47340. };
  47341. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47342. if (this._scene) {
  47343. if (this._onKeyboardObserver) {
  47344. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47345. }
  47346. if (this._onCanvasBlurObserver) {
  47347. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47348. }
  47349. this._onKeyboardObserver = null;
  47350. this._onCanvasBlurObserver = null;
  47351. }
  47352. this._keys = [];
  47353. };
  47354. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47355. if (this._onKeyboardObserver) {
  47356. var camera = this.camera;
  47357. // Keyboard
  47358. for (var index = 0; index < this._keys.length; index++) {
  47359. var keyCode = this._keys[index];
  47360. var speed = camera._computeLocalCameraSpeed();
  47361. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47362. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47363. }
  47364. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47365. camera._localDirection.copyFromFloats(0, 0, speed);
  47366. }
  47367. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47368. camera._localDirection.copyFromFloats(speed, 0, 0);
  47369. }
  47370. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47371. camera._localDirection.copyFromFloats(0, 0, -speed);
  47372. }
  47373. if (camera.getScene().useRightHandedSystem) {
  47374. camera._localDirection.z *= -1;
  47375. }
  47376. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47377. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47378. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47379. }
  47380. }
  47381. };
  47382. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47383. return "FreeCameraKeyboardMoveInput";
  47384. };
  47385. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47386. this._keys = [];
  47387. };
  47388. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47389. return "keyboard";
  47390. };
  47391. __decorate([
  47392. BABYLON.serialize()
  47393. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47394. __decorate([
  47395. BABYLON.serialize()
  47396. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47397. __decorate([
  47398. BABYLON.serialize()
  47399. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47400. __decorate([
  47401. BABYLON.serialize()
  47402. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47403. return FreeCameraKeyboardMoveInput;
  47404. }());
  47405. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47406. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47407. })(BABYLON || (BABYLON = {}));
  47408. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47409. var BABYLON;
  47410. (function (BABYLON) {
  47411. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47412. __extends(FreeCameraInputsManager, _super);
  47413. function FreeCameraInputsManager(camera) {
  47414. return _super.call(this, camera) || this;
  47415. }
  47416. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47417. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47418. return this;
  47419. };
  47420. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47421. if (touchEnabled === void 0) { touchEnabled = true; }
  47422. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47423. return this;
  47424. };
  47425. FreeCameraInputsManager.prototype.addGamepad = function () {
  47426. this.add(new BABYLON.FreeCameraGamepadInput());
  47427. return this;
  47428. };
  47429. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47430. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47431. return this;
  47432. };
  47433. FreeCameraInputsManager.prototype.addTouch = function () {
  47434. this.add(new BABYLON.FreeCameraTouchInput());
  47435. return this;
  47436. };
  47437. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47438. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47439. return this;
  47440. };
  47441. return FreeCameraInputsManager;
  47442. }(BABYLON.CameraInputsManager));
  47443. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47444. })(BABYLON || (BABYLON = {}));
  47445. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47446. var BABYLON;
  47447. (function (BABYLON) {
  47448. var FreeCamera = /** @class */ (function (_super) {
  47449. __extends(FreeCamera, _super);
  47450. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47451. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47452. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47453. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47454. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47455. _this.checkCollisions = false;
  47456. _this.applyGravity = false;
  47457. _this._needMoveForGravity = false;
  47458. _this._oldPosition = BABYLON.Vector3.Zero();
  47459. _this._diffPosition = BABYLON.Vector3.Zero();
  47460. _this._newPosition = BABYLON.Vector3.Zero();
  47461. // Collisions
  47462. _this._collisionMask = -1;
  47463. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47464. if (collidedMesh === void 0) { collidedMesh = null; }
  47465. //TODO move this to the collision coordinator!
  47466. if (_this.getScene().workerCollisions)
  47467. newPosition.multiplyInPlace(_this._collider._radius);
  47468. var updatePosition = function (newPos) {
  47469. _this._newPosition.copyFrom(newPos);
  47470. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47471. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47472. _this.position.addInPlace(_this._diffPosition);
  47473. if (_this.onCollide && collidedMesh) {
  47474. _this.onCollide(collidedMesh);
  47475. }
  47476. }
  47477. };
  47478. updatePosition(newPosition);
  47479. };
  47480. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47481. _this.inputs.addKeyboard().addMouse();
  47482. return _this;
  47483. }
  47484. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47485. //-- begin properties for backward compatibility for inputs
  47486. /**
  47487. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47488. * Higher values reduce sensitivity.
  47489. */
  47490. get: function () {
  47491. var mouse = this.inputs.attached["mouse"];
  47492. if (mouse)
  47493. return mouse.angularSensibility;
  47494. return 0;
  47495. },
  47496. /**
  47497. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47498. * Higher values reduce sensitivity.
  47499. */
  47500. set: function (value) {
  47501. var mouse = this.inputs.attached["mouse"];
  47502. if (mouse)
  47503. mouse.angularSensibility = value;
  47504. },
  47505. enumerable: true,
  47506. configurable: true
  47507. });
  47508. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47509. get: function () {
  47510. var keyboard = this.inputs.attached["keyboard"];
  47511. if (keyboard)
  47512. return keyboard.keysUp;
  47513. return [];
  47514. },
  47515. set: function (value) {
  47516. var keyboard = this.inputs.attached["keyboard"];
  47517. if (keyboard)
  47518. keyboard.keysUp = value;
  47519. },
  47520. enumerable: true,
  47521. configurable: true
  47522. });
  47523. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47524. get: function () {
  47525. var keyboard = this.inputs.attached["keyboard"];
  47526. if (keyboard)
  47527. return keyboard.keysDown;
  47528. return [];
  47529. },
  47530. set: function (value) {
  47531. var keyboard = this.inputs.attached["keyboard"];
  47532. if (keyboard)
  47533. keyboard.keysDown = value;
  47534. },
  47535. enumerable: true,
  47536. configurable: true
  47537. });
  47538. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47539. get: function () {
  47540. var keyboard = this.inputs.attached["keyboard"];
  47541. if (keyboard)
  47542. return keyboard.keysLeft;
  47543. return [];
  47544. },
  47545. set: function (value) {
  47546. var keyboard = this.inputs.attached["keyboard"];
  47547. if (keyboard)
  47548. keyboard.keysLeft = value;
  47549. },
  47550. enumerable: true,
  47551. configurable: true
  47552. });
  47553. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47554. get: function () {
  47555. var keyboard = this.inputs.attached["keyboard"];
  47556. if (keyboard)
  47557. return keyboard.keysRight;
  47558. return [];
  47559. },
  47560. set: function (value) {
  47561. var keyboard = this.inputs.attached["keyboard"];
  47562. if (keyboard)
  47563. keyboard.keysRight = value;
  47564. },
  47565. enumerable: true,
  47566. configurable: true
  47567. });
  47568. // Controls
  47569. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47570. this.inputs.attachElement(element, noPreventDefault);
  47571. };
  47572. FreeCamera.prototype.detachControl = function (element) {
  47573. this.inputs.detachElement(element);
  47574. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47575. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47576. };
  47577. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47578. get: function () {
  47579. return this._collisionMask;
  47580. },
  47581. set: function (mask) {
  47582. this._collisionMask = !isNaN(mask) ? mask : -1;
  47583. },
  47584. enumerable: true,
  47585. configurable: true
  47586. });
  47587. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47588. var globalPosition;
  47589. if (this.parent) {
  47590. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47591. }
  47592. else {
  47593. globalPosition = this.position;
  47594. }
  47595. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47596. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47597. if (!this._collider) {
  47598. this._collider = new BABYLON.Collider();
  47599. }
  47600. this._collider._radius = this.ellipsoid;
  47601. this._collider.collisionMask = this._collisionMask;
  47602. //no need for clone, as long as gravity is not on.
  47603. var actualDisplacement = displacement;
  47604. //add gravity to the direction to prevent the dual-collision checking
  47605. if (this.applyGravity) {
  47606. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47607. actualDisplacement = displacement.add(this.getScene().gravity);
  47608. }
  47609. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47610. };
  47611. FreeCamera.prototype._checkInputs = function () {
  47612. if (!this._localDirection) {
  47613. this._localDirection = BABYLON.Vector3.Zero();
  47614. this._transformedDirection = BABYLON.Vector3.Zero();
  47615. }
  47616. this.inputs.checkInputs();
  47617. _super.prototype._checkInputs.call(this);
  47618. };
  47619. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47620. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47621. };
  47622. FreeCamera.prototype._updatePosition = function () {
  47623. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47624. this._collideWithWorld(this.cameraDirection);
  47625. }
  47626. else {
  47627. _super.prototype._updatePosition.call(this);
  47628. }
  47629. };
  47630. FreeCamera.prototype.dispose = function () {
  47631. this.inputs.clear();
  47632. _super.prototype.dispose.call(this);
  47633. };
  47634. FreeCamera.prototype.getClassName = function () {
  47635. return "FreeCamera";
  47636. };
  47637. __decorate([
  47638. BABYLON.serializeAsVector3()
  47639. ], FreeCamera.prototype, "ellipsoid", void 0);
  47640. __decorate([
  47641. BABYLON.serializeAsVector3()
  47642. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47643. __decorate([
  47644. BABYLON.serialize()
  47645. ], FreeCamera.prototype, "checkCollisions", void 0);
  47646. __decorate([
  47647. BABYLON.serialize()
  47648. ], FreeCamera.prototype, "applyGravity", void 0);
  47649. return FreeCamera;
  47650. }(BABYLON.TargetCamera));
  47651. BABYLON.FreeCamera = FreeCamera;
  47652. })(BABYLON || (BABYLON = {}));
  47653. //# sourceMappingURL=babylon.freeCamera.js.map
  47654. var BABYLON;
  47655. (function (BABYLON) {
  47656. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47657. function ArcRotateCameraKeyboardMoveInput() {
  47658. this._keys = new Array();
  47659. this.keysUp = [38];
  47660. this.keysDown = [40];
  47661. this.keysLeft = [37];
  47662. this.keysRight = [39];
  47663. this.keysReset = [220];
  47664. this.panningSensibility = 50.0;
  47665. this.zoomingSensibility = 25.0;
  47666. this.useAltToZoom = true;
  47667. }
  47668. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47669. var _this = this;
  47670. if (this._onCanvasBlurObserver) {
  47671. return;
  47672. }
  47673. this._scene = this.camera.getScene();
  47674. this._engine = this._scene.getEngine();
  47675. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47676. _this._keys = [];
  47677. });
  47678. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47679. var evt = info.event;
  47680. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47681. _this._ctrlPressed = evt.ctrlKey;
  47682. _this._altPressed = evt.altKey;
  47683. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47684. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47685. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47686. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47687. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47688. var index = _this._keys.indexOf(evt.keyCode);
  47689. if (index === -1) {
  47690. _this._keys.push(evt.keyCode);
  47691. }
  47692. if (evt.preventDefault) {
  47693. if (!noPreventDefault) {
  47694. evt.preventDefault();
  47695. }
  47696. }
  47697. }
  47698. }
  47699. else {
  47700. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47701. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47702. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47703. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47704. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47705. var index = _this._keys.indexOf(evt.keyCode);
  47706. if (index >= 0) {
  47707. _this._keys.splice(index, 1);
  47708. }
  47709. if (evt.preventDefault) {
  47710. if (!noPreventDefault) {
  47711. evt.preventDefault();
  47712. }
  47713. }
  47714. }
  47715. }
  47716. });
  47717. };
  47718. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47719. if (this._scene) {
  47720. if (this._onKeyboardObserver) {
  47721. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47722. }
  47723. if (this._onCanvasBlurObserver) {
  47724. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47725. }
  47726. this._onKeyboardObserver = null;
  47727. this._onCanvasBlurObserver = null;
  47728. }
  47729. this._keys = [];
  47730. };
  47731. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47732. if (this._onKeyboardObserver) {
  47733. var camera = this.camera;
  47734. for (var index = 0; index < this._keys.length; index++) {
  47735. var keyCode = this._keys[index];
  47736. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47737. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47738. camera.inertialPanningX -= 1 / this.panningSensibility;
  47739. }
  47740. else {
  47741. camera.inertialAlphaOffset -= 0.01;
  47742. }
  47743. }
  47744. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47745. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47746. camera.inertialPanningY += 1 / this.panningSensibility;
  47747. }
  47748. else if (this._altPressed && this.useAltToZoom) {
  47749. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47750. }
  47751. else {
  47752. camera.inertialBetaOffset -= 0.01;
  47753. }
  47754. }
  47755. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47756. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47757. camera.inertialPanningX += 1 / this.panningSensibility;
  47758. }
  47759. else {
  47760. camera.inertialAlphaOffset += 0.01;
  47761. }
  47762. }
  47763. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47764. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47765. camera.inertialPanningY -= 1 / this.panningSensibility;
  47766. }
  47767. else if (this._altPressed && this.useAltToZoom) {
  47768. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47769. }
  47770. else {
  47771. camera.inertialBetaOffset += 0.01;
  47772. }
  47773. }
  47774. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47775. camera.restoreState();
  47776. }
  47777. }
  47778. }
  47779. };
  47780. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47781. return "ArcRotateCameraKeyboardMoveInput";
  47782. };
  47783. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47784. return "keyboard";
  47785. };
  47786. __decorate([
  47787. BABYLON.serialize()
  47788. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47789. __decorate([
  47790. BABYLON.serialize()
  47791. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47792. __decorate([
  47793. BABYLON.serialize()
  47794. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47795. __decorate([
  47796. BABYLON.serialize()
  47797. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47798. __decorate([
  47799. BABYLON.serialize()
  47800. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47801. __decorate([
  47802. BABYLON.serialize()
  47803. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47804. __decorate([
  47805. BABYLON.serialize()
  47806. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47807. __decorate([
  47808. BABYLON.serialize()
  47809. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47810. return ArcRotateCameraKeyboardMoveInput;
  47811. }());
  47812. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47813. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47814. })(BABYLON || (BABYLON = {}));
  47815. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47816. var BABYLON;
  47817. (function (BABYLON) {
  47818. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47819. function ArcRotateCameraMouseWheelInput() {
  47820. this.wheelPrecision = 3.0;
  47821. /**
  47822. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47823. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47824. */
  47825. this.wheelDeltaPercentage = 0;
  47826. }
  47827. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47828. var _this = this;
  47829. this._wheel = function (p, s) {
  47830. //sanity check - this should be a PointerWheel event.
  47831. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47832. return;
  47833. var event = p.event;
  47834. var delta = 0;
  47835. if (event.wheelDelta) {
  47836. if (_this.wheelDeltaPercentage) {
  47837. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47838. if (event.wheelDelta > 0) {
  47839. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47840. }
  47841. else {
  47842. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47843. }
  47844. }
  47845. else {
  47846. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47847. }
  47848. }
  47849. else if (event.detail) {
  47850. delta = -event.detail / _this.wheelPrecision;
  47851. }
  47852. if (delta)
  47853. _this.camera.inertialRadiusOffset += delta;
  47854. if (event.preventDefault) {
  47855. if (!noPreventDefault) {
  47856. event.preventDefault();
  47857. }
  47858. }
  47859. };
  47860. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47861. };
  47862. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47863. if (this._observer && element) {
  47864. this.camera.getScene().onPointerObservable.remove(this._observer);
  47865. this._observer = null;
  47866. this._wheel = null;
  47867. }
  47868. };
  47869. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47870. return "ArcRotateCameraMouseWheelInput";
  47871. };
  47872. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47873. return "mousewheel";
  47874. };
  47875. __decorate([
  47876. BABYLON.serialize()
  47877. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47878. __decorate([
  47879. BABYLON.serialize()
  47880. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47881. return ArcRotateCameraMouseWheelInput;
  47882. }());
  47883. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47884. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47885. })(BABYLON || (BABYLON = {}));
  47886. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47887. var BABYLON;
  47888. (function (BABYLON) {
  47889. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47890. function ArcRotateCameraPointersInput() {
  47891. this.buttons = [0, 1, 2];
  47892. this.angularSensibilityX = 1000.0;
  47893. this.angularSensibilityY = 1000.0;
  47894. this.pinchPrecision = 12.0;
  47895. /**
  47896. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47897. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47898. */
  47899. this.pinchDeltaPercentage = 0;
  47900. this.panningSensibility = 1000.0;
  47901. this.multiTouchPanning = true;
  47902. this.multiTouchPanAndZoom = true;
  47903. this._isPanClick = false;
  47904. this.pinchInwards = true;
  47905. }
  47906. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47907. var _this = this;
  47908. var engine = this.camera.getEngine();
  47909. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47910. var pointA = null;
  47911. var pointB = null;
  47912. var previousPinchSquaredDistance = 0;
  47913. var initialDistance = 0;
  47914. var twoFingerActivityCount = 0;
  47915. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47916. this._pointerInput = function (p, s) {
  47917. var evt = p.event;
  47918. var isTouch = p.event.pointerType === "touch";
  47919. if (engine.isInVRExclusivePointerMode) {
  47920. return;
  47921. }
  47922. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47923. return;
  47924. }
  47925. var srcElement = (evt.srcElement || evt.target);
  47926. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47927. try {
  47928. srcElement.setPointerCapture(evt.pointerId);
  47929. }
  47930. catch (e) {
  47931. //Nothing to do with the error. Execution will continue.
  47932. }
  47933. // Manage panning with pan button click
  47934. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47935. // manage pointers
  47936. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47937. if (pointA === null) {
  47938. pointA = cacheSoloPointer;
  47939. }
  47940. else if (pointB === null) {
  47941. pointB = cacheSoloPointer;
  47942. }
  47943. if (!noPreventDefault) {
  47944. evt.preventDefault();
  47945. element.focus();
  47946. }
  47947. }
  47948. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47949. _this.camera.restoreState();
  47950. }
  47951. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47952. try {
  47953. srcElement.releasePointerCapture(evt.pointerId);
  47954. }
  47955. catch (e) {
  47956. //Nothing to do with the error.
  47957. }
  47958. cacheSoloPointer = null;
  47959. previousPinchSquaredDistance = 0;
  47960. previousMultiTouchPanPosition.isPaning = false;
  47961. previousMultiTouchPanPosition.isPinching = false;
  47962. twoFingerActivityCount = 0;
  47963. initialDistance = 0;
  47964. if (!isTouch) {
  47965. pointB = null; // Mouse and pen are mono pointer
  47966. }
  47967. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47968. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47969. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47970. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47971. if (engine._badOS) {
  47972. pointA = pointB = null;
  47973. }
  47974. else {
  47975. //only remove the impacted pointer in case of multitouch allowing on most
  47976. //platforms switching from rotate to zoom and pan seamlessly.
  47977. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47978. pointA = pointB;
  47979. pointB = null;
  47980. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47981. }
  47982. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47983. pointB = null;
  47984. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47985. }
  47986. else {
  47987. pointA = pointB = null;
  47988. }
  47989. }
  47990. if (!noPreventDefault) {
  47991. evt.preventDefault();
  47992. }
  47993. }
  47994. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47995. if (!noPreventDefault) {
  47996. evt.preventDefault();
  47997. }
  47998. // One button down
  47999. if (pointA && pointB === null && cacheSoloPointer) {
  48000. if (_this.panningSensibility !== 0 &&
  48001. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48002. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48003. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48004. }
  48005. else {
  48006. var offsetX = evt.clientX - cacheSoloPointer.x;
  48007. var offsetY = evt.clientY - cacheSoloPointer.y;
  48008. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48009. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48010. }
  48011. cacheSoloPointer.x = evt.clientX;
  48012. cacheSoloPointer.y = evt.clientY;
  48013. }
  48014. // Two buttons down: pinch/pan
  48015. else if (pointA && pointB) {
  48016. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48017. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48018. ed.x = evt.clientX;
  48019. ed.y = evt.clientY;
  48020. var direction = _this.pinchInwards ? 1 : -1;
  48021. var distX = pointA.x - pointB.x;
  48022. var distY = pointA.y - pointB.y;
  48023. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48024. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48025. if (previousPinchSquaredDistance === 0) {
  48026. initialDistance = pinchDistance;
  48027. previousPinchSquaredDistance = pinchSquaredDistance;
  48028. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48029. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48030. return;
  48031. }
  48032. if (_this.multiTouchPanAndZoom) {
  48033. if (_this.pinchDeltaPercentage) {
  48034. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48035. }
  48036. else {
  48037. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48038. (_this.pinchPrecision *
  48039. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48040. direction);
  48041. }
  48042. if (_this.panningSensibility !== 0) {
  48043. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48044. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48045. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48046. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48047. previousMultiTouchPanPosition.x = pointersCenterX;
  48048. previousMultiTouchPanPosition.y = pointersCenterY;
  48049. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48050. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48051. }
  48052. }
  48053. else {
  48054. twoFingerActivityCount++;
  48055. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48056. if (_this.pinchDeltaPercentage) {
  48057. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48058. }
  48059. else {
  48060. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48061. (_this.pinchPrecision *
  48062. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48063. direction);
  48064. }
  48065. previousMultiTouchPanPosition.isPaning = false;
  48066. previousMultiTouchPanPosition.isPinching = true;
  48067. }
  48068. else {
  48069. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48070. if (!previousMultiTouchPanPosition.isPaning) {
  48071. previousMultiTouchPanPosition.isPaning = true;
  48072. previousMultiTouchPanPosition.isPinching = false;
  48073. previousMultiTouchPanPosition.x = ed.x;
  48074. previousMultiTouchPanPosition.y = ed.y;
  48075. return;
  48076. }
  48077. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48078. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48079. }
  48080. }
  48081. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48082. previousMultiTouchPanPosition.x = ed.x;
  48083. previousMultiTouchPanPosition.y = ed.y;
  48084. }
  48085. }
  48086. previousPinchSquaredDistance = pinchSquaredDistance;
  48087. }
  48088. }
  48089. };
  48090. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48091. this._onContextMenu = function (evt) {
  48092. evt.preventDefault();
  48093. };
  48094. if (!this.camera._useCtrlForPanning) {
  48095. element.addEventListener("contextmenu", this._onContextMenu, false);
  48096. }
  48097. this._onLostFocus = function () {
  48098. //this._keys = [];
  48099. pointA = pointB = null;
  48100. previousPinchSquaredDistance = 0;
  48101. previousMultiTouchPanPosition.isPaning = false;
  48102. previousMultiTouchPanPosition.isPinching = false;
  48103. twoFingerActivityCount = 0;
  48104. cacheSoloPointer = null;
  48105. initialDistance = 0;
  48106. };
  48107. this._onMouseMove = function (evt) {
  48108. if (!engine.isPointerLock) {
  48109. return;
  48110. }
  48111. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48112. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48113. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48114. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48115. if (!noPreventDefault) {
  48116. evt.preventDefault();
  48117. }
  48118. };
  48119. this._onGestureStart = function (e) {
  48120. if (window.MSGesture === undefined) {
  48121. return;
  48122. }
  48123. if (!_this._MSGestureHandler) {
  48124. _this._MSGestureHandler = new MSGesture();
  48125. _this._MSGestureHandler.target = element;
  48126. }
  48127. _this._MSGestureHandler.addPointer(e.pointerId);
  48128. };
  48129. this._onGesture = function (e) {
  48130. _this.camera.radius *= e.scale;
  48131. if (e.preventDefault) {
  48132. if (!noPreventDefault) {
  48133. e.stopPropagation();
  48134. e.preventDefault();
  48135. }
  48136. }
  48137. };
  48138. element.addEventListener("mousemove", this._onMouseMove, false);
  48139. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48140. element.addEventListener("MSGestureChange", this._onGesture, false);
  48141. BABYLON.Tools.RegisterTopRootEvents([
  48142. { name: "blur", handler: this._onLostFocus }
  48143. ]);
  48144. };
  48145. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48146. if (this._onLostFocus) {
  48147. BABYLON.Tools.UnregisterTopRootEvents([
  48148. { name: "blur", handler: this._onLostFocus }
  48149. ]);
  48150. }
  48151. if (element && this._observer) {
  48152. this.camera.getScene().onPointerObservable.remove(this._observer);
  48153. this._observer = null;
  48154. if (this._onContextMenu) {
  48155. element.removeEventListener("contextmenu", this._onContextMenu);
  48156. }
  48157. if (this._onMouseMove) {
  48158. element.removeEventListener("mousemove", this._onMouseMove);
  48159. }
  48160. if (this._onGestureStart) {
  48161. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48162. }
  48163. if (this._onGesture) {
  48164. element.removeEventListener("MSGestureChange", this._onGesture);
  48165. }
  48166. this._isPanClick = false;
  48167. this.pinchInwards = true;
  48168. this._onMouseMove = null;
  48169. this._onGestureStart = null;
  48170. this._onGesture = null;
  48171. this._MSGestureHandler = null;
  48172. this._onLostFocus = null;
  48173. this._onContextMenu = null;
  48174. }
  48175. };
  48176. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48177. return "ArcRotateCameraPointersInput";
  48178. };
  48179. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48180. return "pointers";
  48181. };
  48182. __decorate([
  48183. BABYLON.serialize()
  48184. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48185. __decorate([
  48186. BABYLON.serialize()
  48187. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48188. __decorate([
  48189. BABYLON.serialize()
  48190. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48191. __decorate([
  48192. BABYLON.serialize()
  48193. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48194. __decorate([
  48195. BABYLON.serialize()
  48196. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48197. __decorate([
  48198. BABYLON.serialize()
  48199. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48200. __decorate([
  48201. BABYLON.serialize()
  48202. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48203. __decorate([
  48204. BABYLON.serialize()
  48205. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48206. return ArcRotateCameraPointersInput;
  48207. }());
  48208. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48209. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48210. })(BABYLON || (BABYLON = {}));
  48211. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48212. var BABYLON;
  48213. (function (BABYLON) {
  48214. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48215. __extends(ArcRotateCameraInputsManager, _super);
  48216. function ArcRotateCameraInputsManager(camera) {
  48217. return _super.call(this, camera) || this;
  48218. }
  48219. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48220. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48221. return this;
  48222. };
  48223. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48224. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48225. return this;
  48226. };
  48227. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48228. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48229. return this;
  48230. };
  48231. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48232. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48233. return this;
  48234. };
  48235. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48236. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48237. return this;
  48238. };
  48239. return ArcRotateCameraInputsManager;
  48240. }(BABYLON.CameraInputsManager));
  48241. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48242. })(BABYLON || (BABYLON = {}));
  48243. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48244. var BABYLON;
  48245. (function (BABYLON) {
  48246. var ArcRotateCamera = /** @class */ (function (_super) {
  48247. __extends(ArcRotateCamera, _super);
  48248. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48249. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48250. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48251. _this.inertialAlphaOffset = 0;
  48252. _this.inertialBetaOffset = 0;
  48253. _this.inertialRadiusOffset = 0;
  48254. _this.lowerAlphaLimit = null;
  48255. _this.upperAlphaLimit = null;
  48256. _this.lowerBetaLimit = 0.01;
  48257. _this.upperBetaLimit = Math.PI;
  48258. _this.lowerRadiusLimit = null;
  48259. _this.upperRadiusLimit = null;
  48260. _this.inertialPanningX = 0;
  48261. _this.inertialPanningY = 0;
  48262. _this.pinchToPanMaxDistance = 20;
  48263. _this.panningDistanceLimit = null;
  48264. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48265. _this.panningInertia = 0.9;
  48266. //-- end properties for backward compatibility for inputs
  48267. _this.zoomOnFactor = 1;
  48268. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48269. _this.allowUpsideDown = true;
  48270. _this._viewMatrix = new BABYLON.Matrix();
  48271. // Panning
  48272. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48273. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48274. _this.checkCollisions = false;
  48275. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48276. _this._previousPosition = BABYLON.Vector3.Zero();
  48277. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48278. _this._newPosition = BABYLON.Vector3.Zero();
  48279. _this._computationVector = BABYLON.Vector3.Zero();
  48280. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48281. if (collidedMesh === void 0) { collidedMesh = null; }
  48282. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48283. newPosition.multiplyInPlace(_this._collider._radius);
  48284. }
  48285. if (!collidedMesh) {
  48286. _this._previousPosition.copyFrom(_this.position);
  48287. }
  48288. else {
  48289. _this.setPosition(newPosition);
  48290. if (_this.onCollide) {
  48291. _this.onCollide(collidedMesh);
  48292. }
  48293. }
  48294. // Recompute because of constraints
  48295. var cosa = Math.cos(_this.alpha);
  48296. var sina = Math.sin(_this.alpha);
  48297. var cosb = Math.cos(_this.beta);
  48298. var sinb = Math.sin(_this.beta);
  48299. if (sinb === 0) {
  48300. sinb = 0.0001;
  48301. }
  48302. var target = _this._getTargetPosition();
  48303. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48304. target.addToRef(_this._computationVector, _this._newPosition);
  48305. _this.position.copyFrom(_this._newPosition);
  48306. var up = _this.upVector;
  48307. if (_this.allowUpsideDown && _this.beta < 0) {
  48308. up = up.clone();
  48309. up = up.negate();
  48310. }
  48311. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  48312. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48313. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48314. _this._collisionTriggered = false;
  48315. };
  48316. _this._target = BABYLON.Vector3.Zero();
  48317. if (target) {
  48318. _this.setTarget(target);
  48319. }
  48320. _this.alpha = alpha;
  48321. _this.beta = beta;
  48322. _this.radius = radius;
  48323. _this.getViewMatrix();
  48324. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48325. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48326. return _this;
  48327. }
  48328. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48329. get: function () {
  48330. return this._target;
  48331. },
  48332. set: function (value) {
  48333. this.setTarget(value);
  48334. },
  48335. enumerable: true,
  48336. configurable: true
  48337. });
  48338. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48339. //-- begin properties for backward compatibility for inputs
  48340. get: function () {
  48341. var pointers = this.inputs.attached["pointers"];
  48342. if (pointers)
  48343. return pointers.angularSensibilityX;
  48344. return 0;
  48345. },
  48346. set: function (value) {
  48347. var pointers = this.inputs.attached["pointers"];
  48348. if (pointers) {
  48349. pointers.angularSensibilityX = value;
  48350. }
  48351. },
  48352. enumerable: true,
  48353. configurable: true
  48354. });
  48355. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48356. get: function () {
  48357. var pointers = this.inputs.attached["pointers"];
  48358. if (pointers)
  48359. return pointers.angularSensibilityY;
  48360. return 0;
  48361. },
  48362. set: function (value) {
  48363. var pointers = this.inputs.attached["pointers"];
  48364. if (pointers) {
  48365. pointers.angularSensibilityY = value;
  48366. }
  48367. },
  48368. enumerable: true,
  48369. configurable: true
  48370. });
  48371. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48372. get: function () {
  48373. var pointers = this.inputs.attached["pointers"];
  48374. if (pointers)
  48375. return pointers.pinchPrecision;
  48376. return 0;
  48377. },
  48378. set: function (value) {
  48379. var pointers = this.inputs.attached["pointers"];
  48380. if (pointers) {
  48381. pointers.pinchPrecision = value;
  48382. }
  48383. },
  48384. enumerable: true,
  48385. configurable: true
  48386. });
  48387. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48388. get: function () {
  48389. var pointers = this.inputs.attached["pointers"];
  48390. if (pointers)
  48391. return pointers.pinchDeltaPercentage;
  48392. return 0;
  48393. },
  48394. set: function (value) {
  48395. var pointers = this.inputs.attached["pointers"];
  48396. if (pointers) {
  48397. pointers.pinchDeltaPercentage = value;
  48398. }
  48399. },
  48400. enumerable: true,
  48401. configurable: true
  48402. });
  48403. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48404. get: function () {
  48405. var pointers = this.inputs.attached["pointers"];
  48406. if (pointers)
  48407. return pointers.panningSensibility;
  48408. return 0;
  48409. },
  48410. set: function (value) {
  48411. var pointers = this.inputs.attached["pointers"];
  48412. if (pointers) {
  48413. pointers.panningSensibility = value;
  48414. }
  48415. },
  48416. enumerable: true,
  48417. configurable: true
  48418. });
  48419. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48420. get: function () {
  48421. var keyboard = this.inputs.attached["keyboard"];
  48422. if (keyboard)
  48423. return keyboard.keysUp;
  48424. return [];
  48425. },
  48426. set: function (value) {
  48427. var keyboard = this.inputs.attached["keyboard"];
  48428. if (keyboard)
  48429. keyboard.keysUp = value;
  48430. },
  48431. enumerable: true,
  48432. configurable: true
  48433. });
  48434. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48435. get: function () {
  48436. var keyboard = this.inputs.attached["keyboard"];
  48437. if (keyboard)
  48438. return keyboard.keysDown;
  48439. return [];
  48440. },
  48441. set: function (value) {
  48442. var keyboard = this.inputs.attached["keyboard"];
  48443. if (keyboard)
  48444. keyboard.keysDown = value;
  48445. },
  48446. enumerable: true,
  48447. configurable: true
  48448. });
  48449. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48450. get: function () {
  48451. var keyboard = this.inputs.attached["keyboard"];
  48452. if (keyboard)
  48453. return keyboard.keysLeft;
  48454. return [];
  48455. },
  48456. set: function (value) {
  48457. var keyboard = this.inputs.attached["keyboard"];
  48458. if (keyboard)
  48459. keyboard.keysLeft = value;
  48460. },
  48461. enumerable: true,
  48462. configurable: true
  48463. });
  48464. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48465. get: function () {
  48466. var keyboard = this.inputs.attached["keyboard"];
  48467. if (keyboard)
  48468. return keyboard.keysRight;
  48469. return [];
  48470. },
  48471. set: function (value) {
  48472. var keyboard = this.inputs.attached["keyboard"];
  48473. if (keyboard)
  48474. keyboard.keysRight = value;
  48475. },
  48476. enumerable: true,
  48477. configurable: true
  48478. });
  48479. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48480. get: function () {
  48481. var mousewheel = this.inputs.attached["mousewheel"];
  48482. if (mousewheel)
  48483. return mousewheel.wheelPrecision;
  48484. return 0;
  48485. },
  48486. set: function (value) {
  48487. var mousewheel = this.inputs.attached["mousewheel"];
  48488. if (mousewheel)
  48489. mousewheel.wheelPrecision = value;
  48490. },
  48491. enumerable: true,
  48492. configurable: true
  48493. });
  48494. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48495. get: function () {
  48496. var mousewheel = this.inputs.attached["mousewheel"];
  48497. if (mousewheel)
  48498. return mousewheel.wheelDeltaPercentage;
  48499. return 0;
  48500. },
  48501. set: function (value) {
  48502. var mousewheel = this.inputs.attached["mousewheel"];
  48503. if (mousewheel)
  48504. mousewheel.wheelDeltaPercentage = value;
  48505. },
  48506. enumerable: true,
  48507. configurable: true
  48508. });
  48509. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48510. get: function () {
  48511. return this._bouncingBehavior;
  48512. },
  48513. enumerable: true,
  48514. configurable: true
  48515. });
  48516. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48517. get: function () {
  48518. return this._bouncingBehavior != null;
  48519. },
  48520. set: function (value) {
  48521. if (value === this.useBouncingBehavior) {
  48522. return;
  48523. }
  48524. if (value) {
  48525. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48526. this.addBehavior(this._bouncingBehavior);
  48527. }
  48528. else if (this._bouncingBehavior) {
  48529. this.removeBehavior(this._bouncingBehavior);
  48530. this._bouncingBehavior = null;
  48531. }
  48532. },
  48533. enumerable: true,
  48534. configurable: true
  48535. });
  48536. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48537. get: function () {
  48538. return this._framingBehavior;
  48539. },
  48540. enumerable: true,
  48541. configurable: true
  48542. });
  48543. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48544. get: function () {
  48545. return this._framingBehavior != null;
  48546. },
  48547. set: function (value) {
  48548. if (value === this.useFramingBehavior) {
  48549. return;
  48550. }
  48551. if (value) {
  48552. this._framingBehavior = new BABYLON.FramingBehavior();
  48553. this.addBehavior(this._framingBehavior);
  48554. }
  48555. else if (this._framingBehavior) {
  48556. this.removeBehavior(this._framingBehavior);
  48557. this._framingBehavior = null;
  48558. }
  48559. },
  48560. enumerable: true,
  48561. configurable: true
  48562. });
  48563. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48564. get: function () {
  48565. return this._autoRotationBehavior;
  48566. },
  48567. enumerable: true,
  48568. configurable: true
  48569. });
  48570. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48571. get: function () {
  48572. return this._autoRotationBehavior != null;
  48573. },
  48574. set: function (value) {
  48575. if (value === this.useAutoRotationBehavior) {
  48576. return;
  48577. }
  48578. if (value) {
  48579. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48580. this.addBehavior(this._autoRotationBehavior);
  48581. }
  48582. else if (this._autoRotationBehavior) {
  48583. this.removeBehavior(this._autoRotationBehavior);
  48584. this._autoRotationBehavior = null;
  48585. }
  48586. },
  48587. enumerable: true,
  48588. configurable: true
  48589. });
  48590. // Cache
  48591. ArcRotateCamera.prototype._initCache = function () {
  48592. _super.prototype._initCache.call(this);
  48593. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48594. this._cache.alpha = undefined;
  48595. this._cache.beta = undefined;
  48596. this._cache.radius = undefined;
  48597. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48598. };
  48599. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48600. if (!ignoreParentClass) {
  48601. _super.prototype._updateCache.call(this);
  48602. }
  48603. this._cache._target.copyFrom(this._getTargetPosition());
  48604. this._cache.alpha = this.alpha;
  48605. this._cache.beta = this.beta;
  48606. this._cache.radius = this.radius;
  48607. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48608. };
  48609. ArcRotateCamera.prototype._getTargetPosition = function () {
  48610. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48611. var pos = this._targetHost.getAbsolutePosition();
  48612. if (this._targetBoundingCenter) {
  48613. pos.addToRef(this._targetBoundingCenter, this._target);
  48614. }
  48615. else {
  48616. this._target.copyFrom(pos);
  48617. }
  48618. }
  48619. var lockedTargetPosition = this._getLockedTargetPosition();
  48620. if (lockedTargetPosition) {
  48621. return lockedTargetPosition;
  48622. }
  48623. return this._target;
  48624. };
  48625. ArcRotateCamera.prototype.storeState = function () {
  48626. this._storedAlpha = this.alpha;
  48627. this._storedBeta = this.beta;
  48628. this._storedRadius = this.radius;
  48629. this._storedTarget = this._getTargetPosition().clone();
  48630. return _super.prototype.storeState.call(this);
  48631. };
  48632. /**
  48633. * Restored camera state. You must call storeState() first
  48634. */
  48635. ArcRotateCamera.prototype._restoreStateValues = function () {
  48636. if (!_super.prototype._restoreStateValues.call(this)) {
  48637. return false;
  48638. }
  48639. this.alpha = this._storedAlpha;
  48640. this.beta = this._storedBeta;
  48641. this.radius = this._storedRadius;
  48642. this.setTarget(this._storedTarget.clone());
  48643. this.inertialAlphaOffset = 0;
  48644. this.inertialBetaOffset = 0;
  48645. this.inertialRadiusOffset = 0;
  48646. this.inertialPanningX = 0;
  48647. this.inertialPanningY = 0;
  48648. return true;
  48649. };
  48650. // Synchronized
  48651. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48652. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48653. return false;
  48654. return this._cache._target.equals(this._getTargetPosition())
  48655. && this._cache.alpha === this.alpha
  48656. && this._cache.beta === this.beta
  48657. && this._cache.radius === this.radius
  48658. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48659. };
  48660. // Methods
  48661. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48662. var _this = this;
  48663. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48664. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48665. this._useCtrlForPanning = useCtrlForPanning;
  48666. this._panningMouseButton = panningMouseButton;
  48667. this.inputs.attachElement(element, noPreventDefault);
  48668. this._reset = function () {
  48669. _this.inertialAlphaOffset = 0;
  48670. _this.inertialBetaOffset = 0;
  48671. _this.inertialRadiusOffset = 0;
  48672. _this.inertialPanningX = 0;
  48673. _this.inertialPanningY = 0;
  48674. };
  48675. };
  48676. ArcRotateCamera.prototype.detachControl = function (element) {
  48677. this.inputs.detachElement(element);
  48678. if (this._reset) {
  48679. this._reset();
  48680. }
  48681. };
  48682. ArcRotateCamera.prototype._checkInputs = function () {
  48683. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48684. if (this._collisionTriggered) {
  48685. return;
  48686. }
  48687. this.inputs.checkInputs();
  48688. // Inertia
  48689. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48690. var inertialAlphaOffset = this.inertialAlphaOffset;
  48691. if (this.beta <= 0)
  48692. inertialAlphaOffset *= -1;
  48693. if (this.getScene().useRightHandedSystem)
  48694. inertialAlphaOffset *= -1;
  48695. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48696. inertialAlphaOffset *= -1;
  48697. this.alpha += inertialAlphaOffset;
  48698. this.beta += this.inertialBetaOffset;
  48699. this.radius -= this.inertialRadiusOffset;
  48700. this.inertialAlphaOffset *= this.inertia;
  48701. this.inertialBetaOffset *= this.inertia;
  48702. this.inertialRadiusOffset *= this.inertia;
  48703. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48704. this.inertialAlphaOffset = 0;
  48705. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48706. this.inertialBetaOffset = 0;
  48707. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48708. this.inertialRadiusOffset = 0;
  48709. }
  48710. // Panning inertia
  48711. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48712. if (!this._localDirection) {
  48713. this._localDirection = BABYLON.Vector3.Zero();
  48714. this._transformedDirection = BABYLON.Vector3.Zero();
  48715. }
  48716. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48717. this._localDirection.multiplyInPlace(this.panningAxis);
  48718. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48719. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48720. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48721. if (!this.panningAxis.y) {
  48722. this._transformedDirection.y = 0;
  48723. }
  48724. if (!this._targetHost) {
  48725. if (this.panningDistanceLimit) {
  48726. this._transformedDirection.addInPlace(this._target);
  48727. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48728. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48729. this._target.copyFrom(this._transformedDirection);
  48730. }
  48731. }
  48732. else {
  48733. this._target.addInPlace(this._transformedDirection);
  48734. }
  48735. }
  48736. this.inertialPanningX *= this.panningInertia;
  48737. this.inertialPanningY *= this.panningInertia;
  48738. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48739. this.inertialPanningX = 0;
  48740. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48741. this.inertialPanningY = 0;
  48742. }
  48743. // Limits
  48744. this._checkLimits();
  48745. _super.prototype._checkInputs.call(this);
  48746. };
  48747. ArcRotateCamera.prototype._checkLimits = function () {
  48748. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48749. if (this.allowUpsideDown && this.beta > Math.PI) {
  48750. this.beta = this.beta - (2 * Math.PI);
  48751. }
  48752. }
  48753. else {
  48754. if (this.beta < this.lowerBetaLimit) {
  48755. this.beta = this.lowerBetaLimit;
  48756. }
  48757. }
  48758. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48759. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48760. this.beta = this.beta + (2 * Math.PI);
  48761. }
  48762. }
  48763. else {
  48764. if (this.beta > this.upperBetaLimit) {
  48765. this.beta = this.upperBetaLimit;
  48766. }
  48767. }
  48768. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48769. this.alpha = this.lowerAlphaLimit;
  48770. }
  48771. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48772. this.alpha = this.upperAlphaLimit;
  48773. }
  48774. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48775. this.radius = this.lowerRadiusLimit;
  48776. }
  48777. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48778. this.radius = this.upperRadiusLimit;
  48779. }
  48780. };
  48781. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48782. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48783. this.radius = this._computationVector.length();
  48784. if (this.radius === 0) {
  48785. this.radius = 0.0001; // Just to avoid division by zero
  48786. }
  48787. // Alpha
  48788. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48789. if (this._computationVector.z < 0) {
  48790. this.alpha = 2 * Math.PI - this.alpha;
  48791. }
  48792. // Beta
  48793. this.beta = Math.acos(this._computationVector.y / this.radius);
  48794. this._checkLimits();
  48795. };
  48796. ArcRotateCamera.prototype.setPosition = function (position) {
  48797. if (this.position.equals(position)) {
  48798. return;
  48799. }
  48800. this.position.copyFrom(position);
  48801. this.rebuildAnglesAndRadius();
  48802. };
  48803. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48804. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48805. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48806. if (target.getBoundingInfo) {
  48807. if (toBoundingCenter) {
  48808. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48809. }
  48810. else {
  48811. this._targetBoundingCenter = null;
  48812. }
  48813. this._targetHost = target;
  48814. this._target = this._getTargetPosition();
  48815. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48816. }
  48817. else {
  48818. var newTarget = target;
  48819. var currentTarget = this._getTargetPosition();
  48820. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48821. return;
  48822. }
  48823. this._targetHost = null;
  48824. this._target = newTarget;
  48825. this._targetBoundingCenter = null;
  48826. this.onMeshTargetChangedObservable.notifyObservers(null);
  48827. }
  48828. this.rebuildAnglesAndRadius();
  48829. };
  48830. ArcRotateCamera.prototype._getViewMatrix = function () {
  48831. // Compute
  48832. var cosa = Math.cos(this.alpha);
  48833. var sina = Math.sin(this.alpha);
  48834. var cosb = Math.cos(this.beta);
  48835. var sinb = Math.sin(this.beta);
  48836. if (sinb === 0) {
  48837. sinb = 0.0001;
  48838. }
  48839. var target = this._getTargetPosition();
  48840. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48841. target.addToRef(this._computationVector, this._newPosition);
  48842. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48843. if (!this._collider) {
  48844. this._collider = new BABYLON.Collider();
  48845. }
  48846. this._collider._radius = this.collisionRadius;
  48847. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48848. this._collisionTriggered = true;
  48849. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48850. }
  48851. else {
  48852. this.position.copyFrom(this._newPosition);
  48853. var up = this.upVector;
  48854. if (this.allowUpsideDown && sinb < 0) {
  48855. up = up.clone();
  48856. up = up.negate();
  48857. }
  48858. this._computeViewMatrix(this.position, target, up);
  48859. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48860. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48861. }
  48862. this._currentTarget = target;
  48863. return this._viewMatrix;
  48864. };
  48865. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48866. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48867. meshes = meshes || this.getScene().meshes;
  48868. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48869. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48870. this.radius = distance * this.zoomOnFactor;
  48871. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48872. };
  48873. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48874. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48875. var meshesOrMinMaxVector;
  48876. var distance;
  48877. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48878. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48879. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48880. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48881. }
  48882. else { //minMaxVector and distance
  48883. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48884. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48885. distance = minMaxVectorAndDistance.distance;
  48886. }
  48887. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48888. if (!doNotUpdateMaxZ) {
  48889. this.maxZ = distance * 2;
  48890. }
  48891. };
  48892. /**
  48893. * @override
  48894. * Override Camera.createRigCamera
  48895. */
  48896. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48897. var alphaShift = 0;
  48898. switch (this.cameraRigMode) {
  48899. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48900. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48901. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48902. case BABYLON.Camera.RIG_MODE_VR:
  48903. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48904. break;
  48905. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48906. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48907. break;
  48908. }
  48909. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48910. rigCam._cameraRigParams = {};
  48911. return rigCam;
  48912. };
  48913. /**
  48914. * @override
  48915. * Override Camera._updateRigCameras
  48916. */
  48917. ArcRotateCamera.prototype._updateRigCameras = function () {
  48918. var camLeft = this._rigCameras[0];
  48919. var camRight = this._rigCameras[1];
  48920. camLeft.beta = camRight.beta = this.beta;
  48921. camLeft.radius = camRight.radius = this.radius;
  48922. switch (this.cameraRigMode) {
  48923. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48924. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48925. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48926. case BABYLON.Camera.RIG_MODE_VR:
  48927. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48928. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48929. break;
  48930. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48931. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48932. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48933. break;
  48934. }
  48935. _super.prototype._updateRigCameras.call(this);
  48936. };
  48937. ArcRotateCamera.prototype.dispose = function () {
  48938. this.inputs.clear();
  48939. _super.prototype.dispose.call(this);
  48940. };
  48941. ArcRotateCamera.prototype.getClassName = function () {
  48942. return "ArcRotateCamera";
  48943. };
  48944. __decorate([
  48945. BABYLON.serialize()
  48946. ], ArcRotateCamera.prototype, "alpha", void 0);
  48947. __decorate([
  48948. BABYLON.serialize()
  48949. ], ArcRotateCamera.prototype, "beta", void 0);
  48950. __decorate([
  48951. BABYLON.serialize()
  48952. ], ArcRotateCamera.prototype, "radius", void 0);
  48953. __decorate([
  48954. BABYLON.serializeAsVector3("target")
  48955. ], ArcRotateCamera.prototype, "_target", void 0);
  48956. __decorate([
  48957. BABYLON.serialize()
  48958. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48959. __decorate([
  48960. BABYLON.serialize()
  48961. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48962. __decorate([
  48963. BABYLON.serialize()
  48964. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48965. __decorate([
  48966. BABYLON.serialize()
  48967. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48968. __decorate([
  48969. BABYLON.serialize()
  48970. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48971. __decorate([
  48972. BABYLON.serialize()
  48973. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48974. __decorate([
  48975. BABYLON.serialize()
  48976. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48977. __decorate([
  48978. BABYLON.serialize()
  48979. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48980. __decorate([
  48981. BABYLON.serialize()
  48982. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48983. __decorate([
  48984. BABYLON.serialize()
  48985. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48986. __decorate([
  48987. BABYLON.serialize()
  48988. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48989. __decorate([
  48990. BABYLON.serialize()
  48991. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48992. __decorate([
  48993. BABYLON.serialize()
  48994. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48995. __decorate([
  48996. BABYLON.serializeAsVector3()
  48997. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48998. __decorate([
  48999. BABYLON.serialize()
  49000. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49001. __decorate([
  49002. BABYLON.serialize()
  49003. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49004. __decorate([
  49005. BABYLON.serialize()
  49006. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49007. return ArcRotateCamera;
  49008. }(BABYLON.TargetCamera));
  49009. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49010. })(BABYLON || (BABYLON = {}));
  49011. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49012. var BABYLON;
  49013. (function (BABYLON) {
  49014. /**
  49015. * The HemisphericLight simulates the ambient environment light,
  49016. * so the passed direction is the light reflection direction, not the incoming direction.
  49017. */
  49018. var HemisphericLight = /** @class */ (function (_super) {
  49019. __extends(HemisphericLight, _super);
  49020. /**
  49021. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49022. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49023. * The HemisphericLight can't cast shadows.
  49024. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49025. * @param name The friendly name of the light
  49026. * @param direction The direction of the light reflection
  49027. * @param scene The scene the light belongs to
  49028. */
  49029. function HemisphericLight(name, direction, scene) {
  49030. var _this = _super.call(this, name, scene) || this;
  49031. /**
  49032. * The groundColor is the light in the opposite direction to the one specified during creation.
  49033. * 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.
  49034. */
  49035. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49036. _this.direction = direction || BABYLON.Vector3.Up();
  49037. return _this;
  49038. }
  49039. HemisphericLight.prototype._buildUniformLayout = function () {
  49040. this._uniformBuffer.addUniform("vLightData", 4);
  49041. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49042. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49043. this._uniformBuffer.addUniform("vLightGround", 3);
  49044. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49045. this._uniformBuffer.addUniform("depthValues", 2);
  49046. this._uniformBuffer.create();
  49047. };
  49048. /**
  49049. * Returns the string "HemisphericLight".
  49050. * @return The class name
  49051. */
  49052. HemisphericLight.prototype.getClassName = function () {
  49053. return "HemisphericLight";
  49054. };
  49055. /**
  49056. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49057. * Returns the updated direction.
  49058. * @param target The target the direction should point to
  49059. * @return The computed direction
  49060. */
  49061. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49062. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49063. return this.direction;
  49064. };
  49065. /**
  49066. * Returns the shadow generator associated to the light.
  49067. * @returns Always null for hemispheric lights because it does not support shadows.
  49068. */
  49069. HemisphericLight.prototype.getShadowGenerator = function () {
  49070. return null;
  49071. };
  49072. /**
  49073. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49074. * @param effect The effect to update
  49075. * @param lightIndex The index of the light in the effect to update
  49076. * @returns The hemispheric light
  49077. */
  49078. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49079. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49080. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49081. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49082. return this;
  49083. };
  49084. /**
  49085. * @hidden internal use only.
  49086. */
  49087. HemisphericLight.prototype._getWorldMatrix = function () {
  49088. if (!this._worldMatrix) {
  49089. this._worldMatrix = BABYLON.Matrix.Identity();
  49090. }
  49091. return this._worldMatrix;
  49092. };
  49093. /**
  49094. * Returns the integer 3.
  49095. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49096. */
  49097. HemisphericLight.prototype.getTypeID = function () {
  49098. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49099. };
  49100. __decorate([
  49101. BABYLON.serializeAsColor3()
  49102. ], HemisphericLight.prototype, "groundColor", void 0);
  49103. __decorate([
  49104. BABYLON.serializeAsVector3()
  49105. ], HemisphericLight.prototype, "direction", void 0);
  49106. return HemisphericLight;
  49107. }(BABYLON.Light));
  49108. BABYLON.HemisphericLight = HemisphericLight;
  49109. })(BABYLON || (BABYLON = {}));
  49110. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49111. var BABYLON;
  49112. (function (BABYLON) {
  49113. /**
  49114. * Base implementation IShadowLight
  49115. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49116. */
  49117. var ShadowLight = /** @class */ (function (_super) {
  49118. __extends(ShadowLight, _super);
  49119. function ShadowLight() {
  49120. var _this = _super !== null && _super.apply(this, arguments) || this;
  49121. _this._needProjectionMatrixCompute = true;
  49122. return _this;
  49123. }
  49124. ShadowLight.prototype._setPosition = function (value) {
  49125. this._position = value;
  49126. };
  49127. Object.defineProperty(ShadowLight.prototype, "position", {
  49128. /**
  49129. * Sets the position the shadow will be casted from. Also use as the light position for both
  49130. * point and spot lights.
  49131. */
  49132. get: function () {
  49133. return this._position;
  49134. },
  49135. /**
  49136. * Sets the position the shadow will be casted from. Also use as the light position for both
  49137. * point and spot lights.
  49138. */
  49139. set: function (value) {
  49140. this._setPosition(value);
  49141. },
  49142. enumerable: true,
  49143. configurable: true
  49144. });
  49145. ShadowLight.prototype._setDirection = function (value) {
  49146. this._direction = value;
  49147. };
  49148. Object.defineProperty(ShadowLight.prototype, "direction", {
  49149. /**
  49150. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49151. * Also use as the light direction on spot and directional lights.
  49152. */
  49153. get: function () {
  49154. return this._direction;
  49155. },
  49156. /**
  49157. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49158. * Also use as the light direction on spot and directional lights.
  49159. */
  49160. set: function (value) {
  49161. this._setDirection(value);
  49162. },
  49163. enumerable: true,
  49164. configurable: true
  49165. });
  49166. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49167. /**
  49168. * Gets the shadow projection clipping minimum z value.
  49169. */
  49170. get: function () {
  49171. return this._shadowMinZ;
  49172. },
  49173. /**
  49174. * Sets the shadow projection clipping minimum z value.
  49175. */
  49176. set: function (value) {
  49177. this._shadowMinZ = value;
  49178. this.forceProjectionMatrixCompute();
  49179. },
  49180. enumerable: true,
  49181. configurable: true
  49182. });
  49183. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49184. /**
  49185. * Sets the shadow projection clipping maximum z value.
  49186. */
  49187. get: function () {
  49188. return this._shadowMaxZ;
  49189. },
  49190. /**
  49191. * Gets the shadow projection clipping maximum z value.
  49192. */
  49193. set: function (value) {
  49194. this._shadowMaxZ = value;
  49195. this.forceProjectionMatrixCompute();
  49196. },
  49197. enumerable: true,
  49198. configurable: true
  49199. });
  49200. /**
  49201. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49202. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49203. */
  49204. ShadowLight.prototype.computeTransformedInformation = function () {
  49205. if (this.parent && this.parent.getWorldMatrix) {
  49206. if (!this.transformedPosition) {
  49207. this.transformedPosition = BABYLON.Vector3.Zero();
  49208. }
  49209. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49210. // In case the direction is present.
  49211. if (this.direction) {
  49212. if (!this.transformedDirection) {
  49213. this.transformedDirection = BABYLON.Vector3.Zero();
  49214. }
  49215. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49216. }
  49217. return true;
  49218. }
  49219. return false;
  49220. };
  49221. /**
  49222. * Return the depth scale used for the shadow map.
  49223. * @returns the depth scale.
  49224. */
  49225. ShadowLight.prototype.getDepthScale = function () {
  49226. return 50.0;
  49227. };
  49228. /**
  49229. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49230. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49231. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49232. */
  49233. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49234. return this.transformedDirection ? this.transformedDirection : this.direction;
  49235. };
  49236. /**
  49237. * Returns the ShadowLight absolute position in the World.
  49238. * @returns the position vector in world space
  49239. */
  49240. ShadowLight.prototype.getAbsolutePosition = function () {
  49241. return this.transformedPosition ? this.transformedPosition : this.position;
  49242. };
  49243. /**
  49244. * Sets the ShadowLight direction toward the passed target.
  49245. * @param target The point tot target in local space
  49246. * @returns the updated ShadowLight direction
  49247. */
  49248. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49249. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49250. return this.direction;
  49251. };
  49252. /**
  49253. * Returns the light rotation in euler definition.
  49254. * @returns the x y z rotation in local space.
  49255. */
  49256. ShadowLight.prototype.getRotation = function () {
  49257. this.direction.normalize();
  49258. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49259. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49260. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49261. };
  49262. /**
  49263. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49264. * @returns true if a cube texture needs to be use
  49265. */
  49266. ShadowLight.prototype.needCube = function () {
  49267. return false;
  49268. };
  49269. /**
  49270. * Detects if the projection matrix requires to be recomputed this frame.
  49271. * @returns true if it requires to be recomputed otherwise, false.
  49272. */
  49273. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49274. return this._needProjectionMatrixCompute;
  49275. };
  49276. /**
  49277. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49278. */
  49279. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49280. this._needProjectionMatrixCompute = true;
  49281. };
  49282. /**
  49283. * Get the world matrix of the sahdow lights.
  49284. * @hidden Internal Use Only
  49285. */
  49286. ShadowLight.prototype._getWorldMatrix = function () {
  49287. if (!this._worldMatrix) {
  49288. this._worldMatrix = BABYLON.Matrix.Identity();
  49289. }
  49290. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49291. return this._worldMatrix;
  49292. };
  49293. /**
  49294. * Gets the minZ used for shadow according to both the scene and the light.
  49295. * @param activeCamera The camera we are returning the min for
  49296. * @returns the depth min z
  49297. */
  49298. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49299. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49300. };
  49301. /**
  49302. * Gets the maxZ used for shadow according to both the scene and the light.
  49303. * @param activeCamera The camera we are returning the max for
  49304. * @returns the depth max z
  49305. */
  49306. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49307. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49308. };
  49309. /**
  49310. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49311. * @param matrix The materix to updated with the projection information
  49312. * @param viewMatrix The transform matrix of the light
  49313. * @param renderList The list of mesh to render in the map
  49314. * @returns The current light
  49315. */
  49316. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49317. if (this.customProjectionMatrixBuilder) {
  49318. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49319. }
  49320. else {
  49321. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49322. }
  49323. return this;
  49324. };
  49325. __decorate([
  49326. BABYLON.serializeAsVector3()
  49327. ], ShadowLight.prototype, "position", null);
  49328. __decorate([
  49329. BABYLON.serializeAsVector3()
  49330. ], ShadowLight.prototype, "direction", null);
  49331. __decorate([
  49332. BABYLON.serialize()
  49333. ], ShadowLight.prototype, "shadowMinZ", null);
  49334. __decorate([
  49335. BABYLON.serialize()
  49336. ], ShadowLight.prototype, "shadowMaxZ", null);
  49337. return ShadowLight;
  49338. }(BABYLON.Light));
  49339. BABYLON.ShadowLight = ShadowLight;
  49340. })(BABYLON || (BABYLON = {}));
  49341. //# sourceMappingURL=babylon.shadowLight.js.map
  49342. var BABYLON;
  49343. (function (BABYLON) {
  49344. /**
  49345. * A point light is a light defined by an unique point in world space.
  49346. * The light is emitted in every direction from this point.
  49347. * A good example of a point light is a standard light bulb.
  49348. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49349. */
  49350. var PointLight = /** @class */ (function (_super) {
  49351. __extends(PointLight, _super);
  49352. /**
  49353. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49354. * A PointLight emits the light in every direction.
  49355. * It can cast shadows.
  49356. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49357. * ```javascript
  49358. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49359. * ```
  49360. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49361. * @param name The light friendly name
  49362. * @param position The position of the point light in the scene
  49363. * @param scene The scene the lights belongs to
  49364. */
  49365. function PointLight(name, position, scene) {
  49366. var _this = _super.call(this, name, scene) || this;
  49367. _this._shadowAngle = Math.PI / 2;
  49368. _this.position = position;
  49369. return _this;
  49370. }
  49371. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49372. /**
  49373. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49374. * This specifies what angle the shadow will use to be created.
  49375. *
  49376. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49377. */
  49378. get: function () {
  49379. return this._shadowAngle;
  49380. },
  49381. /**
  49382. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49383. * This specifies what angle the shadow will use to be created.
  49384. *
  49385. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49386. */
  49387. set: function (value) {
  49388. this._shadowAngle = value;
  49389. this.forceProjectionMatrixCompute();
  49390. },
  49391. enumerable: true,
  49392. configurable: true
  49393. });
  49394. Object.defineProperty(PointLight.prototype, "direction", {
  49395. /**
  49396. * Gets the direction if it has been set.
  49397. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49398. */
  49399. get: function () {
  49400. return this._direction;
  49401. },
  49402. /**
  49403. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49404. */
  49405. set: function (value) {
  49406. var previousNeedCube = this.needCube();
  49407. this._direction = value;
  49408. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49409. this._shadowGenerator.recreateShadowMap();
  49410. }
  49411. },
  49412. enumerable: true,
  49413. configurable: true
  49414. });
  49415. /**
  49416. * Returns the string "PointLight"
  49417. * @returns the class name
  49418. */
  49419. PointLight.prototype.getClassName = function () {
  49420. return "PointLight";
  49421. };
  49422. /**
  49423. * Returns the integer 0.
  49424. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49425. */
  49426. PointLight.prototype.getTypeID = function () {
  49427. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49428. };
  49429. /**
  49430. * Specifies wether or not the shadowmap should be a cube texture.
  49431. * @returns true if the shadowmap needs to be a cube texture.
  49432. */
  49433. PointLight.prototype.needCube = function () {
  49434. return !this.direction;
  49435. };
  49436. /**
  49437. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49438. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49439. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49440. */
  49441. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49442. if (this.direction) {
  49443. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49444. }
  49445. else {
  49446. switch (faceIndex) {
  49447. case 0:
  49448. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49449. case 1:
  49450. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49451. case 2:
  49452. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49453. case 3:
  49454. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49455. case 4:
  49456. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49457. case 5:
  49458. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49459. }
  49460. }
  49461. return BABYLON.Vector3.Zero();
  49462. };
  49463. /**
  49464. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49465. * - fov = PI / 2
  49466. * - aspect ratio : 1.0
  49467. * - z-near and far equal to the active camera minZ and maxZ.
  49468. * Returns the PointLight.
  49469. */
  49470. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49471. var activeCamera = this.getScene().activeCamera;
  49472. if (!activeCamera) {
  49473. return;
  49474. }
  49475. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49476. };
  49477. PointLight.prototype._buildUniformLayout = function () {
  49478. this._uniformBuffer.addUniform("vLightData", 4);
  49479. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49480. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49481. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49482. this._uniformBuffer.addUniform("depthValues", 2);
  49483. this._uniformBuffer.create();
  49484. };
  49485. /**
  49486. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49487. * @param effect The effect to update
  49488. * @param lightIndex The index of the light in the effect to update
  49489. * @returns The point light
  49490. */
  49491. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49492. if (this.computeTransformedInformation()) {
  49493. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49494. return this;
  49495. }
  49496. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49497. return this;
  49498. };
  49499. __decorate([
  49500. BABYLON.serialize()
  49501. ], PointLight.prototype, "shadowAngle", null);
  49502. return PointLight;
  49503. }(BABYLON.ShadowLight));
  49504. BABYLON.PointLight = PointLight;
  49505. })(BABYLON || (BABYLON = {}));
  49506. //# sourceMappingURL=babylon.pointLight.js.map
  49507. var BABYLON;
  49508. (function (BABYLON) {
  49509. /**
  49510. * A directional light is defined by a direction (what a surprise!).
  49511. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49512. * 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.
  49513. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49514. */
  49515. var DirectionalLight = /** @class */ (function (_super) {
  49516. __extends(DirectionalLight, _super);
  49517. /**
  49518. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49519. * The directional light is emitted from everywhere in the given direction.
  49520. * It can cast shawdows.
  49521. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49522. * @param name The friendly name of the light
  49523. * @param direction The direction of the light
  49524. * @param scene The scene the light belongs to
  49525. */
  49526. function DirectionalLight(name, direction, scene) {
  49527. var _this = _super.call(this, name, scene) || this;
  49528. _this._shadowFrustumSize = 0;
  49529. _this._shadowOrthoScale = 0.1;
  49530. /**
  49531. * Automatically compute the projection matrix to best fit (including all the casters)
  49532. * on each frame.
  49533. */
  49534. _this.autoUpdateExtends = true;
  49535. // Cache
  49536. _this._orthoLeft = Number.MAX_VALUE;
  49537. _this._orthoRight = Number.MIN_VALUE;
  49538. _this._orthoTop = Number.MIN_VALUE;
  49539. _this._orthoBottom = Number.MAX_VALUE;
  49540. _this.position = direction.scale(-1.0);
  49541. _this.direction = direction;
  49542. return _this;
  49543. }
  49544. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49545. /**
  49546. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49547. */
  49548. get: function () {
  49549. return this._shadowFrustumSize;
  49550. },
  49551. /**
  49552. * Specifies a fix frustum size for the shadow generation.
  49553. */
  49554. set: function (value) {
  49555. this._shadowFrustumSize = value;
  49556. this.forceProjectionMatrixCompute();
  49557. },
  49558. enumerable: true,
  49559. configurable: true
  49560. });
  49561. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49562. /**
  49563. * Gets the shadow projection scale against the optimal computed one.
  49564. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49565. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49566. */
  49567. get: function () {
  49568. return this._shadowOrthoScale;
  49569. },
  49570. /**
  49571. * Sets the shadow projection scale against the optimal computed one.
  49572. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49573. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49574. */
  49575. set: function (value) {
  49576. this._shadowOrthoScale = value;
  49577. this.forceProjectionMatrixCompute();
  49578. },
  49579. enumerable: true,
  49580. configurable: true
  49581. });
  49582. /**
  49583. * Returns the string "DirectionalLight".
  49584. * @return The class name
  49585. */
  49586. DirectionalLight.prototype.getClassName = function () {
  49587. return "DirectionalLight";
  49588. };
  49589. /**
  49590. * Returns the integer 1.
  49591. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49592. */
  49593. DirectionalLight.prototype.getTypeID = function () {
  49594. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49595. };
  49596. /**
  49597. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49598. * Returns the DirectionalLight Shadow projection matrix.
  49599. */
  49600. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49601. if (this.shadowFrustumSize > 0) {
  49602. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49603. }
  49604. else {
  49605. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49606. }
  49607. };
  49608. /**
  49609. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49610. * Returns the DirectionalLight Shadow projection matrix.
  49611. */
  49612. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49613. var activeCamera = this.getScene().activeCamera;
  49614. if (!activeCamera) {
  49615. return;
  49616. }
  49617. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49618. };
  49619. /**
  49620. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49621. * Returns the DirectionalLight Shadow projection matrix.
  49622. */
  49623. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49624. var activeCamera = this.getScene().activeCamera;
  49625. if (!activeCamera) {
  49626. return;
  49627. }
  49628. // Check extends
  49629. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49630. var tempVector3 = BABYLON.Vector3.Zero();
  49631. this._orthoLeft = Number.MAX_VALUE;
  49632. this._orthoRight = Number.MIN_VALUE;
  49633. this._orthoTop = Number.MIN_VALUE;
  49634. this._orthoBottom = Number.MAX_VALUE;
  49635. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49636. var mesh = renderList[meshIndex];
  49637. if (!mesh) {
  49638. continue;
  49639. }
  49640. var boundingInfo = mesh.getBoundingInfo();
  49641. var boundingBox = boundingInfo.boundingBox;
  49642. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49643. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49644. if (tempVector3.x < this._orthoLeft)
  49645. this._orthoLeft = tempVector3.x;
  49646. if (tempVector3.y < this._orthoBottom)
  49647. this._orthoBottom = tempVector3.y;
  49648. if (tempVector3.x > this._orthoRight)
  49649. this._orthoRight = tempVector3.x;
  49650. if (tempVector3.y > this._orthoTop)
  49651. this._orthoTop = tempVector3.y;
  49652. }
  49653. }
  49654. }
  49655. var xOffset = this._orthoRight - this._orthoLeft;
  49656. var yOffset = this._orthoTop - this._orthoBottom;
  49657. 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);
  49658. };
  49659. DirectionalLight.prototype._buildUniformLayout = function () {
  49660. this._uniformBuffer.addUniform("vLightData", 4);
  49661. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49662. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49663. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49664. this._uniformBuffer.addUniform("depthValues", 2);
  49665. this._uniformBuffer.create();
  49666. };
  49667. /**
  49668. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49669. * @param effect The effect to update
  49670. * @param lightIndex The index of the light in the effect to update
  49671. * @returns The directional light
  49672. */
  49673. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49674. if (this.computeTransformedInformation()) {
  49675. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49676. return this;
  49677. }
  49678. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49679. return this;
  49680. };
  49681. /**
  49682. * Gets the minZ used for shadow according to both the scene and the light.
  49683. *
  49684. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49685. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49686. * @param activeCamera The camera we are returning the min for
  49687. * @returns the depth min z
  49688. */
  49689. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49690. return 1;
  49691. };
  49692. /**
  49693. * Gets the maxZ used for shadow according to both the scene and the light.
  49694. *
  49695. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49696. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49697. * @param activeCamera The camera we are returning the max for
  49698. * @returns the depth max z
  49699. */
  49700. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49701. return 1;
  49702. };
  49703. __decorate([
  49704. BABYLON.serialize()
  49705. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49706. __decorate([
  49707. BABYLON.serialize()
  49708. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49709. __decorate([
  49710. BABYLON.serialize()
  49711. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49712. return DirectionalLight;
  49713. }(BABYLON.ShadowLight));
  49714. BABYLON.DirectionalLight = DirectionalLight;
  49715. })(BABYLON || (BABYLON = {}));
  49716. //# sourceMappingURL=babylon.directionalLight.js.map
  49717. var BABYLON;
  49718. (function (BABYLON) {
  49719. /**
  49720. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49721. * These values define a cone of light starting from the position, emitting toward the direction.
  49722. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49723. * and the exponent defines the speed of the decay of the light with distance (reach).
  49724. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49725. */
  49726. var SpotLight = /** @class */ (function (_super) {
  49727. __extends(SpotLight, _super);
  49728. /**
  49729. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49730. * It can cast shadows.
  49731. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49732. * @param name The light friendly name
  49733. * @param position The position of the spot light in the scene
  49734. * @param direction The direction of the light in the scene
  49735. * @param angle The cone angle of the light in Radians
  49736. * @param exponent The light decay speed with the distance from the emission spot
  49737. * @param scene The scene the lights belongs to
  49738. */
  49739. function SpotLight(name, position, direction, angle, exponent, scene) {
  49740. var _this = _super.call(this, name, scene) || this;
  49741. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49742. _this._projectionTextureLightNear = 1e-6;
  49743. _this._projectionTextureLightFar = 1000.0;
  49744. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49745. _this._projectionTextureViewLightDirty = true;
  49746. _this._projectionTextureProjectionLightDirty = true;
  49747. _this._projectionTextureDirty = true;
  49748. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49749. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49750. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49751. _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);
  49752. _this.position = position;
  49753. _this.direction = direction;
  49754. _this.angle = angle;
  49755. _this.exponent = exponent;
  49756. return _this;
  49757. }
  49758. Object.defineProperty(SpotLight.prototype, "angle", {
  49759. /**
  49760. * Gets the cone angle of the spot light in Radians.
  49761. */
  49762. get: function () {
  49763. return this._angle;
  49764. },
  49765. /**
  49766. * Sets the cone angle of the spot light in Radians.
  49767. */
  49768. set: function (value) {
  49769. this._angle = value;
  49770. this._projectionTextureProjectionLightDirty = true;
  49771. this.forceProjectionMatrixCompute();
  49772. },
  49773. enumerable: true,
  49774. configurable: true
  49775. });
  49776. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49777. /**
  49778. * Allows scaling the angle of the light for shadow generation only.
  49779. */
  49780. get: function () {
  49781. return this._shadowAngleScale;
  49782. },
  49783. /**
  49784. * Allows scaling the angle of the light for shadow generation only.
  49785. */
  49786. set: function (value) {
  49787. this._shadowAngleScale = value;
  49788. this.forceProjectionMatrixCompute();
  49789. },
  49790. enumerable: true,
  49791. configurable: true
  49792. });
  49793. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49794. /**
  49795. * Allows reading the projecton texture
  49796. */
  49797. get: function () {
  49798. return this._projectionTextureMatrix;
  49799. },
  49800. enumerable: true,
  49801. configurable: true
  49802. });
  49803. ;
  49804. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49805. /**
  49806. * Gets the near clip of the Spotlight for texture projection.
  49807. */
  49808. get: function () {
  49809. return this._projectionTextureLightNear;
  49810. },
  49811. /**
  49812. * Sets the near clip of the Spotlight for texture projection.
  49813. */
  49814. set: function (value) {
  49815. this._projectionTextureLightNear = value;
  49816. this._projectionTextureProjectionLightDirty = true;
  49817. },
  49818. enumerable: true,
  49819. configurable: true
  49820. });
  49821. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49822. /**
  49823. * Gets the far clip of the Spotlight for texture projection.
  49824. */
  49825. get: function () {
  49826. return this._projectionTextureLightFar;
  49827. },
  49828. /**
  49829. * Sets the far clip of the Spotlight for texture projection.
  49830. */
  49831. set: function (value) {
  49832. this._projectionTextureLightFar = value;
  49833. this._projectionTextureProjectionLightDirty = true;
  49834. },
  49835. enumerable: true,
  49836. configurable: true
  49837. });
  49838. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49839. /**
  49840. * Gets the Up vector of the Spotlight for texture projection.
  49841. */
  49842. get: function () {
  49843. return this._projectionTextureUpDirection;
  49844. },
  49845. /**
  49846. * Sets the Up vector of the Spotlight for texture projection.
  49847. */
  49848. set: function (value) {
  49849. this._projectionTextureUpDirection = value;
  49850. this._projectionTextureProjectionLightDirty = true;
  49851. },
  49852. enumerable: true,
  49853. configurable: true
  49854. });
  49855. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49856. /**
  49857. * Gets the projection texture of the light.
  49858. */
  49859. get: function () {
  49860. return this._projectionTexture;
  49861. },
  49862. /**
  49863. * Sets the projection texture of the light.
  49864. */
  49865. set: function (value) {
  49866. this._projectionTexture = value;
  49867. this._projectionTextureDirty = true;
  49868. },
  49869. enumerable: true,
  49870. configurable: true
  49871. });
  49872. /**
  49873. * Returns the string "SpotLight".
  49874. * @returns the class name
  49875. */
  49876. SpotLight.prototype.getClassName = function () {
  49877. return "SpotLight";
  49878. };
  49879. /**
  49880. * Returns the integer 2.
  49881. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49882. */
  49883. SpotLight.prototype.getTypeID = function () {
  49884. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49885. };
  49886. /**
  49887. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49888. */
  49889. SpotLight.prototype._setDirection = function (value) {
  49890. _super.prototype._setDirection.call(this, value);
  49891. this._projectionTextureViewLightDirty = true;
  49892. };
  49893. /**
  49894. * Overrides the position setter to recompute the projection texture view light Matrix.
  49895. */
  49896. SpotLight.prototype._setPosition = function (value) {
  49897. _super.prototype._setPosition.call(this, value);
  49898. this._projectionTextureViewLightDirty = true;
  49899. };
  49900. /**
  49901. * 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.
  49902. * Returns the SpotLight.
  49903. */
  49904. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49905. var activeCamera = this.getScene().activeCamera;
  49906. if (!activeCamera) {
  49907. return;
  49908. }
  49909. this._shadowAngleScale = this._shadowAngleScale || 1;
  49910. var angle = this._shadowAngleScale * this._angle;
  49911. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49912. };
  49913. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49914. this._projectionTextureViewLightDirty = false;
  49915. this._projectionTextureDirty = true;
  49916. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49917. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49918. };
  49919. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49920. this._projectionTextureProjectionLightDirty = false;
  49921. this._projectionTextureDirty = true;
  49922. var light_far = this.projectionTextureLightFar;
  49923. var light_near = this.projectionTextureLightNear;
  49924. var P = light_far / (light_far - light_near);
  49925. var Q = -P * light_near;
  49926. var S = 1.0 / Math.tan(this._angle / 2.0);
  49927. var A = 1.0;
  49928. 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);
  49929. };
  49930. /**
  49931. * Main function for light texture projection matrix computing.
  49932. */
  49933. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49934. this._projectionTextureDirty = false;
  49935. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49936. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49937. };
  49938. SpotLight.prototype._buildUniformLayout = function () {
  49939. this._uniformBuffer.addUniform("vLightData", 4);
  49940. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49941. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49942. this._uniformBuffer.addUniform("vLightDirection", 3);
  49943. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49944. this._uniformBuffer.addUniform("depthValues", 2);
  49945. this._uniformBuffer.create();
  49946. };
  49947. /**
  49948. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49949. * @param effect The effect to update
  49950. * @param lightIndex The index of the light in the effect to update
  49951. * @returns The spot light
  49952. */
  49953. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49954. var normalizeDirection;
  49955. if (this.computeTransformedInformation()) {
  49956. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49957. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49958. }
  49959. else {
  49960. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49961. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49962. }
  49963. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49964. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49965. if (this._projectionTextureViewLightDirty) {
  49966. this._computeProjectionTextureViewLightMatrix();
  49967. }
  49968. if (this._projectionTextureProjectionLightDirty) {
  49969. this._computeProjectionTextureProjectionLightMatrix();
  49970. }
  49971. if (this._projectionTextureDirty) {
  49972. this._computeProjectionTextureMatrix();
  49973. }
  49974. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49975. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49976. }
  49977. return this;
  49978. };
  49979. /**
  49980. * Disposes the light and the associated resources.
  49981. */
  49982. SpotLight.prototype.dispose = function () {
  49983. _super.prototype.dispose.call(this);
  49984. if (this._projectionTexture) {
  49985. this._projectionTexture.dispose();
  49986. }
  49987. };
  49988. __decorate([
  49989. BABYLON.serialize()
  49990. ], SpotLight.prototype, "angle", null);
  49991. __decorate([
  49992. BABYLON.serialize()
  49993. ], SpotLight.prototype, "shadowAngleScale", null);
  49994. __decorate([
  49995. BABYLON.serialize()
  49996. ], SpotLight.prototype, "exponent", void 0);
  49997. __decorate([
  49998. BABYLON.serialize()
  49999. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50000. __decorate([
  50001. BABYLON.serialize()
  50002. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50003. __decorate([
  50004. BABYLON.serialize()
  50005. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50006. __decorate([
  50007. BABYLON.serializeAsTexture("projectedLightTexture")
  50008. ], SpotLight.prototype, "_projectionTexture", void 0);
  50009. return SpotLight;
  50010. }(BABYLON.ShadowLight));
  50011. BABYLON.SpotLight = SpotLight;
  50012. })(BABYLON || (BABYLON = {}));
  50013. //# sourceMappingURL=babylon.spotLight.js.map
  50014. var BABYLON;
  50015. (function (BABYLON) {
  50016. /**
  50017. * Class used to override all child animations of a given target
  50018. */
  50019. var AnimationPropertiesOverride = /** @class */ (function () {
  50020. function AnimationPropertiesOverride() {
  50021. /**
  50022. * Gets or sets a value indicating if animation blending must be used
  50023. */
  50024. this.enableBlending = false;
  50025. /**
  50026. * Gets or sets the blending speed to use when enableBlending is true
  50027. */
  50028. this.blendingSpeed = 0.01;
  50029. /**
  50030. * Gets or sets the default loop mode to use
  50031. */
  50032. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50033. }
  50034. return AnimationPropertiesOverride;
  50035. }());
  50036. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50037. })(BABYLON || (BABYLON = {}));
  50038. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50039. var BABYLON;
  50040. (function (BABYLON) {
  50041. /**
  50042. * Represents the range of an animation
  50043. */
  50044. var AnimationRange = /** @class */ (function () {
  50045. /**
  50046. * Initializes the range of an animation
  50047. * @param name The name of the animation range
  50048. * @param from The starting frame of the animation
  50049. * @param to The ending frame of the animation
  50050. */
  50051. function AnimationRange(
  50052. /**The name of the animation range**/
  50053. name,
  50054. /**The starting frame of the animation */
  50055. from,
  50056. /**The ending frame of the animation*/
  50057. to) {
  50058. this.name = name;
  50059. this.from = from;
  50060. this.to = to;
  50061. }
  50062. /**
  50063. * Makes a copy of the animation range
  50064. * @returns A copy of the animation range
  50065. */
  50066. AnimationRange.prototype.clone = function () {
  50067. return new AnimationRange(this.name, this.from, this.to);
  50068. };
  50069. return AnimationRange;
  50070. }());
  50071. BABYLON.AnimationRange = AnimationRange;
  50072. /**
  50073. * Composed of a frame, and an action function
  50074. */
  50075. var AnimationEvent = /** @class */ (function () {
  50076. /**
  50077. * Initializes the animation event
  50078. * @param frame The frame for which the event is triggered
  50079. * @param action The event to perform when triggered
  50080. * @param onlyOnce Specifies if the event should be triggered only once
  50081. */
  50082. function AnimationEvent(
  50083. /** The frame for which the event is triggered **/
  50084. frame,
  50085. /** The event to perform when triggered **/
  50086. action,
  50087. /** Specifies if the event should be triggered only once**/
  50088. onlyOnce) {
  50089. this.frame = frame;
  50090. this.action = action;
  50091. this.onlyOnce = onlyOnce;
  50092. /**
  50093. * Specifies if the animation event is done
  50094. */
  50095. this.isDone = false;
  50096. }
  50097. return AnimationEvent;
  50098. }());
  50099. BABYLON.AnimationEvent = AnimationEvent;
  50100. /**
  50101. * A cursor which tracks a point on a path
  50102. */
  50103. var PathCursor = /** @class */ (function () {
  50104. /**
  50105. * Initializes the path cursor
  50106. * @param path The path to track
  50107. */
  50108. function PathCursor(path) {
  50109. this.path = path;
  50110. /**
  50111. * Stores path cursor callbacks for when an onchange event is triggered
  50112. */
  50113. this._onchange = new Array();
  50114. /**
  50115. * The value of the path cursor
  50116. */
  50117. this.value = 0;
  50118. /**
  50119. * The animation array of the path cursor
  50120. */
  50121. this.animations = new Array();
  50122. }
  50123. /**
  50124. * Gets the cursor point on the path
  50125. * @returns A point on the path cursor at the cursor location
  50126. */
  50127. PathCursor.prototype.getPoint = function () {
  50128. var point = this.path.getPointAtLengthPosition(this.value);
  50129. return new BABYLON.Vector3(point.x, 0, point.y);
  50130. };
  50131. /**
  50132. * Moves the cursor ahead by the step amount
  50133. * @param step The amount to move the cursor forward
  50134. * @returns This path cursor
  50135. */
  50136. PathCursor.prototype.moveAhead = function (step) {
  50137. if (step === void 0) { step = 0.002; }
  50138. this.move(step);
  50139. return this;
  50140. };
  50141. /**
  50142. * Moves the cursor behind by the step amount
  50143. * @param step The amount to move the cursor back
  50144. * @returns This path cursor
  50145. */
  50146. PathCursor.prototype.moveBack = function (step) {
  50147. if (step === void 0) { step = 0.002; }
  50148. this.move(-step);
  50149. return this;
  50150. };
  50151. /**
  50152. * Moves the cursor by the step amount
  50153. * If the step amount is greater than one, an exception is thrown
  50154. * @param step The amount to move the cursor
  50155. * @returns This path cursor
  50156. */
  50157. PathCursor.prototype.move = function (step) {
  50158. if (Math.abs(step) > 1) {
  50159. throw "step size should be less than 1.";
  50160. }
  50161. this.value += step;
  50162. this.ensureLimits();
  50163. this.raiseOnChange();
  50164. return this;
  50165. };
  50166. /**
  50167. * Ensures that the value is limited between zero and one
  50168. * @returns This path cursor
  50169. */
  50170. PathCursor.prototype.ensureLimits = function () {
  50171. while (this.value > 1) {
  50172. this.value -= 1;
  50173. }
  50174. while (this.value < 0) {
  50175. this.value += 1;
  50176. }
  50177. return this;
  50178. };
  50179. /**
  50180. * Runs onchange callbacks on change (used by the animation engine)
  50181. * @returns This path cursor
  50182. */
  50183. PathCursor.prototype.raiseOnChange = function () {
  50184. var _this = this;
  50185. this._onchange.forEach(function (f) { return f(_this); });
  50186. return this;
  50187. };
  50188. /**
  50189. * Executes a function on change
  50190. * @param f A path cursor onchange callback
  50191. * @returns This path cursor
  50192. */
  50193. PathCursor.prototype.onchange = function (f) {
  50194. this._onchange.push(f);
  50195. return this;
  50196. };
  50197. return PathCursor;
  50198. }());
  50199. BABYLON.PathCursor = PathCursor;
  50200. /**
  50201. * Enum for the animation key frame interpolation type
  50202. */
  50203. var AnimationKeyInterpolation;
  50204. (function (AnimationKeyInterpolation) {
  50205. /**
  50206. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50207. */
  50208. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50209. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50210. /**
  50211. * Class used to store any kind of animation
  50212. */
  50213. var Animation = /** @class */ (function () {
  50214. /**
  50215. * Initializes the animation
  50216. * @param name Name of the animation
  50217. * @param targetProperty Property to animate
  50218. * @param framePerSecond The frames per second of the animation
  50219. * @param dataType The data type of the animation
  50220. * @param loopMode The loop mode of the animation
  50221. * @param enableBlendings Specifies if blending should be enabled
  50222. */
  50223. function Animation(
  50224. /**Name of the animation */
  50225. name,
  50226. /**Property to animate */
  50227. targetProperty,
  50228. /**The frames per second of the animation */
  50229. framePerSecond,
  50230. /**The data type of the animation */
  50231. dataType,
  50232. /**The loop mode of the animation */
  50233. loopMode,
  50234. /**Specifies if blending should be enabled */
  50235. enableBlending) {
  50236. this.name = name;
  50237. this.targetProperty = targetProperty;
  50238. this.framePerSecond = framePerSecond;
  50239. this.dataType = dataType;
  50240. this.loopMode = loopMode;
  50241. this.enableBlending = enableBlending;
  50242. /**
  50243. * @hidden Internal use only
  50244. */
  50245. this._runtimeAnimations = new Array();
  50246. /**
  50247. * The set of event that will be linked to this animation
  50248. */
  50249. this._events = new Array();
  50250. /**
  50251. * Stores the blending speed of the animation
  50252. */
  50253. this.blendingSpeed = 0.01;
  50254. /**
  50255. * Stores the animation ranges for the animation
  50256. */
  50257. this._ranges = {};
  50258. this.targetPropertyPath = targetProperty.split(".");
  50259. this.dataType = dataType;
  50260. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50261. }
  50262. /**
  50263. * @hidden Internal use
  50264. */
  50265. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50266. var dataType = undefined;
  50267. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50268. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50269. }
  50270. else if (from instanceof BABYLON.Quaternion) {
  50271. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50272. }
  50273. else if (from instanceof BABYLON.Vector3) {
  50274. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50275. }
  50276. else if (from instanceof BABYLON.Vector2) {
  50277. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50278. }
  50279. else if (from instanceof BABYLON.Color3) {
  50280. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50281. }
  50282. else if (from instanceof BABYLON.Size) {
  50283. dataType = Animation.ANIMATIONTYPE_SIZE;
  50284. }
  50285. if (dataType == undefined) {
  50286. return null;
  50287. }
  50288. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50289. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50290. animation.setKeys(keys);
  50291. if (easingFunction !== undefined) {
  50292. animation.setEasingFunction(easingFunction);
  50293. }
  50294. return animation;
  50295. };
  50296. /**
  50297. * Sets up an animation
  50298. * @param property The property to animate
  50299. * @param animationType The animation type to apply
  50300. * @param framePerSecond The frames per second of the animation
  50301. * @param easingFunction The easing function used in the animation
  50302. * @returns The created animation
  50303. */
  50304. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50305. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50306. animation.setEasingFunction(easingFunction);
  50307. return animation;
  50308. };
  50309. /**
  50310. * Create and start an animation on a node
  50311. * @param name defines the name of the global animation that will be run on all nodes
  50312. * @param node defines the root node where the animation will take place
  50313. * @param targetProperty defines property to animate
  50314. * @param framePerSecond defines the number of frame per second yo use
  50315. * @param totalFrame defines the number of frames in total
  50316. * @param from defines the initial value
  50317. * @param to defines the final value
  50318. * @param loopMode defines which loop mode you want to use (off by default)
  50319. * @param easingFunction defines the easing function to use (linear by default)
  50320. * @param onAnimationEnd defines the callback to call when animation end
  50321. * @returns the animatable created for this animation
  50322. */
  50323. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50324. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50325. if (!animation) {
  50326. return null;
  50327. }
  50328. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50329. };
  50330. /**
  50331. * Create and start an animation on a node and its descendants
  50332. * @param name defines the name of the global animation that will be run on all nodes
  50333. * @param node defines the root node where the animation will take place
  50334. * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used
  50335. * @param targetProperty defines property to animate
  50336. * @param framePerSecond defines the number of frame per second to use
  50337. * @param totalFrame defines the number of frames in total
  50338. * @param from defines the initial value
  50339. * @param to defines the final value
  50340. * @param loopMode defines which loop mode you want to use (off by default)
  50341. * @param easingFunction defines the easing function to use (linear by default)
  50342. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50343. * @returns the list of animatables created for all nodes
  50344. * @example https://www.babylonjs-playground.com/#MH0VLI
  50345. */
  50346. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50347. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50348. if (!animation) {
  50349. return null;
  50350. }
  50351. var scene = node.getScene();
  50352. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50353. };
  50354. /**
  50355. * Creates a new animation, merges it with the existing animations and starts it
  50356. * @param name Name of the animation
  50357. * @param node Node which contains the scene that begins the animations
  50358. * @param targetProperty Specifies which property to animate
  50359. * @param framePerSecond The frames per second of the animation
  50360. * @param totalFrame The total number of frames
  50361. * @param from The frame at the beginning of the animation
  50362. * @param to The frame at the end of the animation
  50363. * @param loopMode Specifies the loop mode of the animation
  50364. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50365. * @param onAnimationEnd Callback to run once the animation is complete
  50366. * @returns Nullable animation
  50367. */
  50368. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50369. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50370. if (!animation) {
  50371. return null;
  50372. }
  50373. node.animations.push(animation);
  50374. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50375. };
  50376. /**
  50377. * Transition property of the Camera to the target Value
  50378. * @param property The property to transition
  50379. * @param targetValue The target Value of the property
  50380. * @param host The object where the property to animate belongs
  50381. * @param scene Scene used to run the animation
  50382. * @param frameRate Framerate (in frame/s) to use
  50383. * @param transition The transition type we want to use
  50384. * @param duration The duration of the animation, in milliseconds
  50385. * @param onAnimationEnd Callback trigger at the end of the animation
  50386. * @returns Nullable animation
  50387. */
  50388. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50389. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50390. if (duration <= 0) {
  50391. host[property] = targetValue;
  50392. if (onAnimationEnd) {
  50393. onAnimationEnd();
  50394. }
  50395. return null;
  50396. }
  50397. var endFrame = frameRate * (duration / 1000);
  50398. transition.setKeys([{
  50399. frame: 0,
  50400. value: host[property].clone ? host[property].clone() : host[property]
  50401. },
  50402. {
  50403. frame: endFrame,
  50404. value: targetValue
  50405. }]);
  50406. if (!host.animations) {
  50407. host.animations = [];
  50408. }
  50409. host.animations.push(transition);
  50410. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50411. animation.onAnimationEnd = onAnimationEnd;
  50412. return animation;
  50413. };
  50414. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50415. /**
  50416. * Return the array of runtime animations currently using this animation
  50417. */
  50418. get: function () {
  50419. return this._runtimeAnimations;
  50420. },
  50421. enumerable: true,
  50422. configurable: true
  50423. });
  50424. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50425. /**
  50426. * Specifies if any of the runtime animations are currently running
  50427. */
  50428. get: function () {
  50429. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50430. var runtimeAnimation = _a[_i];
  50431. if (!runtimeAnimation.isStopped) {
  50432. return true;
  50433. }
  50434. }
  50435. return false;
  50436. },
  50437. enumerable: true,
  50438. configurable: true
  50439. });
  50440. // Methods
  50441. /**
  50442. * Converts the animation to a string
  50443. * @param fullDetails support for multiple levels of logging within scene loading
  50444. * @returns String form of the animation
  50445. */
  50446. Animation.prototype.toString = function (fullDetails) {
  50447. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50448. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50449. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50450. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50451. if (fullDetails) {
  50452. ret += ", Ranges: {";
  50453. var first = true;
  50454. for (var name in this._ranges) {
  50455. if (first) {
  50456. ret += ", ";
  50457. first = false;
  50458. }
  50459. ret += name;
  50460. }
  50461. ret += "}";
  50462. }
  50463. return ret;
  50464. };
  50465. /**
  50466. * Add an event to this animation
  50467. * @param event Event to add
  50468. */
  50469. Animation.prototype.addEvent = function (event) {
  50470. this._events.push(event);
  50471. };
  50472. /**
  50473. * Remove all events found at the given frame
  50474. * @param frame The frame to remove events from
  50475. */
  50476. Animation.prototype.removeEvents = function (frame) {
  50477. for (var index = 0; index < this._events.length; index++) {
  50478. if (this._events[index].frame === frame) {
  50479. this._events.splice(index, 1);
  50480. index--;
  50481. }
  50482. }
  50483. };
  50484. /**
  50485. * Retrieves all the events from the animation
  50486. * @returns Events from the animation
  50487. */
  50488. Animation.prototype.getEvents = function () {
  50489. return this._events;
  50490. };
  50491. /**
  50492. * Creates an animation range
  50493. * @param name Name of the animation range
  50494. * @param from Starting frame of the animation range
  50495. * @param to Ending frame of the animation
  50496. */
  50497. Animation.prototype.createRange = function (name, from, to) {
  50498. // check name not already in use; could happen for bones after serialized
  50499. if (!this._ranges[name]) {
  50500. this._ranges[name] = new AnimationRange(name, from, to);
  50501. }
  50502. };
  50503. /**
  50504. * Deletes an animation range by name
  50505. * @param name Name of the animation range to delete
  50506. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50507. */
  50508. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50509. if (deleteFrames === void 0) { deleteFrames = true; }
  50510. var range = this._ranges[name];
  50511. if (!range) {
  50512. return;
  50513. }
  50514. if (deleteFrames) {
  50515. var from = range.from;
  50516. var to = range.to;
  50517. // this loop MUST go high to low for multiple splices to work
  50518. for (var key = this._keys.length - 1; key >= 0; key--) {
  50519. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50520. this._keys.splice(key, 1);
  50521. }
  50522. }
  50523. }
  50524. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50525. };
  50526. /**
  50527. * Gets the animation range by name, or null if not defined
  50528. * @param name Name of the animation range
  50529. * @returns Nullable animation range
  50530. */
  50531. Animation.prototype.getRange = function (name) {
  50532. return this._ranges[name];
  50533. };
  50534. /**
  50535. * Gets the key frames from the animation
  50536. * @returns The key frames of the animation
  50537. */
  50538. Animation.prototype.getKeys = function () {
  50539. return this._keys;
  50540. };
  50541. /**
  50542. * Gets the highest frame rate of the animation
  50543. * @returns Highest frame rate of the animation
  50544. */
  50545. Animation.prototype.getHighestFrame = function () {
  50546. var ret = 0;
  50547. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50548. if (ret < this._keys[key].frame) {
  50549. ret = this._keys[key].frame;
  50550. }
  50551. }
  50552. return ret;
  50553. };
  50554. /**
  50555. * Gets the easing function of the animation
  50556. * @returns Easing function of the animation
  50557. */
  50558. Animation.prototype.getEasingFunction = function () {
  50559. return this._easingFunction;
  50560. };
  50561. /**
  50562. * Sets the easing function of the animation
  50563. * @param easingFunction A custom mathematical formula for animation
  50564. */
  50565. Animation.prototype.setEasingFunction = function (easingFunction) {
  50566. this._easingFunction = easingFunction;
  50567. };
  50568. /**
  50569. * Interpolates a scalar linearly
  50570. * @param startValue Start value of the animation curve
  50571. * @param endValue End value of the animation curve
  50572. * @param gradient Scalar amount to interpolate
  50573. * @returns Interpolated scalar value
  50574. */
  50575. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50576. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50577. };
  50578. /**
  50579. * Interpolates a scalar cubically
  50580. * @param startValue Start value of the animation curve
  50581. * @param outTangent End tangent of the animation
  50582. * @param endValue End value of the animation curve
  50583. * @param inTangent Start tangent of the animation curve
  50584. * @param gradient Scalar amount to interpolate
  50585. * @returns Interpolated scalar value
  50586. */
  50587. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50588. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50589. };
  50590. /**
  50591. * Interpolates a quaternion using a spherical linear interpolation
  50592. * @param startValue Start value of the animation curve
  50593. * @param endValue End value of the animation curve
  50594. * @param gradient Scalar amount to interpolate
  50595. * @returns Interpolated quaternion value
  50596. */
  50597. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50598. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50599. };
  50600. /**
  50601. * Interpolates a quaternion cubically
  50602. * @param startValue Start value of the animation curve
  50603. * @param outTangent End tangent of the animation curve
  50604. * @param endValue End value of the animation curve
  50605. * @param inTangent Start tangent of the animation curve
  50606. * @param gradient Scalar amount to interpolate
  50607. * @returns Interpolated quaternion value
  50608. */
  50609. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50610. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50611. };
  50612. /**
  50613. * Interpolates a Vector3 linearl
  50614. * @param startValue Start value of the animation curve
  50615. * @param endValue End value of the animation curve
  50616. * @param gradient Scalar amount to interpolate
  50617. * @returns Interpolated scalar value
  50618. */
  50619. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50620. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50621. };
  50622. /**
  50623. * Interpolates a Vector3 cubically
  50624. * @param startValue Start value of the animation curve
  50625. * @param outTangent End tangent of the animation
  50626. * @param endValue End value of the animation curve
  50627. * @param inTangent Start tangent of the animation curve
  50628. * @param gradient Scalar amount to interpolate
  50629. * @returns InterpolatedVector3 value
  50630. */
  50631. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50632. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50633. };
  50634. /**
  50635. * Interpolates a Vector2 linearly
  50636. * @param startValue Start value of the animation curve
  50637. * @param endValue End value of the animation curve
  50638. * @param gradient Scalar amount to interpolate
  50639. * @returns Interpolated Vector2 value
  50640. */
  50641. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50642. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50643. };
  50644. /**
  50645. * Interpolates a Vector2 cubically
  50646. * @param startValue Start value of the animation curve
  50647. * @param outTangent End tangent of the animation
  50648. * @param endValue End value of the animation curve
  50649. * @param inTangent Start tangent of the animation curve
  50650. * @param gradient Scalar amount to interpolate
  50651. * @returns Interpolated Vector2 value
  50652. */
  50653. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50654. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50655. };
  50656. /**
  50657. * Interpolates a size linearly
  50658. * @param startValue Start value of the animation curve
  50659. * @param endValue End value of the animation curve
  50660. * @param gradient Scalar amount to interpolate
  50661. * @returns Interpolated Size value
  50662. */
  50663. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50664. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50665. };
  50666. /**
  50667. * Interpolates a Color3 linearly
  50668. * @param startValue Start value of the animation curve
  50669. * @param endValue End value of the animation curve
  50670. * @param gradient Scalar amount to interpolate
  50671. * @returns Interpolated Color3 value
  50672. */
  50673. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50674. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50675. };
  50676. /**
  50677. * @hidden Internal use only
  50678. */
  50679. Animation.prototype._getKeyValue = function (value) {
  50680. if (typeof value === "function") {
  50681. return value();
  50682. }
  50683. return value;
  50684. };
  50685. /**
  50686. * @hidden Internal use only
  50687. */
  50688. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50689. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50690. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50691. }
  50692. var keys = this.getKeys();
  50693. // Try to get a hash to find the right key
  50694. 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));
  50695. if (keys[startKeyIndex].frame >= currentFrame) {
  50696. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50697. startKeyIndex--;
  50698. }
  50699. }
  50700. for (var key = startKeyIndex; key < keys.length; key++) {
  50701. var endKey = keys[key + 1];
  50702. if (endKey.frame >= currentFrame) {
  50703. var startKey = keys[key];
  50704. var startValue = this._getKeyValue(startKey.value);
  50705. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50706. return startValue;
  50707. }
  50708. var endValue = this._getKeyValue(endKey.value);
  50709. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50710. var frameDelta = endKey.frame - startKey.frame;
  50711. // gradient : percent of currentFrame between the frame inf and the frame sup
  50712. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50713. // check for easingFunction and correction of gradient
  50714. var easingFunction = this.getEasingFunction();
  50715. if (easingFunction != null) {
  50716. gradient = easingFunction.ease(gradient);
  50717. }
  50718. switch (this.dataType) {
  50719. // Float
  50720. case Animation.ANIMATIONTYPE_FLOAT:
  50721. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50722. switch (loopMode) {
  50723. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50724. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50725. return floatValue;
  50726. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50727. return offsetValue * repeatCount + floatValue;
  50728. }
  50729. break;
  50730. // Quaternion
  50731. case Animation.ANIMATIONTYPE_QUATERNION:
  50732. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50733. switch (loopMode) {
  50734. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50735. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50736. return quatValue;
  50737. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50738. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50739. }
  50740. return quatValue;
  50741. // Vector3
  50742. case Animation.ANIMATIONTYPE_VECTOR3:
  50743. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50744. switch (loopMode) {
  50745. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50746. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50747. return vec3Value;
  50748. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50749. return vec3Value.add(offsetValue.scale(repeatCount));
  50750. }
  50751. // Vector2
  50752. case Animation.ANIMATIONTYPE_VECTOR2:
  50753. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50754. switch (loopMode) {
  50755. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50756. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50757. return vec2Value;
  50758. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50759. return vec2Value.add(offsetValue.scale(repeatCount));
  50760. }
  50761. // Size
  50762. case Animation.ANIMATIONTYPE_SIZE:
  50763. switch (loopMode) {
  50764. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50765. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50766. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50767. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50768. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50769. }
  50770. // Color3
  50771. case Animation.ANIMATIONTYPE_COLOR3:
  50772. switch (loopMode) {
  50773. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50774. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50775. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50776. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50777. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50778. }
  50779. // Matrix
  50780. case Animation.ANIMATIONTYPE_MATRIX:
  50781. switch (loopMode) {
  50782. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50783. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50784. if (Animation.AllowMatricesInterpolation) {
  50785. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50786. }
  50787. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50788. return startValue;
  50789. }
  50790. default:
  50791. break;
  50792. }
  50793. break;
  50794. }
  50795. }
  50796. return this._getKeyValue(keys[keys.length - 1].value);
  50797. };
  50798. /**
  50799. * Defines the function to use to interpolate matrices
  50800. * @param startValue defines the start matrix
  50801. * @param endValue defines the end matrix
  50802. * @param gradient defines the gradient between both matrices
  50803. * @param result defines an optional target matrix where to store the interpolation
  50804. * @returns the interpolated matrix
  50805. */
  50806. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50807. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50808. if (result) {
  50809. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50810. return result;
  50811. }
  50812. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50813. }
  50814. if (result) {
  50815. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50816. return result;
  50817. }
  50818. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50819. };
  50820. /**
  50821. * Makes a copy of the animation
  50822. * @returns Cloned animation
  50823. */
  50824. Animation.prototype.clone = function () {
  50825. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50826. clone.enableBlending = this.enableBlending;
  50827. clone.blendingSpeed = this.blendingSpeed;
  50828. if (this._keys) {
  50829. clone.setKeys(this._keys);
  50830. }
  50831. if (this._ranges) {
  50832. clone._ranges = {};
  50833. for (var name in this._ranges) {
  50834. var range = this._ranges[name];
  50835. if (!range) {
  50836. continue;
  50837. }
  50838. clone._ranges[name] = range.clone();
  50839. }
  50840. }
  50841. return clone;
  50842. };
  50843. /**
  50844. * Sets the key frames of the animation
  50845. * @param values The animation key frames to set
  50846. */
  50847. Animation.prototype.setKeys = function (values) {
  50848. this._keys = values.slice(0);
  50849. };
  50850. /**
  50851. * Serializes the animation to an object
  50852. * @returns Serialized object
  50853. */
  50854. Animation.prototype.serialize = function () {
  50855. var serializationObject = {};
  50856. serializationObject.name = this.name;
  50857. serializationObject.property = this.targetProperty;
  50858. serializationObject.framePerSecond = this.framePerSecond;
  50859. serializationObject.dataType = this.dataType;
  50860. serializationObject.loopBehavior = this.loopMode;
  50861. serializationObject.enableBlending = this.enableBlending;
  50862. serializationObject.blendingSpeed = this.blendingSpeed;
  50863. var dataType = this.dataType;
  50864. serializationObject.keys = [];
  50865. var keys = this.getKeys();
  50866. for (var index = 0; index < keys.length; index++) {
  50867. var animationKey = keys[index];
  50868. var key = {};
  50869. key.frame = animationKey.frame;
  50870. switch (dataType) {
  50871. case Animation.ANIMATIONTYPE_FLOAT:
  50872. key.values = [animationKey.value];
  50873. break;
  50874. case Animation.ANIMATIONTYPE_QUATERNION:
  50875. case Animation.ANIMATIONTYPE_MATRIX:
  50876. case Animation.ANIMATIONTYPE_VECTOR3:
  50877. case Animation.ANIMATIONTYPE_COLOR3:
  50878. key.values = animationKey.value.asArray();
  50879. break;
  50880. }
  50881. serializationObject.keys.push(key);
  50882. }
  50883. serializationObject.ranges = [];
  50884. for (var name in this._ranges) {
  50885. var source = this._ranges[name];
  50886. if (!source) {
  50887. continue;
  50888. }
  50889. var range = {};
  50890. range.name = name;
  50891. range.from = source.from;
  50892. range.to = source.to;
  50893. serializationObject.ranges.push(range);
  50894. }
  50895. return serializationObject;
  50896. };
  50897. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50898. /**
  50899. * Get the float animation type
  50900. */
  50901. get: function () {
  50902. return Animation._ANIMATIONTYPE_FLOAT;
  50903. },
  50904. enumerable: true,
  50905. configurable: true
  50906. });
  50907. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50908. /**
  50909. * Get the Vector3 animation type
  50910. */
  50911. get: function () {
  50912. return Animation._ANIMATIONTYPE_VECTOR3;
  50913. },
  50914. enumerable: true,
  50915. configurable: true
  50916. });
  50917. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50918. /**
  50919. * Get the Vectpr2 animation type
  50920. */
  50921. get: function () {
  50922. return Animation._ANIMATIONTYPE_VECTOR2;
  50923. },
  50924. enumerable: true,
  50925. configurable: true
  50926. });
  50927. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50928. /**
  50929. * Get the Size animation type
  50930. */
  50931. get: function () {
  50932. return Animation._ANIMATIONTYPE_SIZE;
  50933. },
  50934. enumerable: true,
  50935. configurable: true
  50936. });
  50937. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50938. /**
  50939. * Get the Quaternion animation type
  50940. */
  50941. get: function () {
  50942. return Animation._ANIMATIONTYPE_QUATERNION;
  50943. },
  50944. enumerable: true,
  50945. configurable: true
  50946. });
  50947. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50948. /**
  50949. * Get the Matrix animation type
  50950. */
  50951. get: function () {
  50952. return Animation._ANIMATIONTYPE_MATRIX;
  50953. },
  50954. enumerable: true,
  50955. configurable: true
  50956. });
  50957. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50958. /**
  50959. * Get the Color3 animation type
  50960. */
  50961. get: function () {
  50962. return Animation._ANIMATIONTYPE_COLOR3;
  50963. },
  50964. enumerable: true,
  50965. configurable: true
  50966. });
  50967. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50968. /**
  50969. * Get the Relative Loop Mode
  50970. */
  50971. get: function () {
  50972. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50973. },
  50974. enumerable: true,
  50975. configurable: true
  50976. });
  50977. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50978. /**
  50979. * Get the Cycle Loop Mode
  50980. */
  50981. get: function () {
  50982. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50983. },
  50984. enumerable: true,
  50985. configurable: true
  50986. });
  50987. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50988. /**
  50989. * Get the Constant Loop Mode
  50990. */
  50991. get: function () {
  50992. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50993. },
  50994. enumerable: true,
  50995. configurable: true
  50996. });
  50997. /**
  50998. * Parses an animation object and creates an animation
  50999. * @param parsedAnimation Parsed animation object
  51000. * @returns Animation object
  51001. */
  51002. Animation.Parse = function (parsedAnimation) {
  51003. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51004. var dataType = parsedAnimation.dataType;
  51005. var keys = [];
  51006. var data;
  51007. var index;
  51008. if (parsedAnimation.enableBlending) {
  51009. animation.enableBlending = parsedAnimation.enableBlending;
  51010. }
  51011. if (parsedAnimation.blendingSpeed) {
  51012. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51013. }
  51014. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51015. var key = parsedAnimation.keys[index];
  51016. var inTangent;
  51017. var outTangent;
  51018. switch (dataType) {
  51019. case Animation.ANIMATIONTYPE_FLOAT:
  51020. data = key.values[0];
  51021. if (key.values.length >= 1) {
  51022. inTangent = key.values[1];
  51023. }
  51024. if (key.values.length >= 2) {
  51025. outTangent = key.values[2];
  51026. }
  51027. break;
  51028. case Animation.ANIMATIONTYPE_QUATERNION:
  51029. data = BABYLON.Quaternion.FromArray(key.values);
  51030. if (key.values.length >= 8) {
  51031. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51032. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51033. inTangent = _inTangent;
  51034. }
  51035. }
  51036. if (key.values.length >= 12) {
  51037. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51038. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51039. outTangent = _outTangent;
  51040. }
  51041. }
  51042. break;
  51043. case Animation.ANIMATIONTYPE_MATRIX:
  51044. data = BABYLON.Matrix.FromArray(key.values);
  51045. break;
  51046. case Animation.ANIMATIONTYPE_COLOR3:
  51047. data = BABYLON.Color3.FromArray(key.values);
  51048. break;
  51049. case Animation.ANIMATIONTYPE_VECTOR3:
  51050. default:
  51051. data = BABYLON.Vector3.FromArray(key.values);
  51052. break;
  51053. }
  51054. var keyData = {};
  51055. keyData.frame = key.frame;
  51056. keyData.value = data;
  51057. if (inTangent != undefined) {
  51058. keyData.inTangent = inTangent;
  51059. }
  51060. if (outTangent != undefined) {
  51061. keyData.outTangent = outTangent;
  51062. }
  51063. keys.push(keyData);
  51064. }
  51065. animation.setKeys(keys);
  51066. if (parsedAnimation.ranges) {
  51067. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51068. data = parsedAnimation.ranges[index];
  51069. animation.createRange(data.name, data.from, data.to);
  51070. }
  51071. }
  51072. return animation;
  51073. };
  51074. /**
  51075. * Appends the serialized animations from the source animations
  51076. * @param source Source containing the animations
  51077. * @param destination Target to store the animations
  51078. */
  51079. Animation.AppendSerializedAnimations = function (source, destination) {
  51080. if (source.animations) {
  51081. destination.animations = [];
  51082. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51083. var animation = source.animations[animationIndex];
  51084. destination.animations.push(animation.serialize());
  51085. }
  51086. }
  51087. };
  51088. /**
  51089. * Use matrix interpolation instead of using direct key value when animating matrices
  51090. */
  51091. Animation.AllowMatricesInterpolation = false;
  51092. /**
  51093. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51094. */
  51095. Animation.AllowMatrixDecomposeForInterpolation = true;
  51096. // Statics
  51097. /**
  51098. * Float animation type
  51099. */
  51100. Animation._ANIMATIONTYPE_FLOAT = 0;
  51101. /**
  51102. * Vector3 animation type
  51103. */
  51104. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51105. /**
  51106. * Quaternion animation type
  51107. */
  51108. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51109. /**
  51110. * Matrix animation type
  51111. */
  51112. Animation._ANIMATIONTYPE_MATRIX = 3;
  51113. /**
  51114. * Color3 animation type
  51115. */
  51116. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51117. /**
  51118. * Vector2 animation type
  51119. */
  51120. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51121. /**
  51122. * Size animation type
  51123. */
  51124. Animation._ANIMATIONTYPE_SIZE = 6;
  51125. /**
  51126. * Relative Loop Mode
  51127. */
  51128. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51129. /**
  51130. * Cycle Loop Mode
  51131. */
  51132. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51133. /**
  51134. * Constant Loop Mode
  51135. */
  51136. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51137. return Animation;
  51138. }());
  51139. BABYLON.Animation = Animation;
  51140. })(BABYLON || (BABYLON = {}));
  51141. //# sourceMappingURL=babylon.animation.js.map
  51142. var BABYLON;
  51143. (function (BABYLON) {
  51144. /**
  51145. * This class defines the direct association between an animation and a target
  51146. */
  51147. var TargetedAnimation = /** @class */ (function () {
  51148. function TargetedAnimation() {
  51149. }
  51150. return TargetedAnimation;
  51151. }());
  51152. BABYLON.TargetedAnimation = TargetedAnimation;
  51153. /**
  51154. * Use this class to create coordinated animations on multiple targets
  51155. */
  51156. var AnimationGroup = /** @class */ (function () {
  51157. function AnimationGroup(name, scene) {
  51158. if (scene === void 0) { scene = null; }
  51159. this.name = name;
  51160. this._targetedAnimations = new Array();
  51161. this._animatables = new Array();
  51162. this._from = Number.MAX_VALUE;
  51163. this._to = -Number.MAX_VALUE;
  51164. this._speedRatio = 1;
  51165. this.onAnimationEndObservable = new BABYLON.Observable();
  51166. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51167. this._scene.animationGroups.push(this);
  51168. }
  51169. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51170. /**
  51171. * Define if the animations are started
  51172. */
  51173. get: function () {
  51174. return this._isStarted;
  51175. },
  51176. enumerable: true,
  51177. configurable: true
  51178. });
  51179. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51180. /**
  51181. * Gets or sets the speed ratio to use for all animations
  51182. */
  51183. get: function () {
  51184. return this._speedRatio;
  51185. },
  51186. /**
  51187. * Gets or sets the speed ratio to use for all animations
  51188. */
  51189. set: function (value) {
  51190. if (this._speedRatio === value) {
  51191. return;
  51192. }
  51193. this._speedRatio = value;
  51194. for (var index = 0; index < this._animatables.length; index++) {
  51195. var animatable = this._animatables[index];
  51196. animatable.speedRatio = this._speedRatio;
  51197. }
  51198. },
  51199. enumerable: true,
  51200. configurable: true
  51201. });
  51202. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51203. /**
  51204. * Gets the targeted animations for this animation group
  51205. */
  51206. get: function () {
  51207. return this._targetedAnimations;
  51208. },
  51209. enumerable: true,
  51210. configurable: true
  51211. });
  51212. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51213. /**
  51214. * returning the list of animatables controlled by this animation group.
  51215. */
  51216. get: function () {
  51217. return this._animatables;
  51218. },
  51219. enumerable: true,
  51220. configurable: true
  51221. });
  51222. /**
  51223. * Add an animation (with its target) in the group
  51224. * @param animation defines the animation we want to add
  51225. * @param target defines the target of the animation
  51226. * @returns the {BABYLON.TargetedAnimation} object
  51227. */
  51228. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51229. var targetedAnimation = {
  51230. animation: animation,
  51231. target: target
  51232. };
  51233. var keys = animation.getKeys();
  51234. if (this._from > keys[0].frame) {
  51235. this._from = keys[0].frame;
  51236. }
  51237. if (this._to < keys[keys.length - 1].frame) {
  51238. this._to = keys[keys.length - 1].frame;
  51239. }
  51240. this._targetedAnimations.push(targetedAnimation);
  51241. return targetedAnimation;
  51242. };
  51243. /**
  51244. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51245. * It can add constant keys at begin or end
  51246. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  51247. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  51248. */
  51249. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51250. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  51251. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  51252. beginFrame = Math.max(beginFrame, this._from);
  51253. endFrame = Math.min(endFrame, this._to);
  51254. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51255. var targetedAnimation = this._targetedAnimations[index];
  51256. var keys = targetedAnimation.animation.getKeys();
  51257. var startKey = keys[0];
  51258. var endKey = keys[keys.length - 1];
  51259. if (startKey.frame > beginFrame) {
  51260. var newKey = {
  51261. frame: beginFrame,
  51262. value: startKey.value,
  51263. inTangent: startKey.inTangent,
  51264. outTangent: startKey.outTangent,
  51265. interpolation: startKey.interpolation
  51266. };
  51267. keys.splice(0, 0, newKey);
  51268. }
  51269. if (endKey.frame < endFrame) {
  51270. var newKey = {
  51271. frame: endFrame,
  51272. value: endKey.value,
  51273. inTangent: endKey.outTangent,
  51274. outTangent: endKey.outTangent,
  51275. interpolation: endKey.interpolation
  51276. };
  51277. keys.push(newKey);
  51278. }
  51279. }
  51280. return this;
  51281. };
  51282. /**
  51283. * Start all animations on given targets
  51284. * @param loop defines if animations must loop
  51285. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51286. * @param from defines the from key (optional)
  51287. * @param to defines the to key (optional)
  51288. * @returns the current animation group
  51289. */
  51290. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51291. var _this = this;
  51292. if (loop === void 0) { loop = false; }
  51293. if (speedRatio === void 0) { speedRatio = 1; }
  51294. if (this._isStarted || this._targetedAnimations.length === 0) {
  51295. return this;
  51296. }
  51297. var _loop_1 = function (targetedAnimation) {
  51298. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  51299. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51300. }));
  51301. };
  51302. var this_1 = this;
  51303. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51304. var targetedAnimation = _a[_i];
  51305. _loop_1(targetedAnimation);
  51306. }
  51307. this._speedRatio = speedRatio;
  51308. this._isStarted = true;
  51309. return this;
  51310. };
  51311. /**
  51312. * Pause all animations
  51313. */
  51314. AnimationGroup.prototype.pause = function () {
  51315. if (!this._isStarted) {
  51316. return this;
  51317. }
  51318. for (var index = 0; index < this._animatables.length; index++) {
  51319. var animatable = this._animatables[index];
  51320. animatable.pause();
  51321. }
  51322. return this;
  51323. };
  51324. /**
  51325. * Play all animations to initial state
  51326. * This function will start() the animations if they were not started or will restart() them if they were paused
  51327. * @param loop defines if animations must loop
  51328. */
  51329. AnimationGroup.prototype.play = function (loop) {
  51330. if (this.isStarted) {
  51331. if (loop !== undefined) {
  51332. for (var index = 0; index < this._animatables.length; index++) {
  51333. var animatable = this._animatables[index];
  51334. animatable.loopAnimation = loop;
  51335. }
  51336. }
  51337. this.restart();
  51338. }
  51339. else {
  51340. this.start(loop, this._speedRatio);
  51341. }
  51342. return this;
  51343. };
  51344. /**
  51345. * Reset all animations to initial state
  51346. */
  51347. AnimationGroup.prototype.reset = function () {
  51348. if (!this._isStarted) {
  51349. return this;
  51350. }
  51351. for (var index = 0; index < this._animatables.length; index++) {
  51352. var animatable = this._animatables[index];
  51353. animatable.reset();
  51354. }
  51355. return this;
  51356. };
  51357. /**
  51358. * Restart animations from key 0
  51359. */
  51360. AnimationGroup.prototype.restart = function () {
  51361. if (!this._isStarted) {
  51362. return this;
  51363. }
  51364. for (var index = 0; index < this._animatables.length; index++) {
  51365. var animatable = this._animatables[index];
  51366. animatable.restart();
  51367. }
  51368. return this;
  51369. };
  51370. /**
  51371. * Stop all animations
  51372. */
  51373. AnimationGroup.prototype.stop = function () {
  51374. if (!this._isStarted) {
  51375. return this;
  51376. }
  51377. for (var index = 0; index < this._animatables.length; index++) {
  51378. var animatable = this._animatables[index];
  51379. animatable.stop();
  51380. }
  51381. this._isStarted = false;
  51382. return this;
  51383. };
  51384. /**
  51385. * Set animation weight for all animatables
  51386. * @param weight defines the weight to use
  51387. * @return the animationGroup
  51388. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51389. */
  51390. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51391. for (var index = 0; index < this._animatables.length; index++) {
  51392. var animatable = this._animatables[index];
  51393. animatable.weight = weight;
  51394. }
  51395. return this;
  51396. };
  51397. /**
  51398. * Synchronize and normalize all animatables with a source animatable
  51399. * @param root defines the root animatable to synchronize with
  51400. * @return the animationGroup
  51401. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51402. */
  51403. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51404. for (var index = 0; index < this._animatables.length; index++) {
  51405. var animatable = this._animatables[index];
  51406. animatable.syncWith(root);
  51407. }
  51408. return this;
  51409. };
  51410. /**
  51411. * Goes to a specific frame in this animation group
  51412. * @param frame the frame number to go to
  51413. * @return the animationGroup
  51414. */
  51415. AnimationGroup.prototype.goToFrame = function (frame) {
  51416. if (!this._isStarted) {
  51417. return this;
  51418. }
  51419. for (var index = 0; index < this._animatables.length; index++) {
  51420. var animatable = this._animatables[index];
  51421. animatable.goToFrame(frame);
  51422. }
  51423. return this;
  51424. };
  51425. /**
  51426. * Dispose all associated resources
  51427. */
  51428. AnimationGroup.prototype.dispose = function () {
  51429. this._targetedAnimations = [];
  51430. this._animatables = [];
  51431. var index = this._scene.animationGroups.indexOf(this);
  51432. if (index > -1) {
  51433. this._scene.animationGroups.splice(index, 1);
  51434. }
  51435. };
  51436. return AnimationGroup;
  51437. }());
  51438. BABYLON.AnimationGroup = AnimationGroup;
  51439. })(BABYLON || (BABYLON = {}));
  51440. //# sourceMappingURL=babylon.animationGroup.js.map
  51441. var BABYLON;
  51442. (function (BABYLON) {
  51443. /**
  51444. * Defines a runtime animation
  51445. */
  51446. var RuntimeAnimation = /** @class */ (function () {
  51447. /**
  51448. * Create a new RuntimeAnimation object
  51449. * @param target defines the target of the animation
  51450. * @param animation defines the source animation object
  51451. * @param scene defines the hosting scene
  51452. * @param host defines the initiating Animatable
  51453. */
  51454. function RuntimeAnimation(target, animation, scene, host) {
  51455. /**
  51456. * The current frame of the runtime animation
  51457. */
  51458. this._currentFrame = 0;
  51459. /**
  51460. * The offsets cache of the runtime animation
  51461. */
  51462. this._offsetsCache = {};
  51463. /**
  51464. * The high limits cache of the runtime animation
  51465. */
  51466. this._highLimitsCache = {};
  51467. /**
  51468. * Specifies if the runtime animation has been stopped
  51469. */
  51470. this._stopped = false;
  51471. /**
  51472. * The blending factor of the runtime animation
  51473. */
  51474. this._blendingFactor = 0;
  51475. /**
  51476. * The target path of the runtime animation
  51477. */
  51478. this._targetPath = "";
  51479. /**
  51480. * The weight of the runtime animation
  51481. */
  51482. this._weight = 1.0;
  51483. /**
  51484. * The ratio offset of the runtime animation
  51485. */
  51486. this._ratioOffset = 0;
  51487. /**
  51488. * The previous delay of the runtime animation
  51489. */
  51490. this._previousDelay = 0;
  51491. /**
  51492. * The previous ratio of the runtime animation
  51493. */
  51494. this._previousRatio = 0;
  51495. this._animation = animation;
  51496. this._target = target;
  51497. this._scene = scene;
  51498. this._host = host;
  51499. animation._runtimeAnimations.push(this);
  51500. }
  51501. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51502. /**
  51503. * Gets the current frame of the runtime animation
  51504. */
  51505. get: function () {
  51506. return this._currentFrame;
  51507. },
  51508. enumerable: true,
  51509. configurable: true
  51510. });
  51511. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51512. /**
  51513. * Gets the weight of the runtime animation
  51514. */
  51515. get: function () {
  51516. return this._weight;
  51517. },
  51518. enumerable: true,
  51519. configurable: true
  51520. });
  51521. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  51522. /**
  51523. * Gets the original value of the runtime animation
  51524. */
  51525. get: function () {
  51526. return this._originalValue;
  51527. },
  51528. enumerable: true,
  51529. configurable: true
  51530. });
  51531. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51532. /**
  51533. * Gets the current value of the runtime animation
  51534. */
  51535. get: function () {
  51536. return this._currentValue;
  51537. },
  51538. enumerable: true,
  51539. configurable: true
  51540. });
  51541. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51542. /**
  51543. * Gets the target path of the runtime animation
  51544. */
  51545. get: function () {
  51546. return this._targetPath;
  51547. },
  51548. enumerable: true,
  51549. configurable: true
  51550. });
  51551. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51552. /**
  51553. * Gets the actual target of the runtime animation
  51554. */
  51555. get: function () {
  51556. return this._activeTarget;
  51557. },
  51558. enumerable: true,
  51559. configurable: true
  51560. });
  51561. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51562. /**
  51563. * Gets the animation from the runtime animation
  51564. */
  51565. get: function () {
  51566. return this._animation;
  51567. },
  51568. enumerable: true,
  51569. configurable: true
  51570. });
  51571. /**
  51572. * Resets the runtime animation to the beginning
  51573. */
  51574. RuntimeAnimation.prototype.reset = function () {
  51575. this._offsetsCache = {};
  51576. this._highLimitsCache = {};
  51577. this._currentFrame = 0;
  51578. this._blendingFactor = 0;
  51579. this._originalValue = null;
  51580. };
  51581. /**
  51582. * Specifies if the runtime animation is stopped
  51583. * @returns Boolean specifying if the runtime animation is stopped
  51584. */
  51585. RuntimeAnimation.prototype.isStopped = function () {
  51586. return this._stopped;
  51587. };
  51588. /**
  51589. * Disposes of the runtime animation
  51590. */
  51591. RuntimeAnimation.prototype.dispose = function () {
  51592. var index = this._animation.runtimeAnimations.indexOf(this);
  51593. if (index > -1) {
  51594. this._animation.runtimeAnimations.splice(index, 1);
  51595. }
  51596. };
  51597. /**
  51598. * Interpolates the animation from the current frame
  51599. * @param currentFrame The frame to interpolate the animation to
  51600. * @param repeatCount The number of times that the animation should loop
  51601. * @param loopMode The type of looping mode to use
  51602. * @param offsetValue Animation offset value
  51603. * @param highLimitValue The high limit value
  51604. * @returns The interpolated value
  51605. */
  51606. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51607. this._currentFrame = currentFrame;
  51608. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51609. this._workValue = BABYLON.Matrix.Zero();
  51610. }
  51611. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51612. };
  51613. /**
  51614. * Affect the interpolated value to the target
  51615. * @param currentValue defines the value computed by the animation
  51616. * @param weight defines the weight to apply to this value
  51617. */
  51618. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51619. if (weight === void 0) { weight = 1.0; }
  51620. if (this._target instanceof Array) {
  51621. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51622. var target = _a[_i];
  51623. this._setValue(target, currentValue, weight);
  51624. }
  51625. }
  51626. else {
  51627. this._setValue(this._target, currentValue, weight);
  51628. }
  51629. };
  51630. /**
  51631. * Sets the value of the runtime animation
  51632. * @param target The target property of the runtime animation
  51633. * @param currentValue The current value to use for the runtime animation
  51634. * @param weight The weight to use for the runtime animation (Defaults to 1.0)
  51635. */
  51636. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight) {
  51637. if (weight === void 0) { weight = 1.0; }
  51638. // Set value
  51639. var path;
  51640. var destination;
  51641. var targetPropertyPath = this._animation.targetPropertyPath;
  51642. if (targetPropertyPath.length > 1) {
  51643. var property = target[targetPropertyPath[0]];
  51644. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51645. property = property[targetPropertyPath[index]];
  51646. }
  51647. path = targetPropertyPath[targetPropertyPath.length - 1];
  51648. destination = property;
  51649. }
  51650. else {
  51651. path = targetPropertyPath[0];
  51652. destination = target;
  51653. }
  51654. this._targetPath = path;
  51655. this._activeTarget = destination;
  51656. this._weight = weight;
  51657. // Blending
  51658. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51659. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51660. if (enableBlending && this._blendingFactor <= 1.0) {
  51661. if (!this._originalBlendValue) {
  51662. var originalValue = destination[path];
  51663. if (originalValue.clone) {
  51664. this._originalBlendValue = originalValue.clone();
  51665. }
  51666. else {
  51667. this._originalBlendValue = originalValue;
  51668. }
  51669. }
  51670. }
  51671. if (weight !== -1.0) {
  51672. if (!this._originalValue) {
  51673. var originalValue = void 0;
  51674. if (destination.getRestPose && path === "_matrix") { // For bones
  51675. originalValue = destination.getRestPose();
  51676. }
  51677. else {
  51678. originalValue = destination[path];
  51679. }
  51680. if (originalValue.clone) {
  51681. this._originalValue = originalValue.clone();
  51682. }
  51683. else {
  51684. this._originalValue = originalValue;
  51685. }
  51686. }
  51687. }
  51688. if (enableBlending && this._blendingFactor <= 1.0) {
  51689. if (this._originalBlendValue.m) { // Matrix
  51690. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51691. if (this._currentValue) {
  51692. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51693. }
  51694. else {
  51695. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51696. }
  51697. }
  51698. else {
  51699. if (this._currentValue) {
  51700. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51701. }
  51702. else {
  51703. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51704. }
  51705. }
  51706. }
  51707. else {
  51708. var constructor = this._originalBlendValue.constructor;
  51709. if (constructor.Lerp) { // Lerp supported
  51710. this._currentValue = constructor.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51711. }
  51712. else if (constructor.Slerp) { // Slerp supported
  51713. this._currentValue = constructor.Slerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51714. }
  51715. else if (this._originalBlendValue.toFixed) { // Number
  51716. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  51717. }
  51718. else { // Blending not supported
  51719. this._currentValue = currentValue;
  51720. }
  51721. }
  51722. this._blendingFactor += blendingSpeed;
  51723. }
  51724. else {
  51725. this._currentValue = currentValue;
  51726. }
  51727. if (weight !== -1.0) {
  51728. this._scene._registerTargetForLateAnimationBinding(this);
  51729. }
  51730. else {
  51731. destination[path] = this._currentValue;
  51732. }
  51733. if (target.markAsDirty) {
  51734. target.markAsDirty(this._animation.targetProperty);
  51735. }
  51736. };
  51737. /**
  51738. * Gets the loop pmode of the runtime animation
  51739. * @returns Loop Mode
  51740. */
  51741. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51742. if (this._target && this._target.animationPropertiesOverride) {
  51743. return this._target.animationPropertiesOverride.loopMode;
  51744. }
  51745. return this._animation.loopMode;
  51746. };
  51747. /**
  51748. * Move the current animation to a given frame
  51749. * @param frame defines the frame to move to
  51750. */
  51751. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51752. var keys = this._animation.getKeys();
  51753. if (frame < keys[0].frame) {
  51754. frame = keys[0].frame;
  51755. }
  51756. else if (frame > keys[keys.length - 1].frame) {
  51757. frame = keys[keys.length - 1].frame;
  51758. }
  51759. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51760. this.setValue(currentValue, -1);
  51761. };
  51762. /**
  51763. * @hidden Internal use only
  51764. */
  51765. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51766. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51767. this._ratioOffset = this._previousRatio - newRatio;
  51768. };
  51769. /**
  51770. * Execute the current animation
  51771. * @param delay defines the delay to add to the current frame
  51772. * @param from defines the lower bound of the animation range
  51773. * @param to defines the upper bound of the animation range
  51774. * @param loop defines if the current animation must loop
  51775. * @param speedRatio defines the current speed ratio
  51776. * @param weight defines the weight of the animation (default is -1 so no weight)
  51777. * @returns a boolean indicating if the animation has ended
  51778. */
  51779. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51780. if (weight === void 0) { weight = -1.0; }
  51781. var targetPropertyPath = this._animation.targetPropertyPath;
  51782. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51783. this._stopped = true;
  51784. return false;
  51785. }
  51786. var returnValue = true;
  51787. var keys = this._animation.getKeys();
  51788. // Adding a start key at frame 0 if missing
  51789. if (keys[0].frame !== 0) {
  51790. var newKey = { frame: 0, value: keys[0].value };
  51791. keys.splice(0, 0, newKey);
  51792. }
  51793. // Check limits
  51794. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51795. from = keys[0].frame;
  51796. }
  51797. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51798. to = keys[keys.length - 1].frame;
  51799. }
  51800. //to and from cannot be the same key
  51801. if (from === to) {
  51802. if (from > keys[0].frame) {
  51803. from--;
  51804. }
  51805. else if (to < keys[keys.length - 1].frame) {
  51806. to++;
  51807. }
  51808. }
  51809. // Compute ratio
  51810. var range = to - from;
  51811. var offsetValue;
  51812. // ratio represents the frame delta between from and to
  51813. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51814. var highLimitValue = 0;
  51815. this._previousDelay = delay;
  51816. this._previousRatio = ratio;
  51817. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  51818. returnValue = false;
  51819. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51820. }
  51821. else {
  51822. // Get max value if required
  51823. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51824. var keyOffset = to.toString() + from.toString();
  51825. if (!this._offsetsCache[keyOffset]) {
  51826. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51827. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51828. switch (this._animation.dataType) {
  51829. // Float
  51830. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51831. this._offsetsCache[keyOffset] = toValue - fromValue;
  51832. break;
  51833. // Quaternion
  51834. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51835. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51836. break;
  51837. // Vector3
  51838. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51839. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51840. // Vector2
  51841. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51842. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51843. // Size
  51844. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51845. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51846. // Color3
  51847. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51848. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51849. default:
  51850. break;
  51851. }
  51852. this._highLimitsCache[keyOffset] = toValue;
  51853. }
  51854. highLimitValue = this._highLimitsCache[keyOffset];
  51855. offsetValue = this._offsetsCache[keyOffset];
  51856. }
  51857. }
  51858. if (offsetValue === undefined) {
  51859. switch (this._animation.dataType) {
  51860. // Float
  51861. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51862. offsetValue = 0;
  51863. break;
  51864. // Quaternion
  51865. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51866. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51867. break;
  51868. // Vector3
  51869. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51870. offsetValue = BABYLON.Vector3.Zero();
  51871. break;
  51872. // Vector2
  51873. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51874. offsetValue = BABYLON.Vector2.Zero();
  51875. break;
  51876. // Size
  51877. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51878. offsetValue = BABYLON.Size.Zero();
  51879. break;
  51880. // Color3
  51881. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51882. offsetValue = BABYLON.Color3.Black();
  51883. }
  51884. }
  51885. // Compute value
  51886. var repeatCount = (ratio / range) >> 0;
  51887. var currentFrame = returnValue ? from + ratio % range : to;
  51888. // Need to normalize?
  51889. if (this._host && this._host.syncRoot) {
  51890. var syncRoot = this._host.syncRoot;
  51891. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51892. currentFrame = from + (to - from) * hostNormalizedFrame;
  51893. }
  51894. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51895. // Set value
  51896. this.setValue(currentValue, weight);
  51897. // Check events
  51898. var events = this._animation.getEvents();
  51899. for (var index = 0; index < events.length; index++) {
  51900. // Make sure current frame has passed event frame and that event frame is within the current range
  51901. // Also, handle both forward and reverse animations
  51902. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51903. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51904. var event = events[index];
  51905. if (!event.isDone) {
  51906. // If event should be done only once, remove it.
  51907. if (event.onlyOnce) {
  51908. events.splice(index, 1);
  51909. index--;
  51910. }
  51911. event.isDone = true;
  51912. event.action();
  51913. } // Don't do anything if the event has already be done.
  51914. }
  51915. else if (events[index].isDone && !events[index].onlyOnce) {
  51916. // reset event, the animation is looping
  51917. events[index].isDone = false;
  51918. }
  51919. }
  51920. if (!returnValue) {
  51921. this._stopped = true;
  51922. }
  51923. return returnValue;
  51924. };
  51925. return RuntimeAnimation;
  51926. }());
  51927. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51928. })(BABYLON || (BABYLON = {}));
  51929. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51930. var BABYLON;
  51931. (function (BABYLON) {
  51932. var Animatable = /** @class */ (function () {
  51933. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51934. if (fromFrame === void 0) { fromFrame = 0; }
  51935. if (toFrame === void 0) { toFrame = 100; }
  51936. if (loopAnimation === void 0) { loopAnimation = false; }
  51937. if (speedRatio === void 0) { speedRatio = 1.0; }
  51938. this.target = target;
  51939. this.fromFrame = fromFrame;
  51940. this.toFrame = toFrame;
  51941. this.loopAnimation = loopAnimation;
  51942. this.onAnimationEnd = onAnimationEnd;
  51943. this._localDelayOffset = null;
  51944. this._pausedDelay = null;
  51945. this._runtimeAnimations = new Array();
  51946. this._paused = false;
  51947. this._speedRatio = 1;
  51948. this._weight = -1.0;
  51949. this.animationStarted = false;
  51950. this._scene = scene;
  51951. if (animations) {
  51952. this.appendAnimations(target, animations);
  51953. }
  51954. this._speedRatio = speedRatio;
  51955. scene._activeAnimatables.push(this);
  51956. }
  51957. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51958. /**
  51959. * Gets the root Animatable used to synchronize and normalize animations
  51960. */
  51961. get: function () {
  51962. return this._syncRoot;
  51963. },
  51964. enumerable: true,
  51965. configurable: true
  51966. });
  51967. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51968. /**
  51969. * Gets the current frame of the first RuntimeAnimation
  51970. * Used to synchronize Animatables
  51971. */
  51972. get: function () {
  51973. if (this._runtimeAnimations.length === 0) {
  51974. return 0;
  51975. }
  51976. return this._runtimeAnimations[0].currentFrame;
  51977. },
  51978. enumerable: true,
  51979. configurable: true
  51980. });
  51981. Object.defineProperty(Animatable.prototype, "weight", {
  51982. /**
  51983. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51984. */
  51985. get: function () {
  51986. return this._weight;
  51987. },
  51988. set: function (value) {
  51989. if (value === -1) { // -1 is ok and means no weight
  51990. this._weight = -1;
  51991. return;
  51992. }
  51993. // Else weight must be in [0, 1] range
  51994. this._weight = Math.min(Math.max(value, 0), 1.0);
  51995. },
  51996. enumerable: true,
  51997. configurable: true
  51998. });
  51999. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52000. /**
  52001. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52002. */
  52003. get: function () {
  52004. return this._speedRatio;
  52005. },
  52006. set: function (value) {
  52007. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52008. var animation = this._runtimeAnimations[index];
  52009. animation._prepareForSpeedRatioChange(value);
  52010. }
  52011. this._speedRatio = value;
  52012. },
  52013. enumerable: true,
  52014. configurable: true
  52015. });
  52016. // Methods
  52017. /**
  52018. * Synchronize and normalize current Animatable with a source Animatable
  52019. * This is useful when using animation weights and when animations are not of the same length
  52020. * @param root defines the root Animatable to synchronize with
  52021. * @returns the current Animatable
  52022. */
  52023. Animatable.prototype.syncWith = function (root) {
  52024. this._syncRoot = root;
  52025. if (root) {
  52026. // Make sure this animatable will animate after the root
  52027. var index = this._scene._activeAnimatables.indexOf(this);
  52028. if (index > -1) {
  52029. this._scene._activeAnimatables.splice(index, 1);
  52030. this._scene._activeAnimatables.push(this);
  52031. }
  52032. }
  52033. return this;
  52034. };
  52035. Animatable.prototype.getAnimations = function () {
  52036. return this._runtimeAnimations;
  52037. };
  52038. Animatable.prototype.appendAnimations = function (target, animations) {
  52039. for (var index = 0; index < animations.length; index++) {
  52040. var animation = animations[index];
  52041. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52042. }
  52043. };
  52044. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52045. var runtimeAnimations = this._runtimeAnimations;
  52046. for (var index = 0; index < runtimeAnimations.length; index++) {
  52047. if (runtimeAnimations[index].animation.targetProperty === property) {
  52048. return runtimeAnimations[index].animation;
  52049. }
  52050. }
  52051. return null;
  52052. };
  52053. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52054. var runtimeAnimations = this._runtimeAnimations;
  52055. for (var index = 0; index < runtimeAnimations.length; index++) {
  52056. if (runtimeAnimations[index].animation.targetProperty === property) {
  52057. return runtimeAnimations[index];
  52058. }
  52059. }
  52060. return null;
  52061. };
  52062. Animatable.prototype.reset = function () {
  52063. var runtimeAnimations = this._runtimeAnimations;
  52064. for (var index = 0; index < runtimeAnimations.length; index++) {
  52065. runtimeAnimations[index].reset();
  52066. }
  52067. // Reset to original value
  52068. for (index = 0; index < runtimeAnimations.length; index++) {
  52069. var animation = runtimeAnimations[index];
  52070. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  52071. }
  52072. this._localDelayOffset = null;
  52073. this._pausedDelay = null;
  52074. };
  52075. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52076. var runtimeAnimations = this._runtimeAnimations;
  52077. for (var index = 0; index < runtimeAnimations.length; index++) {
  52078. runtimeAnimations[index].animation.enableBlending = true;
  52079. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52080. }
  52081. };
  52082. Animatable.prototype.disableBlending = function () {
  52083. var runtimeAnimations = this._runtimeAnimations;
  52084. for (var index = 0; index < runtimeAnimations.length; index++) {
  52085. runtimeAnimations[index].animation.enableBlending = false;
  52086. }
  52087. };
  52088. Animatable.prototype.goToFrame = function (frame) {
  52089. var runtimeAnimations = this._runtimeAnimations;
  52090. if (runtimeAnimations[0]) {
  52091. var fps = runtimeAnimations[0].animation.framePerSecond;
  52092. var currentFrame = runtimeAnimations[0].currentFrame;
  52093. var adjustTime = frame - currentFrame;
  52094. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52095. if (this._localDelayOffset === null) {
  52096. this._localDelayOffset = 0;
  52097. }
  52098. this._localDelayOffset -= delay;
  52099. }
  52100. for (var index = 0; index < runtimeAnimations.length; index++) {
  52101. runtimeAnimations[index].goToFrame(frame);
  52102. }
  52103. };
  52104. Animatable.prototype.pause = function () {
  52105. if (this._paused) {
  52106. return;
  52107. }
  52108. this._paused = true;
  52109. };
  52110. Animatable.prototype.restart = function () {
  52111. this._paused = false;
  52112. };
  52113. Animatable.prototype.stop = function (animationName) {
  52114. if (animationName) {
  52115. var idx = this._scene._activeAnimatables.indexOf(this);
  52116. if (idx > -1) {
  52117. var runtimeAnimations = this._runtimeAnimations;
  52118. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52119. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52120. continue;
  52121. }
  52122. runtimeAnimations[index].dispose();
  52123. runtimeAnimations.splice(index, 1);
  52124. }
  52125. if (runtimeAnimations.length == 0) {
  52126. this._scene._activeAnimatables.splice(idx, 1);
  52127. if (this.onAnimationEnd) {
  52128. this.onAnimationEnd();
  52129. }
  52130. }
  52131. }
  52132. }
  52133. else {
  52134. var index = this._scene._activeAnimatables.indexOf(this);
  52135. if (index > -1) {
  52136. this._scene._activeAnimatables.splice(index, 1);
  52137. var runtimeAnimations = this._runtimeAnimations;
  52138. for (var index = 0; index < runtimeAnimations.length; index++) {
  52139. runtimeAnimations[index].dispose();
  52140. }
  52141. if (this.onAnimationEnd) {
  52142. this.onAnimationEnd();
  52143. }
  52144. }
  52145. }
  52146. };
  52147. Animatable.prototype._animate = function (delay) {
  52148. if (this._paused) {
  52149. this.animationStarted = false;
  52150. if (this._pausedDelay === null) {
  52151. this._pausedDelay = delay;
  52152. }
  52153. return true;
  52154. }
  52155. if (this._localDelayOffset === null) {
  52156. this._localDelayOffset = delay;
  52157. this._pausedDelay = null;
  52158. }
  52159. else if (this._pausedDelay !== null) {
  52160. this._localDelayOffset += delay - this._pausedDelay;
  52161. this._pausedDelay = null;
  52162. }
  52163. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52164. return true;
  52165. }
  52166. // Animating
  52167. var running = false;
  52168. var runtimeAnimations = this._runtimeAnimations;
  52169. var index;
  52170. for (index = 0; index < runtimeAnimations.length; index++) {
  52171. var animation = runtimeAnimations[index];
  52172. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52173. running = running || isRunning;
  52174. }
  52175. this.animationStarted = running;
  52176. if (!running) {
  52177. // Remove from active animatables
  52178. index = this._scene._activeAnimatables.indexOf(this);
  52179. this._scene._activeAnimatables.splice(index, 1);
  52180. // Dispose all runtime animations
  52181. for (index = 0; index < runtimeAnimations.length; index++) {
  52182. runtimeAnimations[index].dispose();
  52183. }
  52184. }
  52185. if (!running && this.onAnimationEnd) {
  52186. this.onAnimationEnd();
  52187. this.onAnimationEnd = null;
  52188. }
  52189. return running;
  52190. };
  52191. return Animatable;
  52192. }());
  52193. BABYLON.Animatable = Animatable;
  52194. })(BABYLON || (BABYLON = {}));
  52195. //# sourceMappingURL=babylon.animatable.js.map
  52196. var BABYLON;
  52197. (function (BABYLON) {
  52198. var EasingFunction = /** @class */ (function () {
  52199. function EasingFunction() {
  52200. // Properties
  52201. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52202. }
  52203. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52204. get: function () {
  52205. return EasingFunction._EASINGMODE_EASEIN;
  52206. },
  52207. enumerable: true,
  52208. configurable: true
  52209. });
  52210. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52211. get: function () {
  52212. return EasingFunction._EASINGMODE_EASEOUT;
  52213. },
  52214. enumerable: true,
  52215. configurable: true
  52216. });
  52217. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52218. get: function () {
  52219. return EasingFunction._EASINGMODE_EASEINOUT;
  52220. },
  52221. enumerable: true,
  52222. configurable: true
  52223. });
  52224. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52225. var n = Math.min(Math.max(easingMode, 0), 2);
  52226. this._easingMode = n;
  52227. };
  52228. EasingFunction.prototype.getEasingMode = function () {
  52229. return this._easingMode;
  52230. };
  52231. EasingFunction.prototype.easeInCore = function (gradient) {
  52232. throw new Error('You must implement this method');
  52233. };
  52234. EasingFunction.prototype.ease = function (gradient) {
  52235. switch (this._easingMode) {
  52236. case EasingFunction.EASINGMODE_EASEIN:
  52237. return this.easeInCore(gradient);
  52238. case EasingFunction.EASINGMODE_EASEOUT:
  52239. return (1 - this.easeInCore(1 - gradient));
  52240. }
  52241. if (gradient >= 0.5) {
  52242. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52243. }
  52244. return (this.easeInCore(gradient * 2) * 0.5);
  52245. };
  52246. //Statics
  52247. EasingFunction._EASINGMODE_EASEIN = 0;
  52248. EasingFunction._EASINGMODE_EASEOUT = 1;
  52249. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52250. return EasingFunction;
  52251. }());
  52252. BABYLON.EasingFunction = EasingFunction;
  52253. var CircleEase = /** @class */ (function (_super) {
  52254. __extends(CircleEase, _super);
  52255. function CircleEase() {
  52256. return _super !== null && _super.apply(this, arguments) || this;
  52257. }
  52258. CircleEase.prototype.easeInCore = function (gradient) {
  52259. gradient = Math.max(0, Math.min(1, gradient));
  52260. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52261. };
  52262. return CircleEase;
  52263. }(EasingFunction));
  52264. BABYLON.CircleEase = CircleEase;
  52265. var BackEase = /** @class */ (function (_super) {
  52266. __extends(BackEase, _super);
  52267. function BackEase(amplitude) {
  52268. if (amplitude === void 0) { amplitude = 1; }
  52269. var _this = _super.call(this) || this;
  52270. _this.amplitude = amplitude;
  52271. return _this;
  52272. }
  52273. BackEase.prototype.easeInCore = function (gradient) {
  52274. var num = Math.max(0, this.amplitude);
  52275. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52276. };
  52277. return BackEase;
  52278. }(EasingFunction));
  52279. BABYLON.BackEase = BackEase;
  52280. var BounceEase = /** @class */ (function (_super) {
  52281. __extends(BounceEase, _super);
  52282. function BounceEase(bounces, bounciness) {
  52283. if (bounces === void 0) { bounces = 3; }
  52284. if (bounciness === void 0) { bounciness = 2; }
  52285. var _this = _super.call(this) || this;
  52286. _this.bounces = bounces;
  52287. _this.bounciness = bounciness;
  52288. return _this;
  52289. }
  52290. BounceEase.prototype.easeInCore = function (gradient) {
  52291. var y = Math.max(0.0, this.bounces);
  52292. var bounciness = this.bounciness;
  52293. if (bounciness <= 1.0) {
  52294. bounciness = 1.001;
  52295. }
  52296. var num9 = Math.pow(bounciness, y);
  52297. var num5 = 1.0 - bounciness;
  52298. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52299. var num15 = gradient * num4;
  52300. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52301. var num3 = Math.floor(num65);
  52302. var num13 = num3 + 1.0;
  52303. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52304. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52305. var num7 = (num8 + num12) * 0.5;
  52306. var num6 = gradient - num7;
  52307. var num2 = num7 - num8;
  52308. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52309. };
  52310. return BounceEase;
  52311. }(EasingFunction));
  52312. BABYLON.BounceEase = BounceEase;
  52313. var CubicEase = /** @class */ (function (_super) {
  52314. __extends(CubicEase, _super);
  52315. function CubicEase() {
  52316. return _super !== null && _super.apply(this, arguments) || this;
  52317. }
  52318. CubicEase.prototype.easeInCore = function (gradient) {
  52319. return (gradient * gradient * gradient);
  52320. };
  52321. return CubicEase;
  52322. }(EasingFunction));
  52323. BABYLON.CubicEase = CubicEase;
  52324. var ElasticEase = /** @class */ (function (_super) {
  52325. __extends(ElasticEase, _super);
  52326. function ElasticEase(oscillations, springiness) {
  52327. if (oscillations === void 0) { oscillations = 3; }
  52328. if (springiness === void 0) { springiness = 3; }
  52329. var _this = _super.call(this) || this;
  52330. _this.oscillations = oscillations;
  52331. _this.springiness = springiness;
  52332. return _this;
  52333. }
  52334. ElasticEase.prototype.easeInCore = function (gradient) {
  52335. var num2;
  52336. var num3 = Math.max(0.0, this.oscillations);
  52337. var num = Math.max(0.0, this.springiness);
  52338. if (num == 0) {
  52339. num2 = gradient;
  52340. }
  52341. else {
  52342. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52343. }
  52344. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52345. };
  52346. return ElasticEase;
  52347. }(EasingFunction));
  52348. BABYLON.ElasticEase = ElasticEase;
  52349. var ExponentialEase = /** @class */ (function (_super) {
  52350. __extends(ExponentialEase, _super);
  52351. function ExponentialEase(exponent) {
  52352. if (exponent === void 0) { exponent = 2; }
  52353. var _this = _super.call(this) || this;
  52354. _this.exponent = exponent;
  52355. return _this;
  52356. }
  52357. ExponentialEase.prototype.easeInCore = function (gradient) {
  52358. if (this.exponent <= 0) {
  52359. return gradient;
  52360. }
  52361. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52362. };
  52363. return ExponentialEase;
  52364. }(EasingFunction));
  52365. BABYLON.ExponentialEase = ExponentialEase;
  52366. var PowerEase = /** @class */ (function (_super) {
  52367. __extends(PowerEase, _super);
  52368. function PowerEase(power) {
  52369. if (power === void 0) { power = 2; }
  52370. var _this = _super.call(this) || this;
  52371. _this.power = power;
  52372. return _this;
  52373. }
  52374. PowerEase.prototype.easeInCore = function (gradient) {
  52375. var y = Math.max(0.0, this.power);
  52376. return Math.pow(gradient, y);
  52377. };
  52378. return PowerEase;
  52379. }(EasingFunction));
  52380. BABYLON.PowerEase = PowerEase;
  52381. var QuadraticEase = /** @class */ (function (_super) {
  52382. __extends(QuadraticEase, _super);
  52383. function QuadraticEase() {
  52384. return _super !== null && _super.apply(this, arguments) || this;
  52385. }
  52386. QuadraticEase.prototype.easeInCore = function (gradient) {
  52387. return (gradient * gradient);
  52388. };
  52389. return QuadraticEase;
  52390. }(EasingFunction));
  52391. BABYLON.QuadraticEase = QuadraticEase;
  52392. var QuarticEase = /** @class */ (function (_super) {
  52393. __extends(QuarticEase, _super);
  52394. function QuarticEase() {
  52395. return _super !== null && _super.apply(this, arguments) || this;
  52396. }
  52397. QuarticEase.prototype.easeInCore = function (gradient) {
  52398. return (gradient * gradient * gradient * gradient);
  52399. };
  52400. return QuarticEase;
  52401. }(EasingFunction));
  52402. BABYLON.QuarticEase = QuarticEase;
  52403. var QuinticEase = /** @class */ (function (_super) {
  52404. __extends(QuinticEase, _super);
  52405. function QuinticEase() {
  52406. return _super !== null && _super.apply(this, arguments) || this;
  52407. }
  52408. QuinticEase.prototype.easeInCore = function (gradient) {
  52409. return (gradient * gradient * gradient * gradient * gradient);
  52410. };
  52411. return QuinticEase;
  52412. }(EasingFunction));
  52413. BABYLON.QuinticEase = QuinticEase;
  52414. var SineEase = /** @class */ (function (_super) {
  52415. __extends(SineEase, _super);
  52416. function SineEase() {
  52417. return _super !== null && _super.apply(this, arguments) || this;
  52418. }
  52419. SineEase.prototype.easeInCore = function (gradient) {
  52420. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52421. };
  52422. return SineEase;
  52423. }(EasingFunction));
  52424. BABYLON.SineEase = SineEase;
  52425. var BezierCurveEase = /** @class */ (function (_super) {
  52426. __extends(BezierCurveEase, _super);
  52427. function BezierCurveEase(x1, y1, x2, y2) {
  52428. if (x1 === void 0) { x1 = 0; }
  52429. if (y1 === void 0) { y1 = 0; }
  52430. if (x2 === void 0) { x2 = 1; }
  52431. if (y2 === void 0) { y2 = 1; }
  52432. var _this = _super.call(this) || this;
  52433. _this.x1 = x1;
  52434. _this.y1 = y1;
  52435. _this.x2 = x2;
  52436. _this.y2 = y2;
  52437. return _this;
  52438. }
  52439. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52440. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52441. };
  52442. return BezierCurveEase;
  52443. }(EasingFunction));
  52444. BABYLON.BezierCurveEase = BezierCurveEase;
  52445. })(BABYLON || (BABYLON = {}));
  52446. //# sourceMappingURL=babylon.easing.js.map
  52447. var BABYLON;
  52448. (function (BABYLON) {
  52449. /**
  52450. * A Condition applied to an Action
  52451. */
  52452. var Condition = /** @class */ (function () {
  52453. /**
  52454. * Creates a new Condition
  52455. * @param actionManager the manager of the action the condition is applied to
  52456. */
  52457. function Condition(actionManager) {
  52458. this._actionManager = actionManager;
  52459. }
  52460. /**
  52461. * Check if the current condition is valid
  52462. * @returns a boolean
  52463. */
  52464. Condition.prototype.isValid = function () {
  52465. return true;
  52466. };
  52467. /**
  52468. * Internal only
  52469. * @hidden
  52470. */
  52471. Condition.prototype._getProperty = function (propertyPath) {
  52472. return this._actionManager._getProperty(propertyPath);
  52473. };
  52474. /**
  52475. * Internal only
  52476. * @hidden
  52477. */
  52478. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52479. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52480. };
  52481. /**
  52482. * Serialize placeholder for child classes
  52483. * @returns the serialized object
  52484. */
  52485. Condition.prototype.serialize = function () {
  52486. };
  52487. /**
  52488. * Internal only
  52489. * @hidden
  52490. */
  52491. Condition.prototype._serialize = function (serializedCondition) {
  52492. return {
  52493. type: 2,
  52494. children: [],
  52495. name: serializedCondition.name,
  52496. properties: serializedCondition.properties
  52497. };
  52498. };
  52499. return Condition;
  52500. }());
  52501. BABYLON.Condition = Condition;
  52502. /**
  52503. * Defines specific conditional operators as extensions of Condition
  52504. */
  52505. var ValueCondition = /** @class */ (function (_super) {
  52506. __extends(ValueCondition, _super);
  52507. /**
  52508. * Creates a new ValueCondition
  52509. * @param actionManager manager for the action the condition applies to
  52510. * @param target for the action
  52511. * @param propertyPath path to specify the property of the target the conditional operator uses
  52512. * @param value the value compared by the conditional operator against the current value of the property
  52513. * @param operator the conditional operator, default ValueCondition.IsEqual
  52514. */
  52515. function ValueCondition(actionManager, target,
  52516. /** path to specify the property of the target the conditional operator uses */
  52517. propertyPath,
  52518. /** the value compared by the conditional operator against the current value of the property */
  52519. value,
  52520. /** the conditional operator, default ValueCondition.IsEqual */
  52521. operator) {
  52522. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52523. var _this = _super.call(this, actionManager) || this;
  52524. _this.propertyPath = propertyPath;
  52525. _this.value = value;
  52526. _this.operator = operator;
  52527. _this._target = target;
  52528. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52529. _this._property = _this._getProperty(_this.propertyPath);
  52530. return _this;
  52531. }
  52532. Object.defineProperty(ValueCondition, "IsEqual", {
  52533. /**
  52534. * returns the number for IsEqual
  52535. */
  52536. get: function () {
  52537. return ValueCondition._IsEqual;
  52538. },
  52539. enumerable: true,
  52540. configurable: true
  52541. });
  52542. Object.defineProperty(ValueCondition, "IsDifferent", {
  52543. /**
  52544. * Returns the number for IsDifferent
  52545. */
  52546. get: function () {
  52547. return ValueCondition._IsDifferent;
  52548. },
  52549. enumerable: true,
  52550. configurable: true
  52551. });
  52552. Object.defineProperty(ValueCondition, "IsGreater", {
  52553. /**
  52554. * Returns the number for IsGreater
  52555. */
  52556. get: function () {
  52557. return ValueCondition._IsGreater;
  52558. },
  52559. enumerable: true,
  52560. configurable: true
  52561. });
  52562. Object.defineProperty(ValueCondition, "IsLesser", {
  52563. /**
  52564. * Returns the number for IsLesser
  52565. */
  52566. get: function () {
  52567. return ValueCondition._IsLesser;
  52568. },
  52569. enumerable: true,
  52570. configurable: true
  52571. });
  52572. /**
  52573. * Compares the given value with the property value for the specified conditional operator
  52574. * @returns the result of the comparison
  52575. */
  52576. ValueCondition.prototype.isValid = function () {
  52577. switch (this.operator) {
  52578. case ValueCondition.IsGreater:
  52579. return this._effectiveTarget[this._property] > this.value;
  52580. case ValueCondition.IsLesser:
  52581. return this._effectiveTarget[this._property] < this.value;
  52582. case ValueCondition.IsEqual:
  52583. case ValueCondition.IsDifferent:
  52584. var check;
  52585. if (this.value.equals) {
  52586. check = this.value.equals(this._effectiveTarget[this._property]);
  52587. }
  52588. else {
  52589. check = this.value === this._effectiveTarget[this._property];
  52590. }
  52591. return this.operator === ValueCondition.IsEqual ? check : !check;
  52592. }
  52593. return false;
  52594. };
  52595. /**
  52596. * Serialize the ValueCondition into a JSON compatible object
  52597. * @returns serialization object
  52598. */
  52599. ValueCondition.prototype.serialize = function () {
  52600. return this._serialize({
  52601. name: "ValueCondition",
  52602. properties: [
  52603. BABYLON.Action._GetTargetProperty(this._target),
  52604. { name: "propertyPath", value: this.propertyPath },
  52605. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52606. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52607. ]
  52608. });
  52609. };
  52610. /**
  52611. * Gets the name of the conditional operator for the ValueCondition
  52612. * @param operator the conditional operator
  52613. * @returns the name
  52614. */
  52615. ValueCondition.GetOperatorName = function (operator) {
  52616. switch (operator) {
  52617. case ValueCondition._IsEqual: return "IsEqual";
  52618. case ValueCondition._IsDifferent: return "IsDifferent";
  52619. case ValueCondition._IsGreater: return "IsGreater";
  52620. case ValueCondition._IsLesser: return "IsLesser";
  52621. default: return "";
  52622. }
  52623. };
  52624. /**
  52625. * Internal only
  52626. * @hidden
  52627. */
  52628. ValueCondition._IsEqual = 0;
  52629. /**
  52630. * Internal only
  52631. * @hidden
  52632. */
  52633. ValueCondition._IsDifferent = 1;
  52634. /**
  52635. * Internal only
  52636. * @hidden
  52637. */
  52638. ValueCondition._IsGreater = 2;
  52639. /**
  52640. * Internal only
  52641. * @hidden
  52642. */
  52643. ValueCondition._IsLesser = 3;
  52644. return ValueCondition;
  52645. }(Condition));
  52646. BABYLON.ValueCondition = ValueCondition;
  52647. /**
  52648. * Defines a predicate condition as an extension of Condition
  52649. */
  52650. var PredicateCondition = /** @class */ (function (_super) {
  52651. __extends(PredicateCondition, _super);
  52652. /**
  52653. * Creates a new PredicateCondition
  52654. * @param actionManager manager for the action the condition applies to
  52655. * @param predicate defines the predicate function used to validate the condition
  52656. */
  52657. function PredicateCondition(actionManager,
  52658. /** defines the predicate function used to validate the condition */
  52659. predicate) {
  52660. var _this = _super.call(this, actionManager) || this;
  52661. _this.predicate = predicate;
  52662. return _this;
  52663. }
  52664. /**
  52665. * @returns the validity of the predicate condition
  52666. */
  52667. PredicateCondition.prototype.isValid = function () {
  52668. return this.predicate();
  52669. };
  52670. return PredicateCondition;
  52671. }(Condition));
  52672. BABYLON.PredicateCondition = PredicateCondition;
  52673. /**
  52674. * Defines a state condition as an extension of Condition
  52675. */
  52676. var StateCondition = /** @class */ (function (_super) {
  52677. __extends(StateCondition, _super);
  52678. /**
  52679. * Creates a new StateCondition
  52680. * @param actionManager manager for the action the condition applies to
  52681. * @param target of the condition
  52682. * @param value to compare with target state
  52683. */
  52684. function StateCondition(actionManager, target, value) {
  52685. var _this = _super.call(this, actionManager) || this;
  52686. _this.value = value;
  52687. _this._target = target;
  52688. return _this;
  52689. }
  52690. /**
  52691. * @returns the validity of the state
  52692. */
  52693. StateCondition.prototype.isValid = function () {
  52694. return this._target.state === this.value;
  52695. };
  52696. /**
  52697. * Serialize the StateCondition into a JSON compatible object
  52698. * @returns serialization object
  52699. */
  52700. StateCondition.prototype.serialize = function () {
  52701. return this._serialize({
  52702. name: "StateCondition",
  52703. properties: [
  52704. BABYLON.Action._GetTargetProperty(this._target),
  52705. { name: "value", value: this.value }
  52706. ]
  52707. });
  52708. };
  52709. return StateCondition;
  52710. }(Condition));
  52711. BABYLON.StateCondition = StateCondition;
  52712. })(BABYLON || (BABYLON = {}));
  52713. //# sourceMappingURL=babylon.condition.js.map
  52714. var BABYLON;
  52715. (function (BABYLON) {
  52716. /**
  52717. * The action to be carried out following a trigger
  52718. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52719. */
  52720. var Action = /** @class */ (function () {
  52721. /**
  52722. * Creates a new Action
  52723. * @param triggerOptions the trigger, with or without parameters, for the action
  52724. * @param condition an optional determinant of action
  52725. */
  52726. function Action(
  52727. /** the trigger, with or without parameters, for the action */
  52728. triggerOptions, condition) {
  52729. this.triggerOptions = triggerOptions;
  52730. /**
  52731. * An event triggered prior to action being executed.
  52732. */
  52733. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52734. if (triggerOptions.parameter) {
  52735. this.trigger = triggerOptions.trigger;
  52736. this._triggerParameter = triggerOptions.parameter;
  52737. }
  52738. else {
  52739. this.trigger = triggerOptions;
  52740. }
  52741. this._nextActiveAction = this;
  52742. this._condition = condition;
  52743. }
  52744. /**
  52745. * Internal only
  52746. * @hidden
  52747. */
  52748. Action.prototype._prepare = function () {
  52749. };
  52750. /**
  52751. * Gets the trigger parameters
  52752. * @returns the trigger parameters
  52753. */
  52754. Action.prototype.getTriggerParameter = function () {
  52755. return this._triggerParameter;
  52756. };
  52757. /**
  52758. * Internal only - executes current action event
  52759. * @hidden
  52760. */
  52761. Action.prototype._executeCurrent = function (evt) {
  52762. if (this._nextActiveAction._condition) {
  52763. var condition = this._nextActiveAction._condition;
  52764. var currentRenderId = this._actionManager.getScene().getRenderId();
  52765. // We cache the current evaluation for the current frame
  52766. if (condition._evaluationId === currentRenderId) {
  52767. if (!condition._currentResult) {
  52768. return;
  52769. }
  52770. }
  52771. else {
  52772. condition._evaluationId = currentRenderId;
  52773. if (!condition.isValid()) {
  52774. condition._currentResult = false;
  52775. return;
  52776. }
  52777. condition._currentResult = true;
  52778. }
  52779. }
  52780. this.onBeforeExecuteObservable.notifyObservers(this);
  52781. this._nextActiveAction.execute(evt);
  52782. this.skipToNextActiveAction();
  52783. };
  52784. /**
  52785. * Execute placeholder for child classes
  52786. * @param evt optional action event
  52787. */
  52788. Action.prototype.execute = function (evt) {
  52789. };
  52790. /**
  52791. * Skips to next active action
  52792. */
  52793. Action.prototype.skipToNextActiveAction = function () {
  52794. if (this._nextActiveAction._child) {
  52795. if (!this._nextActiveAction._child._actionManager) {
  52796. this._nextActiveAction._child._actionManager = this._actionManager;
  52797. }
  52798. this._nextActiveAction = this._nextActiveAction._child;
  52799. }
  52800. else {
  52801. this._nextActiveAction = this;
  52802. }
  52803. };
  52804. /**
  52805. * Adds action to chain of actions, may be a DoNothingAction
  52806. * @param action defines the next action to execute
  52807. * @returns The action passed in
  52808. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52809. */
  52810. Action.prototype.then = function (action) {
  52811. this._child = action;
  52812. action._actionManager = this._actionManager;
  52813. action._prepare();
  52814. return action;
  52815. };
  52816. /**
  52817. * Internal only
  52818. * @hidden
  52819. */
  52820. Action.prototype._getProperty = function (propertyPath) {
  52821. return this._actionManager._getProperty(propertyPath);
  52822. };
  52823. /**
  52824. * Internal only
  52825. * @hidden
  52826. */
  52827. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52828. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52829. };
  52830. /**
  52831. * Serialize placeholder for child classes
  52832. * @param parent of child
  52833. * @returns the serialized object
  52834. */
  52835. Action.prototype.serialize = function (parent) {
  52836. };
  52837. /**
  52838. * Internal only called by serialize
  52839. * @hidden
  52840. */
  52841. Action.prototype._serialize = function (serializedAction, parent) {
  52842. var serializationObject = {
  52843. type: 1,
  52844. children: [],
  52845. name: serializedAction.name,
  52846. properties: serializedAction.properties || []
  52847. };
  52848. // Serialize child
  52849. if (this._child) {
  52850. this._child.serialize(serializationObject);
  52851. }
  52852. // Check if "this" has a condition
  52853. if (this._condition) {
  52854. var serializedCondition = this._condition.serialize();
  52855. serializedCondition.children.push(serializationObject);
  52856. if (parent) {
  52857. parent.children.push(serializedCondition);
  52858. }
  52859. return serializedCondition;
  52860. }
  52861. if (parent) {
  52862. parent.children.push(serializationObject);
  52863. }
  52864. return serializationObject;
  52865. };
  52866. /**
  52867. * Internal only
  52868. * @hidden
  52869. */
  52870. Action._SerializeValueAsString = function (value) {
  52871. if (typeof value === "number") {
  52872. return value.toString();
  52873. }
  52874. if (typeof value === "boolean") {
  52875. return value ? "true" : "false";
  52876. }
  52877. if (value instanceof BABYLON.Vector2) {
  52878. return value.x + ", " + value.y;
  52879. }
  52880. if (value instanceof BABYLON.Vector3) {
  52881. return value.x + ", " + value.y + ", " + value.z;
  52882. }
  52883. if (value instanceof BABYLON.Color3) {
  52884. return value.r + ", " + value.g + ", " + value.b;
  52885. }
  52886. if (value instanceof BABYLON.Color4) {
  52887. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52888. }
  52889. return value; // string
  52890. };
  52891. /**
  52892. * Internal only
  52893. * @hidden
  52894. */
  52895. Action._GetTargetProperty = function (target) {
  52896. return {
  52897. name: "target",
  52898. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52899. : target instanceof BABYLON.Light ? "LightProperties"
  52900. : target instanceof BABYLON.Camera ? "CameraProperties"
  52901. : "SceneProperties",
  52902. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52903. };
  52904. };
  52905. return Action;
  52906. }());
  52907. BABYLON.Action = Action;
  52908. })(BABYLON || (BABYLON = {}));
  52909. //# sourceMappingURL=babylon.action.js.map
  52910. var BABYLON;
  52911. (function (BABYLON) {
  52912. /**
  52913. * ActionEvent is the event being sent when an action is triggered.
  52914. */
  52915. var ActionEvent = /** @class */ (function () {
  52916. /**
  52917. * Creates a new ActionEvent
  52918. * @param source The mesh or sprite that triggered the action
  52919. * @param pointerX The X mouse cursor position at the time of the event
  52920. * @param pointerY The Y mouse cursor position at the time of the event
  52921. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52922. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52923. * @param additionalData additional data for the event
  52924. */
  52925. function ActionEvent(
  52926. /** The mesh or sprite that triggered the action */
  52927. source,
  52928. /** The X mouse cursor position at the time of the event */
  52929. pointerX,
  52930. /** The Y mouse cursor position at the time of the event */
  52931. pointerY,
  52932. /** The mesh that is currently pointed at (can be null) */
  52933. meshUnderPointer,
  52934. /** the original (browser) event that triggered the ActionEvent */
  52935. sourceEvent,
  52936. /** additional data for the event */
  52937. additionalData) {
  52938. this.source = source;
  52939. this.pointerX = pointerX;
  52940. this.pointerY = pointerY;
  52941. this.meshUnderPointer = meshUnderPointer;
  52942. this.sourceEvent = sourceEvent;
  52943. this.additionalData = additionalData;
  52944. }
  52945. /**
  52946. * Helper function to auto-create an ActionEvent from a source mesh.
  52947. * @param source The source mesh that triggered the event
  52948. * @param evt The original (browser) event
  52949. * @param additionalData additional data for the event
  52950. * @returns the new ActionEvent
  52951. */
  52952. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52953. var scene = source.getScene();
  52954. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52955. };
  52956. /**
  52957. * Helper function to auto-create an ActionEvent from a source sprite
  52958. * @param source The source sprite that triggered the event
  52959. * @param scene Scene associated with the sprite
  52960. * @param evt The original (browser) event
  52961. * @param additionalData additional data for the event
  52962. * @returns the new ActionEvent
  52963. */
  52964. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52965. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52966. };
  52967. /**
  52968. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52969. * @param scene the scene where the event occurred
  52970. * @param evt The original (browser) event
  52971. * @returns the new ActionEvent
  52972. */
  52973. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52974. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52975. };
  52976. /**
  52977. * Helper function to auto-create an ActionEvent from a primitive
  52978. * @param prim defines the target primitive
  52979. * @param pointerPos defines the pointer position
  52980. * @param evt The original (browser) event
  52981. * @param additionalData additional data for the event
  52982. * @returns the new ActionEvent
  52983. */
  52984. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52985. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52986. };
  52987. return ActionEvent;
  52988. }());
  52989. BABYLON.ActionEvent = ActionEvent;
  52990. /**
  52991. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52992. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52993. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52994. */
  52995. var ActionManager = /** @class */ (function () {
  52996. /**
  52997. * Creates a new action manager
  52998. * @param scene defines the hosting scene
  52999. */
  53000. function ActionManager(scene) {
  53001. // Members
  53002. /** Gets the list of actions */
  53003. this.actions = new Array();
  53004. /** Gets the cursor to use when hovering items */
  53005. this.hoverCursor = '';
  53006. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53007. scene._actionManagers.push(this);
  53008. }
  53009. Object.defineProperty(ActionManager, "NothingTrigger", {
  53010. /**
  53011. * Nothing
  53012. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53013. */
  53014. get: function () {
  53015. return ActionManager._NothingTrigger;
  53016. },
  53017. enumerable: true,
  53018. configurable: true
  53019. });
  53020. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53021. /**
  53022. * On pick
  53023. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53024. */
  53025. get: function () {
  53026. return ActionManager._OnPickTrigger;
  53027. },
  53028. enumerable: true,
  53029. configurable: true
  53030. });
  53031. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53032. /**
  53033. * On left pick
  53034. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53035. */
  53036. get: function () {
  53037. return ActionManager._OnLeftPickTrigger;
  53038. },
  53039. enumerable: true,
  53040. configurable: true
  53041. });
  53042. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53043. /**
  53044. * On right pick
  53045. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53046. */
  53047. get: function () {
  53048. return ActionManager._OnRightPickTrigger;
  53049. },
  53050. enumerable: true,
  53051. configurable: true
  53052. });
  53053. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53054. /**
  53055. * On center pick
  53056. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53057. */
  53058. get: function () {
  53059. return ActionManager._OnCenterPickTrigger;
  53060. },
  53061. enumerable: true,
  53062. configurable: true
  53063. });
  53064. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53065. /**
  53066. * On pick down
  53067. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53068. */
  53069. get: function () {
  53070. return ActionManager._OnPickDownTrigger;
  53071. },
  53072. enumerable: true,
  53073. configurable: true
  53074. });
  53075. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53076. /**
  53077. * On double pick
  53078. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53079. */
  53080. get: function () {
  53081. return ActionManager._OnDoublePickTrigger;
  53082. },
  53083. enumerable: true,
  53084. configurable: true
  53085. });
  53086. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53087. /**
  53088. * On pick up
  53089. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53090. */
  53091. get: function () {
  53092. return ActionManager._OnPickUpTrigger;
  53093. },
  53094. enumerable: true,
  53095. configurable: true
  53096. });
  53097. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53098. /**
  53099. * On pick out.
  53100. * This trigger will only be raised if you also declared a OnPickDown
  53101. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53102. */
  53103. get: function () {
  53104. return ActionManager._OnPickOutTrigger;
  53105. },
  53106. enumerable: true,
  53107. configurable: true
  53108. });
  53109. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53110. /**
  53111. * On long press
  53112. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53113. */
  53114. get: function () {
  53115. return ActionManager._OnLongPressTrigger;
  53116. },
  53117. enumerable: true,
  53118. configurable: true
  53119. });
  53120. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53121. /**
  53122. * On pointer over
  53123. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53124. */
  53125. get: function () {
  53126. return ActionManager._OnPointerOverTrigger;
  53127. },
  53128. enumerable: true,
  53129. configurable: true
  53130. });
  53131. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53132. /**
  53133. * On pointer out
  53134. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53135. */
  53136. get: function () {
  53137. return ActionManager._OnPointerOutTrigger;
  53138. },
  53139. enumerable: true,
  53140. configurable: true
  53141. });
  53142. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53143. /**
  53144. * On every frame
  53145. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53146. */
  53147. get: function () {
  53148. return ActionManager._OnEveryFrameTrigger;
  53149. },
  53150. enumerable: true,
  53151. configurable: true
  53152. });
  53153. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53154. /**
  53155. * On intersection enter
  53156. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53157. */
  53158. get: function () {
  53159. return ActionManager._OnIntersectionEnterTrigger;
  53160. },
  53161. enumerable: true,
  53162. configurable: true
  53163. });
  53164. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53165. /**
  53166. * On intersection exit
  53167. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53168. */
  53169. get: function () {
  53170. return ActionManager._OnIntersectionExitTrigger;
  53171. },
  53172. enumerable: true,
  53173. configurable: true
  53174. });
  53175. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53176. /**
  53177. * On key down
  53178. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53179. */
  53180. get: function () {
  53181. return ActionManager._OnKeyDownTrigger;
  53182. },
  53183. enumerable: true,
  53184. configurable: true
  53185. });
  53186. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53187. /**
  53188. * On key up
  53189. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53190. */
  53191. get: function () {
  53192. return ActionManager._OnKeyUpTrigger;
  53193. },
  53194. enumerable: true,
  53195. configurable: true
  53196. });
  53197. // Methods
  53198. /**
  53199. * Releases all associated resources
  53200. */
  53201. ActionManager.prototype.dispose = function () {
  53202. var index = this._scene._actionManagers.indexOf(this);
  53203. for (var i = 0; i < this.actions.length; i++) {
  53204. var action = this.actions[i];
  53205. ActionManager.Triggers[action.trigger]--;
  53206. if (ActionManager.Triggers[action.trigger] === 0) {
  53207. delete ActionManager.Triggers[action.trigger];
  53208. }
  53209. }
  53210. if (index > -1) {
  53211. this._scene._actionManagers.splice(index, 1);
  53212. }
  53213. };
  53214. /**
  53215. * Gets hosting scene
  53216. * @returns the hosting scene
  53217. */
  53218. ActionManager.prototype.getScene = function () {
  53219. return this._scene;
  53220. };
  53221. /**
  53222. * Does this action manager handles actions of any of the given triggers
  53223. * @param triggers defines the triggers to be tested
  53224. * @return a boolean indicating whether one (or more) of the triggers is handled
  53225. */
  53226. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53227. for (var index = 0; index < this.actions.length; index++) {
  53228. var action = this.actions[index];
  53229. if (triggers.indexOf(action.trigger) > -1) {
  53230. return true;
  53231. }
  53232. }
  53233. return false;
  53234. };
  53235. /**
  53236. * Does this action manager handles actions of a given trigger
  53237. * @param trigger defines the trigger to be tested
  53238. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53239. * @return whether the trigger is handled
  53240. */
  53241. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53242. for (var index = 0; index < this.actions.length; index++) {
  53243. var action = this.actions[index];
  53244. if (action.trigger === trigger) {
  53245. if (parameterPredicate) {
  53246. if (parameterPredicate(action.getTriggerParameter())) {
  53247. return true;
  53248. }
  53249. }
  53250. else {
  53251. return true;
  53252. }
  53253. }
  53254. }
  53255. return false;
  53256. };
  53257. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53258. /**
  53259. * Does this action manager has pointer triggers
  53260. */
  53261. get: function () {
  53262. for (var index = 0; index < this.actions.length; index++) {
  53263. var action = this.actions[index];
  53264. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53265. return true;
  53266. }
  53267. }
  53268. return false;
  53269. },
  53270. enumerable: true,
  53271. configurable: true
  53272. });
  53273. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53274. /**
  53275. * Does this action manager has pick triggers
  53276. */
  53277. get: function () {
  53278. for (var index = 0; index < this.actions.length; index++) {
  53279. var action = this.actions[index];
  53280. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53281. return true;
  53282. }
  53283. }
  53284. return false;
  53285. },
  53286. enumerable: true,
  53287. configurable: true
  53288. });
  53289. Object.defineProperty(ActionManager, "HasTriggers", {
  53290. /**
  53291. * Does exist one action manager with at least one trigger
  53292. **/
  53293. get: function () {
  53294. for (var t in ActionManager.Triggers) {
  53295. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53296. return true;
  53297. }
  53298. }
  53299. return false;
  53300. },
  53301. enumerable: true,
  53302. configurable: true
  53303. });
  53304. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53305. /**
  53306. * Does exist one action manager with at least one pick trigger
  53307. **/
  53308. get: function () {
  53309. for (var t in ActionManager.Triggers) {
  53310. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53311. var t_int = parseInt(t);
  53312. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53313. return true;
  53314. }
  53315. }
  53316. }
  53317. return false;
  53318. },
  53319. enumerable: true,
  53320. configurable: true
  53321. });
  53322. /**
  53323. * Does exist one action manager that handles actions of a given trigger
  53324. * @param trigger defines the trigger to be tested
  53325. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53326. **/
  53327. ActionManager.HasSpecificTrigger = function (trigger) {
  53328. for (var t in ActionManager.Triggers) {
  53329. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53330. var t_int = parseInt(t);
  53331. if (t_int === trigger) {
  53332. return true;
  53333. }
  53334. }
  53335. }
  53336. return false;
  53337. };
  53338. /**
  53339. * Registers an action to this action manager
  53340. * @param action defines the action to be registered
  53341. * @return the action amended (prepared) after registration
  53342. */
  53343. ActionManager.prototype.registerAction = function (action) {
  53344. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53345. if (this.getScene().actionManager !== this) {
  53346. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53347. return null;
  53348. }
  53349. }
  53350. this.actions.push(action);
  53351. if (ActionManager.Triggers[action.trigger]) {
  53352. ActionManager.Triggers[action.trigger]++;
  53353. }
  53354. else {
  53355. ActionManager.Triggers[action.trigger] = 1;
  53356. }
  53357. action._actionManager = this;
  53358. action._prepare();
  53359. return action;
  53360. };
  53361. /**
  53362. * Unregisters an action to this action manager
  53363. * @param action defines the action to be unregistered
  53364. * @return a boolean indicating whether the action has been unregistered
  53365. */
  53366. ActionManager.prototype.unregisterAction = function (action) {
  53367. var index = this.actions.indexOf(action);
  53368. if (index !== -1) {
  53369. this.actions.splice(index, 1);
  53370. ActionManager.Triggers[action.trigger] -= 1;
  53371. if (ActionManager.Triggers[action.trigger] === 0) {
  53372. delete ActionManager.Triggers[action.trigger];
  53373. }
  53374. delete action._actionManager;
  53375. return true;
  53376. }
  53377. return false;
  53378. };
  53379. /**
  53380. * Process a specific trigger
  53381. * @param trigger defines the trigger to process
  53382. * @param evt defines the event details to be processed
  53383. */
  53384. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53385. for (var index = 0; index < this.actions.length; index++) {
  53386. var action = this.actions[index];
  53387. if (action.trigger === trigger) {
  53388. if (evt) {
  53389. if (trigger === ActionManager.OnKeyUpTrigger
  53390. || trigger === ActionManager.OnKeyDownTrigger) {
  53391. var parameter = action.getTriggerParameter();
  53392. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53393. if (!parameter.toLowerCase) {
  53394. continue;
  53395. }
  53396. var lowerCase = parameter.toLowerCase();
  53397. if (lowerCase !== evt.sourceEvent.key) {
  53398. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53399. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53400. if (actualkey !== lowerCase) {
  53401. continue;
  53402. }
  53403. }
  53404. }
  53405. }
  53406. }
  53407. action._executeCurrent(evt);
  53408. }
  53409. }
  53410. };
  53411. /** @hidden */
  53412. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53413. var properties = propertyPath.split(".");
  53414. for (var index = 0; index < properties.length - 1; index++) {
  53415. target = target[properties[index]];
  53416. }
  53417. return target;
  53418. };
  53419. /** @hidden */
  53420. ActionManager.prototype._getProperty = function (propertyPath) {
  53421. var properties = propertyPath.split(".");
  53422. return properties[properties.length - 1];
  53423. };
  53424. /**
  53425. * Serialize this manager to a JSON object
  53426. * @param name defines the property name to store this manager
  53427. * @returns a JSON representation of this manager
  53428. */
  53429. ActionManager.prototype.serialize = function (name) {
  53430. var root = {
  53431. children: new Array(),
  53432. name: name,
  53433. type: 3,
  53434. properties: new Array() // Empty for root but required
  53435. };
  53436. for (var i = 0; i < this.actions.length; i++) {
  53437. var triggerObject = {
  53438. type: 0,
  53439. children: new Array(),
  53440. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53441. properties: new Array()
  53442. };
  53443. var triggerOptions = this.actions[i].triggerOptions;
  53444. if (triggerOptions && typeof triggerOptions !== "number") {
  53445. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53446. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53447. }
  53448. else {
  53449. var parameter = {};
  53450. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53451. if (triggerOptions.parameter.mesh) {
  53452. parameter._meshId = triggerOptions.parameter.mesh.id;
  53453. }
  53454. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53455. }
  53456. }
  53457. // Serialize child action, recursively
  53458. this.actions[i].serialize(triggerObject);
  53459. // Add serialized trigger
  53460. root.children.push(triggerObject);
  53461. }
  53462. return root;
  53463. };
  53464. /**
  53465. * Creates a new ActionManager from a JSON data
  53466. * @param parsedActions defines the JSON data to read from
  53467. * @param object defines the hosting mesh
  53468. * @param scene defines the hosting scene
  53469. */
  53470. ActionManager.Parse = function (parsedActions, object, scene) {
  53471. var actionManager = new ActionManager(scene);
  53472. if (object === null)
  53473. scene.actionManager = actionManager;
  53474. else
  53475. object.actionManager = actionManager;
  53476. // instanciate a new object
  53477. var instanciate = function (name, params) {
  53478. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53479. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53480. newInstance.constructor.apply(newInstance, params);
  53481. return newInstance;
  53482. };
  53483. var parseParameter = function (name, value, target, propertyPath) {
  53484. if (propertyPath === null) {
  53485. // String, boolean or float
  53486. var floatValue = parseFloat(value);
  53487. if (value === "true" || value === "false")
  53488. return value === "true";
  53489. else
  53490. return isNaN(floatValue) ? value : floatValue;
  53491. }
  53492. var effectiveTarget = propertyPath.split(".");
  53493. var values = value.split(",");
  53494. // Get effective Target
  53495. for (var i = 0; i < effectiveTarget.length; i++) {
  53496. target = target[effectiveTarget[i]];
  53497. }
  53498. // Return appropriate value with its type
  53499. if (typeof (target) === "boolean")
  53500. return values[0] === "true";
  53501. if (typeof (target) === "string")
  53502. return values[0];
  53503. // Parameters with multiple values such as Vector3 etc.
  53504. var split = new Array();
  53505. for (var i = 0; i < values.length; i++)
  53506. split.push(parseFloat(values[i]));
  53507. if (target instanceof BABYLON.Vector3)
  53508. return BABYLON.Vector3.FromArray(split);
  53509. if (target instanceof BABYLON.Vector4)
  53510. return BABYLON.Vector4.FromArray(split);
  53511. if (target instanceof BABYLON.Color3)
  53512. return BABYLON.Color3.FromArray(split);
  53513. if (target instanceof BABYLON.Color4)
  53514. return BABYLON.Color4.FromArray(split);
  53515. return parseFloat(values[0]);
  53516. };
  53517. // traverse graph per trigger
  53518. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53519. if (combineArray === void 0) { combineArray = null; }
  53520. if (parsedAction.detached)
  53521. return;
  53522. var parameters = new Array();
  53523. var target = null;
  53524. var propertyPath = null;
  53525. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53526. // Parameters
  53527. if (parsedAction.type === 2)
  53528. parameters.push(actionManager);
  53529. else
  53530. parameters.push(trigger);
  53531. if (combine) {
  53532. var actions = new Array();
  53533. for (var j = 0; j < parsedAction.combine.length; j++) {
  53534. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53535. }
  53536. parameters.push(actions);
  53537. }
  53538. else {
  53539. for (var i = 0; i < parsedAction.properties.length; i++) {
  53540. var value = parsedAction.properties[i].value;
  53541. var name = parsedAction.properties[i].name;
  53542. var targetType = parsedAction.properties[i].targetType;
  53543. if (name === "target")
  53544. if (targetType !== null && targetType === "SceneProperties")
  53545. value = target = scene;
  53546. else
  53547. value = target = scene.getNodeByName(value);
  53548. else if (name === "parent")
  53549. value = scene.getNodeByName(value);
  53550. else if (name === "sound")
  53551. value = scene.getSoundByName(value);
  53552. else if (name !== "propertyPath") {
  53553. if (parsedAction.type === 2 && name === "operator")
  53554. value = BABYLON.ValueCondition[value];
  53555. else
  53556. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53557. }
  53558. else {
  53559. propertyPath = value;
  53560. }
  53561. parameters.push(value);
  53562. }
  53563. }
  53564. if (combineArray === null) {
  53565. parameters.push(condition);
  53566. }
  53567. else {
  53568. parameters.push(null);
  53569. }
  53570. // If interpolate value action
  53571. if (parsedAction.name === "InterpolateValueAction") {
  53572. var param = parameters[parameters.length - 2];
  53573. parameters[parameters.length - 1] = param;
  53574. parameters[parameters.length - 2] = condition;
  53575. }
  53576. // Action or condition(s) and not CombineAction
  53577. var newAction = instanciate(parsedAction.name, parameters);
  53578. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53579. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53580. if (action)
  53581. action.then(nothing);
  53582. else
  53583. actionManager.registerAction(nothing);
  53584. action = nothing;
  53585. }
  53586. if (combineArray === null) {
  53587. if (newAction instanceof BABYLON.Condition) {
  53588. condition = newAction;
  53589. newAction = action;
  53590. }
  53591. else {
  53592. condition = null;
  53593. if (action)
  53594. action.then(newAction);
  53595. else
  53596. actionManager.registerAction(newAction);
  53597. }
  53598. }
  53599. else {
  53600. combineArray.push(newAction);
  53601. }
  53602. for (var i = 0; i < parsedAction.children.length; i++)
  53603. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53604. };
  53605. // triggers
  53606. for (var i = 0; i < parsedActions.children.length; i++) {
  53607. var triggerParams;
  53608. var trigger = parsedActions.children[i];
  53609. if (trigger.properties.length > 0) {
  53610. var param = trigger.properties[0].value;
  53611. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53612. if (value._meshId) {
  53613. value.mesh = scene.getMeshByID(value._meshId);
  53614. }
  53615. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53616. }
  53617. else
  53618. triggerParams = ActionManager[trigger.name];
  53619. for (var j = 0; j < trigger.children.length; j++) {
  53620. if (!trigger.detached)
  53621. traverse(trigger.children[j], triggerParams, null, null);
  53622. }
  53623. }
  53624. };
  53625. /**
  53626. * Get a trigger name by index
  53627. * @param trigger defines the trigger index
  53628. * @returns a trigger name
  53629. */
  53630. ActionManager.GetTriggerName = function (trigger) {
  53631. switch (trigger) {
  53632. case 0: return "NothingTrigger";
  53633. case 1: return "OnPickTrigger";
  53634. case 2: return "OnLeftPickTrigger";
  53635. case 3: return "OnRightPickTrigger";
  53636. case 4: return "OnCenterPickTrigger";
  53637. case 5: return "OnPickDownTrigger";
  53638. case 6: return "OnPickUpTrigger";
  53639. case 7: return "OnLongPressTrigger";
  53640. case 8: return "OnPointerOverTrigger";
  53641. case 9: return "OnPointerOutTrigger";
  53642. case 10: return "OnEveryFrameTrigger";
  53643. case 11: return "OnIntersectionEnterTrigger";
  53644. case 12: return "OnIntersectionExitTrigger";
  53645. case 13: return "OnKeyDownTrigger";
  53646. case 14: return "OnKeyUpTrigger";
  53647. case 15: return "OnPickOutTrigger";
  53648. default: return "";
  53649. }
  53650. };
  53651. // Statics
  53652. ActionManager._NothingTrigger = 0;
  53653. ActionManager._OnPickTrigger = 1;
  53654. ActionManager._OnLeftPickTrigger = 2;
  53655. ActionManager._OnRightPickTrigger = 3;
  53656. ActionManager._OnCenterPickTrigger = 4;
  53657. ActionManager._OnPickDownTrigger = 5;
  53658. ActionManager._OnDoublePickTrigger = 6;
  53659. ActionManager._OnPickUpTrigger = 7;
  53660. ActionManager._OnLongPressTrigger = 8;
  53661. ActionManager._OnPointerOverTrigger = 9;
  53662. ActionManager._OnPointerOutTrigger = 10;
  53663. ActionManager._OnEveryFrameTrigger = 11;
  53664. ActionManager._OnIntersectionEnterTrigger = 12;
  53665. ActionManager._OnIntersectionExitTrigger = 13;
  53666. ActionManager._OnKeyDownTrigger = 14;
  53667. ActionManager._OnKeyUpTrigger = 15;
  53668. ActionManager._OnPickOutTrigger = 16;
  53669. /** Gets the list of active triggers */
  53670. ActionManager.Triggers = {};
  53671. return ActionManager;
  53672. }());
  53673. BABYLON.ActionManager = ActionManager;
  53674. })(BABYLON || (BABYLON = {}));
  53675. //# sourceMappingURL=babylon.actionManager.js.map
  53676. var BABYLON;
  53677. (function (BABYLON) {
  53678. var InterpolateValueAction = /** @class */ (function (_super) {
  53679. __extends(InterpolateValueAction, _super);
  53680. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53681. if (duration === void 0) { duration = 1000; }
  53682. var _this = _super.call(this, triggerOptions, condition) || this;
  53683. _this.propertyPath = propertyPath;
  53684. _this.value = value;
  53685. _this.duration = duration;
  53686. _this.stopOtherAnimations = stopOtherAnimations;
  53687. _this.onInterpolationDone = onInterpolationDone;
  53688. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53689. _this._target = _this._effectiveTarget = target;
  53690. return _this;
  53691. }
  53692. InterpolateValueAction.prototype._prepare = function () {
  53693. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53694. this._property = this._getProperty(this.propertyPath);
  53695. };
  53696. InterpolateValueAction.prototype.execute = function () {
  53697. var _this = this;
  53698. var scene = this._actionManager.getScene();
  53699. var keys = [
  53700. {
  53701. frame: 0,
  53702. value: this._effectiveTarget[this._property]
  53703. }, {
  53704. frame: 100,
  53705. value: this.value
  53706. }
  53707. ];
  53708. var dataType;
  53709. if (typeof this.value === "number") {
  53710. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53711. }
  53712. else if (this.value instanceof BABYLON.Color3) {
  53713. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53714. }
  53715. else if (this.value instanceof BABYLON.Vector3) {
  53716. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53717. }
  53718. else if (this.value instanceof BABYLON.Matrix) {
  53719. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53720. }
  53721. else if (this.value instanceof BABYLON.Quaternion) {
  53722. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53723. }
  53724. else {
  53725. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53726. return;
  53727. }
  53728. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53729. animation.setKeys(keys);
  53730. if (this.stopOtherAnimations) {
  53731. scene.stopAnimation(this._effectiveTarget);
  53732. }
  53733. var wrapper = function () {
  53734. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53735. if (_this.onInterpolationDone) {
  53736. _this.onInterpolationDone();
  53737. }
  53738. };
  53739. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53740. };
  53741. InterpolateValueAction.prototype.serialize = function (parent) {
  53742. return _super.prototype._serialize.call(this, {
  53743. name: "InterpolateValueAction",
  53744. properties: [
  53745. BABYLON.Action._GetTargetProperty(this._target),
  53746. { name: "propertyPath", value: this.propertyPath },
  53747. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53748. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53749. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53750. ]
  53751. }, parent);
  53752. };
  53753. return InterpolateValueAction;
  53754. }(BABYLON.Action));
  53755. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53756. })(BABYLON || (BABYLON = {}));
  53757. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53758. var BABYLON;
  53759. (function (BABYLON) {
  53760. var SwitchBooleanAction = /** @class */ (function (_super) {
  53761. __extends(SwitchBooleanAction, _super);
  53762. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53763. var _this = _super.call(this, triggerOptions, condition) || this;
  53764. _this.propertyPath = propertyPath;
  53765. _this._target = _this._effectiveTarget = target;
  53766. return _this;
  53767. }
  53768. SwitchBooleanAction.prototype._prepare = function () {
  53769. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53770. this._property = this._getProperty(this.propertyPath);
  53771. };
  53772. SwitchBooleanAction.prototype.execute = function () {
  53773. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53774. };
  53775. SwitchBooleanAction.prototype.serialize = function (parent) {
  53776. return _super.prototype._serialize.call(this, {
  53777. name: "SwitchBooleanAction",
  53778. properties: [
  53779. BABYLON.Action._GetTargetProperty(this._target),
  53780. { name: "propertyPath", value: this.propertyPath }
  53781. ]
  53782. }, parent);
  53783. };
  53784. return SwitchBooleanAction;
  53785. }(BABYLON.Action));
  53786. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53787. var SetStateAction = /** @class */ (function (_super) {
  53788. __extends(SetStateAction, _super);
  53789. function SetStateAction(triggerOptions, target, value, condition) {
  53790. var _this = _super.call(this, triggerOptions, condition) || this;
  53791. _this.value = value;
  53792. _this._target = target;
  53793. return _this;
  53794. }
  53795. SetStateAction.prototype.execute = function () {
  53796. this._target.state = this.value;
  53797. };
  53798. SetStateAction.prototype.serialize = function (parent) {
  53799. return _super.prototype._serialize.call(this, {
  53800. name: "SetStateAction",
  53801. properties: [
  53802. BABYLON.Action._GetTargetProperty(this._target),
  53803. { name: "value", value: this.value }
  53804. ]
  53805. }, parent);
  53806. };
  53807. return SetStateAction;
  53808. }(BABYLON.Action));
  53809. BABYLON.SetStateAction = SetStateAction;
  53810. var SetValueAction = /** @class */ (function (_super) {
  53811. __extends(SetValueAction, _super);
  53812. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53813. var _this = _super.call(this, triggerOptions, condition) || this;
  53814. _this.propertyPath = propertyPath;
  53815. _this.value = value;
  53816. _this._target = _this._effectiveTarget = target;
  53817. return _this;
  53818. }
  53819. SetValueAction.prototype._prepare = function () {
  53820. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53821. this._property = this._getProperty(this.propertyPath);
  53822. };
  53823. SetValueAction.prototype.execute = function () {
  53824. this._effectiveTarget[this._property] = this.value;
  53825. if (this._target.markAsDirty) {
  53826. this._target.markAsDirty(this._property);
  53827. }
  53828. };
  53829. SetValueAction.prototype.serialize = function (parent) {
  53830. return _super.prototype._serialize.call(this, {
  53831. name: "SetValueAction",
  53832. properties: [
  53833. BABYLON.Action._GetTargetProperty(this._target),
  53834. { name: "propertyPath", value: this.propertyPath },
  53835. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53836. ]
  53837. }, parent);
  53838. };
  53839. return SetValueAction;
  53840. }(BABYLON.Action));
  53841. BABYLON.SetValueAction = SetValueAction;
  53842. var IncrementValueAction = /** @class */ (function (_super) {
  53843. __extends(IncrementValueAction, _super);
  53844. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53845. var _this = _super.call(this, triggerOptions, condition) || this;
  53846. _this.propertyPath = propertyPath;
  53847. _this.value = value;
  53848. _this._target = _this._effectiveTarget = target;
  53849. return _this;
  53850. }
  53851. IncrementValueAction.prototype._prepare = function () {
  53852. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53853. this._property = this._getProperty(this.propertyPath);
  53854. if (typeof this._effectiveTarget[this._property] !== "number") {
  53855. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53856. }
  53857. };
  53858. IncrementValueAction.prototype.execute = function () {
  53859. this._effectiveTarget[this._property] += this.value;
  53860. if (this._target.markAsDirty) {
  53861. this._target.markAsDirty(this._property);
  53862. }
  53863. };
  53864. IncrementValueAction.prototype.serialize = function (parent) {
  53865. return _super.prototype._serialize.call(this, {
  53866. name: "IncrementValueAction",
  53867. properties: [
  53868. BABYLON.Action._GetTargetProperty(this._target),
  53869. { name: "propertyPath", value: this.propertyPath },
  53870. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53871. ]
  53872. }, parent);
  53873. };
  53874. return IncrementValueAction;
  53875. }(BABYLON.Action));
  53876. BABYLON.IncrementValueAction = IncrementValueAction;
  53877. var PlayAnimationAction = /** @class */ (function (_super) {
  53878. __extends(PlayAnimationAction, _super);
  53879. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53880. var _this = _super.call(this, triggerOptions, condition) || this;
  53881. _this.from = from;
  53882. _this.to = to;
  53883. _this.loop = loop;
  53884. _this._target = target;
  53885. return _this;
  53886. }
  53887. PlayAnimationAction.prototype._prepare = function () {
  53888. };
  53889. PlayAnimationAction.prototype.execute = function () {
  53890. var scene = this._actionManager.getScene();
  53891. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53892. };
  53893. PlayAnimationAction.prototype.serialize = function (parent) {
  53894. return _super.prototype._serialize.call(this, {
  53895. name: "PlayAnimationAction",
  53896. properties: [
  53897. BABYLON.Action._GetTargetProperty(this._target),
  53898. { name: "from", value: String(this.from) },
  53899. { name: "to", value: String(this.to) },
  53900. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53901. ]
  53902. }, parent);
  53903. };
  53904. return PlayAnimationAction;
  53905. }(BABYLON.Action));
  53906. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53907. var StopAnimationAction = /** @class */ (function (_super) {
  53908. __extends(StopAnimationAction, _super);
  53909. function StopAnimationAction(triggerOptions, target, condition) {
  53910. var _this = _super.call(this, triggerOptions, condition) || this;
  53911. _this._target = target;
  53912. return _this;
  53913. }
  53914. StopAnimationAction.prototype._prepare = function () {
  53915. };
  53916. StopAnimationAction.prototype.execute = function () {
  53917. var scene = this._actionManager.getScene();
  53918. scene.stopAnimation(this._target);
  53919. };
  53920. StopAnimationAction.prototype.serialize = function (parent) {
  53921. return _super.prototype._serialize.call(this, {
  53922. name: "StopAnimationAction",
  53923. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53924. }, parent);
  53925. };
  53926. return StopAnimationAction;
  53927. }(BABYLON.Action));
  53928. BABYLON.StopAnimationAction = StopAnimationAction;
  53929. var DoNothingAction = /** @class */ (function (_super) {
  53930. __extends(DoNothingAction, _super);
  53931. function DoNothingAction(triggerOptions, condition) {
  53932. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53933. return _super.call(this, triggerOptions, condition) || this;
  53934. }
  53935. DoNothingAction.prototype.execute = function () {
  53936. };
  53937. DoNothingAction.prototype.serialize = function (parent) {
  53938. return _super.prototype._serialize.call(this, {
  53939. name: "DoNothingAction",
  53940. properties: []
  53941. }, parent);
  53942. };
  53943. return DoNothingAction;
  53944. }(BABYLON.Action));
  53945. BABYLON.DoNothingAction = DoNothingAction;
  53946. var CombineAction = /** @class */ (function (_super) {
  53947. __extends(CombineAction, _super);
  53948. function CombineAction(triggerOptions, children, condition) {
  53949. var _this = _super.call(this, triggerOptions, condition) || this;
  53950. _this.children = children;
  53951. return _this;
  53952. }
  53953. CombineAction.prototype._prepare = function () {
  53954. for (var index = 0; index < this.children.length; index++) {
  53955. this.children[index]._actionManager = this._actionManager;
  53956. this.children[index]._prepare();
  53957. }
  53958. };
  53959. CombineAction.prototype.execute = function (evt) {
  53960. for (var index = 0; index < this.children.length; index++) {
  53961. this.children[index].execute(evt);
  53962. }
  53963. };
  53964. CombineAction.prototype.serialize = function (parent) {
  53965. var serializationObject = _super.prototype._serialize.call(this, {
  53966. name: "CombineAction",
  53967. properties: [],
  53968. combine: []
  53969. }, parent);
  53970. for (var i = 0; i < this.children.length; i++) {
  53971. serializationObject.combine.push(this.children[i].serialize(null));
  53972. }
  53973. return serializationObject;
  53974. };
  53975. return CombineAction;
  53976. }(BABYLON.Action));
  53977. BABYLON.CombineAction = CombineAction;
  53978. var ExecuteCodeAction = /** @class */ (function (_super) {
  53979. __extends(ExecuteCodeAction, _super);
  53980. function ExecuteCodeAction(triggerOptions, func, condition) {
  53981. var _this = _super.call(this, triggerOptions, condition) || this;
  53982. _this.func = func;
  53983. return _this;
  53984. }
  53985. ExecuteCodeAction.prototype.execute = function (evt) {
  53986. this.func(evt);
  53987. };
  53988. return ExecuteCodeAction;
  53989. }(BABYLON.Action));
  53990. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53991. var SetParentAction = /** @class */ (function (_super) {
  53992. __extends(SetParentAction, _super);
  53993. function SetParentAction(triggerOptions, target, parent, condition) {
  53994. var _this = _super.call(this, triggerOptions, condition) || this;
  53995. _this._target = target;
  53996. _this._parent = parent;
  53997. return _this;
  53998. }
  53999. SetParentAction.prototype._prepare = function () {
  54000. };
  54001. SetParentAction.prototype.execute = function () {
  54002. if (this._target.parent === this._parent) {
  54003. return;
  54004. }
  54005. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54006. invertParentWorldMatrix.invert();
  54007. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54008. this._target.parent = this._parent;
  54009. };
  54010. SetParentAction.prototype.serialize = function (parent) {
  54011. return _super.prototype._serialize.call(this, {
  54012. name: "SetParentAction",
  54013. properties: [
  54014. BABYLON.Action._GetTargetProperty(this._target),
  54015. BABYLON.Action._GetTargetProperty(this._parent),
  54016. ]
  54017. }, parent);
  54018. };
  54019. return SetParentAction;
  54020. }(BABYLON.Action));
  54021. BABYLON.SetParentAction = SetParentAction;
  54022. var PlaySoundAction = /** @class */ (function (_super) {
  54023. __extends(PlaySoundAction, _super);
  54024. function PlaySoundAction(triggerOptions, sound, condition) {
  54025. var _this = _super.call(this, triggerOptions, condition) || this;
  54026. _this._sound = sound;
  54027. return _this;
  54028. }
  54029. PlaySoundAction.prototype._prepare = function () {
  54030. };
  54031. PlaySoundAction.prototype.execute = function () {
  54032. if (this._sound !== undefined)
  54033. this._sound.play();
  54034. };
  54035. PlaySoundAction.prototype.serialize = function (parent) {
  54036. return _super.prototype._serialize.call(this, {
  54037. name: "PlaySoundAction",
  54038. properties: [{ name: "sound", value: this._sound.name }]
  54039. }, parent);
  54040. };
  54041. return PlaySoundAction;
  54042. }(BABYLON.Action));
  54043. BABYLON.PlaySoundAction = PlaySoundAction;
  54044. var StopSoundAction = /** @class */ (function (_super) {
  54045. __extends(StopSoundAction, _super);
  54046. function StopSoundAction(triggerOptions, sound, condition) {
  54047. var _this = _super.call(this, triggerOptions, condition) || this;
  54048. _this._sound = sound;
  54049. return _this;
  54050. }
  54051. StopSoundAction.prototype._prepare = function () {
  54052. };
  54053. StopSoundAction.prototype.execute = function () {
  54054. if (this._sound !== undefined)
  54055. this._sound.stop();
  54056. };
  54057. StopSoundAction.prototype.serialize = function (parent) {
  54058. return _super.prototype._serialize.call(this, {
  54059. name: "StopSoundAction",
  54060. properties: [{ name: "sound", value: this._sound.name }]
  54061. }, parent);
  54062. };
  54063. return StopSoundAction;
  54064. }(BABYLON.Action));
  54065. BABYLON.StopSoundAction = StopSoundAction;
  54066. })(BABYLON || (BABYLON = {}));
  54067. //# sourceMappingURL=babylon.directActions.js.map
  54068. var BABYLON;
  54069. (function (BABYLON) {
  54070. var SpriteManager = /** @class */ (function () {
  54071. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54072. if (epsilon === void 0) { epsilon = 0.01; }
  54073. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54074. this.name = name;
  54075. this.sprites = new Array();
  54076. this.renderingGroupId = 0;
  54077. this.layerMask = 0x0FFFFFFF;
  54078. this.fogEnabled = true;
  54079. this.isPickable = false;
  54080. /**
  54081. * An event triggered when the manager is disposed.
  54082. */
  54083. this.onDisposeObservable = new BABYLON.Observable();
  54084. this._vertexBuffers = {};
  54085. this._capacity = capacity;
  54086. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54087. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54088. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54089. if (cellSize.width && cellSize.height) {
  54090. this.cellWidth = cellSize.width;
  54091. this.cellHeight = cellSize.height;
  54092. }
  54093. else if (cellSize !== undefined) {
  54094. this.cellWidth = cellSize;
  54095. this.cellHeight = cellSize;
  54096. }
  54097. else {
  54098. return;
  54099. }
  54100. this._epsilon = epsilon;
  54101. this._scene = scene;
  54102. this._scene.spriteManagers.push(this);
  54103. var indices = [];
  54104. var index = 0;
  54105. for (var count = 0; count < capacity; count++) {
  54106. indices.push(index);
  54107. indices.push(index + 1);
  54108. indices.push(index + 2);
  54109. indices.push(index);
  54110. indices.push(index + 2);
  54111. indices.push(index + 3);
  54112. index += 4;
  54113. }
  54114. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54115. // VBO
  54116. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54117. this._vertexData = new Float32Array(capacity * 16 * 4);
  54118. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54119. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54120. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54121. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54122. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54123. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54124. this._vertexBuffers["options"] = options;
  54125. this._vertexBuffers["cellInfo"] = cellInfo;
  54126. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54127. // Effects
  54128. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54129. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54130. }
  54131. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54132. set: function (callback) {
  54133. if (this._onDisposeObserver) {
  54134. this.onDisposeObservable.remove(this._onDisposeObserver);
  54135. }
  54136. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54137. },
  54138. enumerable: true,
  54139. configurable: true
  54140. });
  54141. Object.defineProperty(SpriteManager.prototype, "texture", {
  54142. get: function () {
  54143. return this._spriteTexture;
  54144. },
  54145. set: function (value) {
  54146. this._spriteTexture = value;
  54147. },
  54148. enumerable: true,
  54149. configurable: true
  54150. });
  54151. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54152. var arrayOffset = index * 16;
  54153. if (offsetX === 0)
  54154. offsetX = this._epsilon;
  54155. else if (offsetX === 1)
  54156. offsetX = 1 - this._epsilon;
  54157. if (offsetY === 0)
  54158. offsetY = this._epsilon;
  54159. else if (offsetY === 1)
  54160. offsetY = 1 - this._epsilon;
  54161. this._vertexData[arrayOffset] = sprite.position.x;
  54162. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54163. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54164. this._vertexData[arrayOffset + 3] = sprite.angle;
  54165. this._vertexData[arrayOffset + 4] = sprite.width;
  54166. this._vertexData[arrayOffset + 5] = sprite.height;
  54167. this._vertexData[arrayOffset + 6] = offsetX;
  54168. this._vertexData[arrayOffset + 7] = offsetY;
  54169. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54170. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54171. var offset = (sprite.cellIndex / rowSize) >> 0;
  54172. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54173. this._vertexData[arrayOffset + 11] = offset;
  54174. // Color
  54175. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54176. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54177. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54178. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54179. };
  54180. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54181. var count = Math.min(this._capacity, this.sprites.length);
  54182. var min = BABYLON.Vector3.Zero();
  54183. var max = BABYLON.Vector3.Zero();
  54184. var distance = Number.MAX_VALUE;
  54185. var currentSprite = null;
  54186. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54187. var cameraView = camera.getViewMatrix();
  54188. for (var index = 0; index < count; index++) {
  54189. var sprite = this.sprites[index];
  54190. if (!sprite) {
  54191. continue;
  54192. }
  54193. if (predicate) {
  54194. if (!predicate(sprite)) {
  54195. continue;
  54196. }
  54197. }
  54198. else if (!sprite.isPickable) {
  54199. continue;
  54200. }
  54201. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54202. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54203. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54204. if (ray.intersectsBoxMinMax(min, max)) {
  54205. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54206. if (distance > currentDistance) {
  54207. distance = currentDistance;
  54208. currentSprite = sprite;
  54209. if (fastCheck) {
  54210. break;
  54211. }
  54212. }
  54213. }
  54214. }
  54215. if (currentSprite) {
  54216. var result = new BABYLON.PickingInfo();
  54217. result.hit = true;
  54218. result.pickedSprite = currentSprite;
  54219. result.distance = distance;
  54220. return result;
  54221. }
  54222. return null;
  54223. };
  54224. SpriteManager.prototype.render = function () {
  54225. // Check
  54226. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54227. return;
  54228. var engine = this._scene.getEngine();
  54229. var baseSize = this._spriteTexture.getBaseSize();
  54230. // Sprites
  54231. var deltaTime = engine.getDeltaTime();
  54232. var max = Math.min(this._capacity, this.sprites.length);
  54233. var rowSize = baseSize.width / this.cellWidth;
  54234. var offset = 0;
  54235. for (var index = 0; index < max; index++) {
  54236. var sprite = this.sprites[index];
  54237. if (!sprite) {
  54238. continue;
  54239. }
  54240. sprite._animate(deltaTime);
  54241. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54242. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54243. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54244. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54245. }
  54246. this._buffer.update(this._vertexData);
  54247. // Render
  54248. var effect = this._effectBase;
  54249. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54250. effect = this._effectFog;
  54251. }
  54252. engine.enableEffect(effect);
  54253. var viewMatrix = this._scene.getViewMatrix();
  54254. effect.setTexture("diffuseSampler", this._spriteTexture);
  54255. effect.setMatrix("view", viewMatrix);
  54256. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54257. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54258. // Fog
  54259. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54260. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54261. effect.setColor3("vFogColor", this._scene.fogColor);
  54262. }
  54263. // VBOs
  54264. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54265. // Draw order
  54266. engine.setDepthFunctionToLessOrEqual();
  54267. effect.setBool("alphaTest", true);
  54268. engine.setColorWrite(false);
  54269. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54270. engine.setColorWrite(true);
  54271. effect.setBool("alphaTest", false);
  54272. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54273. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54274. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54275. };
  54276. SpriteManager.prototype.dispose = function () {
  54277. if (this._buffer) {
  54278. this._buffer.dispose();
  54279. this._buffer = null;
  54280. }
  54281. if (this._indexBuffer) {
  54282. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54283. this._indexBuffer = null;
  54284. }
  54285. if (this._spriteTexture) {
  54286. this._spriteTexture.dispose();
  54287. this._spriteTexture = null;
  54288. }
  54289. // Remove from scene
  54290. var index = this._scene.spriteManagers.indexOf(this);
  54291. this._scene.spriteManagers.splice(index, 1);
  54292. // Callback
  54293. this.onDisposeObservable.notifyObservers(this);
  54294. this.onDisposeObservable.clear();
  54295. };
  54296. return SpriteManager;
  54297. }());
  54298. BABYLON.SpriteManager = SpriteManager;
  54299. })(BABYLON || (BABYLON = {}));
  54300. //# sourceMappingURL=babylon.spriteManager.js.map
  54301. var BABYLON;
  54302. (function (BABYLON) {
  54303. var Sprite = /** @class */ (function () {
  54304. function Sprite(name, manager) {
  54305. this.name = name;
  54306. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54307. this.width = 1.0;
  54308. this.height = 1.0;
  54309. this.angle = 0;
  54310. this.cellIndex = 0;
  54311. this.invertU = 0;
  54312. this.invertV = 0;
  54313. this.animations = new Array();
  54314. this.isPickable = false;
  54315. this._animationStarted = false;
  54316. this._loopAnimation = false;
  54317. this._fromIndex = 0;
  54318. this._toIndex = 0;
  54319. this._delay = 0;
  54320. this._direction = 1;
  54321. this._time = 0;
  54322. this._manager = manager;
  54323. this._manager.sprites.push(this);
  54324. this.position = BABYLON.Vector3.Zero();
  54325. }
  54326. Object.defineProperty(Sprite.prototype, "size", {
  54327. get: function () {
  54328. return this.width;
  54329. },
  54330. set: function (value) {
  54331. this.width = value;
  54332. this.height = value;
  54333. },
  54334. enumerable: true,
  54335. configurable: true
  54336. });
  54337. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54338. this._fromIndex = from;
  54339. this._toIndex = to;
  54340. this._loopAnimation = loop;
  54341. this._delay = delay;
  54342. this._animationStarted = true;
  54343. this._direction = from < to ? 1 : -1;
  54344. this.cellIndex = from;
  54345. this._time = 0;
  54346. this._onAnimationEnd = onAnimationEnd;
  54347. };
  54348. Sprite.prototype.stopAnimation = function () {
  54349. this._animationStarted = false;
  54350. };
  54351. Sprite.prototype._animate = function (deltaTime) {
  54352. if (!this._animationStarted)
  54353. return;
  54354. this._time += deltaTime;
  54355. if (this._time > this._delay) {
  54356. this._time = this._time % this._delay;
  54357. this.cellIndex += this._direction;
  54358. if (this.cellIndex > this._toIndex) {
  54359. if (this._loopAnimation) {
  54360. this.cellIndex = this._fromIndex;
  54361. }
  54362. else {
  54363. this.cellIndex = this._toIndex;
  54364. this._animationStarted = false;
  54365. if (this._onAnimationEnd) {
  54366. this._onAnimationEnd();
  54367. }
  54368. if (this.disposeWhenFinishedAnimating) {
  54369. this.dispose();
  54370. }
  54371. }
  54372. }
  54373. }
  54374. };
  54375. Sprite.prototype.dispose = function () {
  54376. for (var i = 0; i < this._manager.sprites.length; i++) {
  54377. if (this._manager.sprites[i] == this) {
  54378. this._manager.sprites.splice(i, 1);
  54379. }
  54380. }
  54381. };
  54382. return Sprite;
  54383. }());
  54384. BABYLON.Sprite = Sprite;
  54385. })(BABYLON || (BABYLON = {}));
  54386. //# sourceMappingURL=babylon.sprite.js.map
  54387. var BABYLON;
  54388. (function (BABYLON) {
  54389. var IntersectionInfo = /** @class */ (function () {
  54390. function IntersectionInfo(bu, bv, distance) {
  54391. this.bu = bu;
  54392. this.bv = bv;
  54393. this.distance = distance;
  54394. this.faceId = 0;
  54395. this.subMeshId = 0;
  54396. }
  54397. return IntersectionInfo;
  54398. }());
  54399. BABYLON.IntersectionInfo = IntersectionInfo;
  54400. var PickingInfo = /** @class */ (function () {
  54401. function PickingInfo() {
  54402. this.hit = false;
  54403. this.distance = 0;
  54404. this.pickedPoint = null;
  54405. this.pickedMesh = null;
  54406. this.bu = 0;
  54407. this.bv = 0;
  54408. this.faceId = -1;
  54409. this.subMeshId = 0;
  54410. this.pickedSprite = null;
  54411. }
  54412. // Methods
  54413. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54414. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54415. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54416. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54417. return null;
  54418. }
  54419. var indices = this.pickedMesh.getIndices();
  54420. if (!indices) {
  54421. return null;
  54422. }
  54423. var result;
  54424. if (useVerticesNormals) {
  54425. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54426. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54427. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54428. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54429. normal0 = normal0.scale(this.bu);
  54430. normal1 = normal1.scale(this.bv);
  54431. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54432. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54433. }
  54434. else {
  54435. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54436. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54437. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54438. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54439. var p1p2 = vertex1.subtract(vertex2);
  54440. var p3p2 = vertex3.subtract(vertex2);
  54441. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54442. }
  54443. if (useWorldCoordinates) {
  54444. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54445. }
  54446. return BABYLON.Vector3.Normalize(result);
  54447. };
  54448. PickingInfo.prototype.getTextureCoordinates = function () {
  54449. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54450. return null;
  54451. }
  54452. var indices = this.pickedMesh.getIndices();
  54453. if (!indices) {
  54454. return null;
  54455. }
  54456. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54457. if (!uvs) {
  54458. return null;
  54459. }
  54460. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54461. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54462. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54463. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54464. uv1 = uv1.scale(this.bu);
  54465. uv2 = uv2.scale(this.bv);
  54466. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54467. };
  54468. return PickingInfo;
  54469. }());
  54470. BABYLON.PickingInfo = PickingInfo;
  54471. })(BABYLON || (BABYLON = {}));
  54472. //# sourceMappingURL=babylon.pickingInfo.js.map
  54473. var BABYLON;
  54474. (function (BABYLON) {
  54475. var Ray = /** @class */ (function () {
  54476. function Ray(origin, direction, length) {
  54477. if (length === void 0) { length = Number.MAX_VALUE; }
  54478. this.origin = origin;
  54479. this.direction = direction;
  54480. this.length = length;
  54481. }
  54482. // Methods
  54483. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54484. var d = 0.0;
  54485. var maxValue = Number.MAX_VALUE;
  54486. var inv;
  54487. var min;
  54488. var max;
  54489. var temp;
  54490. if (Math.abs(this.direction.x) < 0.0000001) {
  54491. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54492. return false;
  54493. }
  54494. }
  54495. else {
  54496. inv = 1.0 / this.direction.x;
  54497. min = (minimum.x - this.origin.x) * inv;
  54498. max = (maximum.x - this.origin.x) * inv;
  54499. if (max === -Infinity) {
  54500. max = Infinity;
  54501. }
  54502. if (min > max) {
  54503. temp = min;
  54504. min = max;
  54505. max = temp;
  54506. }
  54507. d = Math.max(min, d);
  54508. maxValue = Math.min(max, maxValue);
  54509. if (d > maxValue) {
  54510. return false;
  54511. }
  54512. }
  54513. if (Math.abs(this.direction.y) < 0.0000001) {
  54514. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54515. return false;
  54516. }
  54517. }
  54518. else {
  54519. inv = 1.0 / this.direction.y;
  54520. min = (minimum.y - this.origin.y) * inv;
  54521. max = (maximum.y - this.origin.y) * inv;
  54522. if (max === -Infinity) {
  54523. max = Infinity;
  54524. }
  54525. if (min > max) {
  54526. temp = min;
  54527. min = max;
  54528. max = temp;
  54529. }
  54530. d = Math.max(min, d);
  54531. maxValue = Math.min(max, maxValue);
  54532. if (d > maxValue) {
  54533. return false;
  54534. }
  54535. }
  54536. if (Math.abs(this.direction.z) < 0.0000001) {
  54537. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54538. return false;
  54539. }
  54540. }
  54541. else {
  54542. inv = 1.0 / this.direction.z;
  54543. min = (minimum.z - this.origin.z) * inv;
  54544. max = (maximum.z - this.origin.z) * inv;
  54545. if (max === -Infinity) {
  54546. max = Infinity;
  54547. }
  54548. if (min > max) {
  54549. temp = min;
  54550. min = max;
  54551. max = temp;
  54552. }
  54553. d = Math.max(min, d);
  54554. maxValue = Math.min(max, maxValue);
  54555. if (d > maxValue) {
  54556. return false;
  54557. }
  54558. }
  54559. return true;
  54560. };
  54561. Ray.prototype.intersectsBox = function (box) {
  54562. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54563. };
  54564. Ray.prototype.intersectsSphere = function (sphere) {
  54565. var x = sphere.center.x - this.origin.x;
  54566. var y = sphere.center.y - this.origin.y;
  54567. var z = sphere.center.z - this.origin.z;
  54568. var pyth = (x * x) + (y * y) + (z * z);
  54569. var rr = sphere.radius * sphere.radius;
  54570. if (pyth <= rr) {
  54571. return true;
  54572. }
  54573. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54574. if (dot < 0.0) {
  54575. return false;
  54576. }
  54577. var temp = pyth - (dot * dot);
  54578. return temp <= rr;
  54579. };
  54580. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54581. if (!this._edge1) {
  54582. this._edge1 = BABYLON.Vector3.Zero();
  54583. this._edge2 = BABYLON.Vector3.Zero();
  54584. this._pvec = BABYLON.Vector3.Zero();
  54585. this._tvec = BABYLON.Vector3.Zero();
  54586. this._qvec = BABYLON.Vector3.Zero();
  54587. }
  54588. vertex1.subtractToRef(vertex0, this._edge1);
  54589. vertex2.subtractToRef(vertex0, this._edge2);
  54590. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54591. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54592. if (det === 0) {
  54593. return null;
  54594. }
  54595. var invdet = 1 / det;
  54596. this.origin.subtractToRef(vertex0, this._tvec);
  54597. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54598. if (bu < 0 || bu > 1.0) {
  54599. return null;
  54600. }
  54601. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54602. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54603. if (bv < 0 || bu + bv > 1.0) {
  54604. return null;
  54605. }
  54606. //check if the distance is longer than the predefined length.
  54607. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54608. if (distance > this.length) {
  54609. return null;
  54610. }
  54611. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54612. };
  54613. Ray.prototype.intersectsPlane = function (plane) {
  54614. var distance;
  54615. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54616. if (Math.abs(result1) < 9.99999997475243E-07) {
  54617. return null;
  54618. }
  54619. else {
  54620. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54621. distance = (-plane.d - result2) / result1;
  54622. if (distance < 0.0) {
  54623. if (distance < -9.99999997475243E-07) {
  54624. return null;
  54625. }
  54626. else {
  54627. return 0;
  54628. }
  54629. }
  54630. return distance;
  54631. }
  54632. };
  54633. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54634. var tm = BABYLON.Tmp.Matrix[0];
  54635. mesh.getWorldMatrix().invertToRef(tm);
  54636. if (this._tmpRay) {
  54637. Ray.TransformToRef(this, tm, this._tmpRay);
  54638. }
  54639. else {
  54640. this._tmpRay = Ray.Transform(this, tm);
  54641. }
  54642. return mesh.intersects(this._tmpRay, fastCheck);
  54643. };
  54644. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54645. if (results) {
  54646. results.length = 0;
  54647. }
  54648. else {
  54649. results = [];
  54650. }
  54651. for (var i = 0; i < meshes.length; i++) {
  54652. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54653. if (pickInfo.hit) {
  54654. results.push(pickInfo);
  54655. }
  54656. }
  54657. results.sort(this._comparePickingInfo);
  54658. return results;
  54659. };
  54660. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54661. if (pickingInfoA.distance < pickingInfoB.distance) {
  54662. return -1;
  54663. }
  54664. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54665. return 1;
  54666. }
  54667. else {
  54668. return 0;
  54669. }
  54670. };
  54671. /**
  54672. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54673. * @param sega the first point of the segment to test the intersection against
  54674. * @param segb the second point of the segment to test the intersection against
  54675. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54676. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54677. */
  54678. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54679. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54680. var u = segb.subtract(sega);
  54681. var v = rsegb.subtract(this.origin);
  54682. var w = sega.subtract(this.origin);
  54683. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54684. var b = BABYLON.Vector3.Dot(u, v);
  54685. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54686. var d = BABYLON.Vector3.Dot(u, w);
  54687. var e = BABYLON.Vector3.Dot(v, w);
  54688. var D = a * c - b * b; // always >= 0
  54689. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54690. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54691. // compute the line parameters of the two closest points
  54692. if (D < Ray.smallnum) { // the lines are almost parallel
  54693. sN = 0.0; // force using point P0 on segment S1
  54694. sD = 1.0; // to prevent possible division by 0.0 later
  54695. tN = e;
  54696. tD = c;
  54697. }
  54698. else { // get the closest points on the infinite lines
  54699. sN = (b * e - c * d);
  54700. tN = (a * e - b * d);
  54701. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54702. sN = 0.0;
  54703. tN = e;
  54704. tD = c;
  54705. }
  54706. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54707. sN = sD;
  54708. tN = e + b;
  54709. tD = c;
  54710. }
  54711. }
  54712. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54713. tN = 0.0;
  54714. // recompute sc for this edge
  54715. if (-d < 0.0) {
  54716. sN = 0.0;
  54717. }
  54718. else if (-d > a)
  54719. sN = sD;
  54720. else {
  54721. sN = -d;
  54722. sD = a;
  54723. }
  54724. }
  54725. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54726. tN = tD;
  54727. // recompute sc for this edge
  54728. if ((-d + b) < 0.0) {
  54729. sN = 0;
  54730. }
  54731. else if ((-d + b) > a) {
  54732. sN = sD;
  54733. }
  54734. else {
  54735. sN = (-d + b);
  54736. sD = a;
  54737. }
  54738. }
  54739. // finally do the division to get sc and tc
  54740. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54741. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54742. // get the difference of the two closest points
  54743. var qtc = v.multiplyByFloats(tc, tc, tc);
  54744. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54745. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54746. if (isIntersected) {
  54747. return qtc.length();
  54748. }
  54749. return -1;
  54750. };
  54751. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54752. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54753. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54754. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54755. this.direction.normalize();
  54756. return this;
  54757. };
  54758. // Statics
  54759. Ray.Zero = function () {
  54760. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54761. };
  54762. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54763. var result = Ray.Zero();
  54764. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54765. };
  54766. /**
  54767. * 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
  54768. * transformed to the given world matrix.
  54769. * @param origin The origin point
  54770. * @param end The end point
  54771. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54772. */
  54773. Ray.CreateNewFromTo = function (origin, end, world) {
  54774. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54775. var direction = end.subtract(origin);
  54776. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54777. direction.normalize();
  54778. return Ray.Transform(new Ray(origin, direction, length), world);
  54779. };
  54780. Ray.Transform = function (ray, matrix) {
  54781. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54782. Ray.TransformToRef(ray, matrix, result);
  54783. return result;
  54784. };
  54785. Ray.TransformToRef = function (ray, matrix, result) {
  54786. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54787. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54788. result.length = ray.length;
  54789. var dir = result.direction;
  54790. var len = dir.length();
  54791. if (!(len === 0 || len === 1)) {
  54792. var num = 1.0 / len;
  54793. dir.x *= num;
  54794. dir.y *= num;
  54795. dir.z *= num;
  54796. result.length *= len;
  54797. }
  54798. };
  54799. Ray.smallnum = 0.00000001;
  54800. Ray.rayl = 10e8;
  54801. return Ray;
  54802. }());
  54803. BABYLON.Ray = Ray;
  54804. })(BABYLON || (BABYLON = {}));
  54805. //# sourceMappingURL=babylon.ray.js.map
  54806. var BABYLON;
  54807. (function (BABYLON) {
  54808. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54809. if (boxMin.x > sphereCenter.x + sphereRadius)
  54810. return false;
  54811. if (sphereCenter.x - sphereRadius > boxMax.x)
  54812. return false;
  54813. if (boxMin.y > sphereCenter.y + sphereRadius)
  54814. return false;
  54815. if (sphereCenter.y - sphereRadius > boxMax.y)
  54816. return false;
  54817. if (boxMin.z > sphereCenter.z + sphereRadius)
  54818. return false;
  54819. if (sphereCenter.z - sphereRadius > boxMax.z)
  54820. return false;
  54821. return true;
  54822. };
  54823. var getLowestRoot = (function () {
  54824. var result = { root: 0, found: false };
  54825. return function (a, b, c, maxR) {
  54826. result.root = 0;
  54827. result.found = false;
  54828. var determinant = b * b - 4.0 * a * c;
  54829. if (determinant < 0)
  54830. return result;
  54831. var sqrtD = Math.sqrt(determinant);
  54832. var r1 = (-b - sqrtD) / (2.0 * a);
  54833. var r2 = (-b + sqrtD) / (2.0 * a);
  54834. if (r1 > r2) {
  54835. var temp = r2;
  54836. r2 = r1;
  54837. r1 = temp;
  54838. }
  54839. if (r1 > 0 && r1 < maxR) {
  54840. result.root = r1;
  54841. result.found = true;
  54842. return result;
  54843. }
  54844. if (r2 > 0 && r2 < maxR) {
  54845. result.root = r2;
  54846. result.found = true;
  54847. return result;
  54848. }
  54849. return result;
  54850. };
  54851. })();
  54852. var Collider = /** @class */ (function () {
  54853. function Collider() {
  54854. this._collisionPoint = BABYLON.Vector3.Zero();
  54855. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54856. this._tempVector = BABYLON.Vector3.Zero();
  54857. this._tempVector2 = BABYLON.Vector3.Zero();
  54858. this._tempVector3 = BABYLON.Vector3.Zero();
  54859. this._tempVector4 = BABYLON.Vector3.Zero();
  54860. this._edge = BABYLON.Vector3.Zero();
  54861. this._baseToVertex = BABYLON.Vector3.Zero();
  54862. this._destinationPoint = BABYLON.Vector3.Zero();
  54863. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54864. this._displacementVector = BABYLON.Vector3.Zero();
  54865. this._radius = BABYLON.Vector3.One();
  54866. this._retry = 0;
  54867. this._basePointWorld = BABYLON.Vector3.Zero();
  54868. this._velocityWorld = BABYLON.Vector3.Zero();
  54869. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54870. this._collisionMask = -1;
  54871. }
  54872. Object.defineProperty(Collider.prototype, "collisionMask", {
  54873. get: function () {
  54874. return this._collisionMask;
  54875. },
  54876. set: function (mask) {
  54877. this._collisionMask = !isNaN(mask) ? mask : -1;
  54878. },
  54879. enumerable: true,
  54880. configurable: true
  54881. });
  54882. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54883. /**
  54884. * Gets the plane normal used to compute the sliding response (in local space)
  54885. */
  54886. get: function () {
  54887. return this._slidePlaneNormal;
  54888. },
  54889. enumerable: true,
  54890. configurable: true
  54891. });
  54892. // Methods
  54893. Collider.prototype._initialize = function (source, dir, e) {
  54894. this._velocity = dir;
  54895. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54896. this._basePoint = source;
  54897. source.multiplyToRef(this._radius, this._basePointWorld);
  54898. dir.multiplyToRef(this._radius, this._velocityWorld);
  54899. this._velocityWorldLength = this._velocityWorld.length();
  54900. this._epsilon = e;
  54901. this.collisionFound = false;
  54902. };
  54903. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54904. pa.subtractToRef(point, this._tempVector);
  54905. pb.subtractToRef(point, this._tempVector2);
  54906. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54907. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54908. if (d < 0)
  54909. return false;
  54910. pc.subtractToRef(point, this._tempVector3);
  54911. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54912. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54913. if (d < 0)
  54914. return false;
  54915. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54916. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54917. return d >= 0;
  54918. };
  54919. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54920. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54921. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54922. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54923. return false;
  54924. }
  54925. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54926. return false;
  54927. return true;
  54928. };
  54929. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54930. var t0;
  54931. var embeddedInPlane = false;
  54932. //defensive programming, actually not needed.
  54933. if (!trianglePlaneArray) {
  54934. trianglePlaneArray = [];
  54935. }
  54936. if (!trianglePlaneArray[faceIndex]) {
  54937. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54938. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54939. }
  54940. var trianglePlane = trianglePlaneArray[faceIndex];
  54941. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54942. return;
  54943. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54944. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54945. if (normalDotVelocity == 0) {
  54946. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54947. return;
  54948. embeddedInPlane = true;
  54949. t0 = 0;
  54950. }
  54951. else {
  54952. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54953. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54954. if (t0 > t1) {
  54955. var temp = t1;
  54956. t1 = t0;
  54957. t0 = temp;
  54958. }
  54959. if (t0 > 1.0 || t1 < 0.0)
  54960. return;
  54961. if (t0 < 0)
  54962. t0 = 0;
  54963. if (t0 > 1.0)
  54964. t0 = 1.0;
  54965. }
  54966. this._collisionPoint.copyFromFloats(0, 0, 0);
  54967. var found = false;
  54968. var t = 1.0;
  54969. if (!embeddedInPlane) {
  54970. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54971. this._velocity.scaleToRef(t0, this._tempVector);
  54972. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54973. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54974. found = true;
  54975. t = t0;
  54976. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54977. }
  54978. }
  54979. if (!found) {
  54980. var velocitySquaredLength = this._velocity.lengthSquared();
  54981. var a = velocitySquaredLength;
  54982. this._basePoint.subtractToRef(p1, this._tempVector);
  54983. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54984. var c = this._tempVector.lengthSquared() - 1.0;
  54985. var lowestRoot = getLowestRoot(a, b, c, t);
  54986. if (lowestRoot.found) {
  54987. t = lowestRoot.root;
  54988. found = true;
  54989. this._collisionPoint.copyFrom(p1);
  54990. }
  54991. this._basePoint.subtractToRef(p2, this._tempVector);
  54992. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54993. c = this._tempVector.lengthSquared() - 1.0;
  54994. lowestRoot = getLowestRoot(a, b, c, t);
  54995. if (lowestRoot.found) {
  54996. t = lowestRoot.root;
  54997. found = true;
  54998. this._collisionPoint.copyFrom(p2);
  54999. }
  55000. this._basePoint.subtractToRef(p3, this._tempVector);
  55001. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55002. c = this._tempVector.lengthSquared() - 1.0;
  55003. lowestRoot = getLowestRoot(a, b, c, t);
  55004. if (lowestRoot.found) {
  55005. t = lowestRoot.root;
  55006. found = true;
  55007. this._collisionPoint.copyFrom(p3);
  55008. }
  55009. p2.subtractToRef(p1, this._edge);
  55010. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55011. var edgeSquaredLength = this._edge.lengthSquared();
  55012. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55013. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55014. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55015. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55016. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55017. lowestRoot = getLowestRoot(a, b, c, t);
  55018. if (lowestRoot.found) {
  55019. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55020. if (f >= 0.0 && f <= 1.0) {
  55021. t = lowestRoot.root;
  55022. found = true;
  55023. this._edge.scaleInPlace(f);
  55024. p1.addToRef(this._edge, this._collisionPoint);
  55025. }
  55026. }
  55027. p3.subtractToRef(p2, this._edge);
  55028. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55029. edgeSquaredLength = this._edge.lengthSquared();
  55030. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55031. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55032. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55033. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55034. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55035. lowestRoot = getLowestRoot(a, b, c, t);
  55036. if (lowestRoot.found) {
  55037. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55038. if (f >= 0.0 && f <= 1.0) {
  55039. t = lowestRoot.root;
  55040. found = true;
  55041. this._edge.scaleInPlace(f);
  55042. p2.addToRef(this._edge, this._collisionPoint);
  55043. }
  55044. }
  55045. p1.subtractToRef(p3, this._edge);
  55046. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55047. edgeSquaredLength = this._edge.lengthSquared();
  55048. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55049. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55050. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55051. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55052. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55053. lowestRoot = getLowestRoot(a, b, c, t);
  55054. if (lowestRoot.found) {
  55055. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55056. if (f >= 0.0 && f <= 1.0) {
  55057. t = lowestRoot.root;
  55058. found = true;
  55059. this._edge.scaleInPlace(f);
  55060. p3.addToRef(this._edge, this._collisionPoint);
  55061. }
  55062. }
  55063. }
  55064. if (found) {
  55065. var distToCollision = t * this._velocity.length();
  55066. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55067. if (!this.intersectionPoint) {
  55068. this.intersectionPoint = this._collisionPoint.clone();
  55069. }
  55070. else {
  55071. this.intersectionPoint.copyFrom(this._collisionPoint);
  55072. }
  55073. this._nearestDistance = distToCollision;
  55074. this.collisionFound = true;
  55075. }
  55076. }
  55077. };
  55078. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55079. for (var i = indexStart; i < indexEnd; i += 3) {
  55080. var p1 = pts[indices[i] - decal];
  55081. var p2 = pts[indices[i + 1] - decal];
  55082. var p3 = pts[indices[i + 2] - decal];
  55083. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55084. }
  55085. };
  55086. Collider.prototype._getResponse = function (pos, vel) {
  55087. pos.addToRef(vel, this._destinationPoint);
  55088. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55089. this._basePoint.addToRef(vel, pos);
  55090. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55091. this._slidePlaneNormal.normalize();
  55092. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55093. pos.addInPlace(this._displacementVector);
  55094. this.intersectionPoint.addInPlace(this._displacementVector);
  55095. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55096. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55097. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55098. };
  55099. return Collider;
  55100. }());
  55101. BABYLON.Collider = Collider;
  55102. })(BABYLON || (BABYLON = {}));
  55103. //# sourceMappingURL=babylon.collider.js.map
  55104. var BABYLON;
  55105. (function (BABYLON) {
  55106. //WebWorker code will be inserted to this variable.
  55107. BABYLON.CollisionWorker = "";
  55108. /** Defines supported task for worker process */
  55109. var WorkerTaskType;
  55110. (function (WorkerTaskType) {
  55111. /** Initialization */
  55112. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55113. /** Update of geometry */
  55114. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55115. /** Evaluate collision */
  55116. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55117. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55118. /** Defines kind of replies returned by worker */
  55119. var WorkerReplyType;
  55120. (function (WorkerReplyType) {
  55121. /** Success */
  55122. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55123. /** Unkown error */
  55124. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55125. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55126. var CollisionCoordinatorWorker = /** @class */ (function () {
  55127. function CollisionCoordinatorWorker() {
  55128. var _this = this;
  55129. this._scaledPosition = BABYLON.Vector3.Zero();
  55130. this._scaledVelocity = BABYLON.Vector3.Zero();
  55131. this.onMeshUpdated = function (transformNode) {
  55132. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55133. };
  55134. this.onGeometryUpdated = function (geometry) {
  55135. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55136. };
  55137. this._afterRender = function () {
  55138. if (!_this._init)
  55139. return;
  55140. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55141. return;
  55142. }
  55143. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55144. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55145. if (_this._runningUpdated > 4) {
  55146. return;
  55147. }
  55148. ++_this._runningUpdated;
  55149. var payload = {
  55150. updatedMeshes: _this._addUpdateMeshesList,
  55151. updatedGeometries: _this._addUpdateGeometriesList,
  55152. removedGeometries: _this._toRemoveGeometryArray,
  55153. removedMeshes: _this._toRemoveMeshesArray
  55154. };
  55155. var message = {
  55156. payload: payload,
  55157. taskType: WorkerTaskType.UPDATE
  55158. };
  55159. var serializable = [];
  55160. for (var id in payload.updatedGeometries) {
  55161. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55162. //prepare transferables
  55163. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55164. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55165. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55166. }
  55167. }
  55168. _this._worker.postMessage(message, serializable);
  55169. _this._addUpdateMeshesList = {};
  55170. _this._addUpdateGeometriesList = {};
  55171. _this._toRemoveGeometryArray = [];
  55172. _this._toRemoveMeshesArray = [];
  55173. };
  55174. this._onMessageFromWorker = function (e) {
  55175. var returnData = e.data;
  55176. if (returnData.error != WorkerReplyType.SUCCESS) {
  55177. //TODO what errors can be returned from the worker?
  55178. BABYLON.Tools.Warn("error returned from worker!");
  55179. return;
  55180. }
  55181. switch (returnData.taskType) {
  55182. case WorkerTaskType.INIT:
  55183. _this._init = true;
  55184. //Update the worked with ALL of the scene's current state
  55185. _this._scene.meshes.forEach(function (mesh) {
  55186. _this.onMeshAdded(mesh);
  55187. });
  55188. _this._scene.getGeometries().forEach(function (geometry) {
  55189. _this.onGeometryAdded(geometry);
  55190. });
  55191. break;
  55192. case WorkerTaskType.UPDATE:
  55193. _this._runningUpdated--;
  55194. break;
  55195. case WorkerTaskType.COLLIDE:
  55196. var returnPayload = returnData.payload;
  55197. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55198. return;
  55199. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55200. if (callback) {
  55201. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55202. if (mesh) {
  55203. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55204. }
  55205. }
  55206. //cleanup
  55207. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55208. break;
  55209. }
  55210. };
  55211. this._collisionsCallbackArray = [];
  55212. this._init = false;
  55213. this._runningUpdated = 0;
  55214. this._addUpdateMeshesList = {};
  55215. this._addUpdateGeometriesList = {};
  55216. this._toRemoveGeometryArray = [];
  55217. this._toRemoveMeshesArray = [];
  55218. }
  55219. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55220. if (!this._init)
  55221. return;
  55222. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55223. return;
  55224. position.divideToRef(collider._radius, this._scaledPosition);
  55225. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55226. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55227. var payload = {
  55228. collider: {
  55229. position: this._scaledPosition.asArray(),
  55230. velocity: this._scaledVelocity.asArray(),
  55231. radius: collider._radius.asArray()
  55232. },
  55233. collisionId: collisionIndex,
  55234. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55235. maximumRetry: maximumRetry
  55236. };
  55237. var message = {
  55238. payload: payload,
  55239. taskType: WorkerTaskType.COLLIDE
  55240. };
  55241. this._worker.postMessage(message);
  55242. };
  55243. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55244. this._scene = scene;
  55245. this._scene.registerAfterRender(this._afterRender);
  55246. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55247. this._worker = new Worker(workerUrl);
  55248. this._worker.onmessage = this._onMessageFromWorker;
  55249. var message = {
  55250. payload: {},
  55251. taskType: WorkerTaskType.INIT
  55252. };
  55253. this._worker.postMessage(message);
  55254. };
  55255. CollisionCoordinatorWorker.prototype.destroy = function () {
  55256. this._scene.unregisterAfterRender(this._afterRender);
  55257. this._worker.terminate();
  55258. };
  55259. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55260. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55261. this.onMeshUpdated(mesh);
  55262. };
  55263. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55264. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55265. };
  55266. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55267. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55268. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55269. this.onGeometryUpdated(geometry);
  55270. };
  55271. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55272. this._toRemoveGeometryArray.push(geometry.id);
  55273. };
  55274. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55275. var submeshes = [];
  55276. if (mesh.subMeshes) {
  55277. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55278. var boundingInfo = sm.getBoundingInfo();
  55279. return {
  55280. position: idx,
  55281. verticesStart: sm.verticesStart,
  55282. verticesCount: sm.verticesCount,
  55283. indexStart: sm.indexStart,
  55284. indexCount: sm.indexCount,
  55285. hasMaterial: !!sm.getMaterial(),
  55286. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55287. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55288. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55289. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55290. };
  55291. });
  55292. }
  55293. var geometryId = null;
  55294. if (mesh instanceof BABYLON.Mesh) {
  55295. var geometry = mesh.geometry;
  55296. geometryId = geometry ? geometry.id : null;
  55297. }
  55298. else if (mesh instanceof BABYLON.InstancedMesh) {
  55299. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55300. geometryId = geometry ? geometry.id : null;
  55301. }
  55302. var boundingInfo = mesh.getBoundingInfo();
  55303. return {
  55304. uniqueId: mesh.uniqueId,
  55305. id: mesh.id,
  55306. name: mesh.name,
  55307. geometryId: geometryId,
  55308. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55309. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55310. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55311. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55312. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55313. subMeshes: submeshes,
  55314. checkCollisions: mesh.checkCollisions
  55315. };
  55316. };
  55317. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55318. return {
  55319. id: geometry.id,
  55320. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55321. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55322. indices: new Uint32Array(geometry.getIndices() || []),
  55323. };
  55324. };
  55325. return CollisionCoordinatorWorker;
  55326. }());
  55327. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55328. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55329. function CollisionCoordinatorLegacy() {
  55330. this._scaledPosition = BABYLON.Vector3.Zero();
  55331. this._scaledVelocity = BABYLON.Vector3.Zero();
  55332. this._finalPosition = BABYLON.Vector3.Zero();
  55333. }
  55334. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55335. position.divideToRef(collider._radius, this._scaledPosition);
  55336. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55337. collider.collidedMesh = null;
  55338. collider._retry = 0;
  55339. collider._initialVelocity = this._scaledVelocity;
  55340. collider._initialPosition = this._scaledPosition;
  55341. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55342. this._finalPosition.multiplyInPlace(collider._radius);
  55343. //run the callback
  55344. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55345. };
  55346. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55347. this._scene = scene;
  55348. };
  55349. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55350. //Legacy need no destruction method.
  55351. };
  55352. //No update in legacy mode
  55353. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55354. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55355. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55356. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55357. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55358. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55359. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55360. if (excludedMesh === void 0) { excludedMesh = null; }
  55361. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55362. if (collider._retry >= maximumRetry) {
  55363. finalPosition.copyFrom(position);
  55364. return;
  55365. }
  55366. // Check if this is a mesh else camera or -1
  55367. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55368. collider._initialize(position, velocity, closeDistance);
  55369. // Check all meshes
  55370. for (var index = 0; index < this._scene.meshes.length; index++) {
  55371. var mesh = this._scene.meshes[index];
  55372. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55373. mesh._checkCollision(collider);
  55374. }
  55375. }
  55376. if (!collider.collisionFound) {
  55377. position.addToRef(velocity, finalPosition);
  55378. return;
  55379. }
  55380. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55381. collider._getResponse(position, velocity);
  55382. }
  55383. if (velocity.length() <= closeDistance) {
  55384. finalPosition.copyFrom(position);
  55385. return;
  55386. }
  55387. collider._retry++;
  55388. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55389. };
  55390. return CollisionCoordinatorLegacy;
  55391. }());
  55392. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55393. })(BABYLON || (BABYLON = {}));
  55394. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55395. var BABYLON;
  55396. (function (BABYLON) {
  55397. /**
  55398. * A particle represents one of the element emitted by a particle system.
  55399. * This is mainly define by its coordinates, direction, velocity and age.
  55400. */
  55401. var Particle = /** @class */ (function () {
  55402. /**
  55403. * Creates a new instance Particle
  55404. * @param particleSystem the particle system the particle belongs to
  55405. */
  55406. function Particle(
  55407. /**
  55408. * particleSystem the particle system the particle belongs to.
  55409. */
  55410. particleSystem) {
  55411. this.particleSystem = particleSystem;
  55412. /**
  55413. * The world position of the particle in the scene.
  55414. */
  55415. this.position = BABYLON.Vector3.Zero();
  55416. /**
  55417. * The world direction of the particle in the scene.
  55418. */
  55419. this.direction = BABYLON.Vector3.Zero();
  55420. /**
  55421. * The color of the particle.
  55422. */
  55423. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55424. /**
  55425. * The color change of the particle per step.
  55426. */
  55427. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55428. /**
  55429. * Defines how long will the life of the particle be.
  55430. */
  55431. this.lifeTime = 1.0;
  55432. /**
  55433. * The current age of the particle.
  55434. */
  55435. this.age = 0;
  55436. /**
  55437. * The current size of the particle.
  55438. */
  55439. this.size = 0;
  55440. /**
  55441. * The current angle of the particle.
  55442. */
  55443. this.angle = 0;
  55444. /**
  55445. * Defines how fast is the angle changing.
  55446. */
  55447. this.angularSpeed = 0;
  55448. /**
  55449. * Defines the cell index used by the particle to be rendered from a sprite.
  55450. */
  55451. this.cellIndex = 0;
  55452. this._currentFrameCounter = 0;
  55453. if (!this.particleSystem.isAnimationSheetEnabled) {
  55454. return;
  55455. }
  55456. this.updateCellInfoFromSystem();
  55457. }
  55458. Particle.prototype.updateCellInfoFromSystem = function () {
  55459. this.cellIndex = this.particleSystem.startSpriteCellID;
  55460. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55461. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55462. }
  55463. else {
  55464. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55465. }
  55466. };
  55467. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55468. // (ageOffset / scaledUpdateSpeed) / available cells
  55469. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55470. this._currentFrameCounter += scaledUpdateSpeed;
  55471. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55472. this._currentFrameCounter = 0;
  55473. this.cellIndex++;
  55474. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55475. this.cellIndex = this.particleSystem.endSpriteCellID;
  55476. }
  55477. }
  55478. };
  55479. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55480. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55481. this.cellIndex++;
  55482. this._currentFrameCounter = 0;
  55483. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55484. if (this.particleSystem.spriteCellLoop) {
  55485. this.cellIndex = this.particleSystem.startSpriteCellID;
  55486. }
  55487. else {
  55488. this.cellIndex = this.particleSystem.endSpriteCellID;
  55489. }
  55490. }
  55491. }
  55492. else {
  55493. this._currentFrameCounter++;
  55494. }
  55495. };
  55496. /**
  55497. * Copy the properties of particle to another one.
  55498. * @param other the particle to copy the information to.
  55499. */
  55500. Particle.prototype.copyTo = function (other) {
  55501. other.position.copyFrom(this.position);
  55502. other.direction.copyFrom(this.direction);
  55503. other.color.copyFrom(this.color);
  55504. other.colorStep.copyFrom(this.colorStep);
  55505. other.lifeTime = this.lifeTime;
  55506. other.age = this.age;
  55507. other.size = this.size;
  55508. other.angle = this.angle;
  55509. other.angularSpeed = this.angularSpeed;
  55510. other.particleSystem = this.particleSystem;
  55511. other.cellIndex = this.cellIndex;
  55512. };
  55513. return Particle;
  55514. }());
  55515. BABYLON.Particle = Particle;
  55516. })(BABYLON || (BABYLON = {}));
  55517. //# sourceMappingURL=babylon.particle.js.map
  55518. var BABYLON;
  55519. (function (BABYLON) {
  55520. /**
  55521. * This represents a particle system in Babylon.
  55522. * 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.
  55523. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55524. * @example https://doc.babylonjs.com/babylon101/particles
  55525. */
  55526. var ParticleSystem = /** @class */ (function () {
  55527. /**
  55528. * Instantiates a particle system.
  55529. * 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.
  55530. * @param name The name of the particle system
  55531. * @param capacity The max number of particles alive at the same time
  55532. * @param scene The scene the particle system belongs to
  55533. * @param customEffect a custom effect used to change the way particles are rendered by default
  55534. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55535. * @param epsilon Offset used to render the particles
  55536. */
  55537. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55538. if (customEffect === void 0) { customEffect = null; }
  55539. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55540. if (epsilon === void 0) { epsilon = 0.01; }
  55541. var _this = this;
  55542. /**
  55543. * List of animations used by the particle system.
  55544. */
  55545. this.animations = [];
  55546. /**
  55547. * The rendering group used by the Particle system to chose when to render.
  55548. */
  55549. this.renderingGroupId = 0;
  55550. /**
  55551. * The emitter represents the Mesh or position we are attaching the particle system to.
  55552. */
  55553. this.emitter = null;
  55554. /**
  55555. * The maximum number of particles to emit per frame
  55556. */
  55557. this.emitRate = 10;
  55558. /**
  55559. * If you want to launch only a few particles at once, that can be done, as well.
  55560. */
  55561. this.manualEmitCount = -1;
  55562. /**
  55563. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55564. */
  55565. this.updateSpeed = 0.01;
  55566. /**
  55567. * The amount of time the particle system is running (depends of the overall update speed).
  55568. */
  55569. this.targetStopDuration = 0;
  55570. /**
  55571. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55572. */
  55573. this.disposeOnStop = false;
  55574. /**
  55575. * Minimum power of emitting particles.
  55576. */
  55577. this.minEmitPower = 1;
  55578. /**
  55579. * Maximum power of emitting particles.
  55580. */
  55581. this.maxEmitPower = 1;
  55582. /**
  55583. * Minimum life time of emitting particles.
  55584. */
  55585. this.minLifeTime = 1;
  55586. /**
  55587. * Maximum life time of emitting particles.
  55588. */
  55589. this.maxLifeTime = 1;
  55590. /**
  55591. * Minimum Size of emitting particles.
  55592. */
  55593. this.minSize = 1;
  55594. /**
  55595. * Maximum Size of emitting particles.
  55596. */
  55597. this.maxSize = 1;
  55598. /**
  55599. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55600. */
  55601. this.minAngularSpeed = 0;
  55602. /**
  55603. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55604. */
  55605. this.maxAngularSpeed = 0;
  55606. /**
  55607. * The layer mask we are rendering the particles through.
  55608. */
  55609. this.layerMask = 0x0FFFFFFF;
  55610. /**
  55611. * This can help using your own shader to render the particle system.
  55612. * The according effect will be created
  55613. */
  55614. this.customShader = null;
  55615. /**
  55616. * By default particle system starts as soon as they are created. This prevents the
  55617. * automatic start to happen and let you decide when to start emitting particles.
  55618. */
  55619. this.preventAutoStart = false;
  55620. /**
  55621. * Callback triggered when the particle animation is ending.
  55622. */
  55623. this.onAnimationEnd = null;
  55624. /**
  55625. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55626. */
  55627. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55628. /**
  55629. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55630. * to override the particles.
  55631. */
  55632. this.forceDepthWrite = false;
  55633. /**
  55634. * You can use gravity if you want to give an orientation to your particles.
  55635. */
  55636. this.gravity = BABYLON.Vector3.Zero();
  55637. /**
  55638. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55639. */
  55640. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55641. /**
  55642. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55643. */
  55644. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55645. /**
  55646. * Color the particle will have at the end of its lifetime.
  55647. */
  55648. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55649. /**
  55650. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55651. */
  55652. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55653. /**
  55654. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55655. */
  55656. this.spriteCellLoop = true;
  55657. /**
  55658. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55659. */
  55660. this.spriteCellChangeSpeed = 0;
  55661. /**
  55662. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55663. */
  55664. this.startSpriteCellID = 0;
  55665. /**
  55666. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55667. */
  55668. this.endSpriteCellID = 0;
  55669. /**
  55670. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55671. */
  55672. this.spriteCellWidth = 0;
  55673. /**
  55674. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55675. */
  55676. this.spriteCellHeight = 0;
  55677. /**
  55678. * An event triggered when the system is disposed.
  55679. */
  55680. this.onDisposeObservable = new BABYLON.Observable();
  55681. this._particles = new Array();
  55682. this._stockParticles = new Array();
  55683. this._newPartsExcess = 0;
  55684. this._vertexBuffers = {};
  55685. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55686. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55687. this._scaledDirection = BABYLON.Vector3.Zero();
  55688. this._scaledGravity = BABYLON.Vector3.Zero();
  55689. this._currentRenderId = -1;
  55690. this._started = false;
  55691. this._stopped = false;
  55692. this._actualFrame = 0;
  55693. this._vertexBufferSize = 11;
  55694. // start of sub system methods
  55695. /**
  55696. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55697. * Its lifetime will start back at 0.
  55698. */
  55699. this.recycleParticle = function (particle) {
  55700. var lastParticle = _this._particles.pop();
  55701. if (lastParticle !== particle) {
  55702. lastParticle.copyTo(particle);
  55703. }
  55704. _this._stockParticles.push(lastParticle);
  55705. };
  55706. this._createParticle = function () {
  55707. var particle;
  55708. if (_this._stockParticles.length !== 0) {
  55709. particle = _this._stockParticles.pop();
  55710. particle.age = 0;
  55711. particle.cellIndex = _this.startSpriteCellID;
  55712. }
  55713. else {
  55714. particle = new BABYLON.Particle(_this);
  55715. }
  55716. return particle;
  55717. };
  55718. this._emitFromParticle = function (particle) {
  55719. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55720. return;
  55721. }
  55722. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55723. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55724. subSystem._rootParticleSystem = _this;
  55725. _this.activeSubSystems.push(subSystem);
  55726. subSystem.start();
  55727. };
  55728. this._appendParticleVertexes = null;
  55729. this.id = name;
  55730. this.name = name;
  55731. this._capacity = capacity;
  55732. this._epsilon = epsilon;
  55733. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55734. if (isAnimationSheetEnabled) {
  55735. this._vertexBufferSize = 12;
  55736. }
  55737. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55738. this._customEffect = customEffect;
  55739. scene.particleSystems.push(this);
  55740. this._createIndexBuffer();
  55741. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  55742. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55743. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55744. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55745. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55746. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  55747. if (this._isAnimationSheetEnabled) {
  55748. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  55749. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55750. }
  55751. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55752. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55753. this._vertexBuffers["options"] = options;
  55754. // Default emitter type
  55755. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55756. this.updateFunction = function (particles) {
  55757. for (var index = 0; index < particles.length; index++) {
  55758. var particle = particles[index];
  55759. particle.age += _this._scaledUpdateSpeed;
  55760. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55761. _this._emitFromParticle(particle);
  55762. _this.recycleParticle(particle);
  55763. index--;
  55764. continue;
  55765. }
  55766. else {
  55767. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55768. particle.color.addInPlace(_this._scaledColorStep);
  55769. if (particle.color.a < 0)
  55770. particle.color.a = 0;
  55771. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55772. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55773. particle.position.addInPlace(_this._scaledDirection);
  55774. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55775. particle.direction.addInPlace(_this._scaledGravity);
  55776. if (_this._isAnimationSheetEnabled) {
  55777. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55778. }
  55779. }
  55780. }
  55781. };
  55782. }
  55783. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55784. /**
  55785. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55786. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55787. */
  55788. get: function () {
  55789. if (this.particleEmitterType.direction1) {
  55790. return this.particleEmitterType.direction1;
  55791. }
  55792. return BABYLON.Vector3.Zero();
  55793. },
  55794. set: function (value) {
  55795. if (this.particleEmitterType.direction1) {
  55796. this.particleEmitterType.direction1 = value;
  55797. }
  55798. },
  55799. enumerable: true,
  55800. configurable: true
  55801. });
  55802. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55803. /**
  55804. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55805. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55806. */
  55807. get: function () {
  55808. if (this.particleEmitterType.direction2) {
  55809. return this.particleEmitterType.direction2;
  55810. }
  55811. return BABYLON.Vector3.Zero();
  55812. },
  55813. set: function (value) {
  55814. if (this.particleEmitterType.direction2) {
  55815. this.particleEmitterType.direction2 = value;
  55816. }
  55817. },
  55818. enumerable: true,
  55819. configurable: true
  55820. });
  55821. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55822. /**
  55823. * 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.
  55824. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55825. */
  55826. get: function () {
  55827. if (this.particleEmitterType.minEmitBox) {
  55828. return this.particleEmitterType.minEmitBox;
  55829. }
  55830. return BABYLON.Vector3.Zero();
  55831. },
  55832. set: function (value) {
  55833. if (this.particleEmitterType.minEmitBox) {
  55834. this.particleEmitterType.minEmitBox = value;
  55835. }
  55836. },
  55837. enumerable: true,
  55838. configurable: true
  55839. });
  55840. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55841. /**
  55842. * 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.
  55843. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55844. */
  55845. get: function () {
  55846. if (this.particleEmitterType.maxEmitBox) {
  55847. return this.particleEmitterType.maxEmitBox;
  55848. }
  55849. return BABYLON.Vector3.Zero();
  55850. },
  55851. set: function (value) {
  55852. if (this.particleEmitterType.maxEmitBox) {
  55853. this.particleEmitterType.maxEmitBox = value;
  55854. }
  55855. },
  55856. enumerable: true,
  55857. configurable: true
  55858. });
  55859. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55860. /**
  55861. * Sets a callback that will be triggered when the system is disposed.
  55862. */
  55863. set: function (callback) {
  55864. if (this._onDisposeObserver) {
  55865. this.onDisposeObservable.remove(this._onDisposeObserver);
  55866. }
  55867. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55868. },
  55869. enumerable: true,
  55870. configurable: true
  55871. });
  55872. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55873. /**
  55874. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  55875. */
  55876. get: function () {
  55877. return this._isAnimationSheetEnabled;
  55878. },
  55879. enumerable: true,
  55880. configurable: true
  55881. });
  55882. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55883. //end of Sub-emitter
  55884. /**
  55885. * Gets the current list of active particles
  55886. */
  55887. get: function () {
  55888. return this._particles;
  55889. },
  55890. enumerable: true,
  55891. configurable: true
  55892. });
  55893. /**
  55894. * Returns the string "ParticleSystem"
  55895. * @returns a string containing the class name
  55896. */
  55897. ParticleSystem.prototype.getClassName = function () {
  55898. return "ParticleSystem";
  55899. };
  55900. ParticleSystem.prototype._createIndexBuffer = function () {
  55901. var indices = [];
  55902. var index = 0;
  55903. for (var count = 0; count < this._capacity; count++) {
  55904. indices.push(index);
  55905. indices.push(index + 1);
  55906. indices.push(index + 2);
  55907. indices.push(index);
  55908. indices.push(index + 2);
  55909. indices.push(index + 3);
  55910. index += 4;
  55911. }
  55912. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55913. };
  55914. /**
  55915. * Gets the maximum number of particles active at the same time.
  55916. * @returns The max number of active particles.
  55917. */
  55918. ParticleSystem.prototype.getCapacity = function () {
  55919. return this._capacity;
  55920. };
  55921. /**
  55922. * Gets Wether there are still active particles in the system.
  55923. * @returns True if it is alive, otherwise false.
  55924. */
  55925. ParticleSystem.prototype.isAlive = function () {
  55926. return this._alive;
  55927. };
  55928. /**
  55929. * Gets Wether the system has been started.
  55930. * @returns True if it has been started, otherwise false.
  55931. */
  55932. ParticleSystem.prototype.isStarted = function () {
  55933. return this._started;
  55934. };
  55935. /**
  55936. * Starts the particle system and begins to emit.
  55937. */
  55938. ParticleSystem.prototype.start = function () {
  55939. this._started = true;
  55940. this._stopped = false;
  55941. this._actualFrame = 0;
  55942. if (this.subEmitters && this.subEmitters.length != 0) {
  55943. this.activeSubSystems = new Array();
  55944. }
  55945. };
  55946. /**
  55947. * Stops the particle system.
  55948. * @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.
  55949. */
  55950. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55951. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55952. this._stopped = true;
  55953. if (stopSubEmitters) {
  55954. this._stopSubEmitters();
  55955. }
  55956. };
  55957. // animation sheet
  55958. /**
  55959. * Remove all active particles
  55960. */
  55961. ParticleSystem.prototype.reset = function () {
  55962. this._stockParticles = [];
  55963. this._particles = [];
  55964. };
  55965. /**
  55966. * @hidden (for internal use only)
  55967. */
  55968. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55969. var offset = index * this._vertexBufferSize;
  55970. this._vertexData[offset] = particle.position.x;
  55971. this._vertexData[offset + 1] = particle.position.y;
  55972. this._vertexData[offset + 2] = particle.position.z;
  55973. this._vertexData[offset + 3] = particle.color.r;
  55974. this._vertexData[offset + 4] = particle.color.g;
  55975. this._vertexData[offset + 5] = particle.color.b;
  55976. this._vertexData[offset + 6] = particle.color.a;
  55977. this._vertexData[offset + 7] = particle.angle;
  55978. this._vertexData[offset + 8] = particle.size;
  55979. this._vertexData[offset + 9] = offsetX;
  55980. this._vertexData[offset + 10] = offsetY;
  55981. };
  55982. /**
  55983. * @hidden (for internal use only)
  55984. */
  55985. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  55986. if (offsetX === 0)
  55987. offsetX = this._epsilon;
  55988. else if (offsetX === 1)
  55989. offsetX = 1 - this._epsilon;
  55990. if (offsetY === 0)
  55991. offsetY = this._epsilon;
  55992. else if (offsetY === 1)
  55993. offsetY = 1 - this._epsilon;
  55994. var offset = index * this._vertexBufferSize;
  55995. this._vertexData[offset] = particle.position.x;
  55996. this._vertexData[offset + 1] = particle.position.y;
  55997. this._vertexData[offset + 2] = particle.position.z;
  55998. this._vertexData[offset + 3] = particle.color.r;
  55999. this._vertexData[offset + 4] = particle.color.g;
  56000. this._vertexData[offset + 5] = particle.color.b;
  56001. this._vertexData[offset + 6] = particle.color.a;
  56002. this._vertexData[offset + 7] = particle.angle;
  56003. this._vertexData[offset + 8] = particle.size;
  56004. this._vertexData[offset + 9] = offsetX;
  56005. this._vertexData[offset + 10] = offsetY;
  56006. this._vertexData[offset + 11] = particle.cellIndex;
  56007. };
  56008. ParticleSystem.prototype._stopSubEmitters = function () {
  56009. if (!this.activeSubSystems) {
  56010. return;
  56011. }
  56012. this.activeSubSystems.forEach(function (subSystem) {
  56013. subSystem.stop(true);
  56014. });
  56015. this.activeSubSystems = new Array();
  56016. };
  56017. ParticleSystem.prototype._removeFromRoot = function () {
  56018. if (!this._rootParticleSystem) {
  56019. return;
  56020. }
  56021. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56022. if (index !== -1) {
  56023. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56024. }
  56025. };
  56026. // end of sub system methods
  56027. ParticleSystem.prototype._update = function (newParticles) {
  56028. // Update current
  56029. this._alive = this._particles.length > 0;
  56030. this.updateFunction(this._particles);
  56031. // Add new ones
  56032. var worldMatrix;
  56033. if (this.emitter.position) {
  56034. var emitterMesh = this.emitter;
  56035. worldMatrix = emitterMesh.getWorldMatrix();
  56036. }
  56037. else {
  56038. var emitterPosition = this.emitter;
  56039. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56040. }
  56041. var particle;
  56042. for (var index = 0; index < newParticles; index++) {
  56043. if (this._particles.length === this._capacity) {
  56044. break;
  56045. }
  56046. particle = this._createParticle();
  56047. this._particles.push(particle);
  56048. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56049. if (this.startPositionFunction) {
  56050. this.startPositionFunction(worldMatrix, particle.position, particle);
  56051. }
  56052. else {
  56053. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56054. }
  56055. if (this.startDirectionFunction) {
  56056. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56057. }
  56058. else {
  56059. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56060. }
  56061. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56062. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56063. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56064. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56065. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56066. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56067. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56068. }
  56069. };
  56070. ParticleSystem.prototype._getEffect = function () {
  56071. if (this._customEffect) {
  56072. return this._customEffect;
  56073. }
  56074. ;
  56075. var defines = [];
  56076. if (this._scene.clipPlane) {
  56077. defines.push("#define CLIPPLANE");
  56078. }
  56079. if (this._isAnimationSheetEnabled) {
  56080. defines.push("#define ANIMATESHEET");
  56081. }
  56082. // Effect
  56083. var join = defines.join("\n");
  56084. if (this._cachedDefines !== join) {
  56085. this._cachedDefines = join;
  56086. var attributesNamesOrOptions;
  56087. var effectCreationOption;
  56088. if (this._isAnimationSheetEnabled) {
  56089. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56090. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56091. }
  56092. else {
  56093. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56094. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56095. }
  56096. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56097. }
  56098. return this._effect;
  56099. };
  56100. /**
  56101. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56102. */
  56103. ParticleSystem.prototype.animate = function () {
  56104. if (!this._started)
  56105. return;
  56106. var effect = this._getEffect();
  56107. // Check
  56108. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56109. return;
  56110. if (this._currentRenderId === this._scene.getRenderId()) {
  56111. return;
  56112. }
  56113. this._currentRenderId = this._scene.getRenderId();
  56114. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56115. // determine the number of particles we need to create
  56116. var newParticles;
  56117. if (this.manualEmitCount > -1) {
  56118. newParticles = this.manualEmitCount;
  56119. this._newPartsExcess = 0;
  56120. this.manualEmitCount = 0;
  56121. }
  56122. else {
  56123. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56124. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56125. }
  56126. if (this._newPartsExcess > 1.0) {
  56127. newParticles += this._newPartsExcess >> 0;
  56128. this._newPartsExcess -= this._newPartsExcess >> 0;
  56129. }
  56130. this._alive = false;
  56131. if (!this._stopped) {
  56132. this._actualFrame += this._scaledUpdateSpeed;
  56133. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56134. this.stop();
  56135. }
  56136. else {
  56137. newParticles = 0;
  56138. }
  56139. this._update(newParticles);
  56140. // Stopped?
  56141. if (this._stopped) {
  56142. if (!this._alive) {
  56143. this._started = false;
  56144. if (this.onAnimationEnd) {
  56145. this.onAnimationEnd();
  56146. }
  56147. if (this.disposeOnStop) {
  56148. this._scene._toBeDisposed.push(this);
  56149. }
  56150. }
  56151. }
  56152. // Animation sheet
  56153. if (this._isAnimationSheetEnabled) {
  56154. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56155. }
  56156. else {
  56157. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56158. }
  56159. // Update VBO
  56160. var offset = 0;
  56161. for (var index = 0; index < this._particles.length; index++) {
  56162. var particle = this._particles[index];
  56163. this._appendParticleVertexes(offset, particle);
  56164. offset += 4;
  56165. }
  56166. if (this._vertexBuffer) {
  56167. this._vertexBuffer.update(this._vertexData);
  56168. }
  56169. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56170. this.stop();
  56171. }
  56172. };
  56173. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56174. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56175. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56176. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56177. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56178. };
  56179. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56180. this._appendParticleVertex(offset++, particle, 0, 0);
  56181. this._appendParticleVertex(offset++, particle, 1, 0);
  56182. this._appendParticleVertex(offset++, particle, 1, 1);
  56183. this._appendParticleVertex(offset++, particle, 0, 1);
  56184. };
  56185. /**
  56186. * Rebuilds the particle system.
  56187. */
  56188. ParticleSystem.prototype.rebuild = function () {
  56189. this._createIndexBuffer();
  56190. if (this._vertexBuffer) {
  56191. this._vertexBuffer._rebuild();
  56192. }
  56193. };
  56194. /**
  56195. * Is this system ready to be used/rendered
  56196. * @return true if the system is ready
  56197. */
  56198. ParticleSystem.prototype.isReady = function () {
  56199. var effect = this._getEffect();
  56200. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56201. return false;
  56202. }
  56203. return true;
  56204. };
  56205. /**
  56206. * Renders the particle system in its current state.
  56207. * @returns the current number of particles
  56208. */
  56209. ParticleSystem.prototype.render = function () {
  56210. var effect = this._getEffect();
  56211. // Check
  56212. if (!this.isReady() || !this._particles.length) {
  56213. return 0;
  56214. }
  56215. var engine = this._scene.getEngine();
  56216. // Render
  56217. engine.enableEffect(effect);
  56218. engine.setState(false);
  56219. var viewMatrix = this._scene.getViewMatrix();
  56220. effect.setTexture("diffuseSampler", this.particleTexture);
  56221. effect.setMatrix("view", viewMatrix);
  56222. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56223. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56224. var baseSize = this.particleTexture.getBaseSize();
  56225. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56226. }
  56227. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56228. if (this._scene.clipPlane) {
  56229. var clipPlane = this._scene.clipPlane;
  56230. var invView = viewMatrix.clone();
  56231. invView.invert();
  56232. effect.setMatrix("invView", invView);
  56233. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56234. }
  56235. // VBOs
  56236. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56237. // Draw order
  56238. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56239. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56240. }
  56241. else {
  56242. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56243. }
  56244. if (this.forceDepthWrite) {
  56245. engine.setDepthWrite(true);
  56246. }
  56247. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56248. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56249. return this._particles.length;
  56250. };
  56251. /**
  56252. * Disposes the particle system and free the associated resources
  56253. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56254. */
  56255. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56256. if (disposeTexture === void 0) { disposeTexture = true; }
  56257. if (this._vertexBuffer) {
  56258. this._vertexBuffer.dispose();
  56259. this._vertexBuffer = null;
  56260. }
  56261. if (this._indexBuffer) {
  56262. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56263. this._indexBuffer = null;
  56264. }
  56265. if (disposeTexture && this.particleTexture) {
  56266. this.particleTexture.dispose();
  56267. this.particleTexture = null;
  56268. }
  56269. this._removeFromRoot();
  56270. // Remove from scene
  56271. var index = this._scene.particleSystems.indexOf(this);
  56272. if (index > -1) {
  56273. this._scene.particleSystems.splice(index, 1);
  56274. }
  56275. // Callback
  56276. this.onDisposeObservable.notifyObservers(this);
  56277. this.onDisposeObservable.clear();
  56278. };
  56279. /**
  56280. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56281. * @param radius The radius of the sphere to emit from
  56282. * @returns the emitter
  56283. */
  56284. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56285. if (radius === void 0) { radius = 1; }
  56286. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56287. this.particleEmitterType = particleEmitter;
  56288. return particleEmitter;
  56289. };
  56290. /**
  56291. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56292. * @param radius The radius of the sphere to emit from
  56293. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56294. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56295. * @returns the emitter
  56296. */
  56297. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56298. if (radius === void 0) { radius = 1; }
  56299. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56300. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56301. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56302. this.particleEmitterType = particleEmitter;
  56303. return particleEmitter;
  56304. };
  56305. /**
  56306. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56307. * @param radius The radius of the cone to emit from
  56308. * @param angle The base angle of the cone
  56309. * @returns the emitter
  56310. */
  56311. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56312. if (radius === void 0) { radius = 1; }
  56313. if (angle === void 0) { angle = Math.PI / 4; }
  56314. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56315. this.particleEmitterType = particleEmitter;
  56316. return particleEmitter;
  56317. };
  56318. // 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.
  56319. /**
  56320. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56321. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56322. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56323. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56324. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56325. * @returns the emitter
  56326. */
  56327. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56328. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56329. this.particleEmitterType = particleEmitter;
  56330. this.direction1 = direction1;
  56331. this.direction2 = direction2;
  56332. this.minEmitBox = minEmitBox;
  56333. this.maxEmitBox = maxEmitBox;
  56334. return particleEmitter;
  56335. };
  56336. // Clone
  56337. /**
  56338. * Clones the particle system.
  56339. * @param name The name of the cloned object
  56340. * @param newEmitter The new emitter to use
  56341. * @returns the cloned particle system
  56342. */
  56343. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56344. var custom = null;
  56345. var program = null;
  56346. if (this.customShader != null) {
  56347. program = this.customShader;
  56348. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56349. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56350. }
  56351. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56352. result.customShader = program;
  56353. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56354. if (newEmitter === undefined) {
  56355. newEmitter = this.emitter;
  56356. }
  56357. result.emitter = newEmitter;
  56358. if (this.particleTexture) {
  56359. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56360. }
  56361. if (!this.preventAutoStart) {
  56362. result.start();
  56363. }
  56364. return result;
  56365. };
  56366. /**
  56367. * Serializes the particle system to a JSON object.
  56368. * @returns the JSON object
  56369. */
  56370. ParticleSystem.prototype.serialize = function () {
  56371. var serializationObject = {};
  56372. serializationObject.name = this.name;
  56373. serializationObject.id = this.id;
  56374. // Emitter
  56375. if (this.emitter.position) {
  56376. var emitterMesh = this.emitter;
  56377. serializationObject.emitterId = emitterMesh.id;
  56378. }
  56379. else {
  56380. var emitterPosition = this.emitter;
  56381. serializationObject.emitter = emitterPosition.asArray();
  56382. }
  56383. serializationObject.capacity = this.getCapacity();
  56384. if (this.particleTexture) {
  56385. serializationObject.textureName = this.particleTexture.name;
  56386. }
  56387. // Animations
  56388. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56389. // Particle system
  56390. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56391. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56392. serializationObject.minSize = this.minSize;
  56393. serializationObject.maxSize = this.maxSize;
  56394. serializationObject.minEmitPower = this.minEmitPower;
  56395. serializationObject.maxEmitPower = this.maxEmitPower;
  56396. serializationObject.minLifeTime = this.minLifeTime;
  56397. serializationObject.maxLifeTime = this.maxLifeTime;
  56398. serializationObject.emitRate = this.emitRate;
  56399. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56400. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56401. serializationObject.gravity = this.gravity.asArray();
  56402. serializationObject.direction1 = this.direction1.asArray();
  56403. serializationObject.direction2 = this.direction2.asArray();
  56404. serializationObject.color1 = this.color1.asArray();
  56405. serializationObject.color2 = this.color2.asArray();
  56406. serializationObject.colorDead = this.colorDead.asArray();
  56407. serializationObject.updateSpeed = this.updateSpeed;
  56408. serializationObject.targetStopDuration = this.targetStopDuration;
  56409. serializationObject.textureMask = this.textureMask.asArray();
  56410. serializationObject.blendMode = this.blendMode;
  56411. serializationObject.customShader = this.customShader;
  56412. serializationObject.preventAutoStart = this.preventAutoStart;
  56413. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56414. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56415. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56416. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56417. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56418. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56419. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56420. // Emitter
  56421. if (this.particleEmitterType) {
  56422. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56423. }
  56424. return serializationObject;
  56425. };
  56426. /**
  56427. * Parses a JSON object to create a particle system.
  56428. * @param parsedParticleSystem The JSON object to parse
  56429. * @param scene The scene to create the particle system in
  56430. * @param rootUrl The root url to use to load external dependencies like texture
  56431. * @returns the Parsed particle system
  56432. */
  56433. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56434. var name = parsedParticleSystem.name;
  56435. var custom = null;
  56436. var program = null;
  56437. if (parsedParticleSystem.customShader) {
  56438. program = parsedParticleSystem.customShader;
  56439. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56440. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56441. }
  56442. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56443. particleSystem.customShader = program;
  56444. if (parsedParticleSystem.id) {
  56445. particleSystem.id = parsedParticleSystem.id;
  56446. }
  56447. // Auto start
  56448. if (parsedParticleSystem.preventAutoStart) {
  56449. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56450. }
  56451. // Texture
  56452. if (parsedParticleSystem.textureName) {
  56453. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56454. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56455. }
  56456. // Emitter
  56457. if (parsedParticleSystem.emitterId) {
  56458. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56459. }
  56460. else {
  56461. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56462. }
  56463. // Animations
  56464. if (parsedParticleSystem.animations) {
  56465. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56466. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56467. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56468. }
  56469. }
  56470. if (parsedParticleSystem.autoAnimate) {
  56471. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56472. }
  56473. // Particle system
  56474. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56475. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56476. particleSystem.minSize = parsedParticleSystem.minSize;
  56477. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56478. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56479. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56480. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56481. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56482. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56483. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56484. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56485. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56486. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56487. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56488. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56489. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56490. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56491. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56492. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56493. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56494. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56495. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56496. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56497. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56498. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56499. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56500. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56501. if (!particleSystem.preventAutoStart) {
  56502. particleSystem.start();
  56503. }
  56504. return particleSystem;
  56505. };
  56506. /**
  56507. * Source color is added to the destination color without alpha affecting the result.
  56508. */
  56509. ParticleSystem.BLENDMODE_ONEONE = 0;
  56510. /**
  56511. * Blend current color and particle color using particle’s alpha.
  56512. */
  56513. ParticleSystem.BLENDMODE_STANDARD = 1;
  56514. return ParticleSystem;
  56515. }());
  56516. BABYLON.ParticleSystem = ParticleSystem;
  56517. })(BABYLON || (BABYLON = {}));
  56518. //# sourceMappingURL=babylon.particleSystem.js.map
  56519. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56520. var BABYLON;
  56521. (function (BABYLON) {
  56522. /**
  56523. * Particle emitter emitting particles from the inside of a box.
  56524. * It emits the particles randomly between 2 given directions.
  56525. */
  56526. var BoxParticleEmitter = /** @class */ (function () {
  56527. /**
  56528. * Creates a new instance BoxParticleEmitter
  56529. */
  56530. function BoxParticleEmitter() {
  56531. /**
  56532. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56533. */
  56534. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56535. /**
  56536. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56537. */
  56538. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56539. /**
  56540. * 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.
  56541. */
  56542. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56543. /**
  56544. * 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.
  56545. */
  56546. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56547. }
  56548. /**
  56549. * Called by the particle System when the direction is computed for the created particle.
  56550. * @param emitPower is the power of the particle (speed)
  56551. * @param worldMatrix is the world matrix of the particle system
  56552. * @param directionToUpdate is the direction vector to update with the result
  56553. * @param particle is the particle we are computed the direction for
  56554. */
  56555. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56556. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56557. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56558. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56559. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56560. };
  56561. /**
  56562. * Called by the particle System when the position is computed for the created particle.
  56563. * @param worldMatrix is the world matrix of the particle system
  56564. * @param positionToUpdate is the position vector to update with the result
  56565. * @param particle is the particle we are computed the position for
  56566. */
  56567. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56568. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56569. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56570. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56571. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56572. };
  56573. /**
  56574. * Clones the current emitter and returns a copy of it
  56575. * @returns the new emitter
  56576. */
  56577. BoxParticleEmitter.prototype.clone = function () {
  56578. var newOne = new BoxParticleEmitter();
  56579. BABYLON.Tools.DeepCopy(this, newOne);
  56580. return newOne;
  56581. };
  56582. /**
  56583. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56584. * @param effect defines the update shader
  56585. */
  56586. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56587. effect.setVector3("direction1", this.direction1);
  56588. effect.setVector3("direction2", this.direction2);
  56589. effect.setVector3("minEmitBox", this.minEmitBox);
  56590. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56591. };
  56592. /**
  56593. * Returns a string to use to update the GPU particles update shader
  56594. * @returns a string containng the defines string
  56595. */
  56596. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56597. return "#define BOXEMITTER";
  56598. };
  56599. /**
  56600. * Returns the string "BoxEmitter"
  56601. * @returns a string containing the class name
  56602. */
  56603. BoxParticleEmitter.prototype.getClassName = function () {
  56604. return "BoxEmitter";
  56605. };
  56606. /**
  56607. * Serializes the particle system to a JSON object.
  56608. * @returns the JSON object
  56609. */
  56610. BoxParticleEmitter.prototype.serialize = function () {
  56611. var serializationObject = {};
  56612. serializationObject.type = this.getClassName();
  56613. serializationObject.direction1 = this.direction1.asArray();
  56614. ;
  56615. serializationObject.direction2 = this.direction2.asArray();
  56616. ;
  56617. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56618. ;
  56619. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56620. ;
  56621. return serializationObject;
  56622. };
  56623. /**
  56624. * Parse properties from a JSON object
  56625. * @param serializationObject defines the JSON object
  56626. */
  56627. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56628. this.direction1.copyFrom(serializationObject.direction1);
  56629. this.direction2.copyFrom(serializationObject.direction2);
  56630. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56631. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56632. };
  56633. return BoxParticleEmitter;
  56634. }());
  56635. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56636. })(BABYLON || (BABYLON = {}));
  56637. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56638. var BABYLON;
  56639. (function (BABYLON) {
  56640. /**
  56641. * Particle emitter emitting particles from the inside of a cone.
  56642. * It emits the particles alongside the cone volume from the base to the particle.
  56643. * The emission direction might be randomized.
  56644. */
  56645. var ConeParticleEmitter = /** @class */ (function () {
  56646. /**
  56647. * Creates a new instance ConeParticleEmitter
  56648. * @param radius the radius of the emission cone (1 by default)
  56649. * @param angles the cone base angle (PI by default)
  56650. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56651. */
  56652. function ConeParticleEmitter(radius,
  56653. /**
  56654. * The radius of the emission cone.
  56655. */
  56656. angle,
  56657. /**
  56658. * The cone base angle.
  56659. */
  56660. directionRandomizer) {
  56661. if (radius === void 0) { radius = 1; }
  56662. if (angle === void 0) { angle = Math.PI; }
  56663. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56664. this.angle = angle;
  56665. this.directionRandomizer = directionRandomizer;
  56666. this.radius = radius;
  56667. }
  56668. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56669. /**
  56670. * Gets the radius of the emission cone.
  56671. */
  56672. get: function () {
  56673. return this._radius;
  56674. },
  56675. /**
  56676. * Sets the radius of the emission cone.
  56677. */
  56678. set: function (value) {
  56679. this._radius = value;
  56680. if (this.angle !== 0) {
  56681. this._height = value / Math.tan(this.angle / 2);
  56682. }
  56683. else {
  56684. this._height = 1;
  56685. }
  56686. },
  56687. enumerable: true,
  56688. configurable: true
  56689. });
  56690. /**
  56691. * Called by the particle System when the direction is computed for the created particle.
  56692. * @param emitPower is the power of the particle (speed)
  56693. * @param worldMatrix is the world matrix of the particle system
  56694. * @param directionToUpdate is the direction vector to update with the result
  56695. * @param particle is the particle we are computed the direction for
  56696. */
  56697. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56698. if (this.angle === 0) {
  56699. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56700. }
  56701. else {
  56702. // measure the direction Vector from the emitter to the particle.
  56703. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56704. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56705. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56706. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56707. direction.x += randX;
  56708. direction.y += randY;
  56709. direction.z += randZ;
  56710. direction.normalize();
  56711. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56712. }
  56713. };
  56714. /**
  56715. * Called by the particle System when the position is computed for the created particle.
  56716. * @param worldMatrix is the world matrix of the particle system
  56717. * @param positionToUpdate is the position vector to update with the result
  56718. * @param particle is the particle we are computed the position for
  56719. */
  56720. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56721. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56722. var h = BABYLON.Scalar.RandomRange(0, 1);
  56723. // Better distribution in a cone at normal angles.
  56724. h = 1 - h * h;
  56725. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56726. radius = radius * h;
  56727. var randX = radius * Math.sin(s);
  56728. var randZ = radius * Math.cos(s);
  56729. var randY = h * this._height;
  56730. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56731. };
  56732. /**
  56733. * Clones the current emitter and returns a copy of it
  56734. * @returns the new emitter
  56735. */
  56736. ConeParticleEmitter.prototype.clone = function () {
  56737. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  56738. BABYLON.Tools.DeepCopy(this, newOne);
  56739. return newOne;
  56740. };
  56741. /**
  56742. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56743. * @param effect defines the update shader
  56744. */
  56745. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56746. effect.setFloat("radius", this.radius);
  56747. effect.setFloat("angle", this.angle);
  56748. effect.setFloat("height", this._height);
  56749. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56750. };
  56751. /**
  56752. * Returns a string to use to update the GPU particles update shader
  56753. * @returns a string containng the defines string
  56754. */
  56755. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56756. return "#define CONEEMITTER";
  56757. };
  56758. /**
  56759. * Returns the string "BoxEmitter"
  56760. * @returns a string containing the class name
  56761. */
  56762. ConeParticleEmitter.prototype.getClassName = function () {
  56763. return "ConeEmitter";
  56764. };
  56765. /**
  56766. * Serializes the particle system to a JSON object.
  56767. * @returns the JSON object
  56768. */
  56769. ConeParticleEmitter.prototype.serialize = function () {
  56770. var serializationObject = {};
  56771. serializationObject.type = this.getClassName();
  56772. serializationObject.radius = this.radius;
  56773. serializationObject.angle = this.angle;
  56774. serializationObject.directionRandomizer = this.directionRandomizer;
  56775. return serializationObject;
  56776. };
  56777. /**
  56778. * Parse properties from a JSON object
  56779. * @param serializationObject defines the JSON object
  56780. */
  56781. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56782. this.radius = serializationObject.radius;
  56783. this.angle = serializationObject.angle;
  56784. this.directionRandomizer = serializationObject.directionRandomizer;
  56785. };
  56786. return ConeParticleEmitter;
  56787. }());
  56788. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56789. })(BABYLON || (BABYLON = {}));
  56790. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56791. var BABYLON;
  56792. (function (BABYLON) {
  56793. /**
  56794. * Particle emitter emitting particles from the inside of a sphere.
  56795. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56796. */
  56797. var SphereParticleEmitter = /** @class */ (function () {
  56798. /**
  56799. * Creates a new instance SphereParticleEmitter
  56800. * @param radius the radius of the emission sphere (1 by default)
  56801. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56802. */
  56803. function SphereParticleEmitter(
  56804. /**
  56805. * The radius of the emission sphere.
  56806. */
  56807. radius,
  56808. /**
  56809. * How much to randomize the particle direction [0-1].
  56810. */
  56811. directionRandomizer) {
  56812. if (radius === void 0) { radius = 1; }
  56813. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56814. this.radius = radius;
  56815. this.directionRandomizer = directionRandomizer;
  56816. }
  56817. /**
  56818. * Called by the particle System when the direction is computed for the created particle.
  56819. * @param emitPower is the power of the particle (speed)
  56820. * @param worldMatrix is the world matrix of the particle system
  56821. * @param directionToUpdate is the direction vector to update with the result
  56822. * @param particle is the particle we are computed the direction for
  56823. */
  56824. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56825. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56826. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56827. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56828. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56829. direction.x += randX;
  56830. direction.y += randY;
  56831. direction.z += randZ;
  56832. direction.normalize();
  56833. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56834. };
  56835. /**
  56836. * Called by the particle System when the position is computed for the created particle.
  56837. * @param worldMatrix is the world matrix of the particle system
  56838. * @param positionToUpdate is the position vector to update with the result
  56839. * @param particle is the particle we are computed the position for
  56840. */
  56841. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56842. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56843. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  56844. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  56845. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56846. var randY = randRadius * Math.cos(theta);
  56847. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56848. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56849. };
  56850. /**
  56851. * Clones the current emitter and returns a copy of it
  56852. * @returns the new emitter
  56853. */
  56854. SphereParticleEmitter.prototype.clone = function () {
  56855. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56856. BABYLON.Tools.DeepCopy(this, newOne);
  56857. return newOne;
  56858. };
  56859. /**
  56860. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56861. * @param effect defines the update shader
  56862. */
  56863. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56864. effect.setFloat("radius", this.radius);
  56865. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56866. };
  56867. /**
  56868. * Returns a string to use to update the GPU particles update shader
  56869. * @returns a string containng the defines string
  56870. */
  56871. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56872. return "#define SPHEREEMITTER";
  56873. };
  56874. /**
  56875. * Returns the string "SphereParticleEmitter"
  56876. * @returns a string containing the class name
  56877. */
  56878. SphereParticleEmitter.prototype.getClassName = function () {
  56879. return "SphereParticleEmitter";
  56880. };
  56881. /**
  56882. * Serializes the particle system to a JSON object.
  56883. * @returns the JSON object
  56884. */
  56885. SphereParticleEmitter.prototype.serialize = function () {
  56886. var serializationObject = {};
  56887. serializationObject.type = this.getClassName();
  56888. serializationObject.radius = this.radius;
  56889. serializationObject.directionRandomizer = this.directionRandomizer;
  56890. return serializationObject;
  56891. };
  56892. /**
  56893. * Parse properties from a JSON object
  56894. * @param serializationObject defines the JSON object
  56895. */
  56896. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56897. this.radius = serializationObject.radius;
  56898. this.directionRandomizer = serializationObject.directionRandomizer;
  56899. };
  56900. return SphereParticleEmitter;
  56901. }());
  56902. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56903. /**
  56904. * Particle emitter emitting particles from the inside of a sphere.
  56905. * It emits the particles randomly between two vectors.
  56906. */
  56907. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56908. __extends(SphereDirectedParticleEmitter, _super);
  56909. /**
  56910. * Creates a new instance SphereDirectedParticleEmitter
  56911. * @param radius the radius of the emission sphere (1 by default)
  56912. * @param direction1 the min limit of the emission direction (up vector by default)
  56913. * @param direction2 the max limit of the emission direction (up vector by default)
  56914. */
  56915. function SphereDirectedParticleEmitter(radius,
  56916. /**
  56917. * The min limit of the emission direction.
  56918. */
  56919. direction1,
  56920. /**
  56921. * The max limit of the emission direction.
  56922. */
  56923. direction2) {
  56924. if (radius === void 0) { radius = 1; }
  56925. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56926. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56927. var _this = _super.call(this, radius) || this;
  56928. _this.direction1 = direction1;
  56929. _this.direction2 = direction2;
  56930. return _this;
  56931. }
  56932. /**
  56933. * Called by the particle System when the direction is computed for the created particle.
  56934. * @param emitPower is the power of the particle (speed)
  56935. * @param worldMatrix is the world matrix of the particle system
  56936. * @param directionToUpdate is the direction vector to update with the result
  56937. * @param particle is the particle we are computed the direction for
  56938. */
  56939. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56940. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56941. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56942. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56943. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56944. };
  56945. /**
  56946. * Clones the current emitter and returns a copy of it
  56947. * @returns the new emitter
  56948. */
  56949. SphereDirectedParticleEmitter.prototype.clone = function () {
  56950. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56951. BABYLON.Tools.DeepCopy(this, newOne);
  56952. return newOne;
  56953. };
  56954. /**
  56955. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56956. * @param effect defines the update shader
  56957. */
  56958. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56959. effect.setFloat("radius", this.radius);
  56960. effect.setVector3("direction1", this.direction1);
  56961. effect.setVector3("direction2", this.direction2);
  56962. };
  56963. /**
  56964. * Returns a string to use to update the GPU particles update shader
  56965. * @returns a string containng the defines string
  56966. */
  56967. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56968. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56969. };
  56970. /**
  56971. * Returns the string "SphereDirectedParticleEmitter"
  56972. * @returns a string containing the class name
  56973. */
  56974. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56975. return "SphereDirectedParticleEmitter";
  56976. };
  56977. /**
  56978. * Serializes the particle system to a JSON object.
  56979. * @returns the JSON object
  56980. */
  56981. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56982. var serializationObject = _super.prototype.serialize.call(this);
  56983. ;
  56984. serializationObject.direction1 = this.direction1.asArray();
  56985. ;
  56986. serializationObject.direction2 = this.direction2.asArray();
  56987. ;
  56988. return serializationObject;
  56989. };
  56990. /**
  56991. * Parse properties from a JSON object
  56992. * @param serializationObject defines the JSON object
  56993. */
  56994. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56995. _super.prototype.parse.call(this, serializationObject);
  56996. this.direction1.copyFrom(serializationObject.direction1);
  56997. this.direction2.copyFrom(serializationObject.direction2);
  56998. };
  56999. return SphereDirectedParticleEmitter;
  57000. }(SphereParticleEmitter));
  57001. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57002. })(BABYLON || (BABYLON = {}));
  57003. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57004. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57005. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57006. s = arguments[i];
  57007. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57008. t[p] = s[p];
  57009. }
  57010. return t;
  57011. };
  57012. var BABYLON;
  57013. (function (BABYLON) {
  57014. /**
  57015. * This represents a GPU particle system in Babylon
  57016. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57017. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57018. */
  57019. var GPUParticleSystem = /** @class */ (function () {
  57020. /**
  57021. * Instantiates a GPU particle system.
  57022. * 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.
  57023. * @param name The name of the particle system
  57024. * @param capacity The max number of particles alive at the same time
  57025. * @param scene The scene the particle system belongs to
  57026. */
  57027. function GPUParticleSystem(name, options, scene) {
  57028. /**
  57029. * The emitter represents the Mesh or position we are attaching the particle system to.
  57030. */
  57031. this.emitter = null;
  57032. /**
  57033. * The rendering group used by the Particle system to chose when to render.
  57034. */
  57035. this.renderingGroupId = 0;
  57036. /**
  57037. * The layer mask we are rendering the particles through.
  57038. */
  57039. this.layerMask = 0x0FFFFFFF;
  57040. this._targetIndex = 0;
  57041. this._currentRenderId = -1;
  57042. this._started = false;
  57043. this._stopped = false;
  57044. this._timeDelta = 0;
  57045. this._attributesStrideSize = 14;
  57046. this._actualFrame = 0;
  57047. /**
  57048. * List of animations used by the particle system.
  57049. */
  57050. this.animations = [];
  57051. /**
  57052. * An event triggered when the system is disposed.
  57053. */
  57054. this.onDisposeObservable = new BABYLON.Observable();
  57055. /**
  57056. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57057. */
  57058. this.updateSpeed = 0.01;
  57059. /**
  57060. * The amount of time the particle system is running (depends of the overall update speed).
  57061. */
  57062. this.targetStopDuration = 0;
  57063. /**
  57064. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57065. */
  57066. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57067. /**
  57068. * Minimum life time of emitting particles.
  57069. */
  57070. this.minLifeTime = 1;
  57071. /**
  57072. * Maximum life time of emitting particles.
  57073. */
  57074. this.maxLifeTime = 1;
  57075. /**
  57076. * Minimum Size of emitting particles.
  57077. */
  57078. this.minSize = 1;
  57079. /**
  57080. * Maximum Size of emitting particles.
  57081. */
  57082. this.maxSize = 1;
  57083. /**
  57084. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57085. */
  57086. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57087. /**
  57088. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57089. */
  57090. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57091. /**
  57092. * Color the particle will have at the end of its lifetime.
  57093. */
  57094. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57095. /**
  57096. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57097. */
  57098. this.emitRate = 100;
  57099. /**
  57100. * You can use gravity if you want to give an orientation to your particles.
  57101. */
  57102. this.gravity = BABYLON.Vector3.Zero();
  57103. /**
  57104. * Minimum power of emitting particles.
  57105. */
  57106. this.minEmitPower = 1;
  57107. /**
  57108. * Maximum power of emitting particles.
  57109. */
  57110. this.maxEmitPower = 1;
  57111. /**
  57112. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57113. * to override the particles.
  57114. */
  57115. this.forceDepthWrite = false;
  57116. this.id = name;
  57117. this.name = name;
  57118. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57119. this._engine = this._scene.getEngine();
  57120. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57121. this._capacity = fullOptions.capacity;
  57122. this._activeCount = fullOptions.capacity;
  57123. this._currentActiveCount = 0;
  57124. this._scene.particleSystems.push(this);
  57125. this._updateEffectOptions = {
  57126. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  57127. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57128. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  57129. uniformBuffersNames: [],
  57130. samplers: ["randomSampler"],
  57131. defines: "",
  57132. fallbacks: null,
  57133. onCompiled: null,
  57134. onError: null,
  57135. indexParameters: null,
  57136. maxSimultaneousLights: 0,
  57137. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  57138. };
  57139. // Random data
  57140. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57141. var d = [];
  57142. for (var i = 0; i < maxTextureSize; ++i) {
  57143. d.push(Math.random());
  57144. d.push(Math.random());
  57145. d.push(Math.random());
  57146. d.push(Math.random());
  57147. }
  57148. 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);
  57149. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57150. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57151. this._randomTextureSize = maxTextureSize;
  57152. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57153. }
  57154. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57155. /**
  57156. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57157. */
  57158. get: function () {
  57159. if (!BABYLON.Engine.LastCreatedEngine) {
  57160. return false;
  57161. }
  57162. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57163. },
  57164. enumerable: true,
  57165. configurable: true
  57166. });
  57167. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57168. /**
  57169. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57170. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57171. */
  57172. get: function () {
  57173. if (this.particleEmitterType.direction1) {
  57174. return this.particleEmitterType.direction1;
  57175. }
  57176. return BABYLON.Vector3.Zero();
  57177. },
  57178. set: function (value) {
  57179. if (this.particleEmitterType.direction1) {
  57180. this.particleEmitterType.direction1 = value;
  57181. }
  57182. },
  57183. enumerable: true,
  57184. configurable: true
  57185. });
  57186. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57187. /**
  57188. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57189. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57190. */
  57191. get: function () {
  57192. if (this.particleEmitterType.direction2) {
  57193. return this.particleEmitterType.direction2;
  57194. }
  57195. return BABYLON.Vector3.Zero();
  57196. },
  57197. set: function (value) {
  57198. if (this.particleEmitterType.direction2) {
  57199. this.particleEmitterType.direction2 = value;
  57200. }
  57201. },
  57202. enumerable: true,
  57203. configurable: true
  57204. });
  57205. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57206. /**
  57207. * 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.
  57208. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57209. */
  57210. get: function () {
  57211. if (this.particleEmitterType.minEmitBox) {
  57212. return this.particleEmitterType.minEmitBox;
  57213. }
  57214. return BABYLON.Vector3.Zero();
  57215. },
  57216. set: function (value) {
  57217. if (this.particleEmitterType.minEmitBox) {
  57218. this.particleEmitterType.minEmitBox = value;
  57219. }
  57220. },
  57221. enumerable: true,
  57222. configurable: true
  57223. });
  57224. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57225. /**
  57226. * 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.
  57227. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57228. */
  57229. get: function () {
  57230. if (this.particleEmitterType.maxEmitBox) {
  57231. return this.particleEmitterType.maxEmitBox;
  57232. }
  57233. return BABYLON.Vector3.Zero();
  57234. },
  57235. set: function (value) {
  57236. if (this.particleEmitterType.maxEmitBox) {
  57237. this.particleEmitterType.maxEmitBox = value;
  57238. }
  57239. },
  57240. enumerable: true,
  57241. configurable: true
  57242. });
  57243. /**
  57244. * Gets the maximum number of particles active at the same time.
  57245. * @returns The max number of active particles.
  57246. */
  57247. GPUParticleSystem.prototype.getCapacity = function () {
  57248. return this._capacity;
  57249. };
  57250. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57251. /**
  57252. * Gets or set the number of active particles
  57253. */
  57254. get: function () {
  57255. return this._activeCount;
  57256. },
  57257. set: function (value) {
  57258. this._activeCount = Math.min(value, this._capacity);
  57259. },
  57260. enumerable: true,
  57261. configurable: true
  57262. });
  57263. /**
  57264. * Is this system ready to be used/rendered
  57265. * @return true if the system is ready
  57266. */
  57267. GPUParticleSystem.prototype.isReady = function () {
  57268. if (!this._updateEffect) {
  57269. this._recreateUpdateEffect();
  57270. this._recreateRenderEffect();
  57271. return false;
  57272. }
  57273. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57274. return false;
  57275. }
  57276. return true;
  57277. };
  57278. /**
  57279. * Gets Wether the system has been started.
  57280. * @returns True if it has been started, otherwise false.
  57281. */
  57282. GPUParticleSystem.prototype.isStarted = function () {
  57283. return this._started;
  57284. };
  57285. /**
  57286. * Starts the particle system and begins to emit.
  57287. */
  57288. GPUParticleSystem.prototype.start = function () {
  57289. this._started = true;
  57290. this._stopped = false;
  57291. };
  57292. /**
  57293. * Stops the particle system.
  57294. */
  57295. GPUParticleSystem.prototype.stop = function () {
  57296. this._stopped = true;
  57297. };
  57298. /**
  57299. * Remove all active particles
  57300. */
  57301. GPUParticleSystem.prototype.reset = function () {
  57302. this._releaseBuffers();
  57303. this._releaseVAOs();
  57304. this._currentActiveCount = 0;
  57305. this._targetIndex = 0;
  57306. };
  57307. /**
  57308. * Returns the string "GPUParticleSystem"
  57309. * @returns a string containing the class name
  57310. */
  57311. GPUParticleSystem.prototype.getClassName = function () {
  57312. return "GPUParticleSystem";
  57313. };
  57314. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57315. var updateVertexBuffers = {};
  57316. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57317. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57318. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57319. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57320. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57321. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57322. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57323. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57324. this._engine.bindArrayBuffer(null);
  57325. return vao;
  57326. };
  57327. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57328. var renderVertexBuffers = {};
  57329. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57330. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57331. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57332. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57333. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57334. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57335. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57336. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57337. this._engine.bindArrayBuffer(null);
  57338. return vao;
  57339. };
  57340. GPUParticleSystem.prototype._initialize = function (force) {
  57341. if (force === void 0) { force = false; }
  57342. if (this._buffer0 && !force) {
  57343. return;
  57344. }
  57345. var engine = this._scene.getEngine();
  57346. var data = new Array();
  57347. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57348. // position
  57349. data.push(0.0);
  57350. data.push(0.0);
  57351. data.push(0.0);
  57352. // Age and life
  57353. data.push(0.0); // create the particle as a dead one to create a new one at start
  57354. data.push(0.0);
  57355. // Seed
  57356. data.push(Math.random());
  57357. // Size
  57358. data.push(0.0);
  57359. // color
  57360. data.push(0.0);
  57361. data.push(0.0);
  57362. data.push(0.0);
  57363. data.push(0.0);
  57364. // direction
  57365. data.push(0.0);
  57366. data.push(0.0);
  57367. data.push(0.0);
  57368. }
  57369. // Sprite data
  57370. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57371. -0.5, 0.5, 0, 1,
  57372. -0.5, -0.5, 0, 0,
  57373. 0.5, -0.5, 1, 0]);
  57374. // Buffers
  57375. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57376. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57377. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57378. // Update VAO
  57379. this._updateVAO = [];
  57380. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57381. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57382. // Render VAO
  57383. this._renderVAO = [];
  57384. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57385. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57386. // Links
  57387. this._sourceBuffer = this._buffer0;
  57388. this._targetBuffer = this._buffer1;
  57389. };
  57390. /** @hidden */
  57391. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57392. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57393. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57394. return;
  57395. }
  57396. this._updateEffectOptions.defines = defines;
  57397. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57398. };
  57399. /** @hidden */
  57400. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57401. var defines = "";
  57402. if (this._scene.clipPlane) {
  57403. defines = "\n#define CLIPPLANE";
  57404. }
  57405. if (this._renderEffect && this._renderEffect.defines === defines) {
  57406. return;
  57407. }
  57408. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57409. };
  57410. /**
  57411. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57412. */
  57413. GPUParticleSystem.prototype.animate = function () {
  57414. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57415. this._actualFrame += this._timeDelta;
  57416. if (!this._stopped) {
  57417. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57418. this.stop();
  57419. }
  57420. }
  57421. };
  57422. /**
  57423. * Renders the particle system in its current state.
  57424. * @returns the current number of particles
  57425. */
  57426. GPUParticleSystem.prototype.render = function () {
  57427. if (!this._started) {
  57428. return 0;
  57429. }
  57430. this._recreateUpdateEffect();
  57431. this._recreateRenderEffect();
  57432. if (!this.isReady()) {
  57433. return 0;
  57434. }
  57435. if (this._currentRenderId === this._scene.getRenderId()) {
  57436. return 0;
  57437. }
  57438. this._currentRenderId = this._scene.getRenderId();
  57439. // Get everything ready to render
  57440. this._initialize();
  57441. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57442. // Enable update effect
  57443. this._engine.enableEffect(this._updateEffect);
  57444. this._engine.setState(false);
  57445. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57446. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57447. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57448. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57449. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57450. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57451. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57452. this._updateEffect.setDirectColor4("color1", this.color1);
  57453. this._updateEffect.setDirectColor4("color2", this.color2);
  57454. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57455. this._updateEffect.setVector3("gravity", this.gravity);
  57456. if (this.particleEmitterType) {
  57457. this.particleEmitterType.applyToShader(this._updateEffect);
  57458. }
  57459. var emitterWM;
  57460. if (this.emitter.position) {
  57461. var emitterMesh = this.emitter;
  57462. emitterWM = emitterMesh.getWorldMatrix();
  57463. }
  57464. else {
  57465. var emitterPosition = this.emitter;
  57466. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57467. }
  57468. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57469. // Bind source VAO
  57470. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57471. // Update
  57472. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57473. this._engine.setRasterizerState(false);
  57474. this._engine.beginTransformFeedback();
  57475. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57476. this._engine.endTransformFeedback();
  57477. this._engine.setRasterizerState(true);
  57478. this._engine.bindTransformFeedbackBuffer(null);
  57479. // Enable render effect
  57480. this._engine.enableEffect(this._renderEffect);
  57481. var viewMatrix = this._scene.getViewMatrix();
  57482. this._renderEffect.setMatrix("view", viewMatrix);
  57483. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57484. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57485. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57486. if (this._scene.clipPlane) {
  57487. var clipPlane = this._scene.clipPlane;
  57488. var invView = viewMatrix.clone();
  57489. invView.invert();
  57490. this._renderEffect.setMatrix("invView", invView);
  57491. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57492. }
  57493. // Draw order
  57494. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57495. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57496. }
  57497. else {
  57498. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57499. }
  57500. if (this.forceDepthWrite) {
  57501. this._engine.setDepthWrite(true);
  57502. }
  57503. // Bind source VAO
  57504. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57505. // Render
  57506. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57507. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57508. // Switch VAOs
  57509. this._targetIndex++;
  57510. if (this._targetIndex === 2) {
  57511. this._targetIndex = 0;
  57512. }
  57513. // Switch buffers
  57514. var tmpBuffer = this._sourceBuffer;
  57515. this._sourceBuffer = this._targetBuffer;
  57516. this._targetBuffer = tmpBuffer;
  57517. return this._currentActiveCount;
  57518. };
  57519. /**
  57520. * Rebuilds the particle system
  57521. */
  57522. GPUParticleSystem.prototype.rebuild = function () {
  57523. this._initialize(true);
  57524. };
  57525. GPUParticleSystem.prototype._releaseBuffers = function () {
  57526. if (this._buffer0) {
  57527. this._buffer0.dispose();
  57528. this._buffer0 = null;
  57529. }
  57530. if (this._buffer1) {
  57531. this._buffer1.dispose();
  57532. this._buffer1 = null;
  57533. }
  57534. if (this._spriteBuffer) {
  57535. this._spriteBuffer.dispose();
  57536. this._spriteBuffer = null;
  57537. }
  57538. };
  57539. GPUParticleSystem.prototype._releaseVAOs = function () {
  57540. if (!this._updateVAO) {
  57541. return;
  57542. }
  57543. for (var index = 0; index < this._updateVAO.length; index++) {
  57544. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57545. }
  57546. this._updateVAO = [];
  57547. for (var index = 0; index < this._renderVAO.length; index++) {
  57548. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57549. }
  57550. this._renderVAO = [];
  57551. };
  57552. /**
  57553. * Disposes the particle system and free the associated resources
  57554. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57555. */
  57556. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57557. if (disposeTexture === void 0) { disposeTexture = true; }
  57558. var index = this._scene.particleSystems.indexOf(this);
  57559. if (index > -1) {
  57560. this._scene.particleSystems.splice(index, 1);
  57561. }
  57562. this._releaseBuffers();
  57563. this._releaseVAOs();
  57564. if (this._randomTexture) {
  57565. this._randomTexture.dispose();
  57566. this._randomTexture = null;
  57567. }
  57568. if (disposeTexture && this.particleTexture) {
  57569. this.particleTexture.dispose();
  57570. this.particleTexture = null;
  57571. }
  57572. // Callback
  57573. this.onDisposeObservable.notifyObservers(this);
  57574. this.onDisposeObservable.clear();
  57575. };
  57576. /**
  57577. * Clones the particle system.
  57578. * @param name The name of the cloned object
  57579. * @param newEmitter The new emitter to use
  57580. * @returns the cloned particle system
  57581. */
  57582. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57583. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57584. BABYLON.Tools.DeepCopy(this, result);
  57585. if (newEmitter === undefined) {
  57586. newEmitter = this.emitter;
  57587. }
  57588. result.emitter = newEmitter;
  57589. if (this.particleTexture) {
  57590. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57591. }
  57592. return result;
  57593. };
  57594. /**
  57595. * Serializes the particle system to a JSON object.
  57596. * @returns the JSON object
  57597. */
  57598. GPUParticleSystem.prototype.serialize = function () {
  57599. var serializationObject = {};
  57600. serializationObject.name = this.name;
  57601. serializationObject.id = this.id;
  57602. // Emitter
  57603. if (this.emitter.position) {
  57604. var emitterMesh = this.emitter;
  57605. serializationObject.emitterId = emitterMesh.id;
  57606. }
  57607. else {
  57608. var emitterPosition = this.emitter;
  57609. serializationObject.emitter = emitterPosition.asArray();
  57610. }
  57611. serializationObject.capacity = this.getCapacity();
  57612. if (this.particleTexture) {
  57613. serializationObject.textureName = this.particleTexture.name;
  57614. }
  57615. // Animations
  57616. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57617. // Particle system
  57618. serializationObject.activeParticleCount = this.activeParticleCount;
  57619. serializationObject.randomTextureSize = this._randomTextureSize;
  57620. serializationObject.minSize = this.minSize;
  57621. serializationObject.maxSize = this.maxSize;
  57622. serializationObject.minEmitPower = this.minEmitPower;
  57623. serializationObject.maxEmitPower = this.maxEmitPower;
  57624. serializationObject.minLifeTime = this.minLifeTime;
  57625. serializationObject.maxLifeTime = this.maxLifeTime;
  57626. serializationObject.emitRate = this.emitRate;
  57627. serializationObject.gravity = this.gravity.asArray();
  57628. serializationObject.color1 = this.color1.asArray();
  57629. serializationObject.color2 = this.color2.asArray();
  57630. serializationObject.colorDead = this.colorDead.asArray();
  57631. serializationObject.updateSpeed = this.updateSpeed;
  57632. serializationObject.targetStopDuration = this.targetStopDuration;
  57633. serializationObject.blendMode = this.blendMode;
  57634. // Emitter
  57635. if (this.particleEmitterType) {
  57636. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57637. }
  57638. return serializationObject;
  57639. };
  57640. /**
  57641. * Parses a JSON object to create a GPU particle system.
  57642. * @param parsedParticleSystem The JSON object to parse
  57643. * @param scene The scene to create the particle system in
  57644. * @param rootUrl The root url to use to load external dependencies like texture
  57645. * @returns the parsed GPU particle system
  57646. */
  57647. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57648. var name = parsedParticleSystem.name;
  57649. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57650. if (parsedParticleSystem.id) {
  57651. particleSystem.id = parsedParticleSystem.id;
  57652. }
  57653. // Texture
  57654. if (parsedParticleSystem.textureName) {
  57655. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57656. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57657. }
  57658. // Emitter
  57659. if (parsedParticleSystem.emitterId) {
  57660. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57661. }
  57662. else {
  57663. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57664. }
  57665. // Animations
  57666. if (parsedParticleSystem.animations) {
  57667. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57668. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57669. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57670. }
  57671. }
  57672. // Particle system
  57673. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57674. particleSystem.minSize = parsedParticleSystem.minSize;
  57675. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57676. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57677. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57678. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57679. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57680. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57681. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57682. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57683. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57684. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57685. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57686. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57687. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57688. // Emitter
  57689. if (parsedParticleSystem.particleEmitterType) {
  57690. var emitterType = void 0;
  57691. switch (parsedParticleSystem.particleEmitterType.type) {
  57692. case "SphereEmitter":
  57693. emitterType = new BABYLON.SphereParticleEmitter();
  57694. break;
  57695. case "SphereDirectedParticleEmitter":
  57696. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57697. break;
  57698. case "ConeEmitter":
  57699. emitterType = new BABYLON.ConeParticleEmitter();
  57700. break;
  57701. case "BoxEmitter":
  57702. default:
  57703. emitterType = new BABYLON.BoxParticleEmitter();
  57704. break;
  57705. }
  57706. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57707. particleSystem.particleEmitterType = emitterType;
  57708. }
  57709. return particleSystem;
  57710. };
  57711. return GPUParticleSystem;
  57712. }());
  57713. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57714. })(BABYLON || (BABYLON = {}));
  57715. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57716. var BABYLON;
  57717. (function (BABYLON) {
  57718. /**
  57719. * Represents one particle of a solid particle system.
  57720. */
  57721. var SolidParticle = /** @class */ (function () {
  57722. /**
  57723. * Creates a Solid Particle object.
  57724. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57725. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57726. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57727. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57728. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57729. * @param shapeId (integer) is the model shape identifier in the SPS.
  57730. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57731. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57732. */
  57733. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57734. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57735. /**
  57736. * particle global index
  57737. */
  57738. this.idx = 0;
  57739. /**
  57740. * The color of the particle
  57741. */
  57742. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57743. /**
  57744. * The world space position of the particle.
  57745. */
  57746. this.position = BABYLON.Vector3.Zero();
  57747. /**
  57748. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57749. */
  57750. this.rotation = BABYLON.Vector3.Zero();
  57751. /**
  57752. * The scaling of the particle.
  57753. */
  57754. this.scaling = BABYLON.Vector3.One();
  57755. /**
  57756. * The uvs of the particle.
  57757. */
  57758. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57759. /**
  57760. * The current speed of the particle.
  57761. */
  57762. this.velocity = BABYLON.Vector3.Zero();
  57763. /**
  57764. * The pivot point in the particle local space.
  57765. */
  57766. this.pivot = BABYLON.Vector3.Zero();
  57767. /**
  57768. * Must the particle be translated from its pivot point in its local space ?
  57769. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57770. * Default : false
  57771. */
  57772. this.translateFromPivot = false;
  57773. /**
  57774. * Is the particle active or not ?
  57775. */
  57776. this.alive = true;
  57777. /**
  57778. * Is the particle visible or not ?
  57779. */
  57780. this.isVisible = true;
  57781. /**
  57782. * Index of this particle in the global "positions" array (Internal use)
  57783. */
  57784. this._pos = 0;
  57785. /**
  57786. * Index of this particle in the global "indices" array (Internal use)
  57787. */
  57788. this._ind = 0;
  57789. /**
  57790. * ModelShape id of this particle
  57791. */
  57792. this.shapeId = 0;
  57793. /**
  57794. * Index of the particle in its shape id (Internal use)
  57795. */
  57796. this.idxInShape = 0;
  57797. /**
  57798. * Still set as invisible in order to skip useless computations (Internal use)
  57799. */
  57800. this._stillInvisible = false;
  57801. /**
  57802. * Last computed particle rotation matrix
  57803. */
  57804. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57805. /**
  57806. * Parent particle Id, if any.
  57807. * Default null.
  57808. */
  57809. this.parentId = null;
  57810. /**
  57811. * Internal global position in the SPS.
  57812. */
  57813. this._globalPosition = BABYLON.Vector3.Zero();
  57814. this.idx = particleIndex;
  57815. this._pos = positionIndex;
  57816. this._ind = indiceIndex;
  57817. this._model = model;
  57818. this.shapeId = shapeId;
  57819. this.idxInShape = idxInShape;
  57820. this._sps = sps;
  57821. if (modelBoundingInfo) {
  57822. this._modelBoundingInfo = modelBoundingInfo;
  57823. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57824. }
  57825. }
  57826. Object.defineProperty(SolidParticle.prototype, "scale", {
  57827. /**
  57828. * Legacy support, changed scale to scaling
  57829. */
  57830. get: function () {
  57831. return this.scaling;
  57832. },
  57833. /**
  57834. * Legacy support, changed scale to scaling
  57835. */
  57836. set: function (scale) {
  57837. this.scaling = scale;
  57838. },
  57839. enumerable: true,
  57840. configurable: true
  57841. });
  57842. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57843. /**
  57844. * Legacy support, changed quaternion to rotationQuaternion
  57845. */
  57846. get: function () {
  57847. return this.rotationQuaternion;
  57848. },
  57849. /**
  57850. * Legacy support, changed quaternion to rotationQuaternion
  57851. */
  57852. set: function (q) {
  57853. this.rotationQuaternion = q;
  57854. },
  57855. enumerable: true,
  57856. configurable: true
  57857. });
  57858. /**
  57859. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57860. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57861. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57862. * @returns true if it intersects
  57863. */
  57864. SolidParticle.prototype.intersectsMesh = function (target) {
  57865. if (!this._boundingInfo || !target._boundingInfo) {
  57866. return false;
  57867. }
  57868. if (this._sps._bSphereOnly) {
  57869. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57870. }
  57871. return this._boundingInfo.intersects(target._boundingInfo, false);
  57872. };
  57873. return SolidParticle;
  57874. }());
  57875. BABYLON.SolidParticle = SolidParticle;
  57876. /**
  57877. * Represents the shape of the model used by one particle of a solid particle system.
  57878. * SPS internal tool, don't use it manually.
  57879. */
  57880. var ModelShape = /** @class */ (function () {
  57881. /**
  57882. * 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.
  57883. * SPS internal tool, don't use it manually.
  57884. * @hidden
  57885. */
  57886. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57887. /**
  57888. * length of the shape in the model indices array (internal use)
  57889. */
  57890. this._indicesLength = 0;
  57891. this.shapeID = id;
  57892. this._shape = shape;
  57893. this._indicesLength = indicesLength;
  57894. this._shapeUV = shapeUV;
  57895. this._positionFunction = posFunction;
  57896. this._vertexFunction = vtxFunction;
  57897. }
  57898. return ModelShape;
  57899. }());
  57900. BABYLON.ModelShape = ModelShape;
  57901. /**
  57902. * Represents a Depth Sorted Particle in the solid particle system.
  57903. */
  57904. var DepthSortedParticle = /** @class */ (function () {
  57905. function DepthSortedParticle() {
  57906. /**
  57907. * Index of the particle in the "indices" array
  57908. */
  57909. this.ind = 0;
  57910. /**
  57911. * Length of the particle shape in the "indices" array
  57912. */
  57913. this.indicesLength = 0;
  57914. /**
  57915. * Squared distance from the particle to the camera
  57916. */
  57917. this.sqDistance = 0.0;
  57918. }
  57919. return DepthSortedParticle;
  57920. }());
  57921. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57922. })(BABYLON || (BABYLON = {}));
  57923. //# sourceMappingURL=babylon.solidParticle.js.map
  57924. var BABYLON;
  57925. (function (BABYLON) {
  57926. /**
  57927. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  57928. *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.
  57929. * The SPS is also a particle system. It provides some methods to manage the particles.
  57930. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  57931. *
  57932. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57933. */
  57934. var SolidParticleSystem = /** @class */ (function () {
  57935. /**
  57936. * Creates a SPS (Solid Particle System) object.
  57937. * @param name (String) is the SPS name, this will be the underlying mesh name.
  57938. * @param scene (Scene) is the scene in which the SPS is added.
  57939. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  57940. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  57941. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  57942. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  57943. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  57944. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  57945. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  57946. */
  57947. function SolidParticleSystem(name, scene, options) {
  57948. /**
  57949. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57950. * Example : var p = SPS.particles[i];
  57951. */
  57952. this.particles = new Array();
  57953. /**
  57954. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57955. */
  57956. this.nbParticles = 0;
  57957. /**
  57958. * If the particles must ever face the camera (default false). Useful for planar particles.
  57959. */
  57960. this.billboard = false;
  57961. /**
  57962. * Recompute normals when adding a shape
  57963. */
  57964. this.recomputeNormals = true;
  57965. /**
  57966. * This a counter ofr your own usage. It's not set by any SPS functions.
  57967. */
  57968. this.counter = 0;
  57969. /**
  57970. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57971. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57972. */
  57973. this.vars = {};
  57974. /**
  57975. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  57976. */
  57977. this._bSphereOnly = false;
  57978. /**
  57979. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  57980. */
  57981. this._bSphereRadiusFactor = 1.0;
  57982. this._positions = new Array();
  57983. this._indices = new Array();
  57984. this._normals = new Array();
  57985. this._colors = new Array();
  57986. this._uvs = new Array();
  57987. this._index = 0; // indices index
  57988. this._updatable = true;
  57989. this._pickable = false;
  57990. this._isVisibilityBoxLocked = false;
  57991. this._alwaysVisible = false;
  57992. this._depthSort = false;
  57993. this._shapeCounter = 0;
  57994. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  57995. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57996. this._computeParticleColor = true;
  57997. this._computeParticleTexture = true;
  57998. this._computeParticleRotation = true;
  57999. this._computeParticleVertex = false;
  58000. this._computeBoundingBox = false;
  58001. this._depthSortParticles = true;
  58002. this._cam_axisZ = BABYLON.Vector3.Zero();
  58003. this._cam_axisY = BABYLON.Vector3.Zero();
  58004. this._cam_axisX = BABYLON.Vector3.Zero();
  58005. this._axisZ = BABYLON.Axis.Z;
  58006. this._camDir = BABYLON.Vector3.Zero();
  58007. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58008. this._rotMatrix = new BABYLON.Matrix();
  58009. this._invertMatrix = new BABYLON.Matrix();
  58010. this._rotated = BABYLON.Vector3.Zero();
  58011. this._quaternion = new BABYLON.Quaternion();
  58012. this._vertex = BABYLON.Vector3.Zero();
  58013. this._normal = BABYLON.Vector3.Zero();
  58014. this._yaw = 0.0;
  58015. this._pitch = 0.0;
  58016. this._roll = 0.0;
  58017. this._halfroll = 0.0;
  58018. this._halfpitch = 0.0;
  58019. this._halfyaw = 0.0;
  58020. this._sinRoll = 0.0;
  58021. this._cosRoll = 0.0;
  58022. this._sinPitch = 0.0;
  58023. this._cosPitch = 0.0;
  58024. this._sinYaw = 0.0;
  58025. this._cosYaw = 0.0;
  58026. this._mustUnrotateFixedNormals = false;
  58027. this._minimum = BABYLON.Vector3.Zero();
  58028. this._maximum = BABYLON.Vector3.Zero();
  58029. this._minBbox = BABYLON.Vector3.Zero();
  58030. this._maxBbox = BABYLON.Vector3.Zero();
  58031. this._particlesIntersect = false;
  58032. this._depthSortFunction = function (p1, p2) {
  58033. return (p2.sqDistance - p1.sqDistance);
  58034. };
  58035. this._needs32Bits = false;
  58036. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58037. this._scaledPivot = BABYLON.Vector3.Zero();
  58038. this._particleHasParent = false;
  58039. this.name = name;
  58040. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58041. this._camera = scene.activeCamera;
  58042. this._pickable = options ? options.isPickable : false;
  58043. this._depthSort = options ? options.enableDepthSort : false;
  58044. this._particlesIntersect = options ? options.particleIntersection : false;
  58045. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58046. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58047. if (options && options.updatable) {
  58048. this._updatable = options.updatable;
  58049. }
  58050. else {
  58051. this._updatable = true;
  58052. }
  58053. if (this._pickable) {
  58054. this.pickedParticles = [];
  58055. }
  58056. if (this._depthSort) {
  58057. this.depthSortedParticles = [];
  58058. }
  58059. }
  58060. /**
  58061. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58062. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58063. * @returns the created mesh
  58064. */
  58065. SolidParticleSystem.prototype.buildMesh = function () {
  58066. if (this.nbParticles === 0) {
  58067. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58068. this.addShape(triangle, 1);
  58069. triangle.dispose();
  58070. }
  58071. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58072. this._positions32 = new Float32Array(this._positions);
  58073. this._uvs32 = new Float32Array(this._uvs);
  58074. this._colors32 = new Float32Array(this._colors);
  58075. if (this.recomputeNormals) {
  58076. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58077. }
  58078. this._normals32 = new Float32Array(this._normals);
  58079. this._fixedNormal32 = new Float32Array(this._normals);
  58080. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58081. this._unrotateFixedNormals();
  58082. }
  58083. var vertexData = new BABYLON.VertexData();
  58084. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58085. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58086. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58087. if (this._uvs32) {
  58088. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58089. ;
  58090. }
  58091. if (this._colors32) {
  58092. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58093. }
  58094. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58095. vertexData.applyToMesh(mesh, this._updatable);
  58096. this.mesh = mesh;
  58097. this.mesh.isPickable = this._pickable;
  58098. // free memory
  58099. if (!this._depthSort) {
  58100. this._indices = null;
  58101. }
  58102. this._positions = null;
  58103. this._normals = null;
  58104. this._uvs = null;
  58105. this._colors = null;
  58106. if (!this._updatable) {
  58107. this.particles.length = 0;
  58108. }
  58109. return mesh;
  58110. };
  58111. /**
  58112. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58113. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58114. * Thus the particles generated from `digest()` have their property `position` set yet.
  58115. * @param mesh ( Mesh ) is the mesh to be digested
  58116. * @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
  58117. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58118. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58119. * @returns the current SPS
  58120. */
  58121. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58122. var size = (options && options.facetNb) || 1;
  58123. var number = (options && options.number) || 0;
  58124. var delta = (options && options.delta) || 0;
  58125. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58126. var meshInd = mesh.getIndices();
  58127. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58128. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58129. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58130. var f = 0; // facet counter
  58131. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58132. // compute size from number
  58133. if (number) {
  58134. number = (number > totalFacets) ? totalFacets : number;
  58135. size = Math.round(totalFacets / number);
  58136. delta = 0;
  58137. }
  58138. else {
  58139. size = (size > totalFacets) ? totalFacets : size;
  58140. }
  58141. var facetPos = []; // submesh positions
  58142. var facetInd = []; // submesh indices
  58143. var facetUV = []; // submesh UV
  58144. var facetCol = []; // submesh colors
  58145. var barycenter = BABYLON.Vector3.Zero();
  58146. var sizeO = size;
  58147. while (f < totalFacets) {
  58148. size = sizeO + Math.floor((1 + delta) * Math.random());
  58149. if (f > totalFacets - size) {
  58150. size = totalFacets - f;
  58151. }
  58152. // reset temp arrays
  58153. facetPos.length = 0;
  58154. facetInd.length = 0;
  58155. facetUV.length = 0;
  58156. facetCol.length = 0;
  58157. // iterate over "size" facets
  58158. var fi = 0;
  58159. for (var j = f * 3; j < (f + size) * 3; j++) {
  58160. facetInd.push(fi);
  58161. var i = meshInd[j];
  58162. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58163. if (meshUV) {
  58164. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58165. }
  58166. if (meshCol) {
  58167. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58168. }
  58169. fi++;
  58170. }
  58171. // create a model shape for each single particle
  58172. var idx = this.nbParticles;
  58173. var shape = this._posToShape(facetPos);
  58174. var shapeUV = this._uvsToShapeUV(facetUV);
  58175. // compute the barycenter of the shape
  58176. var v;
  58177. for (v = 0; v < shape.length; v++) {
  58178. barycenter.addInPlace(shape[v]);
  58179. }
  58180. barycenter.scaleInPlace(1 / shape.length);
  58181. // shift the shape from its barycenter to the origin
  58182. for (v = 0; v < shape.length; v++) {
  58183. shape[v].subtractInPlace(barycenter);
  58184. }
  58185. var bInfo;
  58186. if (this._particlesIntersect) {
  58187. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58188. }
  58189. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58190. // add the particle in the SPS
  58191. var currentPos = this._positions.length;
  58192. var currentInd = this._indices.length;
  58193. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58194. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58195. // initialize the particle position
  58196. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58197. this._index += shape.length;
  58198. idx++;
  58199. this.nbParticles++;
  58200. this._shapeCounter++;
  58201. f += size;
  58202. }
  58203. return this;
  58204. };
  58205. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58206. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58207. var index = 0;
  58208. var idx = 0;
  58209. for (var p = 0; p < this.particles.length; p++) {
  58210. this._particle = this.particles[p];
  58211. this._shape = this._particle._model._shape;
  58212. if (this._particle.rotationQuaternion) {
  58213. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58214. }
  58215. else {
  58216. this._yaw = this._particle.rotation.y;
  58217. this._pitch = this._particle.rotation.x;
  58218. this._roll = this._particle.rotation.z;
  58219. this._quaternionRotationYPR();
  58220. }
  58221. this._quaternionToRotationMatrix();
  58222. this._rotMatrix.invertToRef(this._invertMatrix);
  58223. for (var pt = 0; pt < this._shape.length; pt++) {
  58224. idx = index + pt * 3;
  58225. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58226. this._fixedNormal32[idx] = this._normal.x;
  58227. this._fixedNormal32[idx + 1] = this._normal.y;
  58228. this._fixedNormal32[idx + 2] = this._normal.z;
  58229. }
  58230. index = idx + 3;
  58231. }
  58232. };
  58233. //reset copy
  58234. SolidParticleSystem.prototype._resetCopy = function () {
  58235. this._copy.position.x = 0;
  58236. this._copy.position.y = 0;
  58237. this._copy.position.z = 0;
  58238. this._copy.rotation.x = 0;
  58239. this._copy.rotation.y = 0;
  58240. this._copy.rotation.z = 0;
  58241. this._copy.rotationQuaternion = null;
  58242. this._copy.scaling.x = 1.0;
  58243. this._copy.scaling.y = 1.0;
  58244. this._copy.scaling.z = 1.0;
  58245. this._copy.uvs.x = 0;
  58246. this._copy.uvs.y = 0;
  58247. this._copy.uvs.z = 1.0;
  58248. this._copy.uvs.w = 1.0;
  58249. this._copy.color = null;
  58250. this._copy.translateFromPivot = false;
  58251. };
  58252. // _meshBuilder : inserts the shape model in the global SPS mesh
  58253. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58254. var i;
  58255. var u = 0;
  58256. var c = 0;
  58257. var n = 0;
  58258. this._resetCopy();
  58259. if (options && options.positionFunction) { // call to custom positionFunction
  58260. options.positionFunction(this._copy, idx, idxInShape);
  58261. this._mustUnrotateFixedNormals = true;
  58262. }
  58263. if (this._copy.rotationQuaternion) {
  58264. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58265. }
  58266. else {
  58267. this._yaw = this._copy.rotation.y;
  58268. this._pitch = this._copy.rotation.x;
  58269. this._roll = this._copy.rotation.z;
  58270. this._quaternionRotationYPR();
  58271. }
  58272. this._quaternionToRotationMatrix();
  58273. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58274. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58275. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58276. if (this._copy.translateFromPivot) {
  58277. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58278. }
  58279. else {
  58280. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58281. }
  58282. for (i = 0; i < shape.length; i++) {
  58283. this._vertex.x = shape[i].x;
  58284. this._vertex.y = shape[i].y;
  58285. this._vertex.z = shape[i].z;
  58286. if (options && options.vertexFunction) {
  58287. options.vertexFunction(this._copy, this._vertex, i);
  58288. }
  58289. this._vertex.x *= this._copy.scaling.x;
  58290. this._vertex.y *= this._copy.scaling.y;
  58291. this._vertex.z *= this._copy.scaling.z;
  58292. this._vertex.x -= this._scaledPivot.x;
  58293. this._vertex.y -= this._scaledPivot.y;
  58294. this._vertex.z -= this._scaledPivot.z;
  58295. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58296. this._rotated.addInPlace(this._pivotBackTranslation);
  58297. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58298. if (meshUV) {
  58299. 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);
  58300. u += 2;
  58301. }
  58302. if (this._copy.color) {
  58303. this._color = this._copy.color;
  58304. }
  58305. else if (meshCol && meshCol[c] !== undefined) {
  58306. this._color.r = meshCol[c];
  58307. this._color.g = meshCol[c + 1];
  58308. this._color.b = meshCol[c + 2];
  58309. this._color.a = meshCol[c + 3];
  58310. }
  58311. else {
  58312. this._color.r = 1.0;
  58313. this._color.g = 1.0;
  58314. this._color.b = 1.0;
  58315. this._color.a = 1.0;
  58316. }
  58317. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58318. c += 4;
  58319. if (!this.recomputeNormals && meshNor) {
  58320. this._normal.x = meshNor[n];
  58321. this._normal.y = meshNor[n + 1];
  58322. this._normal.z = meshNor[n + 2];
  58323. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58324. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58325. n += 3;
  58326. }
  58327. }
  58328. for (i = 0; i < meshInd.length; i++) {
  58329. var current_ind = p + meshInd[i];
  58330. indices.push(current_ind);
  58331. if (current_ind > 65535) {
  58332. this._needs32Bits = true;
  58333. }
  58334. }
  58335. if (this._pickable) {
  58336. var nbfaces = meshInd.length / 3;
  58337. for (i = 0; i < nbfaces; i++) {
  58338. this.pickedParticles.push({ idx: idx, faceId: i });
  58339. }
  58340. }
  58341. if (this._depthSort) {
  58342. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58343. }
  58344. return this._copy;
  58345. };
  58346. // returns a shape array from positions array
  58347. SolidParticleSystem.prototype._posToShape = function (positions) {
  58348. var shape = [];
  58349. for (var i = 0; i < positions.length; i += 3) {
  58350. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58351. }
  58352. return shape;
  58353. };
  58354. // returns a shapeUV array from a Vector4 uvs
  58355. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58356. var shapeUV = [];
  58357. if (uvs) {
  58358. for (var i = 0; i < uvs.length; i++)
  58359. shapeUV.push(uvs[i]);
  58360. }
  58361. return shapeUV;
  58362. };
  58363. // adds a new particle object in the particles array
  58364. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58365. if (bInfo === void 0) { bInfo = null; }
  58366. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58367. this.particles.push(sp);
  58368. return sp;
  58369. };
  58370. /**
  58371. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58372. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58373. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58374. * @param nb (positive integer) the number of particles to be created from this model
  58375. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58376. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58377. * @returns the number of shapes in the system
  58378. */
  58379. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58380. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58381. var meshInd = mesh.getIndices();
  58382. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58383. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58384. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58385. var bbInfo;
  58386. if (this._particlesIntersect) {
  58387. bbInfo = mesh.getBoundingInfo();
  58388. }
  58389. var shape = this._posToShape(meshPos);
  58390. var shapeUV = this._uvsToShapeUV(meshUV);
  58391. var posfunc = options ? options.positionFunction : null;
  58392. var vtxfunc = options ? options.vertexFunction : null;
  58393. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58394. // particles
  58395. var sp;
  58396. var currentCopy;
  58397. var idx = this.nbParticles;
  58398. for (var i = 0; i < nb; i++) {
  58399. var currentPos = this._positions.length;
  58400. var currentInd = this._indices.length;
  58401. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58402. if (this._updatable) {
  58403. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58404. sp.position.copyFrom(currentCopy.position);
  58405. sp.rotation.copyFrom(currentCopy.rotation);
  58406. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58407. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58408. }
  58409. if (currentCopy.color && sp.color) {
  58410. sp.color.copyFrom(currentCopy.color);
  58411. }
  58412. sp.scaling.copyFrom(currentCopy.scaling);
  58413. sp.uvs.copyFrom(currentCopy.uvs);
  58414. }
  58415. this._index += shape.length;
  58416. idx++;
  58417. }
  58418. this.nbParticles += nb;
  58419. this._shapeCounter++;
  58420. return this._shapeCounter - 1;
  58421. };
  58422. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58423. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58424. this._resetCopy();
  58425. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58426. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58427. }
  58428. if (this._copy.rotationQuaternion) {
  58429. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58430. }
  58431. else {
  58432. this._yaw = this._copy.rotation.y;
  58433. this._pitch = this._copy.rotation.x;
  58434. this._roll = this._copy.rotation.z;
  58435. this._quaternionRotationYPR();
  58436. }
  58437. this._quaternionToRotationMatrix();
  58438. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58439. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58440. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58441. if (this._copy.translateFromPivot) {
  58442. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58443. }
  58444. else {
  58445. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58446. }
  58447. this._shape = particle._model._shape;
  58448. for (var pt = 0; pt < this._shape.length; pt++) {
  58449. this._vertex.x = this._shape[pt].x;
  58450. this._vertex.y = this._shape[pt].y;
  58451. this._vertex.z = this._shape[pt].z;
  58452. if (particle._model._vertexFunction) {
  58453. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58454. }
  58455. this._vertex.x *= this._copy.scaling.x;
  58456. this._vertex.y *= this._copy.scaling.y;
  58457. this._vertex.z *= this._copy.scaling.z;
  58458. this._vertex.x -= this._scaledPivot.x;
  58459. this._vertex.y -= this._scaledPivot.y;
  58460. this._vertex.z -= this._scaledPivot.z;
  58461. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58462. this._rotated.addInPlace(this._pivotBackTranslation);
  58463. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58464. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58465. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58466. }
  58467. particle.position.x = 0.0;
  58468. particle.position.y = 0.0;
  58469. particle.position.z = 0.0;
  58470. particle.rotation.x = 0.0;
  58471. particle.rotation.y = 0.0;
  58472. particle.rotation.z = 0.0;
  58473. particle.rotationQuaternion = null;
  58474. particle.scaling.x = 1.0;
  58475. particle.scaling.y = 1.0;
  58476. particle.scaling.z = 1.0;
  58477. particle.uvs.x = 0.0;
  58478. particle.uvs.y = 0.0;
  58479. particle.uvs.z = 1.0;
  58480. particle.uvs.w = 1.0;
  58481. particle.pivot.x = 0.0;
  58482. particle.pivot.y = 0.0;
  58483. particle.pivot.z = 0.0;
  58484. particle.translateFromPivot = false;
  58485. particle.parentId = null;
  58486. };
  58487. /**
  58488. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58489. * @returns the SPS.
  58490. */
  58491. SolidParticleSystem.prototype.rebuildMesh = function () {
  58492. for (var p = 0; p < this.particles.length; p++) {
  58493. this._rebuildParticle(this.particles[p]);
  58494. }
  58495. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58496. return this;
  58497. };
  58498. /**
  58499. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58500. * This method calls `updateParticle()` for each particle of the SPS.
  58501. * For an animated SPS, it is usually called within the render loop.
  58502. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58503. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58504. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58505. * @returns the SPS.
  58506. */
  58507. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58508. if (start === void 0) { start = 0; }
  58509. if (end === void 0) { end = this.nbParticles - 1; }
  58510. if (update === void 0) { update = true; }
  58511. if (!this._updatable) {
  58512. return this;
  58513. }
  58514. // custom beforeUpdate
  58515. this.beforeUpdateParticles(start, end, update);
  58516. this._cam_axisX.x = 1.0;
  58517. this._cam_axisX.y = 0.0;
  58518. this._cam_axisX.z = 0.0;
  58519. this._cam_axisY.x = 0.0;
  58520. this._cam_axisY.y = 1.0;
  58521. this._cam_axisY.z = 0.0;
  58522. this._cam_axisZ.x = 0.0;
  58523. this._cam_axisZ.y = 0.0;
  58524. this._cam_axisZ.z = 1.0;
  58525. // cases when the World Matrix is to be computed first
  58526. if (this.billboard || this._depthSort) {
  58527. this.mesh.computeWorldMatrix(true);
  58528. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58529. }
  58530. // if the particles will always face the camera
  58531. if (this.billboard) {
  58532. // compute the camera position and un-rotate it by the current mesh rotation
  58533. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58534. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58535. this._cam_axisZ.normalize();
  58536. // same for camera up vector extracted from the cam view matrix
  58537. var view = this._camera.getViewMatrix(true);
  58538. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58539. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58540. this._cam_axisY.normalize();
  58541. this._cam_axisX.normalize();
  58542. }
  58543. // if depthSort, compute the camera global position in the mesh local system
  58544. if (this._depthSort) {
  58545. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58546. }
  58547. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58548. var idx = 0; // current position index in the global array positions32
  58549. var index = 0; // position start index in the global array positions32 of the current particle
  58550. var colidx = 0; // current color index in the global array colors32
  58551. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58552. var uvidx = 0; // current uv index in the global array uvs32
  58553. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58554. var pt = 0; // current index in the particle model shape
  58555. if (this.mesh.isFacetDataEnabled) {
  58556. this._computeBoundingBox = true;
  58557. }
  58558. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58559. if (this._computeBoundingBox) {
  58560. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58561. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58562. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58563. }
  58564. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58565. if (this.mesh._boundingInfo) {
  58566. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58567. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58568. }
  58569. }
  58570. }
  58571. // particle loop
  58572. index = this.particles[start]._pos;
  58573. var vpos = (index / 3) | 0;
  58574. colorIndex = vpos * 4;
  58575. uvIndex = vpos * 2;
  58576. for (var p = start; p <= end; p++) {
  58577. this._particle = this.particles[p];
  58578. this._shape = this._particle._model._shape;
  58579. this._shapeUV = this._particle._model._shapeUV;
  58580. // call to custom user function to update the particle properties
  58581. this.updateParticle(this._particle);
  58582. // camera-particle distance for depth sorting
  58583. if (this._depthSort && this._depthSortParticles) {
  58584. var dsp = this.depthSortedParticles[p];
  58585. dsp.ind = this._particle._ind;
  58586. dsp.indicesLength = this._particle._model._indicesLength;
  58587. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58588. }
  58589. // skip the computations for inactive or already invisible particles
  58590. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58591. // increment indexes for the next particle
  58592. pt = this._shape.length;
  58593. index += pt * 3;
  58594. colorIndex += pt * 4;
  58595. uvIndex += pt * 2;
  58596. continue;
  58597. }
  58598. if (this._particle.isVisible) {
  58599. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58600. this._particleHasParent = (this._particle.parentId !== null);
  58601. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58602. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58603. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58604. // particle rotation matrix
  58605. if (this.billboard) {
  58606. this._particle.rotation.x = 0.0;
  58607. this._particle.rotation.y = 0.0;
  58608. }
  58609. if (this._computeParticleRotation || this.billboard) {
  58610. if (this._particle.rotationQuaternion) {
  58611. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58612. }
  58613. else {
  58614. this._yaw = this._particle.rotation.y;
  58615. this._pitch = this._particle.rotation.x;
  58616. this._roll = this._particle.rotation.z;
  58617. this._quaternionRotationYPR();
  58618. }
  58619. this._quaternionToRotationMatrix();
  58620. }
  58621. if (this._particleHasParent) {
  58622. this._parent = this.particles[this._particle.parentId];
  58623. 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];
  58624. 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];
  58625. 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];
  58626. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58627. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58628. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58629. if (this._computeParticleRotation || this.billboard) {
  58630. 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];
  58631. 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];
  58632. 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];
  58633. 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];
  58634. 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];
  58635. 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];
  58636. 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];
  58637. 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];
  58638. 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];
  58639. }
  58640. }
  58641. else {
  58642. this._particle._globalPosition.x = this._particle.position.x;
  58643. this._particle._globalPosition.y = this._particle.position.y;
  58644. this._particle._globalPosition.z = this._particle.position.z;
  58645. if (this._computeParticleRotation || this.billboard) {
  58646. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58647. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58648. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58649. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58650. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58651. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58652. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58653. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58654. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58655. }
  58656. }
  58657. if (this._particle.translateFromPivot) {
  58658. this._pivotBackTranslation.x = 0.0;
  58659. this._pivotBackTranslation.y = 0.0;
  58660. this._pivotBackTranslation.z = 0.0;
  58661. }
  58662. else {
  58663. this._pivotBackTranslation.x = this._scaledPivot.x;
  58664. this._pivotBackTranslation.y = this._scaledPivot.y;
  58665. this._pivotBackTranslation.z = this._scaledPivot.z;
  58666. }
  58667. // particle vertex loop
  58668. for (pt = 0; pt < this._shape.length; pt++) {
  58669. idx = index + pt * 3;
  58670. colidx = colorIndex + pt * 4;
  58671. uvidx = uvIndex + pt * 2;
  58672. this._vertex.x = this._shape[pt].x;
  58673. this._vertex.y = this._shape[pt].y;
  58674. this._vertex.z = this._shape[pt].z;
  58675. if (this._computeParticleVertex) {
  58676. this.updateParticleVertex(this._particle, this._vertex, pt);
  58677. }
  58678. // positions
  58679. this._vertex.x *= this._particle.scaling.x;
  58680. this._vertex.y *= this._particle.scaling.y;
  58681. this._vertex.z *= this._particle.scaling.z;
  58682. this._vertex.x -= this._scaledPivot.x;
  58683. this._vertex.y -= this._scaledPivot.y;
  58684. this._vertex.z -= this._scaledPivot.z;
  58685. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58686. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58687. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58688. this._rotated.x += this._pivotBackTranslation.x;
  58689. this._rotated.y += this._pivotBackTranslation.y;
  58690. this._rotated.z += this._pivotBackTranslation.z;
  58691. 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;
  58692. 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;
  58693. 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;
  58694. if (this._computeBoundingBox) {
  58695. if (this._positions32[idx] < this._minimum.x) {
  58696. this._minimum.x = this._positions32[idx];
  58697. }
  58698. if (this._positions32[idx] > this._maximum.x) {
  58699. this._maximum.x = this._positions32[idx];
  58700. }
  58701. if (this._positions32[idx + 1] < this._minimum.y) {
  58702. this._minimum.y = this._positions32[idx + 1];
  58703. }
  58704. if (this._positions32[idx + 1] > this._maximum.y) {
  58705. this._maximum.y = this._positions32[idx + 1];
  58706. }
  58707. if (this._positions32[idx + 2] < this._minimum.z) {
  58708. this._minimum.z = this._positions32[idx + 2];
  58709. }
  58710. if (this._positions32[idx + 2] > this._maximum.z) {
  58711. this._maximum.z = this._positions32[idx + 2];
  58712. }
  58713. }
  58714. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58715. if (!this._computeParticleVertex) {
  58716. this._normal.x = this._fixedNormal32[idx];
  58717. this._normal.y = this._fixedNormal32[idx + 1];
  58718. this._normal.z = this._fixedNormal32[idx + 2];
  58719. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58720. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58721. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58722. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58723. 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;
  58724. 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;
  58725. }
  58726. if (this._computeParticleColor && this._particle.color) {
  58727. this._colors32[colidx] = this._particle.color.r;
  58728. this._colors32[colidx + 1] = this._particle.color.g;
  58729. this._colors32[colidx + 2] = this._particle.color.b;
  58730. this._colors32[colidx + 3] = this._particle.color.a;
  58731. }
  58732. if (this._computeParticleTexture) {
  58733. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58734. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58735. }
  58736. }
  58737. }
  58738. // particle just set invisible : scaled to zero and positioned at the origin
  58739. else {
  58740. this._particle._stillInvisible = true; // mark the particle as invisible
  58741. for (pt = 0; pt < this._shape.length; pt++) {
  58742. idx = index + pt * 3;
  58743. colidx = colorIndex + pt * 4;
  58744. uvidx = uvIndex + pt * 2;
  58745. this._positions32[idx] = 0.0;
  58746. this._positions32[idx + 1] = 0.0;
  58747. this._positions32[idx + 2] = 0.0;
  58748. this._normals32[idx] = 0.0;
  58749. this._normals32[idx + 1] = 0.0;
  58750. this._normals32[idx + 2] = 0.0;
  58751. if (this._computeParticleColor && this._particle.color) {
  58752. this._colors32[colidx] = this._particle.color.r;
  58753. this._colors32[colidx + 1] = this._particle.color.g;
  58754. this._colors32[colidx + 2] = this._particle.color.b;
  58755. this._colors32[colidx + 3] = this._particle.color.a;
  58756. }
  58757. if (this._computeParticleTexture) {
  58758. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58759. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58760. }
  58761. }
  58762. }
  58763. // if the particle intersections must be computed : update the bbInfo
  58764. if (this._particlesIntersect) {
  58765. var bInfo = this._particle._boundingInfo;
  58766. var bBox = bInfo.boundingBox;
  58767. var bSphere = bInfo.boundingSphere;
  58768. if (!this._bSphereOnly) {
  58769. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58770. for (var b = 0; b < bBox.vectors.length; b++) {
  58771. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58772. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58773. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58774. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58775. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58776. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58777. 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;
  58778. 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;
  58779. 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;
  58780. }
  58781. bBox._update(this.mesh._worldMatrix);
  58782. }
  58783. // place and scale the particle bouding sphere in the SPS local system, then update it
  58784. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58785. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58786. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58787. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58788. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58789. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58790. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58791. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58792. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58793. 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));
  58794. bSphere._update(this.mesh._worldMatrix);
  58795. }
  58796. // increment indexes for the next particle
  58797. index = idx + 3;
  58798. colorIndex = colidx + 4;
  58799. uvIndex = uvidx + 2;
  58800. }
  58801. // if the VBO must be updated
  58802. if (update) {
  58803. if (this._computeParticleColor) {
  58804. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58805. }
  58806. if (this._computeParticleTexture) {
  58807. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58808. }
  58809. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58810. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58811. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58812. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58813. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58814. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58815. for (var i = 0; i < this._normals32.length; i++) {
  58816. this._fixedNormal32[i] = this._normals32[i];
  58817. }
  58818. }
  58819. if (!this.mesh.areNormalsFrozen) {
  58820. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58821. }
  58822. }
  58823. if (this._depthSort && this._depthSortParticles) {
  58824. this.depthSortedParticles.sort(this._depthSortFunction);
  58825. var dspl = this.depthSortedParticles.length;
  58826. var sorted = 0;
  58827. var lind = 0;
  58828. var sind = 0;
  58829. var sid = 0;
  58830. for (sorted = 0; sorted < dspl; sorted++) {
  58831. lind = this.depthSortedParticles[sorted].indicesLength;
  58832. sind = this.depthSortedParticles[sorted].ind;
  58833. for (var i = 0; i < lind; i++) {
  58834. this._indices32[sid] = this._indices[sind + i];
  58835. sid++;
  58836. }
  58837. }
  58838. this.mesh.updateIndices(this._indices32);
  58839. }
  58840. }
  58841. if (this._computeBoundingBox) {
  58842. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58843. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58844. }
  58845. this.afterUpdateParticles(start, end, update);
  58846. return this;
  58847. };
  58848. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58849. this._halfroll = this._roll * 0.5;
  58850. this._halfpitch = this._pitch * 0.5;
  58851. this._halfyaw = this._yaw * 0.5;
  58852. this._sinRoll = Math.sin(this._halfroll);
  58853. this._cosRoll = Math.cos(this._halfroll);
  58854. this._sinPitch = Math.sin(this._halfpitch);
  58855. this._cosPitch = Math.cos(this._halfpitch);
  58856. this._sinYaw = Math.sin(this._halfyaw);
  58857. this._cosYaw = Math.cos(this._halfyaw);
  58858. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58859. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58860. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58861. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58862. };
  58863. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58864. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58865. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58866. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58867. this._rotMatrix.m[3] = 0;
  58868. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58869. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58870. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58871. this._rotMatrix.m[7] = 0;
  58872. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58873. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58874. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58875. this._rotMatrix.m[11] = 0;
  58876. this._rotMatrix.m[12] = 0;
  58877. this._rotMatrix.m[13] = 0;
  58878. this._rotMatrix.m[14] = 0;
  58879. this._rotMatrix.m[15] = 1.0;
  58880. };
  58881. /**
  58882. * Disposes the SPS.
  58883. */
  58884. SolidParticleSystem.prototype.dispose = function () {
  58885. this.mesh.dispose();
  58886. this.vars = null;
  58887. // drop references to internal big arrays for the GC
  58888. this._positions = null;
  58889. this._indices = null;
  58890. this._normals = null;
  58891. this._uvs = null;
  58892. this._colors = null;
  58893. this._indices32 = null;
  58894. this._positions32 = null;
  58895. this._normals32 = null;
  58896. this._fixedNormal32 = null;
  58897. this._uvs32 = null;
  58898. this._colors32 = null;
  58899. this.pickedParticles = null;
  58900. };
  58901. /**
  58902. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58903. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58904. * @returns the SPS.
  58905. */
  58906. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58907. if (!this._isVisibilityBoxLocked) {
  58908. this.mesh.refreshBoundingInfo();
  58909. }
  58910. return this;
  58911. };
  58912. /**
  58913. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58914. * @param size the size (float) of the visibility box
  58915. * note : this doesn't lock the SPS mesh bounding box.
  58916. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58917. */
  58918. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58919. var vis = size / 2;
  58920. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58921. };
  58922. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58923. /**
  58924. * Gets whether the SPS as always visible or not
  58925. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58926. */
  58927. get: function () {
  58928. return this._alwaysVisible;
  58929. },
  58930. /**
  58931. * Sets the SPS as always visible or not
  58932. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58933. */
  58934. set: function (val) {
  58935. this._alwaysVisible = val;
  58936. this.mesh.alwaysSelectAsActiveMesh = val;
  58937. },
  58938. enumerable: true,
  58939. configurable: true
  58940. });
  58941. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58942. /**
  58943. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58944. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58945. */
  58946. get: function () {
  58947. return this._isVisibilityBoxLocked;
  58948. },
  58949. /**
  58950. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58951. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58952. */
  58953. set: function (val) {
  58954. this._isVisibilityBoxLocked = val;
  58955. var boundingInfo = this.mesh.getBoundingInfo();
  58956. boundingInfo.isLocked = val;
  58957. },
  58958. enumerable: true,
  58959. configurable: true
  58960. });
  58961. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58962. /**
  58963. * Gets if `setParticles()` computes the particle rotations or not.
  58964. * Default value : true. The SPS is faster when it's set to false.
  58965. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58966. */
  58967. get: function () {
  58968. return this._computeParticleRotation;
  58969. },
  58970. /**
  58971. * Tells to `setParticles()` to compute the particle rotations or not.
  58972. * Default value : true. The SPS is faster when it's set to false.
  58973. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58974. */
  58975. set: function (val) {
  58976. this._computeParticleRotation = val;
  58977. },
  58978. enumerable: true,
  58979. configurable: true
  58980. });
  58981. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58982. /**
  58983. * Gets if `setParticles()` computes the particle colors or not.
  58984. * Default value : true. The SPS is faster when it's set to false.
  58985. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58986. */
  58987. get: function () {
  58988. return this._computeParticleColor;
  58989. },
  58990. /**
  58991. * Tells to `setParticles()` to compute the particle colors or not.
  58992. * Default value : true. The SPS is faster when it's set to false.
  58993. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58994. */
  58995. set: function (val) {
  58996. this._computeParticleColor = val;
  58997. },
  58998. enumerable: true,
  58999. configurable: true
  59000. });
  59001. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59002. /**
  59003. * Gets if `setParticles()` computes the particle textures or not.
  59004. * Default value : true. The SPS is faster when it's set to false.
  59005. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59006. */
  59007. get: function () {
  59008. return this._computeParticleTexture;
  59009. },
  59010. set: function (val) {
  59011. this._computeParticleTexture = val;
  59012. },
  59013. enumerable: true,
  59014. configurable: true
  59015. });
  59016. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59017. /**
  59018. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59019. * Default value : false. The SPS is faster when it's set to false.
  59020. * Note : the particle custom vertex positions aren't stored values.
  59021. */
  59022. get: function () {
  59023. return this._computeParticleVertex;
  59024. },
  59025. /**
  59026. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59027. * Default value : false. The SPS is faster when it's set to false.
  59028. * Note : the particle custom vertex positions aren't stored values.
  59029. */
  59030. set: function (val) {
  59031. this._computeParticleVertex = val;
  59032. },
  59033. enumerable: true,
  59034. configurable: true
  59035. });
  59036. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59037. /**
  59038. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59039. */
  59040. get: function () {
  59041. return this._computeBoundingBox;
  59042. },
  59043. /**
  59044. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59045. */
  59046. set: function (val) {
  59047. this._computeBoundingBox = val;
  59048. },
  59049. enumerable: true,
  59050. configurable: true
  59051. });
  59052. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59053. /**
  59054. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59055. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59056. * Default : `true`
  59057. */
  59058. get: function () {
  59059. return this._depthSortParticles;
  59060. },
  59061. /**
  59062. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59063. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59064. * Default : `true`
  59065. */
  59066. set: function (val) {
  59067. this._depthSortParticles = val;
  59068. },
  59069. enumerable: true,
  59070. configurable: true
  59071. });
  59072. // =======================================================================
  59073. // Particle behavior logic
  59074. // these following methods may be overwritten by the user to fit his needs
  59075. /**
  59076. * This function does nothing. It may be overwritten to set all the particle first values.
  59077. * The SPS doesn't call this function, you may have to call it by your own.
  59078. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59079. */
  59080. SolidParticleSystem.prototype.initParticles = function () {
  59081. };
  59082. /**
  59083. * This function does nothing. It may be overwritten to recycle a particle.
  59084. * The SPS doesn't call this function, you may have to call it by your own.
  59085. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59086. * @param particle The particle to recycle
  59087. * @returns the recycled particle
  59088. */
  59089. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59090. return particle;
  59091. };
  59092. /**
  59093. * Updates a particle : this function should be overwritten by the user.
  59094. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59095. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59096. * @example : just set a particle position or velocity and recycle conditions
  59097. * @param particle The particle to update
  59098. * @returns the updated particle
  59099. */
  59100. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59101. return particle;
  59102. };
  59103. /**
  59104. * Updates a vertex of a particle : it can be overwritten by the user.
  59105. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59106. * @param particle the current particle
  59107. * @param vertex the current index of the current particle
  59108. * @param pt the index of the current vertex in the particle shape
  59109. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59110. * @example : just set a vertex particle position
  59111. * @returns the updated vertex
  59112. */
  59113. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59114. return vertex;
  59115. };
  59116. /**
  59117. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59118. * This does nothing and may be overwritten by the user.
  59119. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59120. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59121. * @param update the boolean update value actually passed to setParticles()
  59122. */
  59123. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59124. };
  59125. /**
  59126. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59127. * This will be passed three parameters.
  59128. * This does nothing and may be overwritten by the user.
  59129. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59130. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59131. * @param update the boolean update value actually passed to setParticles()
  59132. */
  59133. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59134. };
  59135. return SolidParticleSystem;
  59136. }());
  59137. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59138. })(BABYLON || (BABYLON = {}));
  59139. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59140. var BABYLON;
  59141. (function (BABYLON) {
  59142. var ShaderMaterial = /** @class */ (function (_super) {
  59143. __extends(ShaderMaterial, _super);
  59144. function ShaderMaterial(name, scene, shaderPath, options) {
  59145. var _this = _super.call(this, name, scene) || this;
  59146. _this._textures = {};
  59147. _this._textureArrays = {};
  59148. _this._floats = {};
  59149. _this._ints = {};
  59150. _this._floatsArrays = {};
  59151. _this._colors3 = {};
  59152. _this._colors3Arrays = {};
  59153. _this._colors4 = {};
  59154. _this._vectors2 = {};
  59155. _this._vectors3 = {};
  59156. _this._vectors4 = {};
  59157. _this._matrices = {};
  59158. _this._matrices3x3 = {};
  59159. _this._matrices2x2 = {};
  59160. _this._vectors2Arrays = {};
  59161. _this._vectors3Arrays = {};
  59162. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59163. _this._shaderPath = shaderPath;
  59164. options.needAlphaBlending = options.needAlphaBlending || false;
  59165. options.needAlphaTesting = options.needAlphaTesting || false;
  59166. options.attributes = options.attributes || ["position", "normal", "uv"];
  59167. options.uniforms = options.uniforms || ["worldViewProjection"];
  59168. options.uniformBuffers = options.uniformBuffers || [];
  59169. options.samplers = options.samplers || [];
  59170. options.defines = options.defines || [];
  59171. _this._options = options;
  59172. return _this;
  59173. }
  59174. ShaderMaterial.prototype.getClassName = function () {
  59175. return "ShaderMaterial";
  59176. };
  59177. ShaderMaterial.prototype.needAlphaBlending = function () {
  59178. return this._options.needAlphaBlending;
  59179. };
  59180. ShaderMaterial.prototype.needAlphaTesting = function () {
  59181. return this._options.needAlphaTesting;
  59182. };
  59183. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59184. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59185. this._options.uniforms.push(uniformName);
  59186. }
  59187. };
  59188. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59189. if (this._options.samplers.indexOf(name) === -1) {
  59190. this._options.samplers.push(name);
  59191. }
  59192. this._textures[name] = texture;
  59193. return this;
  59194. };
  59195. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59196. if (this._options.samplers.indexOf(name) === -1) {
  59197. this._options.samplers.push(name);
  59198. }
  59199. this._checkUniform(name);
  59200. this._textureArrays[name] = textures;
  59201. return this;
  59202. };
  59203. ShaderMaterial.prototype.setFloat = function (name, value) {
  59204. this._checkUniform(name);
  59205. this._floats[name] = value;
  59206. return this;
  59207. };
  59208. ShaderMaterial.prototype.setInt = function (name, value) {
  59209. this._checkUniform(name);
  59210. this._ints[name] = value;
  59211. return this;
  59212. };
  59213. ShaderMaterial.prototype.setFloats = function (name, value) {
  59214. this._checkUniform(name);
  59215. this._floatsArrays[name] = value;
  59216. return this;
  59217. };
  59218. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59219. this._checkUniform(name);
  59220. this._colors3[name] = value;
  59221. return this;
  59222. };
  59223. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59224. this._checkUniform(name);
  59225. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59226. color.toArray(arr, arr.length);
  59227. return arr;
  59228. }, []);
  59229. return this;
  59230. };
  59231. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59232. this._checkUniform(name);
  59233. this._colors4[name] = value;
  59234. return this;
  59235. };
  59236. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59237. this._checkUniform(name);
  59238. this._vectors2[name] = value;
  59239. return this;
  59240. };
  59241. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59242. this._checkUniform(name);
  59243. this._vectors3[name] = value;
  59244. return this;
  59245. };
  59246. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59247. this._checkUniform(name);
  59248. this._vectors4[name] = value;
  59249. return this;
  59250. };
  59251. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59252. this._checkUniform(name);
  59253. this._matrices[name] = value;
  59254. return this;
  59255. };
  59256. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59257. this._checkUniform(name);
  59258. this._matrices3x3[name] = value;
  59259. return this;
  59260. };
  59261. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59262. this._checkUniform(name);
  59263. this._matrices2x2[name] = value;
  59264. return this;
  59265. };
  59266. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59267. this._checkUniform(name);
  59268. this._vectors2Arrays[name] = value;
  59269. return this;
  59270. };
  59271. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59272. this._checkUniform(name);
  59273. this._vectors3Arrays[name] = value;
  59274. return this;
  59275. };
  59276. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59277. if (!mesh) {
  59278. return true;
  59279. }
  59280. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59281. return false;
  59282. }
  59283. return false;
  59284. };
  59285. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59286. var scene = this.getScene();
  59287. var engine = scene.getEngine();
  59288. if (!this.checkReadyOnEveryCall) {
  59289. if (this._renderId === scene.getRenderId()) {
  59290. if (this._checkCache(scene, mesh, useInstances)) {
  59291. return true;
  59292. }
  59293. }
  59294. }
  59295. // Instances
  59296. var defines = [];
  59297. var attribs = [];
  59298. var fallbacks = new BABYLON.EffectFallbacks();
  59299. if (useInstances) {
  59300. defines.push("#define INSTANCES");
  59301. }
  59302. for (var index = 0; index < this._options.defines.length; index++) {
  59303. defines.push(this._options.defines[index]);
  59304. }
  59305. for (var index = 0; index < this._options.attributes.length; index++) {
  59306. attribs.push(this._options.attributes[index]);
  59307. }
  59308. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59309. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59310. defines.push("#define VERTEXCOLOR");
  59311. }
  59312. // Bones
  59313. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59314. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59315. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59316. if (mesh.numBoneInfluencers > 4) {
  59317. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59318. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59319. }
  59320. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59321. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59322. fallbacks.addCPUSkinningFallback(0, mesh);
  59323. if (this._options.uniforms.indexOf("mBones") === -1) {
  59324. this._options.uniforms.push("mBones");
  59325. }
  59326. }
  59327. else {
  59328. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59329. }
  59330. // Textures
  59331. for (var name in this._textures) {
  59332. if (!this._textures[name].isReady()) {
  59333. return false;
  59334. }
  59335. }
  59336. // Alpha test
  59337. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59338. defines.push("#define ALPHATEST");
  59339. }
  59340. var previousEffect = this._effect;
  59341. var join = defines.join("\n");
  59342. this._effect = engine.createEffect(this._shaderPath, {
  59343. attributes: attribs,
  59344. uniformsNames: this._options.uniforms,
  59345. uniformBuffersNames: this._options.uniformBuffers,
  59346. samplers: this._options.samplers,
  59347. defines: join,
  59348. fallbacks: fallbacks,
  59349. onCompiled: this.onCompiled,
  59350. onError: this.onError
  59351. }, engine);
  59352. if (!this._effect.isReady()) {
  59353. return false;
  59354. }
  59355. if (previousEffect !== this._effect) {
  59356. scene.resetCachedMaterial();
  59357. }
  59358. this._renderId = scene.getRenderId();
  59359. return true;
  59360. };
  59361. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59362. var scene = this.getScene();
  59363. if (!this._effect) {
  59364. return;
  59365. }
  59366. if (this._options.uniforms.indexOf("world") !== -1) {
  59367. this._effect.setMatrix("world", world);
  59368. }
  59369. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59370. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59371. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59372. }
  59373. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59374. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59375. }
  59376. };
  59377. ShaderMaterial.prototype.bind = function (world, mesh) {
  59378. // Std values
  59379. this.bindOnlyWorldMatrix(world);
  59380. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59381. if (this._options.uniforms.indexOf("view") !== -1) {
  59382. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59383. }
  59384. if (this._options.uniforms.indexOf("projection") !== -1) {
  59385. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59386. }
  59387. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59388. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59389. }
  59390. // Bones
  59391. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59392. var name;
  59393. // Texture
  59394. for (name in this._textures) {
  59395. this._effect.setTexture(name, this._textures[name]);
  59396. }
  59397. // Texture arrays
  59398. for (name in this._textureArrays) {
  59399. this._effect.setTextureArray(name, this._textureArrays[name]);
  59400. }
  59401. // Int
  59402. for (name in this._ints) {
  59403. this._effect.setInt(name, this._ints[name]);
  59404. }
  59405. // Float
  59406. for (name in this._floats) {
  59407. this._effect.setFloat(name, this._floats[name]);
  59408. }
  59409. // Floats
  59410. for (name in this._floatsArrays) {
  59411. this._effect.setArray(name, this._floatsArrays[name]);
  59412. }
  59413. // Color3
  59414. for (name in this._colors3) {
  59415. this._effect.setColor3(name, this._colors3[name]);
  59416. }
  59417. for (name in this._colors3Arrays) {
  59418. this._effect.setArray3(name, this._colors3Arrays[name]);
  59419. }
  59420. // Color4
  59421. for (name in this._colors4) {
  59422. var color = this._colors4[name];
  59423. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59424. }
  59425. // Vector2
  59426. for (name in this._vectors2) {
  59427. this._effect.setVector2(name, this._vectors2[name]);
  59428. }
  59429. // Vector3
  59430. for (name in this._vectors3) {
  59431. this._effect.setVector3(name, this._vectors3[name]);
  59432. }
  59433. // Vector4
  59434. for (name in this._vectors4) {
  59435. this._effect.setVector4(name, this._vectors4[name]);
  59436. }
  59437. // Matrix
  59438. for (name in this._matrices) {
  59439. this._effect.setMatrix(name, this._matrices[name]);
  59440. }
  59441. // Matrix 3x3
  59442. for (name in this._matrices3x3) {
  59443. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59444. }
  59445. // Matrix 2x2
  59446. for (name in this._matrices2x2) {
  59447. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59448. }
  59449. // Vector2Array
  59450. for (name in this._vectors2Arrays) {
  59451. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59452. }
  59453. // Vector3Array
  59454. for (name in this._vectors3Arrays) {
  59455. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59456. }
  59457. }
  59458. this._afterBind(mesh);
  59459. };
  59460. ShaderMaterial.prototype.getActiveTextures = function () {
  59461. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59462. for (var name in this._textures) {
  59463. activeTextures.push(this._textures[name]);
  59464. }
  59465. for (var name in this._textureArrays) {
  59466. var array = this._textureArrays[name];
  59467. for (var index = 0; index < array.length; index++) {
  59468. activeTextures.push(array[index]);
  59469. }
  59470. }
  59471. return activeTextures;
  59472. };
  59473. ShaderMaterial.prototype.hasTexture = function (texture) {
  59474. if (_super.prototype.hasTexture.call(this, texture)) {
  59475. return true;
  59476. }
  59477. for (var name in this._textures) {
  59478. if (this._textures[name] === texture) {
  59479. return true;
  59480. }
  59481. }
  59482. for (var name in this._textureArrays) {
  59483. var array = this._textureArrays[name];
  59484. for (var index = 0; index < array.length; index++) {
  59485. if (array[index] === texture) {
  59486. return true;
  59487. }
  59488. }
  59489. }
  59490. return false;
  59491. };
  59492. ShaderMaterial.prototype.clone = function (name) {
  59493. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59494. return newShaderMaterial;
  59495. };
  59496. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59497. if (forceDisposeTextures) {
  59498. var name;
  59499. for (name in this._textures) {
  59500. this._textures[name].dispose();
  59501. }
  59502. for (name in this._textureArrays) {
  59503. var array = this._textureArrays[name];
  59504. for (var index = 0; index < array.length; index++) {
  59505. array[index].dispose();
  59506. }
  59507. }
  59508. }
  59509. this._textures = {};
  59510. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59511. };
  59512. ShaderMaterial.prototype.serialize = function () {
  59513. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59514. serializationObject.customType = "BABYLON.ShaderMaterial";
  59515. serializationObject.options = this._options;
  59516. serializationObject.shaderPath = this._shaderPath;
  59517. var name;
  59518. // Texture
  59519. serializationObject.textures = {};
  59520. for (name in this._textures) {
  59521. serializationObject.textures[name] = this._textures[name].serialize();
  59522. }
  59523. // Texture arrays
  59524. serializationObject.textureArrays = {};
  59525. for (name in this._textureArrays) {
  59526. serializationObject.textureArrays[name] = [];
  59527. var array = this._textureArrays[name];
  59528. for (var index = 0; index < array.length; index++) {
  59529. serializationObject.textureArrays[name].push(array[index].serialize());
  59530. }
  59531. }
  59532. // Float
  59533. serializationObject.floats = {};
  59534. for (name in this._floats) {
  59535. serializationObject.floats[name] = this._floats[name];
  59536. }
  59537. // Float s
  59538. serializationObject.FloatArrays = {};
  59539. for (name in this._floatsArrays) {
  59540. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59541. }
  59542. // Color3
  59543. serializationObject.colors3 = {};
  59544. for (name in this._colors3) {
  59545. serializationObject.colors3[name] = this._colors3[name].asArray();
  59546. }
  59547. // Color3 array
  59548. serializationObject.colors3Arrays = {};
  59549. for (name in this._colors3Arrays) {
  59550. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59551. }
  59552. // Color4
  59553. serializationObject.colors4 = {};
  59554. for (name in this._colors4) {
  59555. serializationObject.colors4[name] = this._colors4[name].asArray();
  59556. }
  59557. // Vector2
  59558. serializationObject.vectors2 = {};
  59559. for (name in this._vectors2) {
  59560. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59561. }
  59562. // Vector3
  59563. serializationObject.vectors3 = {};
  59564. for (name in this._vectors3) {
  59565. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59566. }
  59567. // Vector4
  59568. serializationObject.vectors4 = {};
  59569. for (name in this._vectors4) {
  59570. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59571. }
  59572. // Matrix
  59573. serializationObject.matrices = {};
  59574. for (name in this._matrices) {
  59575. serializationObject.matrices[name] = this._matrices[name].asArray();
  59576. }
  59577. // Matrix 3x3
  59578. serializationObject.matrices3x3 = {};
  59579. for (name in this._matrices3x3) {
  59580. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59581. }
  59582. // Matrix 2x2
  59583. serializationObject.matrices2x2 = {};
  59584. for (name in this._matrices2x2) {
  59585. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59586. }
  59587. // Vector2Array
  59588. serializationObject.vectors2Arrays = {};
  59589. for (name in this._vectors2Arrays) {
  59590. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59591. }
  59592. // Vector3Array
  59593. serializationObject.vectors3Arrays = {};
  59594. for (name in this._vectors3Arrays) {
  59595. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59596. }
  59597. return serializationObject;
  59598. };
  59599. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59600. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59601. var name;
  59602. // Texture
  59603. for (name in source.textures) {
  59604. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59605. }
  59606. // Texture arrays
  59607. for (name in source.textureArrays) {
  59608. var array = source.textureArrays[name];
  59609. var textureArray = new Array();
  59610. for (var index = 0; index < array.length; index++) {
  59611. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59612. }
  59613. material.setTextureArray(name, textureArray);
  59614. }
  59615. // Float
  59616. for (name in source.floats) {
  59617. material.setFloat(name, source.floats[name]);
  59618. }
  59619. // Float s
  59620. for (name in source.floatsArrays) {
  59621. material.setFloats(name, source.floatsArrays[name]);
  59622. }
  59623. // Color3
  59624. for (name in source.colors3) {
  59625. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59626. }
  59627. // Color3 arrays
  59628. for (name in source.colors3Arrays) {
  59629. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59630. if (i % 3 === 0) {
  59631. arr.push([num]);
  59632. }
  59633. else {
  59634. arr[arr.length - 1].push(num);
  59635. }
  59636. return arr;
  59637. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59638. material.setColor3Array(name, colors);
  59639. }
  59640. // Color4
  59641. for (name in source.colors4) {
  59642. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59643. }
  59644. // Vector2
  59645. for (name in source.vectors2) {
  59646. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59647. }
  59648. // Vector3
  59649. for (name in source.vectors3) {
  59650. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59651. }
  59652. // Vector4
  59653. for (name in source.vectors4) {
  59654. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59655. }
  59656. // Matrix
  59657. for (name in source.matrices) {
  59658. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59659. }
  59660. // Matrix 3x3
  59661. for (name in source.matrices3x3) {
  59662. material.setMatrix3x3(name, source.matrices3x3[name]);
  59663. }
  59664. // Matrix 2x2
  59665. for (name in source.matrices2x2) {
  59666. material.setMatrix2x2(name, source.matrices2x2[name]);
  59667. }
  59668. // Vector2Array
  59669. for (name in source.vectors2Arrays) {
  59670. material.setArray2(name, source.vectors2Arrays[name]);
  59671. }
  59672. // Vector3Array
  59673. for (name in source.vectors3Arrays) {
  59674. material.setArray3(name, source.vectors3Arrays[name]);
  59675. }
  59676. return material;
  59677. };
  59678. return ShaderMaterial;
  59679. }(BABYLON.Material));
  59680. BABYLON.ShaderMaterial = ShaderMaterial;
  59681. })(BABYLON || (BABYLON = {}));
  59682. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59683. var BABYLON;
  59684. (function (BABYLON) {
  59685. var GroundMesh = /** @class */ (function (_super) {
  59686. __extends(GroundMesh, _super);
  59687. function GroundMesh(name, scene) {
  59688. var _this = _super.call(this, name, scene) || this;
  59689. _this.generateOctree = false;
  59690. return _this;
  59691. }
  59692. GroundMesh.prototype.getClassName = function () {
  59693. return "GroundMesh";
  59694. };
  59695. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59696. get: function () {
  59697. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59698. },
  59699. enumerable: true,
  59700. configurable: true
  59701. });
  59702. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59703. get: function () {
  59704. return this._subdivisionsX;
  59705. },
  59706. enumerable: true,
  59707. configurable: true
  59708. });
  59709. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59710. get: function () {
  59711. return this._subdivisionsY;
  59712. },
  59713. enumerable: true,
  59714. configurable: true
  59715. });
  59716. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59717. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59718. this._subdivisionsX = chunksCount;
  59719. this._subdivisionsY = chunksCount;
  59720. this.subdivide(chunksCount);
  59721. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59722. };
  59723. /**
  59724. * Returns a height (y) value in the Worl system :
  59725. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59726. * Returns the ground y position if (x, z) are outside the ground surface.
  59727. */
  59728. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59729. var world = this.getWorldMatrix();
  59730. var invMat = BABYLON.Tmp.Matrix[5];
  59731. world.invertToRef(invMat);
  59732. var tmpVect = BABYLON.Tmp.Vector3[8];
  59733. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59734. x = tmpVect.x;
  59735. z = tmpVect.z;
  59736. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59737. return this.position.y;
  59738. }
  59739. if (!this._heightQuads || this._heightQuads.length == 0) {
  59740. this._initHeightQuads();
  59741. this._computeHeightQuads();
  59742. }
  59743. var facet = this._getFacetAt(x, z);
  59744. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59745. // return y in the World system
  59746. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59747. return tmpVect.y;
  59748. };
  59749. /**
  59750. * Returns a normalized vector (Vector3) orthogonal to the ground
  59751. * at the ground coordinates (x, z) expressed in the World system.
  59752. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59753. */
  59754. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59755. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59756. this.getNormalAtCoordinatesToRef(x, z, normal);
  59757. return normal;
  59758. };
  59759. /**
  59760. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59761. * at the ground coordinates (x, z) expressed in the World system.
  59762. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59763. * Returns the GroundMesh.
  59764. */
  59765. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59766. var world = this.getWorldMatrix();
  59767. var tmpMat = BABYLON.Tmp.Matrix[5];
  59768. world.invertToRef(tmpMat);
  59769. var tmpVect = BABYLON.Tmp.Vector3[8];
  59770. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59771. x = tmpVect.x;
  59772. z = tmpVect.z;
  59773. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59774. return this;
  59775. }
  59776. if (!this._heightQuads || this._heightQuads.length == 0) {
  59777. this._initHeightQuads();
  59778. this._computeHeightQuads();
  59779. }
  59780. var facet = this._getFacetAt(x, z);
  59781. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59782. return this;
  59783. };
  59784. /**
  59785. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59786. * if the ground has been updated.
  59787. * This can be used in the render loop.
  59788. * Returns the GroundMesh.
  59789. */
  59790. GroundMesh.prototype.updateCoordinateHeights = function () {
  59791. if (!this._heightQuads || this._heightQuads.length == 0) {
  59792. this._initHeightQuads();
  59793. }
  59794. this._computeHeightQuads();
  59795. return this;
  59796. };
  59797. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59798. GroundMesh.prototype._getFacetAt = function (x, z) {
  59799. // retrieve col and row from x, z coordinates in the ground local system
  59800. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59801. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59802. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59803. var facet;
  59804. if (z < quad.slope.x * x + quad.slope.y) {
  59805. facet = quad.facet1;
  59806. }
  59807. else {
  59808. facet = quad.facet2;
  59809. }
  59810. return facet;
  59811. };
  59812. // Creates and populates the heightMap array with "facet" elements :
  59813. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59814. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59815. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59816. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59817. // Returns the GroundMesh.
  59818. GroundMesh.prototype._initHeightQuads = function () {
  59819. var subdivisionsX = this._subdivisionsX;
  59820. var subdivisionsY = this._subdivisionsY;
  59821. this._heightQuads = new Array();
  59822. for (var row = 0; row < subdivisionsY; row++) {
  59823. for (var col = 0; col < subdivisionsX; col++) {
  59824. 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) };
  59825. this._heightQuads[row * subdivisionsX + col] = quad;
  59826. }
  59827. }
  59828. return this;
  59829. };
  59830. // Compute each quad element values and update the the heightMap array :
  59831. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59832. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59833. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59834. // Returns the GroundMesh.
  59835. GroundMesh.prototype._computeHeightQuads = function () {
  59836. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59837. if (!positions) {
  59838. return this;
  59839. }
  59840. var v1 = BABYLON.Tmp.Vector3[3];
  59841. var v2 = BABYLON.Tmp.Vector3[2];
  59842. var v3 = BABYLON.Tmp.Vector3[1];
  59843. var v4 = BABYLON.Tmp.Vector3[0];
  59844. var v1v2 = BABYLON.Tmp.Vector3[4];
  59845. var v1v3 = BABYLON.Tmp.Vector3[5];
  59846. var v1v4 = BABYLON.Tmp.Vector3[6];
  59847. var norm1 = BABYLON.Tmp.Vector3[7];
  59848. var norm2 = BABYLON.Tmp.Vector3[8];
  59849. var i = 0;
  59850. var j = 0;
  59851. var k = 0;
  59852. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59853. var h = 0;
  59854. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59855. var d2 = 0;
  59856. var subdivisionsX = this._subdivisionsX;
  59857. var subdivisionsY = this._subdivisionsY;
  59858. for (var row = 0; row < subdivisionsY; row++) {
  59859. for (var col = 0; col < subdivisionsX; col++) {
  59860. i = col * 3;
  59861. j = row * (subdivisionsX + 1) * 3;
  59862. k = (row + 1) * (subdivisionsX + 1) * 3;
  59863. v1.x = positions[j + i];
  59864. v1.y = positions[j + i + 1];
  59865. v1.z = positions[j + i + 2];
  59866. v2.x = positions[j + i + 3];
  59867. v2.y = positions[j + i + 4];
  59868. v2.z = positions[j + i + 5];
  59869. v3.x = positions[k + i];
  59870. v3.y = positions[k + i + 1];
  59871. v3.z = positions[k + i + 2];
  59872. v4.x = positions[k + i + 3];
  59873. v4.y = positions[k + i + 4];
  59874. v4.z = positions[k + i + 5];
  59875. // 2D slope V1V4
  59876. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59877. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59878. // facet equations :
  59879. // we compute each facet normal vector
  59880. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59881. // we compute the value d by applying the equation to v1 which belongs to the plane
  59882. // then we store the facet equation in a Vector4
  59883. v2.subtractToRef(v1, v1v2);
  59884. v3.subtractToRef(v1, v1v3);
  59885. v4.subtractToRef(v1, v1v4);
  59886. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59887. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59888. norm1.normalize();
  59889. norm2.normalize();
  59890. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59891. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59892. var quad = this._heightQuads[row * subdivisionsX + col];
  59893. quad.slope.copyFromFloats(cd, h);
  59894. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59895. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59896. }
  59897. }
  59898. return this;
  59899. };
  59900. GroundMesh.prototype.serialize = function (serializationObject) {
  59901. _super.prototype.serialize.call(this, serializationObject);
  59902. serializationObject.subdivisionsX = this._subdivisionsX;
  59903. serializationObject.subdivisionsY = this._subdivisionsY;
  59904. serializationObject.minX = this._minX;
  59905. serializationObject.maxX = this._maxX;
  59906. serializationObject.minZ = this._minZ;
  59907. serializationObject.maxZ = this._maxZ;
  59908. serializationObject.width = this._width;
  59909. serializationObject.height = this._height;
  59910. };
  59911. GroundMesh.Parse = function (parsedMesh, scene) {
  59912. var result = new GroundMesh(parsedMesh.name, scene);
  59913. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59914. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59915. result._minX = parsedMesh.minX;
  59916. result._maxX = parsedMesh.maxX;
  59917. result._minZ = parsedMesh.minZ;
  59918. result._maxZ = parsedMesh.maxZ;
  59919. result._width = parsedMesh.width;
  59920. result._height = parsedMesh.height;
  59921. return result;
  59922. };
  59923. return GroundMesh;
  59924. }(BABYLON.Mesh));
  59925. BABYLON.GroundMesh = GroundMesh;
  59926. })(BABYLON || (BABYLON = {}));
  59927. //# sourceMappingURL=babylon.groundMesh.js.map
  59928. var BABYLON;
  59929. (function (BABYLON) {
  59930. /**
  59931. * Creates an instance based on a source mesh.
  59932. */
  59933. var InstancedMesh = /** @class */ (function (_super) {
  59934. __extends(InstancedMesh, _super);
  59935. function InstancedMesh(name, source) {
  59936. var _this = _super.call(this, name, source.getScene()) || this;
  59937. source.instances.push(_this);
  59938. _this._sourceMesh = source;
  59939. _this.position.copyFrom(source.position);
  59940. _this.rotation.copyFrom(source.rotation);
  59941. _this.scaling.copyFrom(source.scaling);
  59942. if (source.rotationQuaternion) {
  59943. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59944. }
  59945. _this.infiniteDistance = source.infiniteDistance;
  59946. _this.setPivotMatrix(source.getPivotMatrix());
  59947. _this.refreshBoundingInfo();
  59948. _this._syncSubMeshes();
  59949. return _this;
  59950. }
  59951. /**
  59952. * Returns the string "InstancedMesh".
  59953. */
  59954. InstancedMesh.prototype.getClassName = function () {
  59955. return "InstancedMesh";
  59956. };
  59957. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59958. // Methods
  59959. get: function () {
  59960. return this._sourceMesh.receiveShadows;
  59961. },
  59962. enumerable: true,
  59963. configurable: true
  59964. });
  59965. Object.defineProperty(InstancedMesh.prototype, "material", {
  59966. get: function () {
  59967. return this._sourceMesh.material;
  59968. },
  59969. enumerable: true,
  59970. configurable: true
  59971. });
  59972. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59973. get: function () {
  59974. return this._sourceMesh.visibility;
  59975. },
  59976. enumerable: true,
  59977. configurable: true
  59978. });
  59979. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59980. get: function () {
  59981. return this._sourceMesh.skeleton;
  59982. },
  59983. enumerable: true,
  59984. configurable: true
  59985. });
  59986. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59987. get: function () {
  59988. return this._sourceMesh.renderingGroupId;
  59989. },
  59990. set: function (value) {
  59991. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59992. return;
  59993. }
  59994. //no-op with warning
  59995. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59996. },
  59997. enumerable: true,
  59998. configurable: true
  59999. });
  60000. /**
  60001. * Returns the total number of vertices (integer).
  60002. */
  60003. InstancedMesh.prototype.getTotalVertices = function () {
  60004. return this._sourceMesh.getTotalVertices();
  60005. };
  60006. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60007. get: function () {
  60008. return this._sourceMesh;
  60009. },
  60010. enumerable: true,
  60011. configurable: true
  60012. });
  60013. /**
  60014. * Is this node ready to be used/rendered
  60015. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60016. * @return {boolean} is it ready
  60017. */
  60018. InstancedMesh.prototype.isReady = function (completeCheck) {
  60019. if (completeCheck === void 0) { completeCheck = false; }
  60020. return this._sourceMesh.isReady(completeCheck, true);
  60021. };
  60022. /**
  60023. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60024. */
  60025. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60026. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60027. };
  60028. /**
  60029. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60030. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60031. * The `data` are either a numeric array either a Float32Array.
  60032. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60033. * 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).
  60034. * Note that a new underlying VertexBuffer object is created each call.
  60035. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60036. *
  60037. * Possible `kind` values :
  60038. * - BABYLON.VertexBuffer.PositionKind
  60039. * - BABYLON.VertexBuffer.UVKind
  60040. * - BABYLON.VertexBuffer.UV2Kind
  60041. * - BABYLON.VertexBuffer.UV3Kind
  60042. * - BABYLON.VertexBuffer.UV4Kind
  60043. * - BABYLON.VertexBuffer.UV5Kind
  60044. * - BABYLON.VertexBuffer.UV6Kind
  60045. * - BABYLON.VertexBuffer.ColorKind
  60046. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60047. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60048. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60049. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60050. *
  60051. * Returns the Mesh.
  60052. */
  60053. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60054. if (this.sourceMesh) {
  60055. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60056. }
  60057. return this.sourceMesh;
  60058. };
  60059. /**
  60060. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60061. * If the mesh has no geometry, it is simply returned as it is.
  60062. * The `data` are either a numeric array either a Float32Array.
  60063. * No new underlying VertexBuffer object is created.
  60064. * 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.
  60065. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60066. *
  60067. * Possible `kind` values :
  60068. * - BABYLON.VertexBuffer.PositionKind
  60069. * - BABYLON.VertexBuffer.UVKind
  60070. * - BABYLON.VertexBuffer.UV2Kind
  60071. * - BABYLON.VertexBuffer.UV3Kind
  60072. * - BABYLON.VertexBuffer.UV4Kind
  60073. * - BABYLON.VertexBuffer.UV5Kind
  60074. * - BABYLON.VertexBuffer.UV6Kind
  60075. * - BABYLON.VertexBuffer.ColorKind
  60076. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60077. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60078. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60079. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60080. *
  60081. * Returns the Mesh.
  60082. */
  60083. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60084. if (this.sourceMesh) {
  60085. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60086. }
  60087. return this.sourceMesh;
  60088. };
  60089. /**
  60090. * Sets the mesh indices.
  60091. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60092. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60093. * This method creates a new index buffer each call.
  60094. * Returns the Mesh.
  60095. */
  60096. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60097. if (totalVertices === void 0) { totalVertices = null; }
  60098. if (this.sourceMesh) {
  60099. this.sourceMesh.setIndices(indices, totalVertices);
  60100. }
  60101. return this.sourceMesh;
  60102. };
  60103. /**
  60104. * Boolean : True if the mesh owns the requested kind of data.
  60105. */
  60106. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60107. return this._sourceMesh.isVerticesDataPresent(kind);
  60108. };
  60109. /**
  60110. * Returns an array of indices (IndicesArray).
  60111. */
  60112. InstancedMesh.prototype.getIndices = function () {
  60113. return this._sourceMesh.getIndices();
  60114. };
  60115. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60116. get: function () {
  60117. return this._sourceMesh._positions;
  60118. },
  60119. enumerable: true,
  60120. configurable: true
  60121. });
  60122. /**
  60123. * Sets a new updated BoundingInfo to the mesh.
  60124. * Returns the mesh.
  60125. */
  60126. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60127. var meshBB = this._sourceMesh.getBoundingInfo();
  60128. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60129. this._updateBoundingInfo();
  60130. return this;
  60131. };
  60132. InstancedMesh.prototype._preActivate = function () {
  60133. if (this._currentLOD) {
  60134. this._currentLOD._preActivate();
  60135. }
  60136. return this;
  60137. };
  60138. InstancedMesh.prototype._activate = function (renderId) {
  60139. if (this._currentLOD) {
  60140. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60141. }
  60142. return this;
  60143. };
  60144. /**
  60145. * Returns the current associated LOD AbstractMesh.
  60146. */
  60147. InstancedMesh.prototype.getLOD = function (camera) {
  60148. if (!camera) {
  60149. return this;
  60150. }
  60151. var boundingInfo = this.getBoundingInfo();
  60152. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60153. if (this._currentLOD === this.sourceMesh) {
  60154. return this;
  60155. }
  60156. return this._currentLOD;
  60157. };
  60158. InstancedMesh.prototype._syncSubMeshes = function () {
  60159. this.releaseSubMeshes();
  60160. if (this._sourceMesh.subMeshes) {
  60161. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60162. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60163. }
  60164. }
  60165. return this;
  60166. };
  60167. InstancedMesh.prototype._generatePointsArray = function () {
  60168. return this._sourceMesh._generatePointsArray();
  60169. };
  60170. /**
  60171. * Creates a new InstancedMesh from the current mesh.
  60172. * - name (string) : the cloned mesh name
  60173. * - newParent (optional Node) : the optional Node to parent the clone to.
  60174. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60175. *
  60176. * Returns the clone.
  60177. */
  60178. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60179. var result = this._sourceMesh.createInstance(name);
  60180. // Deep copy
  60181. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60182. // Bounding info
  60183. this.refreshBoundingInfo();
  60184. // Parent
  60185. if (newParent) {
  60186. result.parent = newParent;
  60187. }
  60188. if (!doNotCloneChildren) {
  60189. // Children
  60190. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60191. var mesh = this.getScene().meshes[index];
  60192. if (mesh.parent === this) {
  60193. mesh.clone(mesh.name, result);
  60194. }
  60195. }
  60196. }
  60197. result.computeWorldMatrix(true);
  60198. return result;
  60199. };
  60200. /**
  60201. * Disposes the InstancedMesh.
  60202. * Returns nothing.
  60203. */
  60204. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60205. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60206. // Remove from mesh
  60207. var index = this._sourceMesh.instances.indexOf(this);
  60208. this._sourceMesh.instances.splice(index, 1);
  60209. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60210. };
  60211. return InstancedMesh;
  60212. }(BABYLON.AbstractMesh));
  60213. BABYLON.InstancedMesh = InstancedMesh;
  60214. })(BABYLON || (BABYLON = {}));
  60215. //# sourceMappingURL=babylon.instancedMesh.js.map
  60216. var BABYLON;
  60217. (function (BABYLON) {
  60218. var LinesMesh = /** @class */ (function (_super) {
  60219. __extends(LinesMesh, _super);
  60220. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60221. if (scene === void 0) { scene = null; }
  60222. if (parent === void 0) { parent = null; }
  60223. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60224. _this.useVertexColor = useVertexColor;
  60225. _this.useVertexAlpha = useVertexAlpha;
  60226. _this.color = new BABYLON.Color3(1, 1, 1);
  60227. _this.alpha = 1;
  60228. if (source) {
  60229. _this.color = source.color.clone();
  60230. _this.alpha = source.alpha;
  60231. _this.useVertexColor = source.useVertexColor;
  60232. _this.useVertexAlpha = source.useVertexAlpha;
  60233. }
  60234. _this._intersectionThreshold = 0.1;
  60235. var defines = [];
  60236. var options = {
  60237. attributes: [BABYLON.VertexBuffer.PositionKind],
  60238. uniforms: ["world", "viewProjection"],
  60239. needAlphaBlending: true,
  60240. defines: defines
  60241. };
  60242. if (useVertexAlpha === false) {
  60243. options.needAlphaBlending = false;
  60244. }
  60245. if (!useVertexColor) {
  60246. options.uniforms.push("color");
  60247. }
  60248. else {
  60249. options.defines.push("#define VERTEXCOLOR");
  60250. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60251. }
  60252. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60253. return _this;
  60254. }
  60255. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60256. /**
  60257. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60258. * This margin is expressed in world space coordinates, so its value may vary.
  60259. * Default value is 0.1
  60260. * @returns the intersection Threshold value.
  60261. */
  60262. get: function () {
  60263. return this._intersectionThreshold;
  60264. },
  60265. /**
  60266. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60267. * This margin is expressed in world space coordinates, so its value may vary.
  60268. * @param value the new threshold to apply
  60269. */
  60270. set: function (value) {
  60271. if (this._intersectionThreshold === value) {
  60272. return;
  60273. }
  60274. this._intersectionThreshold = value;
  60275. if (this.geometry) {
  60276. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60277. }
  60278. },
  60279. enumerable: true,
  60280. configurable: true
  60281. });
  60282. /**
  60283. * Returns the string "LineMesh"
  60284. */
  60285. LinesMesh.prototype.getClassName = function () {
  60286. return "LinesMesh";
  60287. };
  60288. Object.defineProperty(LinesMesh.prototype, "material", {
  60289. get: function () {
  60290. return this._colorShader;
  60291. },
  60292. set: function (value) {
  60293. // Do nothing
  60294. },
  60295. enumerable: true,
  60296. configurable: true
  60297. });
  60298. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60299. get: function () {
  60300. return false;
  60301. },
  60302. enumerable: true,
  60303. configurable: true
  60304. });
  60305. LinesMesh.prototype.createInstance = function (name) {
  60306. throw new Error("LinesMeshes do not support createInstance.");
  60307. };
  60308. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60309. if (!this._geometry) {
  60310. return this;
  60311. }
  60312. // VBOs
  60313. this._geometry._bind(this._colorShader.getEffect());
  60314. // Color
  60315. if (!this.useVertexColor) {
  60316. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60317. }
  60318. return this;
  60319. };
  60320. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60321. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60322. return this;
  60323. }
  60324. var engine = this.getScene().getEngine();
  60325. // Draw order
  60326. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60327. return this;
  60328. };
  60329. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60330. this._colorShader.dispose();
  60331. _super.prototype.dispose.call(this, doNotRecurse);
  60332. };
  60333. /**
  60334. * Returns a new LineMesh object cloned from the current one.
  60335. */
  60336. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60337. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60338. };
  60339. return LinesMesh;
  60340. }(BABYLON.Mesh));
  60341. BABYLON.LinesMesh = LinesMesh;
  60342. })(BABYLON || (BABYLON = {}));
  60343. //# sourceMappingURL=babylon.linesMesh.js.map
  60344. var BABYLON;
  60345. (function (BABYLON) {
  60346. /**
  60347. * Class containing static functions to help procedurally build meshes
  60348. */
  60349. var MeshBuilder = /** @class */ (function () {
  60350. function MeshBuilder() {
  60351. }
  60352. MeshBuilder.updateSideOrientation = function (orientation) {
  60353. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60354. return BABYLON.Mesh.DOUBLESIDE;
  60355. }
  60356. if (orientation === undefined || orientation === null) {
  60357. return BABYLON.Mesh.FRONTSIDE;
  60358. }
  60359. return orientation;
  60360. };
  60361. /**
  60362. * Creates a box mesh
  60363. * * The parameter `size` sets the size (float) of each box side (default 1)
  60364. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60365. * * 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)
  60366. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60367. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60368. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60369. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60370. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60371. * @param name defines the name of the mesh
  60372. * @param options defines the options used to create the mesh
  60373. * @param scene defines the hosting scene
  60374. * @returns the box mesh
  60375. */
  60376. MeshBuilder.CreateBox = function (name, options, scene) {
  60377. if (scene === void 0) { scene = null; }
  60378. var box = new BABYLON.Mesh(name, scene);
  60379. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60380. box._originalBuilderSideOrientation = options.sideOrientation;
  60381. var vertexData = BABYLON.VertexData.CreateBox(options);
  60382. vertexData.applyToMesh(box, options.updatable);
  60383. return box;
  60384. };
  60385. /**
  60386. * Creates a sphere mesh
  60387. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60388. * * 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`)
  60389. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60390. * * 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
  60391. * * 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)
  60392. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60393. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60394. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60395. * @param name defines the name of the mesh
  60396. * @param options defines the options used to create the mesh
  60397. * @param scene defines the hosting scene
  60398. * @returns the sphere mesh
  60399. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60400. */
  60401. MeshBuilder.CreateSphere = function (name, options, scene) {
  60402. var sphere = new BABYLON.Mesh(name, scene);
  60403. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60404. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60405. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60406. vertexData.applyToMesh(sphere, options.updatable);
  60407. return sphere;
  60408. };
  60409. /**
  60410. * Creates a plane polygonal mesh. By default, this is a disc
  60411. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60412. * * 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
  60413. * * 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
  60414. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60415. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60416. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60417. * @param name defines the name of the mesh
  60418. * @param options defines the options used to create the mesh
  60419. * @param scene defines the hosting scene
  60420. * @returns the plane polygonal mesh
  60421. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  60422. */
  60423. MeshBuilder.CreateDisc = function (name, options, scene) {
  60424. if (scene === void 0) { scene = null; }
  60425. var disc = new BABYLON.Mesh(name, scene);
  60426. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60427. disc._originalBuilderSideOrientation = options.sideOrientation;
  60428. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60429. vertexData.applyToMesh(disc, options.updatable);
  60430. return disc;
  60431. };
  60432. /**
  60433. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60434. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60435. * * 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`)
  60436. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60437. * * 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
  60438. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60439. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60440. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60441. * @param name defines the name of the mesh
  60442. * @param options defines the options used to create the mesh
  60443. * @param scene defines the hosting scene
  60444. * @returns the icosahedron mesh
  60445. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  60446. */
  60447. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60448. var sphere = new BABYLON.Mesh(name, scene);
  60449. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60450. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60451. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60452. vertexData.applyToMesh(sphere, options.updatable);
  60453. return sphere;
  60454. };
  60455. ;
  60456. /**
  60457. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60458. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60459. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60460. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60461. * * 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
  60462. * * 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
  60463. * * 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
  60464. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60465. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60466. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60467. * * 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
  60468. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60469. * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry
  60470. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60471. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60472. * @param name defines the name of the mesh
  60473. * @param options defines the options used to create the mesh
  60474. * @param scene defines the hosting scene
  60475. * @returns the ribbon mesh
  60476. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60477. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60478. */
  60479. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60480. if (scene === void 0) { scene = null; }
  60481. var pathArray = options.pathArray;
  60482. var closeArray = options.closeArray;
  60483. var closePath = options.closePath;
  60484. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60485. var instance = options.instance;
  60486. var updatable = options.updatable;
  60487. if (instance) { // existing ribbon instance update
  60488. // positionFunction : ribbon case
  60489. // only pathArray and sideOrientation parameters are taken into account for positions update
  60490. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60491. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60492. var positionFunction = function (positions) {
  60493. var minlg = pathArray[0].length;
  60494. var i = 0;
  60495. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60496. for (var si = 1; si <= ns; si++) {
  60497. for (var p = 0; p < pathArray.length; p++) {
  60498. var path = pathArray[p];
  60499. var l = path.length;
  60500. minlg = (minlg < l) ? minlg : l;
  60501. var j = 0;
  60502. while (j < minlg) {
  60503. positions[i] = path[j].x;
  60504. positions[i + 1] = path[j].y;
  60505. positions[i + 2] = path[j].z;
  60506. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60507. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60508. }
  60509. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60510. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60511. }
  60512. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60513. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60514. }
  60515. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60516. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60517. }
  60518. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60519. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60520. }
  60521. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60522. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60523. }
  60524. j++;
  60525. i += 3;
  60526. }
  60527. if (instance._closePath) {
  60528. positions[i] = path[0].x;
  60529. positions[i + 1] = path[0].y;
  60530. positions[i + 2] = path[0].z;
  60531. i += 3;
  60532. }
  60533. }
  60534. }
  60535. };
  60536. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60537. positionFunction(positions);
  60538. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60539. instance._boundingInfo.update(instance._worldMatrix);
  60540. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60541. if (options.colors) {
  60542. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60543. for (var c = 0; c < options.colors.length; c++) {
  60544. colors[c * 4] = options.colors[c].r;
  60545. colors[c * 4 + 1] = options.colors[c].g;
  60546. colors[c * 4 + 2] = options.colors[c].b;
  60547. colors[c * 4 + 3] = options.colors[c].a;
  60548. }
  60549. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60550. }
  60551. if (options.uvs) {
  60552. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60553. for (var i = 0; i < options.uvs.length; i++) {
  60554. uvs[i * 2] = options.uvs[i].x;
  60555. uvs[i * 2 + 1] = options.uvs[i].y;
  60556. }
  60557. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60558. }
  60559. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60560. var indices = instance.getIndices();
  60561. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60562. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60563. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60564. if (instance._closePath) {
  60565. var indexFirst = 0;
  60566. var indexLast = 0;
  60567. for (var p = 0; p < pathArray.length; p++) {
  60568. indexFirst = instance._idx[p] * 3;
  60569. if (p + 1 < pathArray.length) {
  60570. indexLast = (instance._idx[p + 1] - 1) * 3;
  60571. }
  60572. else {
  60573. indexLast = normals.length - 3;
  60574. }
  60575. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60576. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60577. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60578. normals[indexLast] = normals[indexFirst];
  60579. normals[indexLast + 1] = normals[indexFirst + 1];
  60580. normals[indexLast + 2] = normals[indexFirst + 2];
  60581. }
  60582. }
  60583. if (!(instance.areNormalsFrozen)) {
  60584. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60585. }
  60586. }
  60587. return instance;
  60588. }
  60589. else { // new ribbon creation
  60590. var ribbon = new BABYLON.Mesh(name, scene);
  60591. ribbon._originalBuilderSideOrientation = sideOrientation;
  60592. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60593. if (closePath) {
  60594. ribbon._idx = vertexData._idx;
  60595. }
  60596. ribbon._closePath = closePath;
  60597. ribbon._closeArray = closeArray;
  60598. vertexData.applyToMesh(ribbon, updatable);
  60599. return ribbon;
  60600. }
  60601. };
  60602. /**
  60603. * Creates a cylinder or a cone mesh
  60604. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60605. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60606. * * 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.
  60607. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60608. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60609. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60610. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60611. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60612. * * 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).
  60613. * * 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
  60614. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60615. * * 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
  60616. * * 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.
  60617. * * If `enclose` is false, a ring surface is one element.
  60618. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60619. * * 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
  60620. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60621. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60622. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60623. * @param name defines the name of the mesh
  60624. * @param options defines the options used to create the mesh
  60625. * @param scene defines the hosting scene
  60626. * @returns the cylinder mesh
  60627. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60628. */
  60629. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60630. var cylinder = new BABYLON.Mesh(name, scene);
  60631. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60632. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60633. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60634. vertexData.applyToMesh(cylinder, options.updatable);
  60635. return cylinder;
  60636. };
  60637. /**
  60638. * Creates a torus mesh
  60639. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60640. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60641. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60642. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60643. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60644. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60645. * @param name defines the name of the mesh
  60646. * @param options defines the options used to create the mesh
  60647. * @param scene defines the hosting scene
  60648. * @returns the torus mesh
  60649. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60650. */
  60651. MeshBuilder.CreateTorus = function (name, options, scene) {
  60652. var torus = new BABYLON.Mesh(name, scene);
  60653. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60654. torus._originalBuilderSideOrientation = options.sideOrientation;
  60655. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60656. vertexData.applyToMesh(torus, options.updatable);
  60657. return torus;
  60658. };
  60659. /**
  60660. * Creates a torus knot mesh
  60661. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60662. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60663. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60664. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60665. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60666. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60667. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60668. * @param name defines the name of the mesh
  60669. * @param options defines the options used to create the mesh
  60670. * @param scene defines the hosting scene
  60671. * @returns the torus knot mesh
  60672. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60673. */
  60674. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60675. var torusKnot = new BABYLON.Mesh(name, scene);
  60676. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60677. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60678. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60679. vertexData.applyToMesh(torusKnot, options.updatable);
  60680. return torusKnot;
  60681. };
  60682. /**
  60683. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60684. * * 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
  60685. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60686. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60687. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60688. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60689. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60690. * * 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
  60691. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60692. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60693. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  60694. * @param name defines the name of the new line system
  60695. * @param options defines the options used to create the line system
  60696. * @param scene defines the hosting scene
  60697. * @returns a new line system mesh
  60698. */
  60699. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60700. var instance = options.instance;
  60701. var lines = options.lines;
  60702. var colors = options.colors;
  60703. if (instance) { // lines update
  60704. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60705. var vertexColor;
  60706. var lineColors;
  60707. if (colors) {
  60708. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60709. }
  60710. var i = 0;
  60711. var c = 0;
  60712. for (var l = 0; l < lines.length; l++) {
  60713. var points = lines[l];
  60714. for (var p = 0; p < points.length; p++) {
  60715. positions[i] = points[p].x;
  60716. positions[i + 1] = points[p].y;
  60717. positions[i + 2] = points[p].z;
  60718. if (colors && vertexColor) {
  60719. lineColors = colors[l];
  60720. vertexColor[c] = lineColors[p].r;
  60721. vertexColor[c + 1] = lineColors[p].g;
  60722. vertexColor[c + 2] = lineColors[p].b;
  60723. vertexColor[c + 3] = lineColors[p].a;
  60724. c += 4;
  60725. }
  60726. i += 3;
  60727. }
  60728. }
  60729. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60730. if (colors && vertexColor) {
  60731. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60732. }
  60733. return instance;
  60734. }
  60735. // line system creation
  60736. var useVertexColor = (colors) ? true : false;
  60737. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60738. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60739. vertexData.applyToMesh(lineSystem, options.updatable);
  60740. return lineSystem;
  60741. };
  60742. /**
  60743. * Creates a line mesh
  60744. * 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
  60745. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60746. * * The parameter `points` is an array successive Vector3
  60747. * * 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
  60748. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60749. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60750. * * When updating an instance, remember that only point positions can change, not the number of points
  60751. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60752. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  60753. * @param name defines the name of the new line system
  60754. * @param options defines the options used to create the line system
  60755. * @param scene defines the hosting scene
  60756. * @returns a new line mesh
  60757. */
  60758. MeshBuilder.CreateLines = function (name, options, scene) {
  60759. if (scene === void 0) { scene = null; }
  60760. var colors = (options.colors) ? [options.colors] : null;
  60761. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60762. return lines;
  60763. };
  60764. /**
  60765. * Creates a dashed line mesh
  60766. * * 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
  60767. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60768. * * The parameter `points` is an array successive Vector3
  60769. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60770. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60771. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60772. * * 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
  60773. * * When updating an instance, remember that only point positions can change, not the number of points
  60774. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60775. * @param name defines the name of the mesh
  60776. * @param options defines the options used to create the mesh
  60777. * @param scene defines the hosting scene
  60778. * @returns the dashed line mesh
  60779. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  60780. */
  60781. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60782. if (scene === void 0) { scene = null; }
  60783. var points = options.points;
  60784. var instance = options.instance;
  60785. var gapSize = options.gapSize || 1;
  60786. var dashSize = options.dashSize || 3;
  60787. if (instance) { // dashed lines update
  60788. var positionFunction = function (positions) {
  60789. var curvect = BABYLON.Vector3.Zero();
  60790. var nbSeg = positions.length / 6;
  60791. var lg = 0;
  60792. var nb = 0;
  60793. var shft = 0;
  60794. var dashshft = 0;
  60795. var curshft = 0;
  60796. var p = 0;
  60797. var i = 0;
  60798. var j = 0;
  60799. for (i = 0; i < points.length - 1; i++) {
  60800. points[i + 1].subtractToRef(points[i], curvect);
  60801. lg += curvect.length();
  60802. }
  60803. shft = lg / nbSeg;
  60804. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60805. for (i = 0; i < points.length - 1; i++) {
  60806. points[i + 1].subtractToRef(points[i], curvect);
  60807. nb = Math.floor(curvect.length() / shft);
  60808. curvect.normalize();
  60809. j = 0;
  60810. while (j < nb && p < positions.length) {
  60811. curshft = shft * j;
  60812. positions[p] = points[i].x + curshft * curvect.x;
  60813. positions[p + 1] = points[i].y + curshft * curvect.y;
  60814. positions[p + 2] = points[i].z + curshft * curvect.z;
  60815. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60816. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60817. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60818. p += 6;
  60819. j++;
  60820. }
  60821. }
  60822. while (p < positions.length) {
  60823. positions[p] = points[i].x;
  60824. positions[p + 1] = points[i].y;
  60825. positions[p + 2] = points[i].z;
  60826. p += 3;
  60827. }
  60828. };
  60829. instance.updateMeshPositions(positionFunction, false);
  60830. return instance;
  60831. }
  60832. // dashed lines creation
  60833. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60834. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60835. vertexData.applyToMesh(dashedLines, options.updatable);
  60836. dashedLines.dashSize = dashSize;
  60837. dashedLines.gapSize = gapSize;
  60838. return dashedLines;
  60839. };
  60840. /**
  60841. * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60842. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  60843. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60844. * * 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.
  60845. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60846. * * 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
  60847. * * 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
  60848. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60849. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60850. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60851. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60852. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60853. * @param name defines the name of the mesh
  60854. * @param options defines the options used to create the mesh
  60855. * @param scene defines the hosting scene
  60856. * @returns the extruded shape mesh
  60857. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60858. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  60859. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  60860. */
  60861. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60862. if (scene === void 0) { scene = null; }
  60863. var path = options.path;
  60864. var shape = options.shape;
  60865. var scale = options.scale || 1;
  60866. var rotation = options.rotation || 0;
  60867. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60868. var updatable = options.updatable;
  60869. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60870. var instance = options.instance || null;
  60871. var invertUV = options.invertUV || false;
  60872. 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);
  60873. };
  60874. /**
  60875. * Creates an custom extruded shape mesh.
  60876. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60877. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
  60878. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60879. * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  60880. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60881. * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
  60882. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60883. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60884. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60885. * * 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
  60886. * * 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
  60887. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60888. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60889. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60890. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60891. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60892. * @param name defines the name of the mesh
  60893. * @param options defines the options used to create the mesh
  60894. * @param scene defines the hosting scene
  60895. * @returns the custom extruded shape mesh
  60896. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  60897. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60898. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  60899. */
  60900. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60901. var path = options.path;
  60902. var shape = options.shape;
  60903. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60904. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60905. var ribbonCloseArray = options.ribbonCloseArray || false;
  60906. var ribbonClosePath = options.ribbonClosePath || false;
  60907. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60908. var updatable = options.updatable;
  60909. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60910. var instance = options.instance;
  60911. var invertUV = options.invertUV || false;
  60912. 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);
  60913. };
  60914. /**
  60915. * Creates lathe mesh.
  60916. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60917. * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  60918. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60919. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60920. * * 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
  60921. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60922. * * 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
  60923. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60924. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60925. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60926. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60927. * @param name defines the name of the mesh
  60928. * @param options defines the options used to create the mesh
  60929. * @param scene defines the hosting scene
  60930. * @returns the lathe mesh
  60931. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  60932. */
  60933. MeshBuilder.CreateLathe = function (name, options, scene) {
  60934. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  60935. var closed = (options.closed === undefined) ? true : options.closed;
  60936. var shape = options.shape;
  60937. var radius = options.radius || 1;
  60938. var tessellation = options.tessellation || 64;
  60939. var updatable = options.updatable;
  60940. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60941. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60942. var pi2 = Math.PI * 2;
  60943. var paths = new Array();
  60944. var invertUV = options.invertUV || false;
  60945. var i = 0;
  60946. var p = 0;
  60947. var step = pi2 / tessellation * arc;
  60948. var rotated;
  60949. var path = new Array();
  60950. ;
  60951. for (i = 0; i <= tessellation; i++) {
  60952. var path = [];
  60953. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  60954. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  60955. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  60956. }
  60957. for (p = 0; p < shape.length; p++) {
  60958. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  60959. path.push(rotated);
  60960. }
  60961. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  60962. 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));
  60963. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  60964. }
  60965. paths.push(path);
  60966. }
  60967. // lathe ribbon
  60968. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60969. return lathe;
  60970. };
  60971. /**
  60972. * Creates a plane mesh
  60973. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  60974. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  60975. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  60976. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60977. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  60978. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60979. * @param name defines the name of the mesh
  60980. * @param options defines the options used to create the mesh
  60981. * @param scene defines the hosting scene
  60982. * @returns the plane mesh
  60983. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60984. */
  60985. MeshBuilder.CreatePlane = function (name, options, scene) {
  60986. var plane = new BABYLON.Mesh(name, scene);
  60987. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60988. plane._originalBuilderSideOrientation = options.sideOrientation;
  60989. var vertexData = BABYLON.VertexData.CreatePlane(options);
  60990. vertexData.applyToMesh(plane, options.updatable);
  60991. if (options.sourcePlane) {
  60992. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  60993. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  60994. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  60995. plane.rotate(vectorProduct, product);
  60996. }
  60997. return plane;
  60998. };
  60999. /**
  61000. * Creates a ground mesh
  61001. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61002. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61003. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61004. * @param name defines the name of the mesh
  61005. * @param options defines the options used to create the mesh
  61006. * @param scene defines the hosting scene
  61007. * @returns the ground mesh
  61008. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61009. */
  61010. MeshBuilder.CreateGround = function (name, options, scene) {
  61011. var ground = new BABYLON.GroundMesh(name, scene);
  61012. ground._setReady(false);
  61013. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61014. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61015. ground._width = options.width || 1;
  61016. ground._height = options.height || 1;
  61017. ground._maxX = ground._width / 2;
  61018. ground._maxZ = ground._height / 2;
  61019. ground._minX = -ground._maxX;
  61020. ground._minZ = -ground._maxZ;
  61021. var vertexData = BABYLON.VertexData.CreateGround(options);
  61022. vertexData.applyToMesh(ground, options.updatable);
  61023. ground._setReady(true);
  61024. return ground;
  61025. };
  61026. /**
  61027. * Creates a tiled ground mesh
  61028. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61029. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61030. * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  61031. * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  61032. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61033. * @param name defines the name of the mesh
  61034. * @param options defines the options used to create the mesh
  61035. * @param scene defines the hosting scene
  61036. * @returns the tiled ground mesh
  61037. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61038. */
  61039. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61040. var tiledGround = new BABYLON.Mesh(name, scene);
  61041. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61042. vertexData.applyToMesh(tiledGround, options.updatable);
  61043. return tiledGround;
  61044. };
  61045. /**
  61046. * Creates a ground mesh from a height map
  61047. * * The parameter `url` sets the URL of the height map image resource.
  61048. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61049. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61050. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61051. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61052. * * 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.
  61053. * * 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).
  61054. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61055. * @param name defines the name of the mesh
  61056. * @param url defines the url to the height map
  61057. * @param options defines the options used to create the mesh
  61058. * @param scene defines the hosting scene
  61059. * @returns the ground mesh
  61060. * @see http://doc.babylonjs.com/tutorials/14._Height_Map
  61061. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61062. */
  61063. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61064. var width = options.width || 10.0;
  61065. var height = options.height || 10.0;
  61066. var subdivisions = options.subdivisions || 1 | 0;
  61067. var minHeight = options.minHeight || 0.0;
  61068. var maxHeight = options.maxHeight || 1.0;
  61069. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61070. var updatable = options.updatable;
  61071. var onReady = options.onReady;
  61072. var ground = new BABYLON.GroundMesh(name, scene);
  61073. ground._subdivisionsX = subdivisions;
  61074. ground._subdivisionsY = subdivisions;
  61075. ground._width = width;
  61076. ground._height = height;
  61077. ground._maxX = ground._width / 2.0;
  61078. ground._maxZ = ground._height / 2.0;
  61079. ground._minX = -ground._maxX;
  61080. ground._minZ = -ground._maxZ;
  61081. ground._setReady(false);
  61082. var onload = function (img) {
  61083. // Getting height map data
  61084. var canvas = document.createElement("canvas");
  61085. var context = canvas.getContext("2d");
  61086. if (!context) {
  61087. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61088. }
  61089. if (scene.isDisposed) {
  61090. return;
  61091. }
  61092. var bufferWidth = img.width;
  61093. var bufferHeight = img.height;
  61094. canvas.width = bufferWidth;
  61095. canvas.height = bufferHeight;
  61096. context.drawImage(img, 0, 0);
  61097. // Create VertexData from map data
  61098. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61099. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61100. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61101. width: width, height: height,
  61102. subdivisions: subdivisions,
  61103. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61104. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61105. });
  61106. vertexData.applyToMesh(ground, updatable);
  61107. //execute ready callback, if set
  61108. if (onReady) {
  61109. onReady(ground);
  61110. }
  61111. ground._setReady(true);
  61112. };
  61113. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61114. return ground;
  61115. };
  61116. /**
  61117. * Creates a polygon mesh
  61118. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61119. * * 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
  61120. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61121. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61122. * * 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)
  61123. * * Remember you can only change the shape positions, not their number when updating a polygon
  61124. * @param name defines the name of the mesh
  61125. * @param options defines the options used to create the mesh
  61126. * @param scene defines the hosting scene
  61127. * @returns the polygon mesh
  61128. */
  61129. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61130. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61131. var shape = options.shape;
  61132. var holes = options.holes || [];
  61133. var depth = options.depth || 0;
  61134. var contours = [];
  61135. var hole = [];
  61136. for (var i = 0; i < shape.length; i++) {
  61137. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61138. }
  61139. var epsilon = 0.00000001;
  61140. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61141. contours.pop();
  61142. }
  61143. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61144. for (var hNb = 0; hNb < holes.length; hNb++) {
  61145. hole = [];
  61146. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61147. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61148. }
  61149. polygonTriangulation.addHole(hole);
  61150. }
  61151. var polygon = polygonTriangulation.build(options.updatable, depth);
  61152. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61153. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61154. vertexData.applyToMesh(polygon, options.updatable);
  61155. return polygon;
  61156. };
  61157. ;
  61158. /**
  61159. * Creates an extruded polygon mesh, with depth in the Y direction.
  61160. * * 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)
  61161. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61162. * @param name defines the name of the mesh
  61163. * @param options defines the options used to create the mesh
  61164. * @param scene defines the hosting scene
  61165. * @returns the polygon mesh
  61166. */
  61167. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61168. return MeshBuilder.CreatePolygon(name, options, scene);
  61169. };
  61170. ;
  61171. /**
  61172. * Creates a tube mesh.
  61173. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61174. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61175. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61176. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61177. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61178. * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float)
  61179. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61180. * * 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
  61181. * * 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
  61182. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61183. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  61184. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61185. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61186. * @param name defines the name of the mesh
  61187. * @param options defines the options used to create the mesh
  61188. * @param scene defines the hosting scene
  61189. * @returns the tube mesh
  61190. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61191. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61192. */
  61193. MeshBuilder.CreateTube = function (name, options, scene) {
  61194. var path = options.path;
  61195. var instance = options.instance;
  61196. var radius = 1.0;
  61197. if (instance) {
  61198. radius = instance.radius;
  61199. }
  61200. if (options.radius !== undefined) {
  61201. radius = options.radius;
  61202. }
  61203. ;
  61204. var tessellation = options.tessellation || 64 | 0;
  61205. var radiusFunction = options.radiusFunction || null;
  61206. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61207. var invertUV = options.invertUV || false;
  61208. var updatable = options.updatable;
  61209. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61210. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61211. // tube geometry
  61212. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61213. var tangents = path3D.getTangents();
  61214. var normals = path3D.getNormals();
  61215. var distances = path3D.getDistances();
  61216. var pi2 = Math.PI * 2;
  61217. var step = pi2 / tessellation * arc;
  61218. var returnRadius = function () { return radius; };
  61219. var radiusFunctionFinal = radiusFunction || returnRadius;
  61220. var circlePath;
  61221. var rad;
  61222. var normal;
  61223. var rotated;
  61224. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61225. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61226. for (var i = 0; i < path.length; i++) {
  61227. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61228. circlePath = Array(); // current circle array
  61229. normal = normals[i]; // current normal
  61230. for (var t = 0; t < tessellation; t++) {
  61231. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61232. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61233. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61234. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61235. circlePath[t] = rotated;
  61236. }
  61237. circlePaths[index] = circlePath;
  61238. index++;
  61239. }
  61240. // cap
  61241. var capPath = function (nbPoints, pathIndex) {
  61242. var pointCap = Array();
  61243. for (var i = 0; i < nbPoints; i++) {
  61244. pointCap.push(path[pathIndex]);
  61245. }
  61246. return pointCap;
  61247. };
  61248. switch (cap) {
  61249. case BABYLON.Mesh.NO_CAP:
  61250. break;
  61251. case BABYLON.Mesh.CAP_START:
  61252. circlePaths[0] = capPath(tessellation, 0);
  61253. circlePaths[1] = circlePaths[2].slice(0);
  61254. break;
  61255. case BABYLON.Mesh.CAP_END:
  61256. circlePaths[index] = circlePaths[index - 1].slice(0);
  61257. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61258. break;
  61259. case BABYLON.Mesh.CAP_ALL:
  61260. circlePaths[0] = capPath(tessellation, 0);
  61261. circlePaths[1] = circlePaths[2].slice(0);
  61262. circlePaths[index] = circlePaths[index - 1].slice(0);
  61263. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61264. break;
  61265. default:
  61266. break;
  61267. }
  61268. return circlePaths;
  61269. };
  61270. var path3D;
  61271. var pathArray;
  61272. if (instance) { // tube update
  61273. var arc = options.arc || instance.arc;
  61274. path3D = (instance.path3D).update(path);
  61275. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61276. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61277. instance.path3D = path3D;
  61278. instance.pathArray = pathArray;
  61279. instance.arc = arc;
  61280. instance.radius = radius;
  61281. return instance;
  61282. }
  61283. // tube creation
  61284. path3D = new BABYLON.Path3D(path);
  61285. var newPathArray = new Array();
  61286. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61287. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61288. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61289. tube.pathArray = pathArray;
  61290. tube.path3D = path3D;
  61291. tube.tessellation = tessellation;
  61292. tube.cap = cap;
  61293. tube.arc = options.arc;
  61294. tube.radius = radius;
  61295. return tube;
  61296. };
  61297. /**
  61298. * Creates a polyhedron mesh
  61299. * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type
  61300. * * The parameter `size` (positive float, default 1) sets the polygon size
  61301. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61302. * * 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`
  61303. * * 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
  61304. * * 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)`)
  61305. * * 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
  61306. * * 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
  61307. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61308. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  61309. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61310. * @param name defines the name of the mesh
  61311. * @param options defines the options used to create the mesh
  61312. * @param scene defines the hosting scene
  61313. * @returns the polyhedron mesh
  61314. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  61315. */
  61316. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61317. var polyhedron = new BABYLON.Mesh(name, scene);
  61318. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61319. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61320. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61321. vertexData.applyToMesh(polyhedron, options.updatable);
  61322. return polyhedron;
  61323. };
  61324. /**
  61325. * Creates a decal mesh.
  61326. * 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
  61327. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61328. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61329. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61330. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61331. * @param name defines the name of the mesh
  61332. * @param sourceMesh defines the mesh where the decal must be applied
  61333. * @param options defines the options used to create the mesh
  61334. * @param scene defines the hosting scene
  61335. * @returns the decal mesh
  61336. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  61337. */
  61338. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61339. var indices = sourceMesh.getIndices();
  61340. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61341. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61342. var position = options.position || BABYLON.Vector3.Zero();
  61343. var normal = options.normal || BABYLON.Vector3.Up();
  61344. var size = options.size || BABYLON.Vector3.One();
  61345. var angle = options.angle || 0;
  61346. // Getting correct rotation
  61347. if (!normal) {
  61348. var target = new BABYLON.Vector3(0, 0, 1);
  61349. var camera = sourceMesh.getScene().activeCamera;
  61350. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61351. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61352. }
  61353. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61354. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61355. var pitch = Math.atan2(normal.y, len);
  61356. // Matrix
  61357. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61358. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61359. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61360. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61361. var vertexData = new BABYLON.VertexData();
  61362. vertexData.indices = [];
  61363. vertexData.positions = [];
  61364. vertexData.normals = [];
  61365. vertexData.uvs = [];
  61366. var currentVertexDataIndex = 0;
  61367. var extractDecalVector3 = function (indexId) {
  61368. var result = new BABYLON.PositionNormalVertex();
  61369. if (!indices || !positions || !normals) {
  61370. return result;
  61371. }
  61372. var vertexId = indices[indexId];
  61373. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61374. // Send vector to decal local world
  61375. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61376. // Get normal
  61377. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61378. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61379. return result;
  61380. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61381. var clip = function (vertices, axis) {
  61382. if (vertices.length === 0) {
  61383. return vertices;
  61384. }
  61385. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61386. var clipVertices = function (v0, v1) {
  61387. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61388. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61389. };
  61390. var result = new Array();
  61391. for (var index = 0; index < vertices.length; index += 3) {
  61392. var v1Out;
  61393. var v2Out;
  61394. var v3Out;
  61395. var total = 0;
  61396. var nV1 = null;
  61397. var nV2 = null;
  61398. var nV3 = null;
  61399. var nV4 = null;
  61400. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61401. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61402. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61403. v1Out = d1 > 0;
  61404. v2Out = d2 > 0;
  61405. v3Out = d3 > 0;
  61406. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61407. switch (total) {
  61408. case 0:
  61409. result.push(vertices[index]);
  61410. result.push(vertices[index + 1]);
  61411. result.push(vertices[index + 2]);
  61412. break;
  61413. case 1:
  61414. if (v1Out) {
  61415. nV1 = vertices[index + 1];
  61416. nV2 = vertices[index + 2];
  61417. nV3 = clipVertices(vertices[index], nV1);
  61418. nV4 = clipVertices(vertices[index], nV2);
  61419. }
  61420. if (v2Out) {
  61421. nV1 = vertices[index];
  61422. nV2 = vertices[index + 2];
  61423. nV3 = clipVertices(vertices[index + 1], nV1);
  61424. nV4 = clipVertices(vertices[index + 1], nV2);
  61425. result.push(nV3);
  61426. result.push(nV2.clone());
  61427. result.push(nV1.clone());
  61428. result.push(nV2.clone());
  61429. result.push(nV3.clone());
  61430. result.push(nV4);
  61431. break;
  61432. }
  61433. if (v3Out) {
  61434. nV1 = vertices[index];
  61435. nV2 = vertices[index + 1];
  61436. nV3 = clipVertices(vertices[index + 2], nV1);
  61437. nV4 = clipVertices(vertices[index + 2], nV2);
  61438. }
  61439. if (nV1 && nV2 && nV3 && nV4) {
  61440. result.push(nV1.clone());
  61441. result.push(nV2.clone());
  61442. result.push(nV3);
  61443. result.push(nV4);
  61444. result.push(nV3.clone());
  61445. result.push(nV2.clone());
  61446. }
  61447. break;
  61448. case 2:
  61449. if (!v1Out) {
  61450. nV1 = vertices[index].clone();
  61451. nV2 = clipVertices(nV1, vertices[index + 1]);
  61452. nV3 = clipVertices(nV1, vertices[index + 2]);
  61453. result.push(nV1);
  61454. result.push(nV2);
  61455. result.push(nV3);
  61456. }
  61457. if (!v2Out) {
  61458. nV1 = vertices[index + 1].clone();
  61459. nV2 = clipVertices(nV1, vertices[index + 2]);
  61460. nV3 = clipVertices(nV1, vertices[index]);
  61461. result.push(nV1);
  61462. result.push(nV2);
  61463. result.push(nV3);
  61464. }
  61465. if (!v3Out) {
  61466. nV1 = vertices[index + 2].clone();
  61467. nV2 = clipVertices(nV1, vertices[index]);
  61468. nV3 = clipVertices(nV1, vertices[index + 1]);
  61469. result.push(nV1);
  61470. result.push(nV2);
  61471. result.push(nV3);
  61472. }
  61473. break;
  61474. case 3:
  61475. break;
  61476. }
  61477. }
  61478. return result;
  61479. };
  61480. for (var index = 0; index < indices.length; index += 3) {
  61481. var faceVertices = new Array();
  61482. faceVertices.push(extractDecalVector3(index));
  61483. faceVertices.push(extractDecalVector3(index + 1));
  61484. faceVertices.push(extractDecalVector3(index + 2));
  61485. // Clip
  61486. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61487. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61488. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61489. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61490. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61491. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61492. if (faceVertices.length === 0) {
  61493. continue;
  61494. }
  61495. // Add UVs and get back to world
  61496. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61497. var vertex = faceVertices[vIndex];
  61498. //TODO check for Int32Array | Uint32Array | Uint16Array
  61499. vertexData.indices.push(currentVertexDataIndex);
  61500. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61501. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61502. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61503. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61504. currentVertexDataIndex++;
  61505. }
  61506. }
  61507. // Return mesh
  61508. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61509. vertexData.applyToMesh(decal);
  61510. decal.position = position.clone();
  61511. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61512. return decal;
  61513. };
  61514. // Privates
  61515. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61516. // extrusion geometry
  61517. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61518. var tangents = path3D.getTangents();
  61519. var normals = path3D.getNormals();
  61520. var binormals = path3D.getBinormals();
  61521. var distances = path3D.getDistances();
  61522. var angle = 0;
  61523. var returnScale = function () { return scale !== null ? scale : 1; };
  61524. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61525. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61526. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61527. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61528. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61529. for (var i = 0; i < curve.length; i++) {
  61530. var shapePath = new Array();
  61531. var angleStep = rotate(i, distances[i]);
  61532. var scaleRatio = scl(i, distances[i]);
  61533. for (var p = 0; p < shape.length; p++) {
  61534. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61535. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61536. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61537. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61538. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61539. shapePath[p] = rotated;
  61540. }
  61541. shapePaths[index] = shapePath;
  61542. angle += angleStep;
  61543. index++;
  61544. }
  61545. // cap
  61546. var capPath = function (shapePath) {
  61547. var pointCap = Array();
  61548. var barycenter = BABYLON.Vector3.Zero();
  61549. var i;
  61550. for (i = 0; i < shapePath.length; i++) {
  61551. barycenter.addInPlace(shapePath[i]);
  61552. }
  61553. barycenter.scaleInPlace(1.0 / shapePath.length);
  61554. for (i = 0; i < shapePath.length; i++) {
  61555. pointCap.push(barycenter);
  61556. }
  61557. return pointCap;
  61558. };
  61559. switch (cap) {
  61560. case BABYLON.Mesh.NO_CAP:
  61561. break;
  61562. case BABYLON.Mesh.CAP_START:
  61563. shapePaths[0] = capPath(shapePaths[2]);
  61564. shapePaths[1] = shapePaths[2];
  61565. break;
  61566. case BABYLON.Mesh.CAP_END:
  61567. shapePaths[index] = shapePaths[index - 1];
  61568. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61569. break;
  61570. case BABYLON.Mesh.CAP_ALL:
  61571. shapePaths[0] = capPath(shapePaths[2]);
  61572. shapePaths[1] = shapePaths[2];
  61573. shapePaths[index] = shapePaths[index - 1];
  61574. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61575. break;
  61576. default:
  61577. break;
  61578. }
  61579. return shapePaths;
  61580. };
  61581. var path3D;
  61582. var pathArray;
  61583. if (instance) { // instance update
  61584. path3D = (instance.path3D).update(curve);
  61585. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61586. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61587. return instance;
  61588. }
  61589. // extruded shape creation
  61590. path3D = new BABYLON.Path3D(curve);
  61591. var newShapePaths = new Array();
  61592. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61593. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61594. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61595. extrudedGeneric.pathArray = pathArray;
  61596. extrudedGeneric.path3D = path3D;
  61597. extrudedGeneric.cap = cap;
  61598. return extrudedGeneric;
  61599. };
  61600. return MeshBuilder;
  61601. }());
  61602. BABYLON.MeshBuilder = MeshBuilder;
  61603. })(BABYLON || (BABYLON = {}));
  61604. //# sourceMappingURL=babylon.meshBuilder.js.map
  61605. var BABYLON;
  61606. (function (BABYLON) {
  61607. /**
  61608. * Draco compression (https://google.github.io/draco/)
  61609. */
  61610. var DracoCompression = /** @class */ (function () {
  61611. /**
  61612. * Constructor
  61613. */
  61614. function DracoCompression() {
  61615. }
  61616. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61617. /**
  61618. * Returns true if the decoder is available.
  61619. */
  61620. get: function () {
  61621. if (typeof DracoDecoderModule !== "undefined") {
  61622. return true;
  61623. }
  61624. var decoder = DracoCompression.Configuration.decoder;
  61625. if (decoder) {
  61626. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61627. return true;
  61628. }
  61629. if (decoder.fallbackUrl) {
  61630. return true;
  61631. }
  61632. }
  61633. return false;
  61634. },
  61635. enumerable: true,
  61636. configurable: true
  61637. });
  61638. /**
  61639. * Stop all async operations and release resources.
  61640. */
  61641. DracoCompression.prototype.dispose = function () {
  61642. };
  61643. /**
  61644. * Decode Draco compressed mesh data to vertex data.
  61645. * @param data The array buffer view for the Draco compression data
  61646. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61647. * @returns A promise that resolves with the decoded vertex data
  61648. */
  61649. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61650. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61651. var module = wrappedModule.module;
  61652. var vertexData = new BABYLON.VertexData();
  61653. var buffer = new module.DecoderBuffer();
  61654. buffer.Init(data, data.byteLength);
  61655. var decoder = new module.Decoder();
  61656. var geometry;
  61657. var status;
  61658. try {
  61659. var type = decoder.GetEncodedGeometryType(buffer);
  61660. switch (type) {
  61661. case module.TRIANGULAR_MESH:
  61662. geometry = new module.Mesh();
  61663. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61664. break;
  61665. case module.POINT_CLOUD:
  61666. geometry = new module.PointCloud();
  61667. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61668. break;
  61669. default:
  61670. throw new Error("Invalid geometry type " + type);
  61671. }
  61672. if (!status.ok() || !geometry.ptr) {
  61673. throw new Error(status.error_msg());
  61674. }
  61675. var numPoints = geometry.num_points();
  61676. if (type === module.TRIANGULAR_MESH) {
  61677. var numFaces = geometry.num_faces();
  61678. var faceIndices = new module.DracoInt32Array();
  61679. try {
  61680. var indices = new Uint32Array(numFaces * 3);
  61681. for (var i = 0; i < numFaces; i++) {
  61682. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61683. var offset = i * 3;
  61684. indices[offset + 0] = faceIndices.GetValue(0);
  61685. indices[offset + 1] = faceIndices.GetValue(1);
  61686. indices[offset + 2] = faceIndices.GetValue(2);
  61687. }
  61688. vertexData.indices = indices;
  61689. }
  61690. finally {
  61691. module.destroy(faceIndices);
  61692. }
  61693. }
  61694. for (var kind in attributes) {
  61695. var uniqueId = attributes[kind];
  61696. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61697. var dracoData = new module.DracoFloat32Array();
  61698. try {
  61699. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61700. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61701. for (var i = 0; i < babylonData.length; i++) {
  61702. babylonData[i] = dracoData.GetValue(i);
  61703. }
  61704. vertexData.set(babylonData, kind);
  61705. }
  61706. finally {
  61707. module.destroy(dracoData);
  61708. }
  61709. }
  61710. }
  61711. finally {
  61712. if (geometry) {
  61713. module.destroy(geometry);
  61714. }
  61715. module.destroy(decoder);
  61716. module.destroy(buffer);
  61717. }
  61718. return vertexData;
  61719. });
  61720. };
  61721. DracoCompression._GetDecoderModule = function () {
  61722. if (!DracoCompression._DecoderModulePromise) {
  61723. var promise = null;
  61724. var config_1 = {};
  61725. if (typeof DracoDecoderModule !== "undefined") {
  61726. promise = Promise.resolve();
  61727. }
  61728. else {
  61729. var decoder = DracoCompression.Configuration.decoder;
  61730. if (decoder) {
  61731. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61732. promise = Promise.all([
  61733. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61734. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61735. config_1.wasmBinary = data;
  61736. })
  61737. ]);
  61738. }
  61739. else if (decoder.fallbackUrl) {
  61740. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61741. }
  61742. }
  61743. }
  61744. if (!promise) {
  61745. throw new Error("Draco decoder module is not available");
  61746. }
  61747. DracoCompression._DecoderModulePromise = promise.then(function () {
  61748. return new Promise(function (resolve) {
  61749. config_1.onModuleLoaded = function (decoderModule) {
  61750. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61751. resolve({ module: decoderModule });
  61752. };
  61753. DracoDecoderModule(config_1);
  61754. });
  61755. });
  61756. }
  61757. return DracoCompression._DecoderModulePromise;
  61758. };
  61759. DracoCompression._LoadScriptAsync = function (url) {
  61760. return new Promise(function (resolve, reject) {
  61761. BABYLON.Tools.LoadScript(url, function () {
  61762. resolve();
  61763. }, function (message) {
  61764. reject(new Error(message));
  61765. });
  61766. });
  61767. };
  61768. DracoCompression._LoadFileAsync = function (url) {
  61769. return new Promise(function (resolve, reject) {
  61770. BABYLON.Tools.LoadFile(url, function (data) {
  61771. resolve(data);
  61772. }, undefined, undefined, true, function (request, exception) {
  61773. reject(exception);
  61774. });
  61775. });
  61776. };
  61777. /**
  61778. * The configuration.
  61779. */
  61780. DracoCompression.Configuration = {
  61781. decoder: {
  61782. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61783. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61784. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61785. }
  61786. };
  61787. return DracoCompression;
  61788. }());
  61789. BABYLON.DracoCompression = DracoCompression;
  61790. })(BABYLON || (BABYLON = {}));
  61791. //# sourceMappingURL=babylon.dracoCompression.js.map
  61792. var BABYLON;
  61793. (function (BABYLON) {
  61794. var AudioEngine = /** @class */ (function () {
  61795. function AudioEngine() {
  61796. this._audioContext = null;
  61797. this._audioContextInitialized = false;
  61798. this.canUseWebAudio = false;
  61799. this.WarnedWebAudioUnsupported = false;
  61800. this.unlocked = false;
  61801. this.isMP3supported = false;
  61802. this.isOGGsupported = false;
  61803. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61804. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61805. this.canUseWebAudio = true;
  61806. }
  61807. var audioElem = document.createElement('audio');
  61808. try {
  61809. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61810. this.isMP3supported = true;
  61811. }
  61812. }
  61813. catch (e) {
  61814. // protect error during capability check.
  61815. }
  61816. try {
  61817. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61818. this.isOGGsupported = true;
  61819. }
  61820. }
  61821. catch (e) {
  61822. // protect error during capability check.
  61823. }
  61824. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61825. this._unlockiOSaudio();
  61826. }
  61827. else {
  61828. this.unlocked = true;
  61829. }
  61830. }
  61831. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61832. get: function () {
  61833. if (!this._audioContextInitialized) {
  61834. this._initializeAudioContext();
  61835. }
  61836. return this._audioContext;
  61837. },
  61838. enumerable: true,
  61839. configurable: true
  61840. });
  61841. AudioEngine.prototype._unlockiOSaudio = function () {
  61842. var _this = this;
  61843. var unlockaudio = function () {
  61844. if (!_this.audioContext) {
  61845. return;
  61846. }
  61847. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61848. var source = _this.audioContext.createBufferSource();
  61849. source.buffer = buffer;
  61850. source.connect(_this.audioContext.destination);
  61851. source.start(0);
  61852. setTimeout(function () {
  61853. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61854. _this.unlocked = true;
  61855. window.removeEventListener('touchend', unlockaudio, false);
  61856. if (_this.onAudioUnlocked) {
  61857. _this.onAudioUnlocked();
  61858. }
  61859. }
  61860. }, 0);
  61861. };
  61862. window.addEventListener('touchend', unlockaudio, false);
  61863. };
  61864. AudioEngine.prototype._initializeAudioContext = function () {
  61865. try {
  61866. if (this.canUseWebAudio) {
  61867. this._audioContext = new AudioContext();
  61868. // create a global volume gain node
  61869. this.masterGain = this._audioContext.createGain();
  61870. this.masterGain.gain.value = 1;
  61871. this.masterGain.connect(this._audioContext.destination);
  61872. this._audioContextInitialized = true;
  61873. }
  61874. }
  61875. catch (e) {
  61876. this.canUseWebAudio = false;
  61877. BABYLON.Tools.Error("Web Audio: " + e.message);
  61878. }
  61879. };
  61880. AudioEngine.prototype.dispose = function () {
  61881. if (this.canUseWebAudio && this._audioContextInitialized) {
  61882. if (this._connectedAnalyser && this._audioContext) {
  61883. this._connectedAnalyser.stopDebugCanvas();
  61884. this._connectedAnalyser.dispose();
  61885. this.masterGain.disconnect();
  61886. this.masterGain.connect(this._audioContext.destination);
  61887. this._connectedAnalyser = null;
  61888. }
  61889. this.masterGain.gain.value = 1;
  61890. }
  61891. this.WarnedWebAudioUnsupported = false;
  61892. };
  61893. AudioEngine.prototype.getGlobalVolume = function () {
  61894. if (this.canUseWebAudio && this._audioContextInitialized) {
  61895. return this.masterGain.gain.value;
  61896. }
  61897. else {
  61898. return -1;
  61899. }
  61900. };
  61901. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61902. if (this.canUseWebAudio && this._audioContextInitialized) {
  61903. this.masterGain.gain.value = newVolume;
  61904. }
  61905. };
  61906. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61907. if (this._connectedAnalyser) {
  61908. this._connectedAnalyser.stopDebugCanvas();
  61909. }
  61910. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61911. this._connectedAnalyser = analyser;
  61912. this.masterGain.disconnect();
  61913. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61914. }
  61915. };
  61916. return AudioEngine;
  61917. }());
  61918. BABYLON.AudioEngine = AudioEngine;
  61919. })(BABYLON || (BABYLON = {}));
  61920. //# sourceMappingURL=babylon.audioEngine.js.map
  61921. var BABYLON;
  61922. (function (BABYLON) {
  61923. var Sound = /** @class */ (function () {
  61924. /**
  61925. * Create a sound and attach it to a scene
  61926. * @param name Name of your sound
  61927. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  61928. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  61929. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  61930. */
  61931. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  61932. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  61933. var _this = this;
  61934. this.autoplay = false;
  61935. this.loop = false;
  61936. this.useCustomAttenuation = false;
  61937. this.spatialSound = false;
  61938. this.refDistance = 1;
  61939. this.rolloffFactor = 1;
  61940. this.maxDistance = 100;
  61941. this.distanceModel = "linear";
  61942. this._panningModel = "equalpower";
  61943. this._playbackRate = 1;
  61944. this._streaming = false;
  61945. this._startTime = 0;
  61946. this._startOffset = 0;
  61947. this._position = BABYLON.Vector3.Zero();
  61948. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  61949. this._volume = 1;
  61950. this._isReadyToPlay = false;
  61951. this.isPlaying = false;
  61952. this.isPaused = false;
  61953. this._isDirectional = false;
  61954. // Used if you'd like to create a directional sound.
  61955. // If not set, the sound will be omnidirectional
  61956. this._coneInnerAngle = 360;
  61957. this._coneOuterAngle = 360;
  61958. this._coneOuterGain = 0;
  61959. this._isOutputConnected = false;
  61960. this._urlType = "Unknown";
  61961. this.name = name;
  61962. this._scene = scene;
  61963. this._readyToPlayCallback = readyToPlayCallback;
  61964. // Default custom attenuation function is a linear attenuation
  61965. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  61966. if (currentDistance < maxDistance) {
  61967. return currentVolume * (1 - currentDistance / maxDistance);
  61968. }
  61969. else {
  61970. return 0;
  61971. }
  61972. };
  61973. if (options) {
  61974. this.autoplay = options.autoplay || false;
  61975. this.loop = options.loop || false;
  61976. // if volume === 0, we need another way to check this option
  61977. if (options.volume !== undefined) {
  61978. this._volume = options.volume;
  61979. }
  61980. this.spatialSound = options.spatialSound || false;
  61981. this.maxDistance = options.maxDistance || 100;
  61982. this.useCustomAttenuation = options.useCustomAttenuation || false;
  61983. this.rolloffFactor = options.rolloffFactor || 1;
  61984. this.refDistance = options.refDistance || 1;
  61985. this.distanceModel = options.distanceModel || "linear";
  61986. this._playbackRate = options.playbackRate || 1;
  61987. this._streaming = options.streaming || false;
  61988. }
  61989. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61990. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  61991. this._soundGain.gain.value = this._volume;
  61992. this._inputAudioNode = this._soundGain;
  61993. this._ouputAudioNode = this._soundGain;
  61994. if (this.spatialSound) {
  61995. this._createSpatialParameters();
  61996. }
  61997. this._scene.mainSoundTrack.AddSound(this);
  61998. var validParameter = true;
  61999. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62000. if (urlOrArrayBuffer) {
  62001. try {
  62002. if (typeof (urlOrArrayBuffer) === "string")
  62003. this._urlType = "String";
  62004. if (Array.isArray(urlOrArrayBuffer))
  62005. this._urlType = "Array";
  62006. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62007. this._urlType = "ArrayBuffer";
  62008. var urls = [];
  62009. var codecSupportedFound = false;
  62010. switch (this._urlType) {
  62011. case "ArrayBuffer":
  62012. if (urlOrArrayBuffer.byteLength > 0) {
  62013. codecSupportedFound = true;
  62014. this._soundLoaded(urlOrArrayBuffer);
  62015. }
  62016. break;
  62017. case "String":
  62018. urls.push(urlOrArrayBuffer);
  62019. case "Array":
  62020. if (urls.length === 0)
  62021. urls = urlOrArrayBuffer;
  62022. // If we found a supported format, we load it immediately and stop the loop
  62023. for (var i = 0; i < urls.length; i++) {
  62024. var url = urls[i];
  62025. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62026. codecSupportedFound = true;
  62027. }
  62028. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62029. codecSupportedFound = true;
  62030. }
  62031. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62032. codecSupportedFound = true;
  62033. }
  62034. if (url.indexOf("blob:") !== -1) {
  62035. codecSupportedFound = true;
  62036. }
  62037. if (codecSupportedFound) {
  62038. // Loading sound using XHR2
  62039. if (!this._streaming) {
  62040. this._scene._loadFile(url, function (data) {
  62041. _this._soundLoaded(data);
  62042. }, undefined, true, true, function (exception) {
  62043. if (exception) {
  62044. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62045. }
  62046. BABYLON.Tools.Error("Sound creation aborted.");
  62047. _this._scene.mainSoundTrack.RemoveSound(_this);
  62048. });
  62049. }
  62050. // Streaming sound using HTML5 Audio tag
  62051. else {
  62052. this._htmlAudioElement = new Audio(url);
  62053. this._htmlAudioElement.controls = false;
  62054. this._htmlAudioElement.loop = this.loop;
  62055. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62056. this._htmlAudioElement.preload = "auto";
  62057. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62058. _this._isReadyToPlay = true;
  62059. if (_this.autoplay) {
  62060. _this.play();
  62061. }
  62062. if (_this._readyToPlayCallback) {
  62063. _this._readyToPlayCallback();
  62064. }
  62065. });
  62066. document.body.appendChild(this._htmlAudioElement);
  62067. }
  62068. break;
  62069. }
  62070. }
  62071. break;
  62072. default:
  62073. validParameter = false;
  62074. break;
  62075. }
  62076. if (!validParameter) {
  62077. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62078. }
  62079. else {
  62080. if (!codecSupportedFound) {
  62081. this._isReadyToPlay = true;
  62082. // Simulating a ready to play event to avoid breaking code path
  62083. if (this._readyToPlayCallback) {
  62084. window.setTimeout(function () {
  62085. if (_this._readyToPlayCallback) {
  62086. _this._readyToPlayCallback();
  62087. }
  62088. }, 1000);
  62089. }
  62090. }
  62091. }
  62092. }
  62093. catch (ex) {
  62094. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62095. this._scene.mainSoundTrack.RemoveSound(this);
  62096. }
  62097. }
  62098. }
  62099. else {
  62100. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62101. this._scene.mainSoundTrack.AddSound(this);
  62102. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62103. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62104. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62105. }
  62106. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62107. if (this._readyToPlayCallback) {
  62108. window.setTimeout(function () {
  62109. if (_this._readyToPlayCallback) {
  62110. _this._readyToPlayCallback();
  62111. }
  62112. }, 1000);
  62113. }
  62114. }
  62115. }
  62116. Sound.prototype.dispose = function () {
  62117. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62118. if (this.isPlaying) {
  62119. this.stop();
  62120. }
  62121. this._isReadyToPlay = false;
  62122. if (this.soundTrackId === -1) {
  62123. this._scene.mainSoundTrack.RemoveSound(this);
  62124. }
  62125. else {
  62126. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62127. }
  62128. if (this._soundGain) {
  62129. this._soundGain.disconnect();
  62130. this._soundGain = null;
  62131. }
  62132. if (this._soundPanner) {
  62133. this._soundPanner.disconnect();
  62134. this._soundPanner = null;
  62135. }
  62136. if (this._soundSource) {
  62137. this._soundSource.disconnect();
  62138. this._soundSource = null;
  62139. }
  62140. this._audioBuffer = null;
  62141. if (this._htmlAudioElement) {
  62142. this._htmlAudioElement.pause();
  62143. this._htmlAudioElement.src = "";
  62144. document.body.removeChild(this._htmlAudioElement);
  62145. }
  62146. if (this._connectedMesh && this._registerFunc) {
  62147. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62148. this._connectedMesh = null;
  62149. }
  62150. }
  62151. };
  62152. Sound.prototype.isReady = function () {
  62153. return this._isReadyToPlay;
  62154. };
  62155. Sound.prototype._soundLoaded = function (audioData) {
  62156. var _this = this;
  62157. if (!BABYLON.Engine.audioEngine.audioContext) {
  62158. return;
  62159. }
  62160. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62161. _this._audioBuffer = buffer;
  62162. _this._isReadyToPlay = true;
  62163. if (_this.autoplay) {
  62164. _this.play();
  62165. }
  62166. if (_this._readyToPlayCallback) {
  62167. _this._readyToPlayCallback();
  62168. }
  62169. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62170. };
  62171. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62172. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62173. this._audioBuffer = audioBuffer;
  62174. this._isReadyToPlay = true;
  62175. }
  62176. };
  62177. Sound.prototype.updateOptions = function (options) {
  62178. if (options) {
  62179. this.loop = options.loop || this.loop;
  62180. this.maxDistance = options.maxDistance || this.maxDistance;
  62181. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62182. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62183. this.refDistance = options.refDistance || this.refDistance;
  62184. this.distanceModel = options.distanceModel || this.distanceModel;
  62185. this._playbackRate = options.playbackRate || this._playbackRate;
  62186. this._updateSpatialParameters();
  62187. if (this.isPlaying) {
  62188. if (this._streaming) {
  62189. this._htmlAudioElement.playbackRate = this._playbackRate;
  62190. }
  62191. else {
  62192. if (this._soundSource) {
  62193. this._soundSource.playbackRate.value = this._playbackRate;
  62194. }
  62195. }
  62196. }
  62197. }
  62198. };
  62199. Sound.prototype._createSpatialParameters = function () {
  62200. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62201. if (this._scene.headphone) {
  62202. this._panningModel = "HRTF";
  62203. }
  62204. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62205. this._updateSpatialParameters();
  62206. this._soundPanner.connect(this._ouputAudioNode);
  62207. this._inputAudioNode = this._soundPanner;
  62208. }
  62209. };
  62210. Sound.prototype._updateSpatialParameters = function () {
  62211. if (this.spatialSound && this._soundPanner) {
  62212. if (this.useCustomAttenuation) {
  62213. // Tricks to disable in a way embedded Web Audio attenuation
  62214. this._soundPanner.distanceModel = "linear";
  62215. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62216. this._soundPanner.refDistance = 1;
  62217. this._soundPanner.rolloffFactor = 1;
  62218. this._soundPanner.panningModel = this._panningModel;
  62219. }
  62220. else {
  62221. this._soundPanner.distanceModel = this.distanceModel;
  62222. this._soundPanner.maxDistance = this.maxDistance;
  62223. this._soundPanner.refDistance = this.refDistance;
  62224. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62225. this._soundPanner.panningModel = this._panningModel;
  62226. }
  62227. }
  62228. };
  62229. Sound.prototype.switchPanningModelToHRTF = function () {
  62230. this._panningModel = "HRTF";
  62231. this._switchPanningModel();
  62232. };
  62233. Sound.prototype.switchPanningModelToEqualPower = function () {
  62234. this._panningModel = "equalpower";
  62235. this._switchPanningModel();
  62236. };
  62237. Sound.prototype._switchPanningModel = function () {
  62238. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62239. this._soundPanner.panningModel = this._panningModel;
  62240. }
  62241. };
  62242. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62243. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62244. if (this._isOutputConnected) {
  62245. this._ouputAudioNode.disconnect();
  62246. }
  62247. this._ouputAudioNode.connect(soundTrackAudioNode);
  62248. this._isOutputConnected = true;
  62249. }
  62250. };
  62251. /**
  62252. * Transform this sound into a directional source
  62253. * @param coneInnerAngle Size of the inner cone in degree
  62254. * @param coneOuterAngle Size of the outer cone in degree
  62255. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62256. */
  62257. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62258. if (coneOuterAngle < coneInnerAngle) {
  62259. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62260. return;
  62261. }
  62262. this._coneInnerAngle = coneInnerAngle;
  62263. this._coneOuterAngle = coneOuterAngle;
  62264. this._coneOuterGain = coneOuterGain;
  62265. this._isDirectional = true;
  62266. if (this.isPlaying && this.loop) {
  62267. this.stop();
  62268. this.play();
  62269. }
  62270. };
  62271. Sound.prototype.setPosition = function (newPosition) {
  62272. this._position = newPosition;
  62273. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62274. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62275. }
  62276. };
  62277. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62278. this._localDirection = newLocalDirection;
  62279. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62280. this._updateDirection();
  62281. }
  62282. };
  62283. Sound.prototype._updateDirection = function () {
  62284. if (!this._connectedMesh || !this._soundPanner) {
  62285. return;
  62286. }
  62287. var mat = this._connectedMesh.getWorldMatrix();
  62288. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62289. direction.normalize();
  62290. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62291. };
  62292. Sound.prototype.updateDistanceFromListener = function () {
  62293. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62294. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62295. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62296. }
  62297. };
  62298. Sound.prototype.setAttenuationFunction = function (callback) {
  62299. this._customAttenuationFunction = callback;
  62300. };
  62301. /**
  62302. * Play the sound
  62303. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62304. * @param offset (optional) Start the sound setting it at a specific time
  62305. */
  62306. Sound.prototype.play = function (time, offset) {
  62307. var _this = this;
  62308. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62309. try {
  62310. if (this._startOffset < 0) {
  62311. time = -this._startOffset;
  62312. this._startOffset = 0;
  62313. }
  62314. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62315. if (!this._soundSource || !this._streamingSource) {
  62316. if (this.spatialSound && this._soundPanner) {
  62317. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62318. if (this._isDirectional) {
  62319. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62320. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62321. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62322. if (this._connectedMesh) {
  62323. this._updateDirection();
  62324. }
  62325. else {
  62326. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62327. }
  62328. }
  62329. }
  62330. }
  62331. if (this._streaming) {
  62332. if (!this._streamingSource) {
  62333. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62334. this._htmlAudioElement.onended = function () { _this._onended(); };
  62335. this._htmlAudioElement.playbackRate = this._playbackRate;
  62336. }
  62337. this._streamingSource.disconnect();
  62338. this._streamingSource.connect(this._inputAudioNode);
  62339. this._htmlAudioElement.play();
  62340. }
  62341. else {
  62342. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62343. this._soundSource.buffer = this._audioBuffer;
  62344. this._soundSource.connect(this._inputAudioNode);
  62345. this._soundSource.loop = this.loop;
  62346. this._soundSource.playbackRate.value = this._playbackRate;
  62347. this._soundSource.onended = function () { _this._onended(); };
  62348. if (this._soundSource.buffer) {
  62349. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62350. }
  62351. }
  62352. this._startTime = startTime;
  62353. this.isPlaying = true;
  62354. this.isPaused = false;
  62355. }
  62356. catch (ex) {
  62357. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62358. }
  62359. }
  62360. };
  62361. Sound.prototype._onended = function () {
  62362. this.isPlaying = false;
  62363. if (this.onended) {
  62364. this.onended();
  62365. }
  62366. };
  62367. /**
  62368. * Stop the sound
  62369. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62370. */
  62371. Sound.prototype.stop = function (time) {
  62372. if (this.isPlaying) {
  62373. if (this._streaming) {
  62374. this._htmlAudioElement.pause();
  62375. // Test needed for Firefox or it will generate an Invalid State Error
  62376. if (this._htmlAudioElement.currentTime > 0) {
  62377. this._htmlAudioElement.currentTime = 0;
  62378. }
  62379. }
  62380. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62381. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62382. this._soundSource.stop(stopTime);
  62383. this._soundSource.onended = function () { };
  62384. if (!this.isPaused) {
  62385. this._startOffset = 0;
  62386. }
  62387. }
  62388. this.isPlaying = false;
  62389. }
  62390. };
  62391. Sound.prototype.pause = function () {
  62392. if (this.isPlaying) {
  62393. this.isPaused = true;
  62394. if (this._streaming) {
  62395. this._htmlAudioElement.pause();
  62396. }
  62397. else if (BABYLON.Engine.audioEngine.audioContext) {
  62398. this.stop(0);
  62399. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62400. }
  62401. }
  62402. };
  62403. Sound.prototype.setVolume = function (newVolume, time) {
  62404. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62405. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62406. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62407. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62408. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62409. }
  62410. else {
  62411. this._soundGain.gain.value = newVolume;
  62412. }
  62413. }
  62414. this._volume = newVolume;
  62415. };
  62416. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62417. this._playbackRate = newPlaybackRate;
  62418. if (this.isPlaying) {
  62419. if (this._streaming) {
  62420. this._htmlAudioElement.playbackRate = this._playbackRate;
  62421. }
  62422. else if (this._soundSource) {
  62423. this._soundSource.playbackRate.value = this._playbackRate;
  62424. }
  62425. }
  62426. };
  62427. Sound.prototype.getVolume = function () {
  62428. return this._volume;
  62429. };
  62430. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62431. var _this = this;
  62432. if (this._connectedMesh && this._registerFunc) {
  62433. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62434. this._registerFunc = null;
  62435. }
  62436. this._connectedMesh = meshToConnectTo;
  62437. if (!this.spatialSound) {
  62438. this.spatialSound = true;
  62439. this._createSpatialParameters();
  62440. if (this.isPlaying && this.loop) {
  62441. this.stop();
  62442. this.play();
  62443. }
  62444. }
  62445. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62446. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62447. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62448. };
  62449. Sound.prototype.detachFromMesh = function () {
  62450. if (this._connectedMesh && this._registerFunc) {
  62451. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62452. this._registerFunc = null;
  62453. this._connectedMesh = null;
  62454. }
  62455. };
  62456. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62457. if (!node.getBoundingInfo) {
  62458. return;
  62459. }
  62460. var mesh = node;
  62461. var boundingInfo = mesh.getBoundingInfo();
  62462. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62463. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62464. this._updateDirection();
  62465. }
  62466. };
  62467. Sound.prototype.clone = function () {
  62468. var _this = this;
  62469. if (!this._streaming) {
  62470. var setBufferAndRun = function () {
  62471. if (_this._isReadyToPlay) {
  62472. clonedSound._audioBuffer = _this.getAudioBuffer();
  62473. clonedSound._isReadyToPlay = true;
  62474. if (clonedSound.autoplay) {
  62475. clonedSound.play();
  62476. }
  62477. }
  62478. else {
  62479. window.setTimeout(setBufferAndRun, 300);
  62480. }
  62481. };
  62482. var currentOptions = {
  62483. autoplay: this.autoplay, loop: this.loop,
  62484. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62485. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62486. refDistance: this.refDistance, distanceModel: this.distanceModel
  62487. };
  62488. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62489. if (this.useCustomAttenuation) {
  62490. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62491. }
  62492. clonedSound.setPosition(this._position);
  62493. clonedSound.setPlaybackRate(this._playbackRate);
  62494. setBufferAndRun();
  62495. return clonedSound;
  62496. }
  62497. // Can't clone a streaming sound
  62498. else {
  62499. return null;
  62500. }
  62501. };
  62502. Sound.prototype.getAudioBuffer = function () {
  62503. return this._audioBuffer;
  62504. };
  62505. Sound.prototype.serialize = function () {
  62506. var serializationObject = {
  62507. name: this.name,
  62508. url: this.name,
  62509. autoplay: this.autoplay,
  62510. loop: this.loop,
  62511. volume: this._volume,
  62512. spatialSound: this.spatialSound,
  62513. maxDistance: this.maxDistance,
  62514. rolloffFactor: this.rolloffFactor,
  62515. refDistance: this.refDistance,
  62516. distanceModel: this.distanceModel,
  62517. playbackRate: this._playbackRate,
  62518. panningModel: this._panningModel,
  62519. soundTrackId: this.soundTrackId
  62520. };
  62521. if (this.spatialSound) {
  62522. if (this._connectedMesh)
  62523. serializationObject.connectedMeshId = this._connectedMesh.id;
  62524. serializationObject.position = this._position.asArray();
  62525. serializationObject.refDistance = this.refDistance;
  62526. serializationObject.distanceModel = this.distanceModel;
  62527. serializationObject.isDirectional = this._isDirectional;
  62528. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62529. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62530. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62531. serializationObject.coneOuterGain = this._coneOuterGain;
  62532. }
  62533. return serializationObject;
  62534. };
  62535. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62536. var soundName = parsedSound.name;
  62537. var soundUrl;
  62538. if (parsedSound.url) {
  62539. soundUrl = rootUrl + parsedSound.url;
  62540. }
  62541. else {
  62542. soundUrl = rootUrl + soundName;
  62543. }
  62544. var options = {
  62545. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62546. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62547. rolloffFactor: parsedSound.rolloffFactor,
  62548. refDistance: parsedSound.refDistance,
  62549. distanceModel: parsedSound.distanceModel,
  62550. playbackRate: parsedSound.playbackRate
  62551. };
  62552. var newSound;
  62553. if (!sourceSound) {
  62554. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62555. scene._addPendingData(newSound);
  62556. }
  62557. else {
  62558. var setBufferAndRun = function () {
  62559. if (sourceSound._isReadyToPlay) {
  62560. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62561. newSound._isReadyToPlay = true;
  62562. if (newSound.autoplay) {
  62563. newSound.play();
  62564. }
  62565. }
  62566. else {
  62567. window.setTimeout(setBufferAndRun, 300);
  62568. }
  62569. };
  62570. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62571. setBufferAndRun();
  62572. }
  62573. if (parsedSound.position) {
  62574. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62575. newSound.setPosition(soundPosition);
  62576. }
  62577. if (parsedSound.isDirectional) {
  62578. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62579. if (parsedSound.localDirectionToMesh) {
  62580. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62581. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62582. }
  62583. }
  62584. if (parsedSound.connectedMeshId) {
  62585. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62586. if (connectedMesh) {
  62587. newSound.attachToMesh(connectedMesh);
  62588. }
  62589. }
  62590. return newSound;
  62591. };
  62592. return Sound;
  62593. }());
  62594. BABYLON.Sound = Sound;
  62595. })(BABYLON || (BABYLON = {}));
  62596. //# sourceMappingURL=babylon.sound.js.map
  62597. var BABYLON;
  62598. (function (BABYLON) {
  62599. var SoundTrack = /** @class */ (function () {
  62600. function SoundTrack(scene, options) {
  62601. this.id = -1;
  62602. this._isMainTrack = false;
  62603. this._isInitialized = false;
  62604. this._scene = scene;
  62605. this.soundCollection = new Array();
  62606. this._options = options;
  62607. if (!this._isMainTrack) {
  62608. this._scene.soundTracks.push(this);
  62609. this.id = this._scene.soundTracks.length - 1;
  62610. }
  62611. }
  62612. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62613. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62614. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62615. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62616. if (this._options) {
  62617. if (this._options.volume) {
  62618. this._outputAudioNode.gain.value = this._options.volume;
  62619. }
  62620. if (this._options.mainTrack) {
  62621. this._isMainTrack = this._options.mainTrack;
  62622. }
  62623. }
  62624. this._isInitialized = true;
  62625. }
  62626. };
  62627. SoundTrack.prototype.dispose = function () {
  62628. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62629. if (this._connectedAnalyser) {
  62630. this._connectedAnalyser.stopDebugCanvas();
  62631. }
  62632. while (this.soundCollection.length) {
  62633. this.soundCollection[0].dispose();
  62634. }
  62635. if (this._outputAudioNode) {
  62636. this._outputAudioNode.disconnect();
  62637. }
  62638. this._outputAudioNode = null;
  62639. }
  62640. };
  62641. SoundTrack.prototype.AddSound = function (sound) {
  62642. if (!this._isInitialized) {
  62643. this._initializeSoundTrackAudioGraph();
  62644. }
  62645. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62646. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62647. }
  62648. if (sound.soundTrackId) {
  62649. if (sound.soundTrackId === -1) {
  62650. this._scene.mainSoundTrack.RemoveSound(sound);
  62651. }
  62652. else {
  62653. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62654. }
  62655. }
  62656. this.soundCollection.push(sound);
  62657. sound.soundTrackId = this.id;
  62658. };
  62659. SoundTrack.prototype.RemoveSound = function (sound) {
  62660. var index = this.soundCollection.indexOf(sound);
  62661. if (index !== -1) {
  62662. this.soundCollection.splice(index, 1);
  62663. }
  62664. };
  62665. SoundTrack.prototype.setVolume = function (newVolume) {
  62666. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62667. this._outputAudioNode.gain.value = newVolume;
  62668. }
  62669. };
  62670. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62671. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62672. for (var i = 0; i < this.soundCollection.length; i++) {
  62673. this.soundCollection[i].switchPanningModelToHRTF();
  62674. }
  62675. }
  62676. };
  62677. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62678. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62679. for (var i = 0; i < this.soundCollection.length; i++) {
  62680. this.soundCollection[i].switchPanningModelToEqualPower();
  62681. }
  62682. }
  62683. };
  62684. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62685. if (this._connectedAnalyser) {
  62686. this._connectedAnalyser.stopDebugCanvas();
  62687. }
  62688. this._connectedAnalyser = analyser;
  62689. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62690. this._outputAudioNode.disconnect();
  62691. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62692. }
  62693. };
  62694. return SoundTrack;
  62695. }());
  62696. BABYLON.SoundTrack = SoundTrack;
  62697. })(BABYLON || (BABYLON = {}));
  62698. //# sourceMappingURL=babylon.soundtrack.js.map
  62699. var BABYLON;
  62700. (function (BABYLON) {
  62701. /**
  62702. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62703. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62704. */
  62705. var Analyser = /** @class */ (function () {
  62706. /**
  62707. * Creates a new analyser
  62708. * @param scene defines hosting scene
  62709. */
  62710. function Analyser(scene) {
  62711. /**
  62712. * Gets or sets the smoothing
  62713. * @ignorenaming
  62714. */
  62715. this.SMOOTHING = 0.75;
  62716. /**
  62717. * Gets or sets the FFT table size
  62718. * @ignorenaming
  62719. */
  62720. this.FFT_SIZE = 512;
  62721. /**
  62722. * Gets or sets the bar graph amplitude
  62723. * @ignorenaming
  62724. */
  62725. this.BARGRAPHAMPLITUDE = 256;
  62726. /**
  62727. * Gets or sets the position of the debug canvas
  62728. * @ignorenaming
  62729. */
  62730. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62731. /**
  62732. * Gets or sets the debug canvas size
  62733. * @ignorenaming
  62734. */
  62735. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62736. this._scene = scene;
  62737. this._audioEngine = BABYLON.Engine.audioEngine;
  62738. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62739. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62740. this._webAudioAnalyser.minDecibels = -140;
  62741. this._webAudioAnalyser.maxDecibels = 0;
  62742. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62743. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62744. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62745. }
  62746. }
  62747. /**
  62748. * Get the number of data values you will have to play with for the visualization
  62749. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62750. * @returns a number
  62751. */
  62752. Analyser.prototype.getFrequencyBinCount = function () {
  62753. if (this._audioEngine.canUseWebAudio) {
  62754. return this._webAudioAnalyser.frequencyBinCount;
  62755. }
  62756. else {
  62757. return 0;
  62758. }
  62759. };
  62760. /**
  62761. * Gets the current frequency data as a byte array
  62762. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62763. * @returns a Uint8Array
  62764. */
  62765. Analyser.prototype.getByteFrequencyData = function () {
  62766. if (this._audioEngine.canUseWebAudio) {
  62767. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62768. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62769. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62770. }
  62771. return this._byteFreqs;
  62772. };
  62773. /**
  62774. * Gets the current waveform as a byte array
  62775. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62776. * @returns a Uint8Array
  62777. */
  62778. Analyser.prototype.getByteTimeDomainData = function () {
  62779. if (this._audioEngine.canUseWebAudio) {
  62780. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62781. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62782. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62783. }
  62784. return this._byteTime;
  62785. };
  62786. /**
  62787. * Gets the current frequency data as a float array
  62788. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62789. * @returns a Float32Array
  62790. */
  62791. Analyser.prototype.getFloatFrequencyData = function () {
  62792. if (this._audioEngine.canUseWebAudio) {
  62793. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62794. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62795. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62796. }
  62797. return this._floatFreqs;
  62798. };
  62799. /**
  62800. * Renders the debug canvas
  62801. */
  62802. Analyser.prototype.drawDebugCanvas = function () {
  62803. var _this = this;
  62804. if (this._audioEngine.canUseWebAudio) {
  62805. if (!this._debugCanvas) {
  62806. this._debugCanvas = document.createElement("canvas");
  62807. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62808. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62809. this._debugCanvas.style.position = "absolute";
  62810. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62811. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62812. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62813. document.body.appendChild(this._debugCanvas);
  62814. this._registerFunc = function () {
  62815. _this.drawDebugCanvas();
  62816. };
  62817. this._scene.registerBeforeRender(this._registerFunc);
  62818. }
  62819. if (this._registerFunc && this._debugCanvasContext) {
  62820. var workingArray = this.getByteFrequencyData();
  62821. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62822. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62823. // Draw the frequency domain chart.
  62824. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62825. var value = workingArray[i];
  62826. var percent = value / this.BARGRAPHAMPLITUDE;
  62827. var height = this.DEBUGCANVASSIZE.height * percent;
  62828. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62829. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62830. var hue = i / this.getFrequencyBinCount() * 360;
  62831. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62832. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62833. }
  62834. }
  62835. }
  62836. };
  62837. /**
  62838. * Stops rendering the debug canvas and removes it
  62839. */
  62840. Analyser.prototype.stopDebugCanvas = function () {
  62841. if (this._debugCanvas) {
  62842. if (this._registerFunc) {
  62843. this._scene.unregisterBeforeRender(this._registerFunc);
  62844. this._registerFunc = null;
  62845. }
  62846. document.body.removeChild(this._debugCanvas);
  62847. this._debugCanvas = null;
  62848. this._debugCanvasContext = null;
  62849. }
  62850. };
  62851. /**
  62852. * Connects two audio nodes
  62853. * @param inputAudioNode defines first node to connect
  62854. * @param outputAudioNode defines second node to connect
  62855. */
  62856. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62857. if (this._audioEngine.canUseWebAudio) {
  62858. inputAudioNode.connect(this._webAudioAnalyser);
  62859. this._webAudioAnalyser.connect(outputAudioNode);
  62860. }
  62861. };
  62862. /**
  62863. * Releases all associated resources
  62864. */
  62865. Analyser.prototype.dispose = function () {
  62866. if (this._audioEngine.canUseWebAudio) {
  62867. this._webAudioAnalyser.disconnect();
  62868. }
  62869. };
  62870. return Analyser;
  62871. }());
  62872. BABYLON.Analyser = Analyser;
  62873. })(BABYLON || (BABYLON = {}));
  62874. //# sourceMappingURL=babylon.analyser.js.map
  62875. var BABYLON;
  62876. (function (BABYLON) {
  62877. var CubeTexture = /** @class */ (function (_super) {
  62878. __extends(CubeTexture, _super);
  62879. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  62880. if (extensions === void 0) { extensions = null; }
  62881. if (noMipmap === void 0) { noMipmap = false; }
  62882. if (files === void 0) { files = null; }
  62883. if (onLoad === void 0) { onLoad = null; }
  62884. if (onError === void 0) { onError = null; }
  62885. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62886. if (prefiltered === void 0) { prefiltered = false; }
  62887. if (forcedExtension === void 0) { forcedExtension = null; }
  62888. var _this = _super.call(this, scene) || this;
  62889. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62890. /**
  62891. * Gets or sets the center of the bounding box associated with the cube texture
  62892. * It must define where the camera used to render the texture was set
  62893. */
  62894. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62895. _this._rotationY = 0;
  62896. _this.name = rootUrl;
  62897. _this.url = rootUrl;
  62898. _this._noMipmap = noMipmap;
  62899. _this.hasAlpha = false;
  62900. _this._format = format;
  62901. _this._prefiltered = prefiltered;
  62902. _this.isCube = true;
  62903. _this._textureMatrix = BABYLON.Matrix.Identity();
  62904. if (prefiltered) {
  62905. _this.gammaSpace = false;
  62906. }
  62907. if (!rootUrl && !files) {
  62908. return _this;
  62909. }
  62910. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62911. var lastDot = rootUrl.lastIndexOf(".");
  62912. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62913. var isDDS = (extension === ".dds");
  62914. if (!files) {
  62915. if (!isDDS && !extensions) {
  62916. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  62917. }
  62918. files = [];
  62919. if (extensions) {
  62920. for (var index = 0; index < extensions.length; index++) {
  62921. files.push(rootUrl + extensions[index]);
  62922. }
  62923. }
  62924. }
  62925. _this._files = files;
  62926. if (!_this._texture) {
  62927. if (!scene.useDelayedTextureLoading) {
  62928. if (prefiltered) {
  62929. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  62930. }
  62931. else {
  62932. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  62933. }
  62934. }
  62935. else {
  62936. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62937. }
  62938. }
  62939. else if (onLoad) {
  62940. if (_this._texture.isReady) {
  62941. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  62942. }
  62943. else {
  62944. _this._texture.onLoadedObservable.add(onLoad);
  62945. }
  62946. }
  62947. return _this;
  62948. }
  62949. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  62950. get: function () {
  62951. return this._boundingBoxSize;
  62952. },
  62953. /**
  62954. * Gets or sets the size of the bounding box associated with the cube texture
  62955. * When defined, the cubemap will switch to local mode
  62956. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62957. * @example https://www.babylonjs-playground.com/#RNASML
  62958. */
  62959. set: function (value) {
  62960. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62961. return;
  62962. }
  62963. this._boundingBoxSize = value;
  62964. var scene = this.getScene();
  62965. if (scene) {
  62966. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62967. }
  62968. },
  62969. enumerable: true,
  62970. configurable: true
  62971. });
  62972. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  62973. /**
  62974. * Gets texture matrix rotation angle around Y axis radians.
  62975. */
  62976. get: function () {
  62977. return this._rotationY;
  62978. },
  62979. /**
  62980. * Sets texture matrix rotation angle around Y axis in radians.
  62981. */
  62982. set: function (value) {
  62983. this._rotationY = value;
  62984. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  62985. },
  62986. enumerable: true,
  62987. configurable: true
  62988. });
  62989. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  62990. var rootUrlKey = "";
  62991. files.forEach(function (url) { return rootUrlKey += url; });
  62992. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  62993. };
  62994. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  62995. if (forcedExtension === void 0) { forcedExtension = null; }
  62996. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  62997. };
  62998. // Methods
  62999. CubeTexture.prototype.delayLoad = function () {
  63000. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63001. return;
  63002. }
  63003. var scene = this.getScene();
  63004. if (!scene) {
  63005. return;
  63006. }
  63007. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63008. this._texture = this._getFromCache(this.url, this._noMipmap);
  63009. if (!this._texture) {
  63010. if (this._prefiltered) {
  63011. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  63012. }
  63013. else {
  63014. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63015. }
  63016. }
  63017. };
  63018. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63019. return this._textureMatrix;
  63020. };
  63021. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63022. this._textureMatrix = value;
  63023. };
  63024. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63025. var texture = BABYLON.SerializationHelper.Parse(function () {
  63026. var prefiltered = false;
  63027. if (parsedTexture.prefiltered) {
  63028. prefiltered = parsedTexture.prefiltered;
  63029. }
  63030. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63031. }, parsedTexture, scene);
  63032. // Local Cubemaps
  63033. if (parsedTexture.boundingBoxPosition) {
  63034. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63035. }
  63036. if (parsedTexture.boundingBoxSize) {
  63037. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63038. }
  63039. // Animations
  63040. if (parsedTexture.animations) {
  63041. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63042. var parsedAnimation = parsedTexture.animations[animationIndex];
  63043. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63044. }
  63045. }
  63046. return texture;
  63047. };
  63048. CubeTexture.prototype.clone = function () {
  63049. var _this = this;
  63050. return BABYLON.SerializationHelper.Clone(function () {
  63051. var scene = _this.getScene();
  63052. if (!scene) {
  63053. return _this;
  63054. }
  63055. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63056. }, this);
  63057. };
  63058. __decorate([
  63059. BABYLON.serialize("rotationY")
  63060. ], CubeTexture.prototype, "_rotationY", void 0);
  63061. return CubeTexture;
  63062. }(BABYLON.BaseTexture));
  63063. BABYLON.CubeTexture = CubeTexture;
  63064. })(BABYLON || (BABYLON = {}));
  63065. //# sourceMappingURL=babylon.cubeTexture.js.map
  63066. var BABYLON;
  63067. (function (BABYLON) {
  63068. var RenderTargetTexture = /** @class */ (function (_super) {
  63069. __extends(RenderTargetTexture, _super);
  63070. /**
  63071. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63072. * or used a shadow, depth texture...
  63073. * @param name The friendly name of the texture
  63074. * @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)
  63075. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63076. * @param generateMipMaps True if mip maps need to be generated after render.
  63077. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63078. * @param type The type of the buffer in the RTT (int, half float, float...)
  63079. * @param isCube True if a cube texture needs to be created
  63080. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63081. * @param generateDepthBuffer True to generate a depth buffer
  63082. * @param generateStencilBuffer True to generate a stencil buffer
  63083. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63084. */
  63085. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63086. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63087. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63088. if (isCube === void 0) { isCube = false; }
  63089. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63090. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63091. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63092. if (isMulti === void 0) { isMulti = false; }
  63093. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63094. _this.isCube = isCube;
  63095. /**
  63096. * Use this list to define the list of mesh you want to render.
  63097. */
  63098. _this.renderList = new Array();
  63099. _this.renderParticles = true;
  63100. _this.renderSprites = false;
  63101. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63102. _this.ignoreCameraViewport = false;
  63103. // Events
  63104. /**
  63105. * An event triggered when the texture is unbind.
  63106. */
  63107. _this.onBeforeBindObservable = new BABYLON.Observable();
  63108. /**
  63109. * An event triggered when the texture is unbind.
  63110. */
  63111. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63112. /**
  63113. * An event triggered before rendering the texture
  63114. */
  63115. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63116. /**
  63117. * An event triggered after rendering the texture
  63118. */
  63119. _this.onAfterRenderObservable = new BABYLON.Observable();
  63120. /**
  63121. * An event triggered after the texture clear
  63122. */
  63123. _this.onClearObservable = new BABYLON.Observable();
  63124. _this._currentRefreshId = -1;
  63125. _this._refreshRate = 1;
  63126. _this._samples = 1;
  63127. /**
  63128. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63129. * It must define where the camera used to render the texture is set
  63130. */
  63131. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63132. scene = _this.getScene();
  63133. if (!scene) {
  63134. return _this;
  63135. }
  63136. _this._engine = scene.getEngine();
  63137. _this.name = name;
  63138. _this.isRenderTarget = true;
  63139. _this._initialSizeParameter = size;
  63140. _this._processSizeParameter(size);
  63141. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63142. });
  63143. _this._generateMipMaps = generateMipMaps ? true : false;
  63144. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63145. // Rendering groups
  63146. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63147. if (isMulti) {
  63148. return _this;
  63149. }
  63150. _this._renderTargetOptions = {
  63151. generateMipMaps: generateMipMaps,
  63152. type: type,
  63153. samplingMode: samplingMode,
  63154. generateDepthBuffer: generateDepthBuffer,
  63155. generateStencilBuffer: generateStencilBuffer
  63156. };
  63157. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63158. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63159. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63160. }
  63161. if (isCube) {
  63162. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63163. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63164. _this._textureMatrix = BABYLON.Matrix.Identity();
  63165. }
  63166. else {
  63167. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63168. }
  63169. return _this;
  63170. }
  63171. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63172. get: function () {
  63173. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63174. },
  63175. enumerable: true,
  63176. configurable: true
  63177. });
  63178. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63179. get: function () {
  63180. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63181. },
  63182. enumerable: true,
  63183. configurable: true
  63184. });
  63185. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63186. get: function () {
  63187. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63188. },
  63189. enumerable: true,
  63190. configurable: true
  63191. });
  63192. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63193. set: function (callback) {
  63194. if (this._onAfterUnbindObserver) {
  63195. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63196. }
  63197. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63198. },
  63199. enumerable: true,
  63200. configurable: true
  63201. });
  63202. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63203. set: function (callback) {
  63204. if (this._onBeforeRenderObserver) {
  63205. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63206. }
  63207. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63208. },
  63209. enumerable: true,
  63210. configurable: true
  63211. });
  63212. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63213. set: function (callback) {
  63214. if (this._onAfterRenderObserver) {
  63215. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63216. }
  63217. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63218. },
  63219. enumerable: true,
  63220. configurable: true
  63221. });
  63222. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63223. set: function (callback) {
  63224. if (this._onClearObserver) {
  63225. this.onClearObservable.remove(this._onClearObserver);
  63226. }
  63227. this._onClearObserver = this.onClearObservable.add(callback);
  63228. },
  63229. enumerable: true,
  63230. configurable: true
  63231. });
  63232. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63233. get: function () {
  63234. return this._renderTargetOptions;
  63235. },
  63236. enumerable: true,
  63237. configurable: true
  63238. });
  63239. RenderTargetTexture.prototype._onRatioRescale = function () {
  63240. if (this._sizeRatio) {
  63241. this.resize(this._initialSizeParameter);
  63242. }
  63243. };
  63244. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63245. get: function () {
  63246. return this._boundingBoxSize;
  63247. },
  63248. /**
  63249. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63250. * When defined, the cubemap will switch to local mode
  63251. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63252. * @example https://www.babylonjs-playground.com/#RNASML
  63253. */
  63254. set: function (value) {
  63255. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63256. return;
  63257. }
  63258. this._boundingBoxSize = value;
  63259. var scene = this.getScene();
  63260. if (scene) {
  63261. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63262. }
  63263. },
  63264. enumerable: true,
  63265. configurable: true
  63266. });
  63267. /**
  63268. * Creates a depth stencil texture.
  63269. * This is only available in WebGL 2 or with the depth texture extension available.
  63270. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63271. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63272. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63273. */
  63274. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63275. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63276. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63277. if (generateStencil === void 0) { generateStencil = false; }
  63278. if (!this.getScene()) {
  63279. return;
  63280. }
  63281. var engine = this.getScene().getEngine();
  63282. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63283. bilinearFiltering: bilinearFiltering,
  63284. comparisonFunction: comparisonFunction,
  63285. generateStencil: generateStencil,
  63286. isCube: this.isCube
  63287. });
  63288. engine.setFrameBufferDepthStencilTexture(this);
  63289. };
  63290. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63291. if (size.ratio) {
  63292. this._sizeRatio = size.ratio;
  63293. this._size = {
  63294. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63295. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63296. };
  63297. }
  63298. else {
  63299. this._size = size;
  63300. }
  63301. };
  63302. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63303. get: function () {
  63304. return this._samples;
  63305. },
  63306. set: function (value) {
  63307. if (this._samples === value) {
  63308. return;
  63309. }
  63310. var scene = this.getScene();
  63311. if (!scene) {
  63312. return;
  63313. }
  63314. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63315. },
  63316. enumerable: true,
  63317. configurable: true
  63318. });
  63319. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63320. this._currentRefreshId = -1;
  63321. };
  63322. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63323. get: function () {
  63324. return this._refreshRate;
  63325. },
  63326. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63327. set: function (value) {
  63328. this._refreshRate = value;
  63329. this.resetRefreshCounter();
  63330. },
  63331. enumerable: true,
  63332. configurable: true
  63333. });
  63334. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63335. if (!this._postProcessManager) {
  63336. var scene = this.getScene();
  63337. if (!scene) {
  63338. return;
  63339. }
  63340. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63341. this._postProcesses = new Array();
  63342. }
  63343. this._postProcesses.push(postProcess);
  63344. this._postProcesses[0].autoClear = false;
  63345. };
  63346. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63347. if (!this._postProcesses) {
  63348. return;
  63349. }
  63350. if (dispose) {
  63351. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63352. var postProcess = _a[_i];
  63353. postProcess.dispose();
  63354. }
  63355. }
  63356. this._postProcesses = [];
  63357. };
  63358. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63359. if (!this._postProcesses) {
  63360. return;
  63361. }
  63362. var index = this._postProcesses.indexOf(postProcess);
  63363. if (index === -1) {
  63364. return;
  63365. }
  63366. this._postProcesses.splice(index, 1);
  63367. if (this._postProcesses.length > 0) {
  63368. this._postProcesses[0].autoClear = false;
  63369. }
  63370. };
  63371. RenderTargetTexture.prototype._shouldRender = function () {
  63372. if (this._currentRefreshId === -1) { // At least render once
  63373. this._currentRefreshId = 1;
  63374. return true;
  63375. }
  63376. if (this.refreshRate === this._currentRefreshId) {
  63377. this._currentRefreshId = 1;
  63378. return true;
  63379. }
  63380. this._currentRefreshId++;
  63381. return false;
  63382. };
  63383. RenderTargetTexture.prototype.getRenderSize = function () {
  63384. if (this._size.width) {
  63385. return this._size.width;
  63386. }
  63387. return this._size;
  63388. };
  63389. RenderTargetTexture.prototype.getRenderWidth = function () {
  63390. if (this._size.width) {
  63391. return this._size.width;
  63392. }
  63393. return this._size;
  63394. };
  63395. RenderTargetTexture.prototype.getRenderHeight = function () {
  63396. if (this._size.width) {
  63397. return this._size.height;
  63398. }
  63399. return this._size;
  63400. };
  63401. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63402. get: function () {
  63403. return true;
  63404. },
  63405. enumerable: true,
  63406. configurable: true
  63407. });
  63408. RenderTargetTexture.prototype.scale = function (ratio) {
  63409. var newSize = this.getRenderSize() * ratio;
  63410. this.resize(newSize);
  63411. };
  63412. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63413. if (this.isCube) {
  63414. return this._textureMatrix;
  63415. }
  63416. return _super.prototype.getReflectionTextureMatrix.call(this);
  63417. };
  63418. RenderTargetTexture.prototype.resize = function (size) {
  63419. this.releaseInternalTexture();
  63420. var scene = this.getScene();
  63421. if (!scene) {
  63422. return;
  63423. }
  63424. this._processSizeParameter(size);
  63425. if (this.isCube) {
  63426. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63427. }
  63428. else {
  63429. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63430. }
  63431. };
  63432. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63433. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63434. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63435. var scene = this.getScene();
  63436. if (!scene) {
  63437. return;
  63438. }
  63439. var engine = scene.getEngine();
  63440. if (this.useCameraPostProcesses !== undefined) {
  63441. useCameraPostProcess = this.useCameraPostProcesses;
  63442. }
  63443. if (this._waitingRenderList) {
  63444. this.renderList = [];
  63445. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63446. var id = this._waitingRenderList[index];
  63447. var mesh_1 = scene.getMeshByID(id);
  63448. if (mesh_1) {
  63449. this.renderList.push(mesh_1);
  63450. }
  63451. }
  63452. delete this._waitingRenderList;
  63453. }
  63454. // Is predicate defined?
  63455. if (this.renderListPredicate) {
  63456. if (this.renderList) {
  63457. this.renderList.splice(0); // Clear previous renderList
  63458. }
  63459. else {
  63460. this.renderList = [];
  63461. }
  63462. var scene = this.getScene();
  63463. if (!scene) {
  63464. return;
  63465. }
  63466. var sceneMeshes = scene.meshes;
  63467. for (var index = 0; index < sceneMeshes.length; index++) {
  63468. var mesh = sceneMeshes[index];
  63469. if (this.renderListPredicate(mesh)) {
  63470. this.renderList.push(mesh);
  63471. }
  63472. }
  63473. }
  63474. this.onBeforeBindObservable.notifyObservers(this);
  63475. // Set custom projection.
  63476. // Needs to be before binding to prevent changing the aspect ratio.
  63477. var camera;
  63478. if (this.activeCamera) {
  63479. camera = this.activeCamera;
  63480. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63481. if (this.activeCamera !== scene.activeCamera) {
  63482. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63483. }
  63484. }
  63485. else {
  63486. camera = scene.activeCamera;
  63487. if (camera) {
  63488. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63489. }
  63490. }
  63491. // Prepare renderingManager
  63492. this._renderingManager.reset();
  63493. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63494. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63495. var sceneRenderId = scene.getRenderId();
  63496. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63497. var mesh = currentRenderList[meshIndex];
  63498. if (mesh) {
  63499. if (!mesh.isReady(this.refreshRate === 0)) {
  63500. this.resetRefreshCounter();
  63501. continue;
  63502. }
  63503. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63504. var isMasked = void 0;
  63505. if (!this.renderList && camera) {
  63506. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63507. }
  63508. else {
  63509. isMasked = false;
  63510. }
  63511. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63512. mesh._activate(sceneRenderId);
  63513. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63514. var subMesh = mesh.subMeshes[subIndex];
  63515. scene._activeIndices.addCount(subMesh.indexCount, false);
  63516. this._renderingManager.dispatch(subMesh, mesh);
  63517. }
  63518. }
  63519. }
  63520. }
  63521. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63522. var particleSystem = scene.particleSystems[particleIndex];
  63523. var emitter = particleSystem.emitter;
  63524. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63525. continue;
  63526. }
  63527. if (currentRenderList.indexOf(emitter) >= 0) {
  63528. this._renderingManager.dispatchParticles(particleSystem);
  63529. }
  63530. }
  63531. if (this.isCube) {
  63532. for (var face = 0; face < 6; face++) {
  63533. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63534. scene.incrementRenderId();
  63535. scene.resetCachedMaterial();
  63536. }
  63537. }
  63538. else {
  63539. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63540. }
  63541. this.onAfterUnbindObservable.notifyObservers(this);
  63542. if (scene.activeCamera) {
  63543. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63544. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63545. }
  63546. engine.setViewport(scene.activeCamera.viewport);
  63547. }
  63548. scene.resetCachedMaterial();
  63549. };
  63550. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63551. var minimum = 128;
  63552. var x = renderDimension * scale;
  63553. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63554. // Ensure we don't exceed the render dimension (while staying POT)
  63555. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63556. };
  63557. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63558. var _this = this;
  63559. if (!this._texture) {
  63560. return;
  63561. }
  63562. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63563. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63564. });
  63565. };
  63566. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63567. var scene = this.getScene();
  63568. if (!scene) {
  63569. return;
  63570. }
  63571. var engine = scene.getEngine();
  63572. if (!this._texture) {
  63573. return;
  63574. }
  63575. // Bind
  63576. if (this._postProcessManager) {
  63577. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63578. }
  63579. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63580. if (this._texture) {
  63581. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63582. }
  63583. }
  63584. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63585. // Clear
  63586. if (this.onClearObservable.hasObservers()) {
  63587. this.onClearObservable.notifyObservers(engine);
  63588. }
  63589. else {
  63590. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63591. }
  63592. if (!this._doNotChangeAspectRatio) {
  63593. scene.updateTransformMatrix(true);
  63594. }
  63595. // Render
  63596. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63597. if (this._postProcessManager) {
  63598. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63599. }
  63600. else if (useCameraPostProcess) {
  63601. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63602. }
  63603. if (!this._doNotChangeAspectRatio) {
  63604. scene.updateTransformMatrix(true);
  63605. }
  63606. // Dump ?
  63607. if (dumpForDebug) {
  63608. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63609. }
  63610. // Unbind
  63611. if (!this.isCube || faceIndex === 5) {
  63612. if (this.isCube) {
  63613. if (faceIndex === 5) {
  63614. engine.generateMipMapsForCubemap(this._texture);
  63615. }
  63616. }
  63617. this.unbindFrameBuffer(engine, faceIndex);
  63618. }
  63619. else {
  63620. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63621. }
  63622. };
  63623. /**
  63624. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63625. * This allowed control for front to back rendering or reversly depending of the special needs.
  63626. *
  63627. * @param renderingGroupId The rendering group id corresponding to its index
  63628. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63629. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63630. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63631. */
  63632. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63633. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63634. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63635. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63636. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63637. };
  63638. /**
  63639. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63640. *
  63641. * @param renderingGroupId The rendering group id corresponding to its index
  63642. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63643. */
  63644. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63645. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63646. };
  63647. RenderTargetTexture.prototype.clone = function () {
  63648. var textureSize = this.getSize();
  63649. var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  63650. // Base texture
  63651. newTexture.hasAlpha = this.hasAlpha;
  63652. newTexture.level = this.level;
  63653. // RenderTarget Texture
  63654. newTexture.coordinatesMode = this.coordinatesMode;
  63655. if (this.renderList) {
  63656. newTexture.renderList = this.renderList.slice(0);
  63657. }
  63658. return newTexture;
  63659. };
  63660. RenderTargetTexture.prototype.serialize = function () {
  63661. if (!this.name) {
  63662. return null;
  63663. }
  63664. var serializationObject = _super.prototype.serialize.call(this);
  63665. serializationObject.renderTargetSize = this.getRenderSize();
  63666. serializationObject.renderList = [];
  63667. if (this.renderList) {
  63668. for (var index = 0; index < this.renderList.length; index++) {
  63669. serializationObject.renderList.push(this.renderList[index].id);
  63670. }
  63671. }
  63672. return serializationObject;
  63673. };
  63674. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63675. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63676. var objBuffer = this.getInternalTexture();
  63677. var scene = this.getScene();
  63678. if (objBuffer && scene) {
  63679. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63680. }
  63681. };
  63682. RenderTargetTexture.prototype.dispose = function () {
  63683. if (this._postProcessManager) {
  63684. this._postProcessManager.dispose();
  63685. this._postProcessManager = null;
  63686. }
  63687. this.clearPostProcesses(true);
  63688. if (this._resizeObserver) {
  63689. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63690. this._resizeObserver = null;
  63691. }
  63692. this.renderList = null;
  63693. // Remove from custom render targets
  63694. var scene = this.getScene();
  63695. if (!scene) {
  63696. return;
  63697. }
  63698. var index = scene.customRenderTargets.indexOf(this);
  63699. if (index >= 0) {
  63700. scene.customRenderTargets.splice(index, 1);
  63701. }
  63702. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63703. var camera = _a[_i];
  63704. index = camera.customRenderTargets.indexOf(this);
  63705. if (index >= 0) {
  63706. camera.customRenderTargets.splice(index, 1);
  63707. }
  63708. }
  63709. _super.prototype.dispose.call(this);
  63710. };
  63711. RenderTargetTexture.prototype._rebuild = function () {
  63712. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63713. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63714. }
  63715. if (this._postProcessManager) {
  63716. this._postProcessManager._rebuild();
  63717. }
  63718. };
  63719. /**
  63720. * Clear the info related to rendering groups preventing retention point in material dispose.
  63721. */
  63722. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63723. if (this._renderingManager) {
  63724. this._renderingManager.freeRenderingGroups();
  63725. }
  63726. };
  63727. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63728. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63729. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63730. return RenderTargetTexture;
  63731. }(BABYLON.Texture));
  63732. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63733. })(BABYLON || (BABYLON = {}));
  63734. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63735. var BABYLON;
  63736. (function (BABYLON) {
  63737. ;
  63738. var MultiRenderTarget = /** @class */ (function (_super) {
  63739. __extends(MultiRenderTarget, _super);
  63740. function MultiRenderTarget(name, size, count, scene, options) {
  63741. var _this = this;
  63742. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63743. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63744. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63745. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63746. _this._engine = scene.getEngine();
  63747. if (!_this.isSupported) {
  63748. _this.dispose();
  63749. return;
  63750. }
  63751. var types = [];
  63752. var samplingModes = [];
  63753. for (var i = 0; i < count; i++) {
  63754. if (options && options.types && options.types[i] !== undefined) {
  63755. types.push(options.types[i]);
  63756. }
  63757. else {
  63758. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63759. }
  63760. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63761. samplingModes.push(options.samplingModes[i]);
  63762. }
  63763. else {
  63764. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63765. }
  63766. }
  63767. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63768. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63769. _this._size = size;
  63770. _this._multiRenderTargetOptions = {
  63771. samplingModes: samplingModes,
  63772. generateMipMaps: generateMipMaps,
  63773. generateDepthBuffer: generateDepthBuffer,
  63774. generateStencilBuffer: generateStencilBuffer,
  63775. generateDepthTexture: generateDepthTexture,
  63776. types: types,
  63777. textureCount: count
  63778. };
  63779. _this._createInternalTextures();
  63780. _this._createTextures();
  63781. return _this;
  63782. }
  63783. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63784. get: function () {
  63785. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63786. },
  63787. enumerable: true,
  63788. configurable: true
  63789. });
  63790. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63791. get: function () {
  63792. return this._textures;
  63793. },
  63794. enumerable: true,
  63795. configurable: true
  63796. });
  63797. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63798. get: function () {
  63799. return this._textures[this._textures.length - 1];
  63800. },
  63801. enumerable: true,
  63802. configurable: true
  63803. });
  63804. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63805. set: function (wrap) {
  63806. if (this._textures) {
  63807. for (var i = 0; i < this._textures.length; i++) {
  63808. this._textures[i].wrapU = wrap;
  63809. }
  63810. }
  63811. },
  63812. enumerable: true,
  63813. configurable: true
  63814. });
  63815. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63816. set: function (wrap) {
  63817. if (this._textures) {
  63818. for (var i = 0; i < this._textures.length; i++) {
  63819. this._textures[i].wrapV = wrap;
  63820. }
  63821. }
  63822. },
  63823. enumerable: true,
  63824. configurable: true
  63825. });
  63826. MultiRenderTarget.prototype._rebuild = function () {
  63827. this.releaseInternalTextures();
  63828. this._createInternalTextures();
  63829. for (var i = 0; i < this._internalTextures.length; i++) {
  63830. var texture = this._textures[i];
  63831. texture._texture = this._internalTextures[i];
  63832. }
  63833. // Keeps references to frame buffer and stencil/depth buffer
  63834. this._texture = this._internalTextures[0];
  63835. };
  63836. MultiRenderTarget.prototype._createInternalTextures = function () {
  63837. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63838. };
  63839. MultiRenderTarget.prototype._createTextures = function () {
  63840. this._textures = [];
  63841. for (var i = 0; i < this._internalTextures.length; i++) {
  63842. var texture = new BABYLON.Texture(null, this.getScene());
  63843. texture._texture = this._internalTextures[i];
  63844. this._textures.push(texture);
  63845. }
  63846. // Keeps references to frame buffer and stencil/depth buffer
  63847. this._texture = this._internalTextures[0];
  63848. };
  63849. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63850. get: function () {
  63851. return this._samples;
  63852. },
  63853. set: function (value) {
  63854. if (this._samples === value) {
  63855. return;
  63856. }
  63857. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63858. },
  63859. enumerable: true,
  63860. configurable: true
  63861. });
  63862. MultiRenderTarget.prototype.resize = function (size) {
  63863. this.releaseInternalTextures();
  63864. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63865. this._createInternalTextures();
  63866. };
  63867. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63868. var _this = this;
  63869. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63870. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63871. });
  63872. };
  63873. MultiRenderTarget.prototype.dispose = function () {
  63874. this.releaseInternalTextures();
  63875. _super.prototype.dispose.call(this);
  63876. };
  63877. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63878. if (!this._internalTextures) {
  63879. return;
  63880. }
  63881. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63882. if (this._internalTextures[i] !== undefined) {
  63883. this._internalTextures[i].dispose();
  63884. this._internalTextures.splice(i, 1);
  63885. }
  63886. }
  63887. };
  63888. return MultiRenderTarget;
  63889. }(BABYLON.RenderTargetTexture));
  63890. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63891. })(BABYLON || (BABYLON = {}));
  63892. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63893. var BABYLON;
  63894. (function (BABYLON) {
  63895. var MirrorTexture = /** @class */ (function (_super) {
  63896. __extends(MirrorTexture, _super);
  63897. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63898. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63899. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63900. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63901. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63902. _this.scene = scene;
  63903. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63904. _this._transformMatrix = BABYLON.Matrix.Zero();
  63905. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63906. _this._adaptiveBlurKernel = 0;
  63907. _this._blurKernelX = 0;
  63908. _this._blurKernelY = 0;
  63909. _this._blurRatio = 1.0;
  63910. _this.ignoreCameraViewport = true;
  63911. _this._updateGammaSpace();
  63912. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63913. _this._updateGammaSpace;
  63914. });
  63915. _this.onBeforeRenderObservable.add(function () {
  63916. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  63917. _this._savedViewMatrix = scene.getViewMatrix();
  63918. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  63919. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  63920. scene.clipPlane = _this.mirrorPlane;
  63921. scene.getEngine().cullBackFaces = false;
  63922. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  63923. });
  63924. _this.onAfterRenderObservable.add(function () {
  63925. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  63926. scene.getEngine().cullBackFaces = true;
  63927. scene._mirroredCameraPosition = null;
  63928. delete scene.clipPlane;
  63929. });
  63930. return _this;
  63931. }
  63932. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  63933. get: function () {
  63934. return this._blurRatio;
  63935. },
  63936. set: function (value) {
  63937. if (this._blurRatio === value) {
  63938. return;
  63939. }
  63940. this._blurRatio = value;
  63941. this._preparePostProcesses();
  63942. },
  63943. enumerable: true,
  63944. configurable: true
  63945. });
  63946. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  63947. set: function (value) {
  63948. this._adaptiveBlurKernel = value;
  63949. this._autoComputeBlurKernel();
  63950. },
  63951. enumerable: true,
  63952. configurable: true
  63953. });
  63954. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  63955. set: function (value) {
  63956. this.blurKernelX = value;
  63957. this.blurKernelY = value;
  63958. },
  63959. enumerable: true,
  63960. configurable: true
  63961. });
  63962. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  63963. get: function () {
  63964. return this._blurKernelX;
  63965. },
  63966. set: function (value) {
  63967. if (this._blurKernelX === value) {
  63968. return;
  63969. }
  63970. this._blurKernelX = value;
  63971. this._preparePostProcesses();
  63972. },
  63973. enumerable: true,
  63974. configurable: true
  63975. });
  63976. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  63977. get: function () {
  63978. return this._blurKernelY;
  63979. },
  63980. set: function (value) {
  63981. if (this._blurKernelY === value) {
  63982. return;
  63983. }
  63984. this._blurKernelY = value;
  63985. this._preparePostProcesses();
  63986. },
  63987. enumerable: true,
  63988. configurable: true
  63989. });
  63990. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  63991. var engine = this.getScene().getEngine();
  63992. var dw = this.getRenderWidth() / engine.getRenderWidth();
  63993. var dh = this.getRenderHeight() / engine.getRenderHeight();
  63994. this.blurKernelX = this._adaptiveBlurKernel * dw;
  63995. this.blurKernelY = this._adaptiveBlurKernel * dh;
  63996. };
  63997. MirrorTexture.prototype._onRatioRescale = function () {
  63998. if (this._sizeRatio) {
  63999. this.resize(this._initialSizeParameter);
  64000. if (!this._adaptiveBlurKernel) {
  64001. this._preparePostProcesses();
  64002. }
  64003. }
  64004. if (this._adaptiveBlurKernel) {
  64005. this._autoComputeBlurKernel();
  64006. }
  64007. };
  64008. MirrorTexture.prototype._updateGammaSpace = function () {
  64009. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64010. };
  64011. MirrorTexture.prototype._preparePostProcesses = function () {
  64012. this.clearPostProcesses(true);
  64013. if (this._blurKernelX && this._blurKernelY) {
  64014. var engine = this.getScene().getEngine();
  64015. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64016. 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);
  64017. this._blurX.autoClear = false;
  64018. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64019. this._blurX.inputTexture = this._texture;
  64020. }
  64021. else {
  64022. this._blurX.alwaysForcePOT = true;
  64023. }
  64024. 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);
  64025. this._blurY.autoClear = false;
  64026. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64027. this.addPostProcess(this._blurX);
  64028. this.addPostProcess(this._blurY);
  64029. }
  64030. else {
  64031. if (this._blurY) {
  64032. this.removePostProcess(this._blurY);
  64033. this._blurY.dispose();
  64034. this._blurY = null;
  64035. }
  64036. if (this._blurX) {
  64037. this.removePostProcess(this._blurX);
  64038. this._blurX.dispose();
  64039. this._blurX = null;
  64040. }
  64041. }
  64042. };
  64043. MirrorTexture.prototype.clone = function () {
  64044. var scene = this.getScene();
  64045. if (!scene) {
  64046. return this;
  64047. }
  64048. var textureSize = this.getSize();
  64049. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64050. // Base texture
  64051. newTexture.hasAlpha = this.hasAlpha;
  64052. newTexture.level = this.level;
  64053. // Mirror Texture
  64054. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64055. if (this.renderList) {
  64056. newTexture.renderList = this.renderList.slice(0);
  64057. }
  64058. return newTexture;
  64059. };
  64060. MirrorTexture.prototype.serialize = function () {
  64061. if (!this.name) {
  64062. return null;
  64063. }
  64064. var serializationObject = _super.prototype.serialize.call(this);
  64065. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64066. return serializationObject;
  64067. };
  64068. MirrorTexture.prototype.dispose = function () {
  64069. _super.prototype.dispose.call(this);
  64070. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64071. };
  64072. return MirrorTexture;
  64073. }(BABYLON.RenderTargetTexture));
  64074. BABYLON.MirrorTexture = MirrorTexture;
  64075. })(BABYLON || (BABYLON = {}));
  64076. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64077. var BABYLON;
  64078. (function (BABYLON) {
  64079. /**
  64080. * Creates a refraction texture used by refraction channel of the standard material.
  64081. * @param name the texture name
  64082. * @param size size of the underlying texture
  64083. * @param scene root scene
  64084. */
  64085. var RefractionTexture = /** @class */ (function (_super) {
  64086. __extends(RefractionTexture, _super);
  64087. function RefractionTexture(name, size, scene, generateMipMaps) {
  64088. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64089. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64090. _this.depth = 2.0;
  64091. _this.onBeforeRenderObservable.add(function () {
  64092. scene.clipPlane = _this.refractionPlane;
  64093. });
  64094. _this.onAfterRenderObservable.add(function () {
  64095. delete scene.clipPlane;
  64096. });
  64097. return _this;
  64098. }
  64099. RefractionTexture.prototype.clone = function () {
  64100. var scene = this.getScene();
  64101. if (!scene) {
  64102. return this;
  64103. }
  64104. var textureSize = this.getSize();
  64105. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64106. // Base texture
  64107. newTexture.hasAlpha = this.hasAlpha;
  64108. newTexture.level = this.level;
  64109. // Refraction Texture
  64110. newTexture.refractionPlane = this.refractionPlane.clone();
  64111. if (this.renderList) {
  64112. newTexture.renderList = this.renderList.slice(0);
  64113. }
  64114. newTexture.depth = this.depth;
  64115. return newTexture;
  64116. };
  64117. RefractionTexture.prototype.serialize = function () {
  64118. if (!this.name) {
  64119. return null;
  64120. }
  64121. var serializationObject = _super.prototype.serialize.call(this);
  64122. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64123. serializationObject.depth = this.depth;
  64124. return serializationObject;
  64125. };
  64126. return RefractionTexture;
  64127. }(BABYLON.RenderTargetTexture));
  64128. BABYLON.RefractionTexture = RefractionTexture;
  64129. })(BABYLON || (BABYLON = {}));
  64130. //# sourceMappingURL=babylon.refractionTexture.js.map
  64131. var BABYLON;
  64132. (function (BABYLON) {
  64133. /**
  64134. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64135. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64136. */
  64137. var DynamicTexture = /** @class */ (function (_super) {
  64138. __extends(DynamicTexture, _super);
  64139. /**
  64140. * Creates a {BABYLON.DynamicTexture}
  64141. * @param name defines the name of the texture
  64142. * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height
  64143. * @param scene defines the scene where you want the texture
  64144. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64145. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64146. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64147. */
  64148. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64149. if (scene === void 0) { scene = null; }
  64150. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64151. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64152. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64153. _this.name = name;
  64154. _this._engine = _this.getScene().getEngine();
  64155. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64156. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64157. _this._generateMipMaps = generateMipMaps;
  64158. if (options.getContext) {
  64159. _this._canvas = options;
  64160. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64161. }
  64162. else {
  64163. _this._canvas = document.createElement("canvas");
  64164. if (options.width || options.width === 0) {
  64165. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64166. }
  64167. else {
  64168. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64169. }
  64170. }
  64171. var textureSize = _this.getSize();
  64172. _this._canvas.width = textureSize.width;
  64173. _this._canvas.height = textureSize.height;
  64174. _this._context = _this._canvas.getContext("2d");
  64175. return _this;
  64176. }
  64177. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64178. /**
  64179. * Gets the current state of canRescale
  64180. */
  64181. get: function () {
  64182. return true;
  64183. },
  64184. enumerable: true,
  64185. configurable: true
  64186. });
  64187. DynamicTexture.prototype._recreate = function (textureSize) {
  64188. this._canvas.width = textureSize.width;
  64189. this._canvas.height = textureSize.height;
  64190. this.releaseInternalTexture();
  64191. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64192. };
  64193. /**
  64194. * Scales the texture
  64195. * @param ratio the scale factor to apply to both width and height
  64196. */
  64197. DynamicTexture.prototype.scale = function (ratio) {
  64198. var textureSize = this.getSize();
  64199. textureSize.width *= ratio;
  64200. textureSize.height *= ratio;
  64201. this._recreate(textureSize);
  64202. };
  64203. /**
  64204. * Resizes the texture
  64205. * @param width the new width
  64206. * @param height the new height
  64207. */
  64208. DynamicTexture.prototype.scaleTo = function (width, height) {
  64209. var textureSize = this.getSize();
  64210. textureSize.width = width;
  64211. textureSize.height = height;
  64212. this._recreate(textureSize);
  64213. };
  64214. /**
  64215. * Gets the context of the canvas used by the texture
  64216. * @returns the canvas context of the dynamic texture
  64217. */
  64218. DynamicTexture.prototype.getContext = function () {
  64219. return this._context;
  64220. };
  64221. /**
  64222. * Clears the texture
  64223. */
  64224. DynamicTexture.prototype.clear = function () {
  64225. var size = this.getSize();
  64226. this._context.fillRect(0, 0, size.width, size.height);
  64227. };
  64228. /**
  64229. * Updates the texture
  64230. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64231. */
  64232. DynamicTexture.prototype.update = function (invertY) {
  64233. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  64234. };
  64235. /**
  64236. * Draws text onto the texture
  64237. * @param text defines the text to be drawn
  64238. * @param x defines the placement of the text from the left
  64239. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64240. * @param font defines the font to be used with font-style, font-size, font-name
  64241. * @param color defines the color used for the text
  64242. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64243. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64244. * @param update defines whether texture is immediately update (default is true)
  64245. */
  64246. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64247. if (update === void 0) { update = true; }
  64248. var size = this.getSize();
  64249. if (clearColor) {
  64250. this._context.fillStyle = clearColor;
  64251. this._context.fillRect(0, 0, size.width, size.height);
  64252. }
  64253. this._context.font = font;
  64254. if (x === null || x === undefined) {
  64255. var textSize = this._context.measureText(text);
  64256. x = (size.width - textSize.width) / 2;
  64257. }
  64258. if (y === null || y === undefined) {
  64259. var fontSize = parseInt((font.replace(/\D/g, '')));
  64260. ;
  64261. y = (size.height / 2) + (fontSize / 3.65);
  64262. }
  64263. this._context.fillStyle = color;
  64264. this._context.fillText(text, x, y);
  64265. if (update) {
  64266. this.update(invertY);
  64267. }
  64268. };
  64269. /**
  64270. * Clones the texture
  64271. * @returns the clone of the texture.
  64272. */
  64273. DynamicTexture.prototype.clone = function () {
  64274. var scene = this.getScene();
  64275. if (!scene) {
  64276. return this;
  64277. }
  64278. var textureSize = this.getSize();
  64279. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64280. // Base texture
  64281. newTexture.hasAlpha = this.hasAlpha;
  64282. newTexture.level = this.level;
  64283. // Dynamic Texture
  64284. newTexture.wrapU = this.wrapU;
  64285. newTexture.wrapV = this.wrapV;
  64286. return newTexture;
  64287. };
  64288. /** @hidden */
  64289. DynamicTexture.prototype._rebuild = function () {
  64290. this.update();
  64291. };
  64292. return DynamicTexture;
  64293. }(BABYLON.Texture));
  64294. BABYLON.DynamicTexture = DynamicTexture;
  64295. })(BABYLON || (BABYLON = {}));
  64296. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64297. var BABYLON;
  64298. (function (BABYLON) {
  64299. var VideoTexture = /** @class */ (function (_super) {
  64300. __extends(VideoTexture, _super);
  64301. /**
  64302. * Creates a video texture.
  64303. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64304. * @param {string | null} name optional name, will detect from video source, if not defined
  64305. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64306. * @param {BABYLON.Scene} scene is obviously the current scene.
  64307. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64308. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64309. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64310. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64311. */
  64312. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64313. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64314. if (invertY === void 0) { invertY = false; }
  64315. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64316. if (settings === void 0) { settings = {
  64317. autoPlay: true,
  64318. loop: true,
  64319. autoUpdateTexture: true,
  64320. }; }
  64321. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64322. _this._stillImageCaptured = false;
  64323. _this._createInternalTexture = function () {
  64324. if (_this._texture != null) {
  64325. return;
  64326. }
  64327. if (!_this._engine.needPOTTextures ||
  64328. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64329. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64330. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64331. }
  64332. else {
  64333. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64334. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64335. _this._generateMipMaps = false;
  64336. }
  64337. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64338. _this._texture.isReady = true;
  64339. _this._updateInternalTexture();
  64340. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64341. _this.onLoadObservable.notifyObservers(_this);
  64342. }
  64343. };
  64344. _this.reset = function () {
  64345. if (_this._texture == null) {
  64346. return;
  64347. }
  64348. _this._texture.dispose();
  64349. _this._texture = null;
  64350. };
  64351. _this._updateInternalTexture = function (e) {
  64352. if (_this._texture == null || !_this._texture.isReady) {
  64353. return;
  64354. }
  64355. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64356. return;
  64357. }
  64358. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64359. };
  64360. _this._engine = _this.getScene().getEngine();
  64361. _this._generateMipMaps = generateMipMaps;
  64362. _this._samplingMode = samplingMode;
  64363. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64364. _this.name = name || _this._getName(src);
  64365. _this.video = _this._getVideo(src);
  64366. if (settings.autoPlay !== undefined) {
  64367. _this.video.autoplay = settings.autoPlay;
  64368. }
  64369. if (settings.loop !== undefined) {
  64370. _this.video.loop = settings.loop;
  64371. }
  64372. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64373. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64374. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64375. _this.video.addEventListener("emptied", _this.reset);
  64376. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64377. _this._createInternalTexture();
  64378. }
  64379. return _this;
  64380. }
  64381. VideoTexture.prototype._getName = function (src) {
  64382. if (src instanceof HTMLVideoElement) {
  64383. return src.currentSrc;
  64384. }
  64385. if (typeof src === "object") {
  64386. return src.toString();
  64387. }
  64388. return src;
  64389. };
  64390. ;
  64391. VideoTexture.prototype._getVideo = function (src) {
  64392. if (src instanceof HTMLVideoElement) {
  64393. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64394. return src;
  64395. }
  64396. var video = document.createElement("video");
  64397. if (typeof src === "string") {
  64398. BABYLON.Tools.SetCorsBehavior(src, video);
  64399. video.src = src;
  64400. }
  64401. else {
  64402. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64403. src.forEach(function (url) {
  64404. var source = document.createElement("source");
  64405. source.src = url;
  64406. video.appendChild(source);
  64407. });
  64408. }
  64409. return video;
  64410. };
  64411. ;
  64412. /**
  64413. * Internal method to initiate `update`.
  64414. */
  64415. VideoTexture.prototype._rebuild = function () {
  64416. this.update();
  64417. };
  64418. /**
  64419. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64420. */
  64421. VideoTexture.prototype.update = function () {
  64422. if (!this.autoUpdateTexture) {
  64423. // Expecting user to call `updateTexture` manually
  64424. return;
  64425. }
  64426. this.updateTexture(true);
  64427. };
  64428. /**
  64429. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64430. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64431. */
  64432. VideoTexture.prototype.updateTexture = function (isVisible) {
  64433. if (!isVisible) {
  64434. return;
  64435. }
  64436. if (this.video.paused && this._stillImageCaptured) {
  64437. return;
  64438. }
  64439. this._stillImageCaptured = true;
  64440. this._updateInternalTexture();
  64441. };
  64442. /**
  64443. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64444. * @param url New url.
  64445. */
  64446. VideoTexture.prototype.updateURL = function (url) {
  64447. this.video.src = url;
  64448. };
  64449. VideoTexture.prototype.dispose = function () {
  64450. _super.prototype.dispose.call(this);
  64451. this.video.removeEventListener("canplay", this._createInternalTexture);
  64452. this.video.removeEventListener("paused", this._updateInternalTexture);
  64453. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64454. this.video.removeEventListener("emptied", this.reset);
  64455. this.video.pause();
  64456. };
  64457. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64458. var video = document.createElement("video");
  64459. var constraintsDeviceId;
  64460. if (constraints && constraints.deviceId) {
  64461. constraintsDeviceId = {
  64462. exact: constraints.deviceId,
  64463. };
  64464. }
  64465. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64466. if (navigator.mediaDevices) {
  64467. navigator.mediaDevices.getUserMedia({ video: constraints })
  64468. .then(function (stream) {
  64469. if (video.mozSrcObject !== undefined) {
  64470. // hack for Firefox < 19
  64471. video.mozSrcObject = stream;
  64472. }
  64473. else {
  64474. video.srcObject = stream;
  64475. }
  64476. var onPlaying = function () {
  64477. if (onReady) {
  64478. onReady(new VideoTexture("video", video, scene, true, true));
  64479. }
  64480. video.removeEventListener("playing", onPlaying);
  64481. };
  64482. video.addEventListener("playing", onPlaying);
  64483. video.play();
  64484. })
  64485. .catch(function (err) {
  64486. BABYLON.Tools.Error(err.name);
  64487. });
  64488. }
  64489. else {
  64490. navigator.getUserMedia =
  64491. navigator.getUserMedia ||
  64492. navigator.webkitGetUserMedia ||
  64493. navigator.mozGetUserMedia ||
  64494. navigator.msGetUserMedia;
  64495. if (navigator.getUserMedia) {
  64496. navigator.getUserMedia({
  64497. video: {
  64498. deviceId: constraintsDeviceId,
  64499. width: {
  64500. min: (constraints && constraints.minWidth) || 256,
  64501. max: (constraints && constraints.maxWidth) || 640,
  64502. },
  64503. height: {
  64504. min: (constraints && constraints.minHeight) || 256,
  64505. max: (constraints && constraints.maxHeight) || 480,
  64506. },
  64507. },
  64508. }, function (stream) {
  64509. if (video.mozSrcObject !== undefined) {
  64510. // hack for Firefox < 19
  64511. video.mozSrcObject = stream;
  64512. }
  64513. else {
  64514. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64515. }
  64516. video.play();
  64517. if (onReady) {
  64518. onReady(new VideoTexture("video", video, scene, true, true));
  64519. }
  64520. }, function (e) {
  64521. BABYLON.Tools.Error(e.name);
  64522. });
  64523. }
  64524. }
  64525. };
  64526. return VideoTexture;
  64527. }(BABYLON.Texture));
  64528. BABYLON.VideoTexture = VideoTexture;
  64529. })(BABYLON || (BABYLON = {}));
  64530. //# sourceMappingURL=babylon.videoTexture.js.map
  64531. var BABYLON;
  64532. (function (BABYLON) {
  64533. var RawTexture = /** @class */ (function (_super) {
  64534. __extends(RawTexture, _super);
  64535. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64536. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64537. if (invertY === void 0) { invertY = false; }
  64538. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64539. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64540. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64541. _this.format = format;
  64542. _this._engine = scene.getEngine();
  64543. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64544. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64545. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64546. return _this;
  64547. }
  64548. RawTexture.prototype.update = function (data) {
  64549. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64550. };
  64551. // Statics
  64552. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64553. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64554. if (invertY === void 0) { invertY = false; }
  64555. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64556. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64557. };
  64558. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64559. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64560. if (invertY === void 0) { invertY = false; }
  64561. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64562. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64563. };
  64564. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64565. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64566. if (invertY === void 0) { invertY = false; }
  64567. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64568. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64569. };
  64570. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64571. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64572. if (invertY === void 0) { invertY = false; }
  64573. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64574. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64575. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64576. };
  64577. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64578. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64579. if (invertY === void 0) { invertY = false; }
  64580. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64581. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64582. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64583. };
  64584. return RawTexture;
  64585. }(BABYLON.Texture));
  64586. BABYLON.RawTexture = RawTexture;
  64587. })(BABYLON || (BABYLON = {}));
  64588. //# sourceMappingURL=babylon.rawTexture.js.map
  64589. var BABYLON;
  64590. (function (BABYLON) {
  64591. /**
  64592. * Class used to store 3D textures containing user data
  64593. */
  64594. var RawTexture3D = /** @class */ (function (_super) {
  64595. __extends(RawTexture3D, _super);
  64596. /**
  64597. * Create a new RawTexture3D
  64598. * @param data defines the data of the texture
  64599. * @param width defines the width of the texture
  64600. * @param height defines the height of the texture
  64601. * @param depth defines the depth of the texture
  64602. * @param format defines the texture format to use
  64603. * @param scene defines the hosting scene
  64604. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64605. * @param invertY defines if texture must be stored with Y axis inverted
  64606. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64607. */
  64608. function RawTexture3D(data, width, height, depth,
  64609. /** Gets or sets the texture format to use*/
  64610. format, scene, generateMipMaps, invertY, samplingMode) {
  64611. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64612. if (invertY === void 0) { invertY = false; }
  64613. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64614. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64615. _this.format = format;
  64616. _this._engine = scene.getEngine();
  64617. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64618. _this.is3D = true;
  64619. return _this;
  64620. }
  64621. /**
  64622. * Update the texture with new data
  64623. * @param data defines the data to store in the texture
  64624. */
  64625. RawTexture3D.prototype.update = function (data) {
  64626. if (!this._texture) {
  64627. return;
  64628. }
  64629. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64630. };
  64631. return RawTexture3D;
  64632. }(BABYLON.Texture));
  64633. BABYLON.RawTexture3D = RawTexture3D;
  64634. })(BABYLON || (BABYLON = {}));
  64635. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64636. var BABYLON;
  64637. (function (BABYLON) {
  64638. /**
  64639. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64640. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64641. */
  64642. var PostProcess = /** @class */ (function () {
  64643. /**
  64644. * Creates a new instance PostProcess
  64645. * @param name The name of the PostProcess.
  64646. * @param fragmentUrl The url of the fragment shader to be used.
  64647. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64648. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64649. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64650. * @param camera The camera to apply the render pass to.
  64651. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64652. * @param engine The engine which the post process will be applied. (default: current engine)
  64653. * @param reusable If the post process can be reused on the same frame. (default: false)
  64654. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64655. * @param textureType Type of textures used when performing the post process. (default: 0)
  64656. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64657. * @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
  64658. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64659. */
  64660. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64661. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64662. if (defines === void 0) { defines = null; }
  64663. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64664. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64665. if (blockCompilation === void 0) { blockCompilation = false; }
  64666. this.name = name;
  64667. /**
  64668. * Width of the texture to apply the post process on
  64669. */
  64670. this.width = -1;
  64671. /**
  64672. * Height of the texture to apply the post process on
  64673. */
  64674. this.height = -1;
  64675. /**
  64676. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64677. */
  64678. this._outputTexture = null;
  64679. /**
  64680. * If the buffer needs to be cleared before applying the post process. (default: true)
  64681. * Should be set to false if shader will overwrite all previous pixels.
  64682. */
  64683. this.autoClear = true;
  64684. /**
  64685. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64686. */
  64687. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64688. /**
  64689. * Animations to be used for the post processing
  64690. */
  64691. this.animations = new Array();
  64692. /**
  64693. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64694. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64695. */
  64696. this.enablePixelPerfectMode = false;
  64697. /**
  64698. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64699. */
  64700. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64701. /**
  64702. * Force textures to be a power of two (default: false)
  64703. */
  64704. this.alwaysForcePOT = false;
  64705. /**
  64706. * Number of sample textures (default: 1)
  64707. */
  64708. this.samples = 1;
  64709. /**
  64710. * Modify the scale of the post process to be the same as the viewport (default: false)
  64711. */
  64712. this.adaptScaleToCurrentViewport = false;
  64713. this._reusable = false;
  64714. /**
  64715. * Smart array of input and output textures for the post process.
  64716. */
  64717. this._textures = new BABYLON.SmartArray(2);
  64718. /**
  64719. * The index in _textures that corresponds to the output texture.
  64720. */
  64721. this._currentRenderTextureInd = 0;
  64722. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64723. this._texelSize = BABYLON.Vector2.Zero();
  64724. // Events
  64725. /**
  64726. * An event triggered when the postprocess is activated.
  64727. */
  64728. this.onActivateObservable = new BABYLON.Observable();
  64729. /**
  64730. * An event triggered when the postprocess changes its size.
  64731. */
  64732. this.onSizeChangedObservable = new BABYLON.Observable();
  64733. /**
  64734. * An event triggered when the postprocess applies its effect.
  64735. */
  64736. this.onApplyObservable = new BABYLON.Observable();
  64737. /**
  64738. * An event triggered before rendering the postprocess
  64739. */
  64740. this.onBeforeRenderObservable = new BABYLON.Observable();
  64741. /**
  64742. * An event triggered after rendering the postprocess
  64743. */
  64744. this.onAfterRenderObservable = new BABYLON.Observable();
  64745. if (camera != null) {
  64746. this._camera = camera;
  64747. this._scene = camera.getScene();
  64748. camera.attachPostProcess(this);
  64749. this._engine = this._scene.getEngine();
  64750. this._scene.postProcesses.push(this);
  64751. }
  64752. else if (engine) {
  64753. this._engine = engine;
  64754. this._engine.postProcesses.push(this);
  64755. }
  64756. this._options = options;
  64757. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64758. this._reusable = reusable || false;
  64759. this._textureType = textureType;
  64760. this._samplers = samplers || [];
  64761. this._samplers.push("textureSampler");
  64762. this._fragmentUrl = fragmentUrl;
  64763. this._vertexUrl = vertexUrl;
  64764. this._parameters = parameters || [];
  64765. this._parameters.push("scale");
  64766. this._indexParameters = indexParameters;
  64767. if (!blockCompilation) {
  64768. this.updateEffect(defines);
  64769. }
  64770. }
  64771. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64772. /**
  64773. * A function that is added to the onActivateObservable
  64774. */
  64775. set: function (callback) {
  64776. if (this._onActivateObserver) {
  64777. this.onActivateObservable.remove(this._onActivateObserver);
  64778. }
  64779. if (callback) {
  64780. this._onActivateObserver = this.onActivateObservable.add(callback);
  64781. }
  64782. },
  64783. enumerable: true,
  64784. configurable: true
  64785. });
  64786. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64787. /**
  64788. * A function that is added to the onSizeChangedObservable
  64789. */
  64790. set: function (callback) {
  64791. if (this._onSizeChangedObserver) {
  64792. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64793. }
  64794. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64795. },
  64796. enumerable: true,
  64797. configurable: true
  64798. });
  64799. Object.defineProperty(PostProcess.prototype, "onApply", {
  64800. /**
  64801. * A function that is added to the onApplyObservable
  64802. */
  64803. set: function (callback) {
  64804. if (this._onApplyObserver) {
  64805. this.onApplyObservable.remove(this._onApplyObserver);
  64806. }
  64807. this._onApplyObserver = this.onApplyObservable.add(callback);
  64808. },
  64809. enumerable: true,
  64810. configurable: true
  64811. });
  64812. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64813. /**
  64814. * A function that is added to the onBeforeRenderObservable
  64815. */
  64816. set: function (callback) {
  64817. if (this._onBeforeRenderObserver) {
  64818. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64819. }
  64820. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64821. },
  64822. enumerable: true,
  64823. configurable: true
  64824. });
  64825. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  64826. /**
  64827. * A function that is added to the onAfterRenderObservable
  64828. */
  64829. set: function (callback) {
  64830. if (this._onAfterRenderObserver) {
  64831. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64832. }
  64833. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64834. },
  64835. enumerable: true,
  64836. configurable: true
  64837. });
  64838. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  64839. /**
  64840. * 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
  64841. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  64842. */
  64843. get: function () {
  64844. return this._textures.data[this._currentRenderTextureInd];
  64845. },
  64846. set: function (value) {
  64847. this._forcedOutputTexture = value;
  64848. },
  64849. enumerable: true,
  64850. configurable: true
  64851. });
  64852. /**
  64853. * Gets the camera which post process is applied to.
  64854. * @returns The camera the post process is applied to.
  64855. */
  64856. PostProcess.prototype.getCamera = function () {
  64857. return this._camera;
  64858. };
  64859. Object.defineProperty(PostProcess.prototype, "texelSize", {
  64860. /**
  64861. * Gets the texel size of the postprocess.
  64862. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  64863. */
  64864. get: function () {
  64865. if (this._shareOutputWithPostProcess) {
  64866. return this._shareOutputWithPostProcess.texelSize;
  64867. }
  64868. if (this._forcedOutputTexture) {
  64869. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  64870. }
  64871. return this._texelSize;
  64872. },
  64873. enumerable: true,
  64874. configurable: true
  64875. });
  64876. /**
  64877. * Gets the engine which this post process belongs to.
  64878. * @returns The engine the post process was enabled with.
  64879. */
  64880. PostProcess.prototype.getEngine = function () {
  64881. return this._engine;
  64882. };
  64883. /**
  64884. * The effect that is created when initializing the post process.
  64885. * @returns The created effect corrisponding the the postprocess.
  64886. */
  64887. PostProcess.prototype.getEffect = function () {
  64888. return this._effect;
  64889. };
  64890. /**
  64891. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  64892. * @param postProcess The post process to share the output with.
  64893. * @returns This post process.
  64894. */
  64895. PostProcess.prototype.shareOutputWith = function (postProcess) {
  64896. this._disposeTextures();
  64897. this._shareOutputWithPostProcess = postProcess;
  64898. return this;
  64899. };
  64900. /**
  64901. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  64902. * This should be called if the post process that shares output with this post process is disabled/disposed.
  64903. */
  64904. PostProcess.prototype.useOwnOutput = function () {
  64905. if (this._textures.length == 0) {
  64906. this._textures = new BABYLON.SmartArray(2);
  64907. }
  64908. this._shareOutputWithPostProcess = null;
  64909. };
  64910. /**
  64911. * Updates the effect with the current post process compile time values and recompiles the shader.
  64912. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  64913. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  64914. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  64915. * @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
  64916. * @param onCompiled Called when the shader has been compiled.
  64917. * @param onError Called if there is an error when compiling a shader.
  64918. */
  64919. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  64920. if (defines === void 0) { defines = null; }
  64921. if (uniforms === void 0) { uniforms = null; }
  64922. if (samplers === void 0) { samplers = null; }
  64923. 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);
  64924. };
  64925. /**
  64926. * The post process is reusable if it can be used multiple times within one frame.
  64927. * @returns If the post process is reusable
  64928. */
  64929. PostProcess.prototype.isReusable = function () {
  64930. return this._reusable;
  64931. };
  64932. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  64933. PostProcess.prototype.markTextureDirty = function () {
  64934. this.width = -1;
  64935. };
  64936. /**
  64937. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  64938. * 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.
  64939. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  64940. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  64941. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  64942. * @returns The target texture that was bound to be written to.
  64943. */
  64944. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  64945. var _this = this;
  64946. if (sourceTexture === void 0) { sourceTexture = null; }
  64947. camera = camera || this._camera;
  64948. var scene = camera.getScene();
  64949. var engine = scene.getEngine();
  64950. var maxSize = engine.getCaps().maxTextureSize;
  64951. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  64952. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  64953. // 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
  64954. var webVRCamera = camera.parent;
  64955. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  64956. requiredWidth /= 2;
  64957. }
  64958. var desiredWidth = (this._options.width || requiredWidth);
  64959. var desiredHeight = this._options.height || requiredHeight;
  64960. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  64961. if (this.adaptScaleToCurrentViewport) {
  64962. var currentViewport = engine.currentViewport;
  64963. if (currentViewport) {
  64964. desiredWidth *= currentViewport.width;
  64965. desiredHeight *= currentViewport.height;
  64966. }
  64967. }
  64968. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  64969. if (!this._options.width) {
  64970. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  64971. }
  64972. if (!this._options.height) {
  64973. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  64974. }
  64975. }
  64976. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  64977. if (this._textures.length > 0) {
  64978. for (var i = 0; i < this._textures.length; i++) {
  64979. this._engine._releaseTexture(this._textures.data[i]);
  64980. }
  64981. this._textures.reset();
  64982. }
  64983. this.width = desiredWidth;
  64984. this.height = desiredHeight;
  64985. var textureSize = { width: this.width, height: this.height };
  64986. var textureOptions = {
  64987. generateMipMaps: false,
  64988. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  64989. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  64990. samplingMode: this.renderTargetSamplingMode,
  64991. type: this._textureType
  64992. };
  64993. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64994. if (this._reusable) {
  64995. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64996. }
  64997. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  64998. this.onSizeChangedObservable.notifyObservers(this);
  64999. }
  65000. this._textures.forEach(function (texture) {
  65001. if (texture.samples !== _this.samples) {
  65002. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65003. }
  65004. });
  65005. }
  65006. var target;
  65007. if (this._shareOutputWithPostProcess) {
  65008. target = this._shareOutputWithPostProcess.inputTexture;
  65009. }
  65010. else if (this._forcedOutputTexture) {
  65011. target = this._forcedOutputTexture;
  65012. this.width = this._forcedOutputTexture.width;
  65013. this.height = this._forcedOutputTexture.height;
  65014. }
  65015. else {
  65016. target = this.inputTexture;
  65017. }
  65018. // Bind the input of this post process to be used as the output of the previous post process.
  65019. if (this.enablePixelPerfectMode) {
  65020. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65021. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  65022. }
  65023. else {
  65024. this._scaleRatio.copyFromFloats(1, 1);
  65025. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  65026. }
  65027. this.onActivateObservable.notifyObservers(camera);
  65028. // Clear
  65029. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65030. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65031. }
  65032. if (this._reusable) {
  65033. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65034. }
  65035. return target;
  65036. };
  65037. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65038. /**
  65039. * If the post process is supported.
  65040. */
  65041. get: function () {
  65042. return this._effect.isSupported;
  65043. },
  65044. enumerable: true,
  65045. configurable: true
  65046. });
  65047. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65048. /**
  65049. * The aspect ratio of the output texture.
  65050. */
  65051. get: function () {
  65052. if (this._shareOutputWithPostProcess) {
  65053. return this._shareOutputWithPostProcess.aspectRatio;
  65054. }
  65055. if (this._forcedOutputTexture) {
  65056. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65057. }
  65058. return this.width / this.height;
  65059. },
  65060. enumerable: true,
  65061. configurable: true
  65062. });
  65063. /**
  65064. * Get a value indicating if the post-process is ready to be used
  65065. * @returns true if the post-process is ready (shader is compiled)
  65066. */
  65067. PostProcess.prototype.isReady = function () {
  65068. return this._effect && this._effect.isReady();
  65069. };
  65070. /**
  65071. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65072. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65073. */
  65074. PostProcess.prototype.apply = function () {
  65075. // Check
  65076. if (!this._effect || !this._effect.isReady())
  65077. return null;
  65078. // States
  65079. this._engine.enableEffect(this._effect);
  65080. this._engine.setState(false);
  65081. this._engine.setDepthBuffer(false);
  65082. this._engine.setDepthWrite(false);
  65083. // Alpha
  65084. this._engine.setAlphaMode(this.alphaMode);
  65085. if (this.alphaConstants) {
  65086. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65087. }
  65088. // Bind the output texture of the preivous post process as the input to this post process.
  65089. var source;
  65090. if (this._shareOutputWithPostProcess) {
  65091. source = this._shareOutputWithPostProcess.inputTexture;
  65092. }
  65093. else if (this._forcedOutputTexture) {
  65094. source = this._forcedOutputTexture;
  65095. }
  65096. else {
  65097. source = this.inputTexture;
  65098. }
  65099. this._effect._bindTexture("textureSampler", source);
  65100. // Parameters
  65101. this._effect.setVector2("scale", this._scaleRatio);
  65102. this.onApplyObservable.notifyObservers(this._effect);
  65103. return this._effect;
  65104. };
  65105. PostProcess.prototype._disposeTextures = function () {
  65106. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65107. return;
  65108. }
  65109. if (this._textures.length > 0) {
  65110. for (var i = 0; i < this._textures.length; i++) {
  65111. this._engine._releaseTexture(this._textures.data[i]);
  65112. }
  65113. }
  65114. this._textures.dispose();
  65115. };
  65116. /**
  65117. * Disposes the post process.
  65118. * @param camera The camera to dispose the post process on.
  65119. */
  65120. PostProcess.prototype.dispose = function (camera) {
  65121. camera = camera || this._camera;
  65122. this._disposeTextures();
  65123. if (this._scene) {
  65124. var index_1 = this._scene.postProcesses.indexOf(this);
  65125. if (index_1 !== -1) {
  65126. this._scene.postProcesses.splice(index_1, 1);
  65127. }
  65128. }
  65129. else {
  65130. var index_2 = this._engine.postProcesses.indexOf(this);
  65131. if (index_2 !== -1) {
  65132. this._engine.postProcesses.splice(index_2, 1);
  65133. }
  65134. }
  65135. if (!camera) {
  65136. return;
  65137. }
  65138. camera.detachPostProcess(this);
  65139. var index = camera._postProcesses.indexOf(this);
  65140. if (index === 0 && camera._postProcesses.length > 0) {
  65141. var firstPostProcess = this._camera._getFirstPostProcess();
  65142. if (firstPostProcess) {
  65143. firstPostProcess.markTextureDirty();
  65144. }
  65145. }
  65146. this.onActivateObservable.clear();
  65147. this.onAfterRenderObservable.clear();
  65148. this.onApplyObservable.clear();
  65149. this.onBeforeRenderObservable.clear();
  65150. this.onSizeChangedObservable.clear();
  65151. };
  65152. return PostProcess;
  65153. }());
  65154. BABYLON.PostProcess = PostProcess;
  65155. })(BABYLON || (BABYLON = {}));
  65156. //# sourceMappingURL=babylon.postProcess.js.map
  65157. var BABYLON;
  65158. (function (BABYLON) {
  65159. var PassPostProcess = /** @class */ (function (_super) {
  65160. __extends(PassPostProcess, _super);
  65161. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65162. if (camera === void 0) { camera = null; }
  65163. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65164. if (blockCompilation === void 0) { blockCompilation = false; }
  65165. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65166. }
  65167. return PassPostProcess;
  65168. }(BABYLON.PostProcess));
  65169. BABYLON.PassPostProcess = PassPostProcess;
  65170. })(BABYLON || (BABYLON = {}));
  65171. //# sourceMappingURL=babylon.passPostProcess.js.map
  65172. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65173. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65174. s = arguments[i];
  65175. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65176. t[p] = s[p];
  65177. }
  65178. return t;
  65179. };
  65180. var BABYLON;
  65181. (function (BABYLON) {
  65182. /**
  65183. * Default implementation IShadowGenerator.
  65184. * This is the main object responsible of generating shadows in the framework.
  65185. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65186. */
  65187. var ShadowGenerator = /** @class */ (function () {
  65188. /**
  65189. * Creates a ShadowGenerator object.
  65190. * A ShadowGenerator is the required tool to use the shadows.
  65191. * Each light casting shadows needs to use its own ShadowGenerator.
  65192. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65193. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65194. * @param light The light object generating the shadows.
  65195. * @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.
  65196. */
  65197. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65198. this._bias = 0.00005;
  65199. this._normalBias = 0;
  65200. this._blurBoxOffset = 1;
  65201. this._blurScale = 2;
  65202. this._blurKernel = 1;
  65203. this._useKernelBlur = false;
  65204. this._filter = ShadowGenerator.FILTER_NONE;
  65205. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65206. this._contactHardeningLightSizeUVRatio = 0.1;
  65207. this._darkness = 0;
  65208. this._transparencyShadow = false;
  65209. /**
  65210. * Controls the extent to which the shadows fade out at the edge of the frustum
  65211. * Used only by directionals and spots
  65212. */
  65213. this.frustumEdgeFalloff = 0;
  65214. /**
  65215. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65216. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65217. * It might on the other hand introduce peter panning.
  65218. */
  65219. this.forceBackFacesOnly = false;
  65220. this._lightDirection = BABYLON.Vector3.Zero();
  65221. this._viewMatrix = BABYLON.Matrix.Zero();
  65222. this._projectionMatrix = BABYLON.Matrix.Zero();
  65223. this._transformMatrix = BABYLON.Matrix.Zero();
  65224. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65225. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65226. this._currentFaceIndex = 0;
  65227. this._currentFaceIndexCache = 0;
  65228. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65229. this._mapSize = mapSize;
  65230. this._light = light;
  65231. this._scene = light.getScene();
  65232. light._shadowGenerator = this;
  65233. // Texture type fallback from float to int if not supported.
  65234. var caps = this._scene.getEngine().getCaps();
  65235. if (!useFullFloatFirst) {
  65236. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65237. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65238. }
  65239. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65240. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65241. }
  65242. else {
  65243. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65244. }
  65245. }
  65246. else {
  65247. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65248. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65249. }
  65250. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65251. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65252. }
  65253. else {
  65254. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65255. }
  65256. }
  65257. this._initializeGenerator();
  65258. this._applyFilterValues();
  65259. }
  65260. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65261. /**
  65262. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65263. */
  65264. get: function () {
  65265. return this._bias;
  65266. },
  65267. /**
  65268. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65269. */
  65270. set: function (bias) {
  65271. this._bias = bias;
  65272. },
  65273. enumerable: true,
  65274. configurable: true
  65275. });
  65276. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65277. /**
  65278. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65279. */
  65280. get: function () {
  65281. return this._normalBias;
  65282. },
  65283. /**
  65284. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65285. */
  65286. set: function (normalBias) {
  65287. this._normalBias = normalBias;
  65288. },
  65289. enumerable: true,
  65290. configurable: true
  65291. });
  65292. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65293. /**
  65294. * Gets the blur box offset: offset applied during the blur pass.
  65295. * Only usefull if useKernelBlur = false
  65296. */
  65297. get: function () {
  65298. return this._blurBoxOffset;
  65299. },
  65300. /**
  65301. * Sets the blur box offset: offset applied during the blur pass.
  65302. * Only usefull if useKernelBlur = false
  65303. */
  65304. set: function (value) {
  65305. if (this._blurBoxOffset === value) {
  65306. return;
  65307. }
  65308. this._blurBoxOffset = value;
  65309. this._disposeBlurPostProcesses();
  65310. },
  65311. enumerable: true,
  65312. configurable: true
  65313. });
  65314. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65315. /**
  65316. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65317. * 2 means half of the size.
  65318. */
  65319. get: function () {
  65320. return this._blurScale;
  65321. },
  65322. /**
  65323. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65324. * 2 means half of the size.
  65325. */
  65326. set: function (value) {
  65327. if (this._blurScale === value) {
  65328. return;
  65329. }
  65330. this._blurScale = value;
  65331. this._disposeBlurPostProcesses();
  65332. },
  65333. enumerable: true,
  65334. configurable: true
  65335. });
  65336. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65337. /**
  65338. * Gets the blur kernel: kernel size of the blur pass.
  65339. * Only usefull if useKernelBlur = true
  65340. */
  65341. get: function () {
  65342. return this._blurKernel;
  65343. },
  65344. /**
  65345. * Sets the blur kernel: kernel size of the blur pass.
  65346. * Only usefull if useKernelBlur = true
  65347. */
  65348. set: function (value) {
  65349. if (this._blurKernel === value) {
  65350. return;
  65351. }
  65352. this._blurKernel = value;
  65353. this._disposeBlurPostProcesses();
  65354. },
  65355. enumerable: true,
  65356. configurable: true
  65357. });
  65358. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65359. /**
  65360. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65361. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65362. */
  65363. get: function () {
  65364. return this._useKernelBlur;
  65365. },
  65366. /**
  65367. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65368. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65369. */
  65370. set: function (value) {
  65371. if (this._useKernelBlur === value) {
  65372. return;
  65373. }
  65374. this._useKernelBlur = value;
  65375. this._disposeBlurPostProcesses();
  65376. },
  65377. enumerable: true,
  65378. configurable: true
  65379. });
  65380. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65381. /**
  65382. * Gets the depth scale used in ESM mode.
  65383. */
  65384. get: function () {
  65385. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65386. },
  65387. /**
  65388. * Sets the depth scale used in ESM mode.
  65389. * This can override the scale stored on the light.
  65390. */
  65391. set: function (value) {
  65392. this._depthScale = value;
  65393. },
  65394. enumerable: true,
  65395. configurable: true
  65396. });
  65397. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65398. /**
  65399. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65400. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65401. */
  65402. get: function () {
  65403. return this._filter;
  65404. },
  65405. /**
  65406. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65407. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65408. */
  65409. set: function (value) {
  65410. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65411. if (this._light.needCube()) {
  65412. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65413. this.useExponentialShadowMap = true;
  65414. return;
  65415. }
  65416. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65417. this.useCloseExponentialShadowMap = true;
  65418. return;
  65419. }
  65420. // PCF on cubemap would also be expensive
  65421. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65422. this.usePoissonSampling = true;
  65423. return;
  65424. }
  65425. }
  65426. // Weblg1 fallback for PCF.
  65427. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65428. if (this._scene.getEngine().webGLVersion === 1) {
  65429. this.usePoissonSampling = true;
  65430. return;
  65431. }
  65432. }
  65433. if (this._filter === value) {
  65434. return;
  65435. }
  65436. this._filter = value;
  65437. this._disposeBlurPostProcesses();
  65438. this._applyFilterValues();
  65439. this._light._markMeshesAsLightDirty();
  65440. },
  65441. enumerable: true,
  65442. configurable: true
  65443. });
  65444. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65445. /**
  65446. * Gets if the current filter is set to Poisson Sampling.
  65447. */
  65448. get: function () {
  65449. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65450. },
  65451. /**
  65452. * Sets the current filter to Poisson Sampling.
  65453. */
  65454. set: function (value) {
  65455. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65456. return;
  65457. }
  65458. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65459. },
  65460. enumerable: true,
  65461. configurable: true
  65462. });
  65463. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65464. /**
  65465. * Gets if the current filter is set to VSM.
  65466. * DEPRECATED. Should use useExponentialShadowMap instead.
  65467. */
  65468. get: function () {
  65469. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65470. return this.useExponentialShadowMap;
  65471. },
  65472. /**
  65473. * Sets the current filter is to VSM.
  65474. * DEPRECATED. Should use useExponentialShadowMap instead.
  65475. */
  65476. set: function (value) {
  65477. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65478. this.useExponentialShadowMap = value;
  65479. },
  65480. enumerable: true,
  65481. configurable: true
  65482. });
  65483. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65484. /**
  65485. * Gets if the current filter is set to blurred VSM.
  65486. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65487. */
  65488. get: function () {
  65489. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65490. return this.useBlurExponentialShadowMap;
  65491. },
  65492. /**
  65493. * Sets the current filter is to blurred VSM.
  65494. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65495. */
  65496. set: function (value) {
  65497. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65498. this.useBlurExponentialShadowMap = value;
  65499. },
  65500. enumerable: true,
  65501. configurable: true
  65502. });
  65503. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65504. /**
  65505. * Gets if the current filter is set to ESM.
  65506. */
  65507. get: function () {
  65508. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65509. },
  65510. /**
  65511. * Sets the current filter is to ESM.
  65512. */
  65513. set: function (value) {
  65514. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65515. return;
  65516. }
  65517. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65518. },
  65519. enumerable: true,
  65520. configurable: true
  65521. });
  65522. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65523. /**
  65524. * Gets if the current filter is set to filtered ESM.
  65525. */
  65526. get: function () {
  65527. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65528. },
  65529. /**
  65530. * Gets if the current filter is set to filtered ESM.
  65531. */
  65532. set: function (value) {
  65533. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65534. return;
  65535. }
  65536. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65537. },
  65538. enumerable: true,
  65539. configurable: true
  65540. });
  65541. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65542. /**
  65543. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65544. * exponential to prevent steep falloff artifacts).
  65545. */
  65546. get: function () {
  65547. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65548. },
  65549. /**
  65550. * Sets the current filter to "close ESM" (using the inverse of the
  65551. * exponential to prevent steep falloff artifacts).
  65552. */
  65553. set: function (value) {
  65554. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65555. return;
  65556. }
  65557. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65558. },
  65559. enumerable: true,
  65560. configurable: true
  65561. });
  65562. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65563. /**
  65564. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65565. * exponential to prevent steep falloff artifacts).
  65566. */
  65567. get: function () {
  65568. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65569. },
  65570. /**
  65571. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65572. * exponential to prevent steep falloff artifacts).
  65573. */
  65574. set: function (value) {
  65575. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65576. return;
  65577. }
  65578. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65579. },
  65580. enumerable: true,
  65581. configurable: true
  65582. });
  65583. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65584. /**
  65585. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65586. */
  65587. get: function () {
  65588. return this.filter === ShadowGenerator.FILTER_PCF;
  65589. },
  65590. /**
  65591. * Sets the current filter to "PCF" (percentage closer filtering).
  65592. */
  65593. set: function (value) {
  65594. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65595. return;
  65596. }
  65597. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65598. },
  65599. enumerable: true,
  65600. configurable: true
  65601. });
  65602. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65603. /**
  65604. * Gets the PCF or PCSS Quality.
  65605. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65606. */
  65607. get: function () {
  65608. return this._filteringQuality;
  65609. },
  65610. /**
  65611. * Sets the PCF or PCSS Quality.
  65612. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65613. */
  65614. set: function (filteringQuality) {
  65615. this._filteringQuality = filteringQuality;
  65616. },
  65617. enumerable: true,
  65618. configurable: true
  65619. });
  65620. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65621. /**
  65622. * Gets if the current filter is set to "PCSS" (contact hardening).
  65623. */
  65624. get: function () {
  65625. return this.filter === ShadowGenerator.FILTER_PCSS;
  65626. },
  65627. /**
  65628. * Sets the current filter to "PCSS" (contact hardening).
  65629. */
  65630. set: function (value) {
  65631. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65632. return;
  65633. }
  65634. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65635. },
  65636. enumerable: true,
  65637. configurable: true
  65638. });
  65639. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65640. /**
  65641. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65642. * Using a ratio helps keeping shape stability independently of the map size.
  65643. *
  65644. * It does not account for the light projection as it was having too much
  65645. * instability during the light setup or during light position changes.
  65646. *
  65647. * Only valid if useContactHardeningShadow is true.
  65648. */
  65649. get: function () {
  65650. return this._contactHardeningLightSizeUVRatio;
  65651. },
  65652. /**
  65653. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65654. * Using a ratio helps keeping shape stability independently of the map size.
  65655. *
  65656. * It does not account for the light projection as it was having too much
  65657. * instability during the light setup or during light position changes.
  65658. *
  65659. * Only valid if useContactHardeningShadow is true.
  65660. */
  65661. set: function (contactHardeningLightSizeUVRatio) {
  65662. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65663. },
  65664. enumerable: true,
  65665. configurable: true
  65666. });
  65667. /**
  65668. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65669. * 0 means strongest and 1 would means no shadow.
  65670. * @returns the darkness.
  65671. */
  65672. ShadowGenerator.prototype.getDarkness = function () {
  65673. return this._darkness;
  65674. };
  65675. /**
  65676. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65677. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65678. * @returns the shadow generator allowing fluent coding.
  65679. */
  65680. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65681. if (darkness >= 1.0)
  65682. this._darkness = 1.0;
  65683. else if (darkness <= 0.0)
  65684. this._darkness = 0.0;
  65685. else
  65686. this._darkness = darkness;
  65687. return this;
  65688. };
  65689. /**
  65690. * Sets the ability to have transparent shadow (boolean).
  65691. * @param transparent True if transparent else False
  65692. * @returns the shadow generator allowing fluent coding
  65693. */
  65694. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65695. this._transparencyShadow = transparent;
  65696. return this;
  65697. };
  65698. /**
  65699. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65700. * @returns The render target texture if present otherwise, null
  65701. */
  65702. ShadowGenerator.prototype.getShadowMap = function () {
  65703. return this._shadowMap;
  65704. };
  65705. /**
  65706. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65707. * @returns The render target texture if the shadow map is present otherwise, null
  65708. */
  65709. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65710. if (this._shadowMap2) {
  65711. return this._shadowMap2;
  65712. }
  65713. return this._shadowMap;
  65714. };
  65715. /**
  65716. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65717. * @param mesh Mesh to add
  65718. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65719. * @returns the Shadow Generator itself
  65720. */
  65721. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65722. if (includeDescendants === void 0) { includeDescendants = true; }
  65723. if (!this._shadowMap) {
  65724. return this;
  65725. }
  65726. if (!this._shadowMap.renderList) {
  65727. this._shadowMap.renderList = [];
  65728. }
  65729. this._shadowMap.renderList.push(mesh);
  65730. if (includeDescendants) {
  65731. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65732. }
  65733. return this;
  65734. var _a;
  65735. };
  65736. /**
  65737. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65738. * @param mesh Mesh to remove
  65739. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65740. * @returns the Shadow Generator itself
  65741. */
  65742. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65743. if (includeDescendants === void 0) { includeDescendants = true; }
  65744. if (!this._shadowMap || !this._shadowMap.renderList) {
  65745. return this;
  65746. }
  65747. var index = this._shadowMap.renderList.indexOf(mesh);
  65748. if (index !== -1) {
  65749. this._shadowMap.renderList.splice(index, 1);
  65750. }
  65751. if (includeDescendants) {
  65752. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65753. var child = _a[_i];
  65754. this.removeShadowCaster(child);
  65755. }
  65756. }
  65757. return this;
  65758. };
  65759. /**
  65760. * Returns the associated light object.
  65761. * @returns the light generating the shadow
  65762. */
  65763. ShadowGenerator.prototype.getLight = function () {
  65764. return this._light;
  65765. };
  65766. ShadowGenerator.prototype._initializeGenerator = function () {
  65767. this._light._markMeshesAsLightDirty();
  65768. this._initializeShadowMap();
  65769. };
  65770. ShadowGenerator.prototype._initializeShadowMap = function () {
  65771. var _this = this;
  65772. // Render target
  65773. var engine = this._scene.getEngine();
  65774. if (engine.webGLVersion > 1) {
  65775. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65776. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65777. }
  65778. else {
  65779. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65780. }
  65781. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65782. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65783. this._shadowMap.anisotropicFilteringLevel = 1;
  65784. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65785. this._shadowMap.renderParticles = false;
  65786. this._shadowMap.ignoreCameraViewport = true;
  65787. // Record Face Index before render.
  65788. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65789. _this._currentFaceIndex = faceIndex;
  65790. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65791. engine.setColorWrite(false);
  65792. }
  65793. });
  65794. // Custom render function.
  65795. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65796. // Blur if required afer render.
  65797. this._shadowMap.onAfterUnbindObservable.add(function () {
  65798. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65799. engine.setColorWrite(true);
  65800. }
  65801. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65802. return;
  65803. }
  65804. var shadowMap = _this.getShadowMapForRendering();
  65805. if (shadowMap) {
  65806. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65807. }
  65808. });
  65809. // Clear according to the chosen filter.
  65810. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65811. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65812. this._shadowMap.onClearObservable.add(function (engine) {
  65813. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65814. engine.clear(clearOne, false, true, false);
  65815. }
  65816. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65817. engine.clear(clearZero, true, true, false);
  65818. }
  65819. else {
  65820. engine.clear(clearOne, true, true, false);
  65821. }
  65822. });
  65823. };
  65824. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65825. var _this = this;
  65826. var engine = this._scene.getEngine();
  65827. var targetSize = this._mapSize / this.blurScale;
  65828. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  65829. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  65830. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65831. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65832. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65833. }
  65834. if (this.useKernelBlur) {
  65835. 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);
  65836. this._kernelBlurXPostprocess.width = targetSize;
  65837. this._kernelBlurXPostprocess.height = targetSize;
  65838. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  65839. effect.setTexture("textureSampler", _this._shadowMap);
  65840. });
  65841. 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);
  65842. this._kernelBlurXPostprocess.autoClear = false;
  65843. this._kernelBlurYPostprocess.autoClear = false;
  65844. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65845. this._kernelBlurXPostprocess.packedFloat = true;
  65846. this._kernelBlurYPostprocess.packedFloat = true;
  65847. }
  65848. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  65849. }
  65850. else {
  65851. 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);
  65852. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  65853. effect.setFloat2("screenSize", targetSize, targetSize);
  65854. effect.setTexture("textureSampler", _this._shadowMap);
  65855. });
  65856. this._boxBlurPostprocess.autoClear = false;
  65857. this._blurPostProcesses = [this._boxBlurPostprocess];
  65858. }
  65859. };
  65860. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65861. var index;
  65862. var engine = this._scene.getEngine();
  65863. if (depthOnlySubMeshes.length) {
  65864. engine.setColorWrite(false);
  65865. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65866. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  65867. }
  65868. engine.setColorWrite(true);
  65869. }
  65870. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65871. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  65872. }
  65873. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65874. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  65875. }
  65876. if (this._transparencyShadow) {
  65877. for (index = 0; index < transparentSubMeshes.length; index++) {
  65878. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  65879. }
  65880. }
  65881. };
  65882. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  65883. var _this = this;
  65884. var mesh = subMesh.getRenderingMesh();
  65885. var scene = this._scene;
  65886. var engine = scene.getEngine();
  65887. var material = subMesh.getMaterial();
  65888. if (!material) {
  65889. return;
  65890. }
  65891. // Culling
  65892. engine.setState(material.backFaceCulling);
  65893. // Managing instances
  65894. var batch = mesh._getInstancesRenderList(subMesh._id);
  65895. if (batch.mustReturn) {
  65896. return;
  65897. }
  65898. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65899. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  65900. engine.enableEffect(this._effect);
  65901. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65902. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  65903. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  65904. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65905. this._effect.setVector3("lightData", this._cachedDirection);
  65906. }
  65907. else {
  65908. this._effect.setVector3("lightData", this._cachedPosition);
  65909. }
  65910. if (scene.activeCamera) {
  65911. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  65912. }
  65913. // Alpha test
  65914. if (material && material.needAlphaTesting()) {
  65915. var alphaTexture = material.getAlphaTestTexture();
  65916. if (alphaTexture) {
  65917. this._effect.setTexture("diffuseSampler", alphaTexture);
  65918. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  65919. }
  65920. }
  65921. // Bones
  65922. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65923. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  65924. }
  65925. // Morph targets
  65926. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  65927. if (this.forceBackFacesOnly) {
  65928. engine.setState(true, 0, false, true);
  65929. }
  65930. // Draw
  65931. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65932. if (this.forceBackFacesOnly) {
  65933. engine.setState(true, 0, false, false);
  65934. }
  65935. }
  65936. else {
  65937. // Need to reset refresh rate of the shadowMap
  65938. if (this._shadowMap) {
  65939. this._shadowMap.resetRefreshCounter();
  65940. }
  65941. }
  65942. };
  65943. ShadowGenerator.prototype._applyFilterValues = function () {
  65944. if (!this._shadowMap) {
  65945. return;
  65946. }
  65947. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  65948. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65949. }
  65950. else {
  65951. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65952. }
  65953. };
  65954. /**
  65955. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65956. * @param onCompiled Callback triggered at the and of the effects compilation
  65957. * @param options Sets of optional options forcing the compilation with different modes
  65958. */
  65959. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  65960. var _this = this;
  65961. var localOptions = __assign({ useInstances: false }, options);
  65962. var shadowMap = this.getShadowMap();
  65963. if (!shadowMap) {
  65964. if (onCompiled) {
  65965. onCompiled(this);
  65966. }
  65967. return;
  65968. }
  65969. var renderList = shadowMap.renderList;
  65970. if (!renderList) {
  65971. if (onCompiled) {
  65972. onCompiled(this);
  65973. }
  65974. return;
  65975. }
  65976. var subMeshes = new Array();
  65977. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  65978. var mesh = renderList_1[_i];
  65979. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  65980. }
  65981. if (subMeshes.length === 0) {
  65982. if (onCompiled) {
  65983. onCompiled(this);
  65984. }
  65985. return;
  65986. }
  65987. var currentIndex = 0;
  65988. var checkReady = function () {
  65989. if (!_this._scene || !_this._scene.getEngine()) {
  65990. return;
  65991. }
  65992. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  65993. currentIndex++;
  65994. if (currentIndex >= subMeshes.length) {
  65995. if (onCompiled) {
  65996. onCompiled(_this);
  65997. }
  65998. return;
  65999. }
  66000. }
  66001. setTimeout(checkReady, 16);
  66002. };
  66003. checkReady();
  66004. };
  66005. /**
  66006. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66007. * @param options Sets of optional options forcing the compilation with different modes
  66008. * @returns A promise that resolves when the compilation completes
  66009. */
  66010. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66011. var _this = this;
  66012. return new Promise(function (resolve) {
  66013. _this.forceCompilation(function () {
  66014. resolve();
  66015. }, options);
  66016. });
  66017. };
  66018. /**
  66019. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66020. * @param subMesh The submesh we want to render in the shadow map
  66021. * @param useInstances Defines wether will draw in the map using instances
  66022. * @returns true if ready otherwise, false
  66023. */
  66024. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66025. var defines = [];
  66026. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66027. defines.push("#define FLOAT");
  66028. }
  66029. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66030. defines.push("#define ESM");
  66031. }
  66032. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66033. defines.push("#define DEPTHTEXTURE");
  66034. }
  66035. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66036. var mesh = subMesh.getMesh();
  66037. var material = subMesh.getMaterial();
  66038. // Normal bias.
  66039. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66040. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66041. defines.push("#define NORMAL");
  66042. if (mesh.nonUniformScaling) {
  66043. defines.push("#define NONUNIFORMSCALING");
  66044. }
  66045. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66046. defines.push("#define DIRECTIONINLIGHTDATA");
  66047. }
  66048. }
  66049. // Alpha test
  66050. if (material && material.needAlphaTesting()) {
  66051. var alphaTexture = material.getAlphaTestTexture();
  66052. if (alphaTexture) {
  66053. defines.push("#define ALPHATEST");
  66054. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66055. attribs.push(BABYLON.VertexBuffer.UVKind);
  66056. defines.push("#define UV1");
  66057. }
  66058. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66059. if (alphaTexture.coordinatesIndex === 1) {
  66060. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66061. defines.push("#define UV2");
  66062. }
  66063. }
  66064. }
  66065. }
  66066. // Bones
  66067. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66068. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66069. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66070. if (mesh.numBoneInfluencers > 4) {
  66071. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66072. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66073. }
  66074. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66075. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66076. }
  66077. else {
  66078. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66079. }
  66080. // Morph targets
  66081. var manager = mesh.morphTargetManager;
  66082. var morphInfluencers = 0;
  66083. if (manager) {
  66084. if (manager.numInfluencers > 0) {
  66085. defines.push("#define MORPHTARGETS");
  66086. morphInfluencers = manager.numInfluencers;
  66087. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66088. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66089. }
  66090. }
  66091. // Instances
  66092. if (useInstances) {
  66093. defines.push("#define INSTANCES");
  66094. attribs.push("world0");
  66095. attribs.push("world1");
  66096. attribs.push("world2");
  66097. attribs.push("world3");
  66098. }
  66099. // Get correct effect
  66100. var join = defines.join("\n");
  66101. if (this._cachedDefines !== join) {
  66102. this._cachedDefines = join;
  66103. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66104. }
  66105. if (!this._effect.isReady()) {
  66106. return false;
  66107. }
  66108. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66109. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66110. this._initializeBlurRTTAndPostProcesses();
  66111. }
  66112. }
  66113. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66114. return false;
  66115. }
  66116. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66117. return false;
  66118. }
  66119. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66120. return false;
  66121. }
  66122. return true;
  66123. };
  66124. /**
  66125. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66126. * @param defines Defines of the material we want to update
  66127. * @param lightIndex Index of the light in the enabled light list of the material
  66128. */
  66129. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66130. var scene = this._scene;
  66131. var light = this._light;
  66132. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66133. return;
  66134. }
  66135. defines["SHADOW" + lightIndex] = true;
  66136. if (this.useContactHardeningShadow) {
  66137. defines["SHADOWPCSS" + lightIndex] = true;
  66138. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66139. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66140. }
  66141. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66142. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66143. }
  66144. // else default to high.
  66145. }
  66146. if (this.usePercentageCloserFiltering) {
  66147. defines["SHADOWPCF" + lightIndex] = true;
  66148. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66149. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66150. }
  66151. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66152. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66153. }
  66154. // else default to high.
  66155. }
  66156. else if (this.usePoissonSampling) {
  66157. defines["SHADOWPOISSON" + lightIndex] = true;
  66158. }
  66159. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66160. defines["SHADOWESM" + lightIndex] = true;
  66161. }
  66162. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66163. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66164. }
  66165. if (light.needCube()) {
  66166. defines["SHADOWCUBE" + lightIndex] = true;
  66167. }
  66168. };
  66169. /**
  66170. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66171. * defined in the generator but impacting the effect).
  66172. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66173. * @param effect The effect we are binfing the information for
  66174. */
  66175. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66176. var light = this._light;
  66177. var scene = this._scene;
  66178. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66179. return;
  66180. }
  66181. var camera = scene.activeCamera;
  66182. if (!camera) {
  66183. return;
  66184. }
  66185. var shadowMap = this.getShadowMap();
  66186. if (!shadowMap) {
  66187. return;
  66188. }
  66189. if (!light.needCube()) {
  66190. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66191. }
  66192. // Only PCF uses depth stencil texture.
  66193. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66194. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66195. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66196. }
  66197. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66198. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66199. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66200. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66201. }
  66202. else {
  66203. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66204. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66205. }
  66206. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66207. };
  66208. /**
  66209. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66210. * (eq to shadow prjection matrix * light transform matrix)
  66211. * @returns The transform matrix used to create the shadow map
  66212. */
  66213. ShadowGenerator.prototype.getTransformMatrix = function () {
  66214. var scene = this._scene;
  66215. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66216. return this._transformMatrix;
  66217. }
  66218. this._currentRenderID = scene.getRenderId();
  66219. this._currentFaceIndexCache = this._currentFaceIndex;
  66220. var lightPosition = this._light.position;
  66221. if (this._light.computeTransformedInformation()) {
  66222. lightPosition = this._light.transformedPosition;
  66223. }
  66224. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66225. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66226. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66227. }
  66228. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66229. this._cachedPosition.copyFrom(lightPosition);
  66230. this._cachedDirection.copyFrom(this._lightDirection);
  66231. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66232. var shadowMap = this.getShadowMap();
  66233. if (shadowMap) {
  66234. var renderList = shadowMap.renderList;
  66235. if (renderList) {
  66236. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66237. }
  66238. }
  66239. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66240. }
  66241. return this._transformMatrix;
  66242. };
  66243. /**
  66244. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66245. * Cube and 2D textures for instance.
  66246. */
  66247. ShadowGenerator.prototype.recreateShadowMap = function () {
  66248. var shadowMap = this._shadowMap;
  66249. if (!shadowMap) {
  66250. return;
  66251. }
  66252. // Track render list.
  66253. var renderList = shadowMap.renderList;
  66254. // Clean up existing data.
  66255. this._disposeRTTandPostProcesses();
  66256. // Reinitializes.
  66257. this._initializeGenerator();
  66258. // Reaffect the filter to ensure a correct fallback if necessary.
  66259. this.filter = this.filter;
  66260. // Reaffect the filter.
  66261. this._applyFilterValues();
  66262. // Reaffect Render List.
  66263. this._shadowMap.renderList = renderList;
  66264. };
  66265. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66266. if (this._shadowMap2) {
  66267. this._shadowMap2.dispose();
  66268. this._shadowMap2 = null;
  66269. }
  66270. if (this._boxBlurPostprocess) {
  66271. this._boxBlurPostprocess.dispose();
  66272. this._boxBlurPostprocess = null;
  66273. }
  66274. if (this._kernelBlurXPostprocess) {
  66275. this._kernelBlurXPostprocess.dispose();
  66276. this._kernelBlurXPostprocess = null;
  66277. }
  66278. if (this._kernelBlurYPostprocess) {
  66279. this._kernelBlurYPostprocess.dispose();
  66280. this._kernelBlurYPostprocess = null;
  66281. }
  66282. this._blurPostProcesses = [];
  66283. };
  66284. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66285. if (this._shadowMap) {
  66286. this._shadowMap.dispose();
  66287. this._shadowMap = null;
  66288. }
  66289. this._disposeBlurPostProcesses();
  66290. };
  66291. /**
  66292. * Disposes the ShadowGenerator.
  66293. * Returns nothing.
  66294. */
  66295. ShadowGenerator.prototype.dispose = function () {
  66296. this._disposeRTTandPostProcesses();
  66297. if (this._light) {
  66298. this._light._shadowGenerator = null;
  66299. this._light._markMeshesAsLightDirty();
  66300. }
  66301. };
  66302. /**
  66303. * Serializes the shadow generator setup to a json object.
  66304. * @returns The serialized JSON object
  66305. */
  66306. ShadowGenerator.prototype.serialize = function () {
  66307. var serializationObject = {};
  66308. var shadowMap = this.getShadowMap();
  66309. if (!shadowMap) {
  66310. return serializationObject;
  66311. }
  66312. serializationObject.lightId = this._light.id;
  66313. serializationObject.mapSize = shadowMap.getRenderSize();
  66314. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66315. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66316. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66317. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66318. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66319. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66320. serializationObject.depthScale = this.depthScale;
  66321. serializationObject.darkness = this.getDarkness();
  66322. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66323. serializationObject.blurKernel = this.blurKernel;
  66324. serializationObject.blurScale = this.blurScale;
  66325. serializationObject.useKernelBlur = this.useKernelBlur;
  66326. serializationObject.transparencyShadow = this._transparencyShadow;
  66327. serializationObject.bias = this.bias;
  66328. serializationObject.normalBias = this.normalBias;
  66329. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66330. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66331. serializationObject.filteringQuality = this.filteringQuality;
  66332. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66333. serializationObject.renderList = [];
  66334. if (shadowMap.renderList) {
  66335. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66336. var mesh = shadowMap.renderList[meshIndex];
  66337. serializationObject.renderList.push(mesh.id);
  66338. }
  66339. }
  66340. return serializationObject;
  66341. };
  66342. /**
  66343. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66344. * @param parsedShadowGenerator The JSON object to parse
  66345. * @param scene The scene to create the shadow map for
  66346. * @returns The parsed shadow generator
  66347. */
  66348. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66349. //casting to point light, as light is missing the position attr and typescript complains.
  66350. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66351. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66352. var shadowMap = shadowGenerator.getShadowMap();
  66353. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66354. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66355. meshes.forEach(function (mesh) {
  66356. if (!shadowMap) {
  66357. return;
  66358. }
  66359. if (!shadowMap.renderList) {
  66360. shadowMap.renderList = [];
  66361. }
  66362. shadowMap.renderList.push(mesh);
  66363. });
  66364. }
  66365. if (parsedShadowGenerator.usePoissonSampling) {
  66366. shadowGenerator.usePoissonSampling = true;
  66367. }
  66368. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66369. shadowGenerator.useExponentialShadowMap = true;
  66370. }
  66371. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66372. shadowGenerator.useBlurExponentialShadowMap = true;
  66373. }
  66374. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66375. shadowGenerator.useCloseExponentialShadowMap = true;
  66376. }
  66377. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66378. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66379. }
  66380. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66381. shadowGenerator.usePercentageCloserFiltering = true;
  66382. }
  66383. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66384. shadowGenerator.useContactHardeningShadow = true;
  66385. }
  66386. if (parsedShadowGenerator.filteringQuality) {
  66387. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66388. }
  66389. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66390. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66391. }
  66392. // Backward compat
  66393. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66394. shadowGenerator.useExponentialShadowMap = true;
  66395. }
  66396. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66397. shadowGenerator.useBlurExponentialShadowMap = true;
  66398. }
  66399. if (parsedShadowGenerator.depthScale) {
  66400. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66401. }
  66402. if (parsedShadowGenerator.blurScale) {
  66403. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66404. }
  66405. if (parsedShadowGenerator.blurBoxOffset) {
  66406. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66407. }
  66408. if (parsedShadowGenerator.useKernelBlur) {
  66409. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66410. }
  66411. if (parsedShadowGenerator.blurKernel) {
  66412. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66413. }
  66414. if (parsedShadowGenerator.bias !== undefined) {
  66415. shadowGenerator.bias = parsedShadowGenerator.bias;
  66416. }
  66417. if (parsedShadowGenerator.normalBias !== undefined) {
  66418. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66419. }
  66420. if (parsedShadowGenerator.darkness) {
  66421. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66422. }
  66423. if (parsedShadowGenerator.transparencyShadow) {
  66424. shadowGenerator.setTransparencyShadow(true);
  66425. }
  66426. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66427. return shadowGenerator;
  66428. };
  66429. /**
  66430. * Shadow generator mode None: no filtering applied.
  66431. */
  66432. ShadowGenerator.FILTER_NONE = 0;
  66433. /**
  66434. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66435. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66436. */
  66437. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66438. /**
  66439. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66440. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66441. */
  66442. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66443. /**
  66444. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66445. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66446. */
  66447. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66448. /**
  66449. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66450. * edge artifacts on steep falloff.
  66451. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66452. */
  66453. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66454. /**
  66455. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66456. * edge artifacts on steep falloff.
  66457. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66458. */
  66459. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66460. /**
  66461. * Shadow generator mode PCF: Percentage Closer Filtering
  66462. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66463. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66464. */
  66465. ShadowGenerator.FILTER_PCF = 6;
  66466. /**
  66467. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66468. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66469. * Contact Hardening
  66470. */
  66471. ShadowGenerator.FILTER_PCSS = 7;
  66472. /**
  66473. * Reserved for PCF and PCSS
  66474. * Highest Quality.
  66475. *
  66476. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66477. *
  66478. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66479. */
  66480. ShadowGenerator.QUALITY_HIGH = 0;
  66481. /**
  66482. * Reserved for PCF and PCSS
  66483. * Good tradeoff for quality/perf cross devices
  66484. *
  66485. * Execute PCF on a 3*3 kernel.
  66486. *
  66487. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66488. */
  66489. ShadowGenerator.QUALITY_MEDIUM = 1;
  66490. /**
  66491. * Reserved for PCF and PCSS
  66492. * The lowest quality but the fastest.
  66493. *
  66494. * Execute PCF on a 1*1 kernel.
  66495. *
  66496. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66497. */
  66498. ShadowGenerator.QUALITY_LOW = 2;
  66499. return ShadowGenerator;
  66500. }());
  66501. BABYLON.ShadowGenerator = ShadowGenerator;
  66502. })(BABYLON || (BABYLON = {}));
  66503. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66504. var BABYLON;
  66505. (function (BABYLON) {
  66506. var DefaultLoadingScreen = /** @class */ (function () {
  66507. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66508. if (_loadingText === void 0) { _loadingText = ""; }
  66509. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66510. var _this = this;
  66511. this._renderingCanvas = _renderingCanvas;
  66512. this._loadingText = _loadingText;
  66513. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66514. // Resize
  66515. this._resizeLoadingUI = function () {
  66516. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66517. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66518. if (!_this._loadingDiv) {
  66519. return;
  66520. }
  66521. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66522. _this._loadingDiv.style.left = canvasRect.left + "px";
  66523. _this._loadingDiv.style.top = canvasRect.top + "px";
  66524. _this._loadingDiv.style.width = canvasRect.width + "px";
  66525. _this._loadingDiv.style.height = canvasRect.height + "px";
  66526. };
  66527. }
  66528. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66529. if (this._loadingDiv) {
  66530. // Do not add a loading screen if there is already one
  66531. return;
  66532. }
  66533. this._loadingDiv = document.createElement("div");
  66534. this._loadingDiv.id = "babylonjsLoadingDiv";
  66535. this._loadingDiv.style.opacity = "0";
  66536. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66537. this._loadingDiv.style.pointerEvents = "none";
  66538. // Loading text
  66539. this._loadingTextDiv = document.createElement("div");
  66540. this._loadingTextDiv.style.position = "absolute";
  66541. this._loadingTextDiv.style.left = "0";
  66542. this._loadingTextDiv.style.top = "50%";
  66543. this._loadingTextDiv.style.marginTop = "80px";
  66544. this._loadingTextDiv.style.width = "100%";
  66545. this._loadingTextDiv.style.height = "20px";
  66546. this._loadingTextDiv.style.fontFamily = "Arial";
  66547. this._loadingTextDiv.style.fontSize = "14px";
  66548. this._loadingTextDiv.style.color = "white";
  66549. this._loadingTextDiv.style.textAlign = "center";
  66550. this._loadingTextDiv.innerHTML = "Loading";
  66551. this._loadingDiv.appendChild(this._loadingTextDiv);
  66552. //set the predefined text
  66553. this._loadingTextDiv.innerHTML = this._loadingText;
  66554. // Generating keyframes
  66555. var style = document.createElement('style');
  66556. style.type = 'text/css';
  66557. 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 }";
  66558. style.innerHTML = keyFrames;
  66559. document.getElementsByTagName('head')[0].appendChild(style);
  66560. // Loading img
  66561. var imgBack = new Image();
  66562. 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";
  66563. imgBack.style.position = "absolute";
  66564. imgBack.style.left = "50%";
  66565. imgBack.style.top = "50%";
  66566. imgBack.style.marginLeft = "-60px";
  66567. imgBack.style.marginTop = "-60px";
  66568. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66569. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66570. imgBack.style.transformOrigin = "50% 50%";
  66571. imgBack.style.webkitTransformOrigin = "50% 50%";
  66572. this._loadingDiv.appendChild(imgBack);
  66573. this._resizeLoadingUI();
  66574. window.addEventListener("resize", this._resizeLoadingUI);
  66575. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66576. document.body.appendChild(this._loadingDiv);
  66577. this._loadingDiv.style.opacity = "1";
  66578. };
  66579. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66580. var _this = this;
  66581. if (!this._loadingDiv) {
  66582. return;
  66583. }
  66584. var onTransitionEnd = function () {
  66585. if (!_this._loadingDiv) {
  66586. return;
  66587. }
  66588. document.body.removeChild(_this._loadingDiv);
  66589. window.removeEventListener("resize", _this._resizeLoadingUI);
  66590. _this._loadingDiv = null;
  66591. };
  66592. this._loadingDiv.style.opacity = "0";
  66593. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66594. };
  66595. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66596. set: function (text) {
  66597. this._loadingText = text;
  66598. if (this._loadingTextDiv) {
  66599. this._loadingTextDiv.innerHTML = this._loadingText;
  66600. }
  66601. },
  66602. enumerable: true,
  66603. configurable: true
  66604. });
  66605. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66606. get: function () {
  66607. return this._loadingDivBackgroundColor;
  66608. },
  66609. set: function (color) {
  66610. this._loadingDivBackgroundColor = color;
  66611. if (!this._loadingDiv) {
  66612. return;
  66613. }
  66614. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66615. },
  66616. enumerable: true,
  66617. configurable: true
  66618. });
  66619. return DefaultLoadingScreen;
  66620. }());
  66621. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66622. })(BABYLON || (BABYLON = {}));
  66623. //# sourceMappingURL=babylon.loadingScreen.js.map
  66624. var BABYLON;
  66625. (function (BABYLON) {
  66626. var SceneLoaderProgressEvent = /** @class */ (function () {
  66627. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66628. this.lengthComputable = lengthComputable;
  66629. this.loaded = loaded;
  66630. this.total = total;
  66631. }
  66632. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66633. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66634. };
  66635. return SceneLoaderProgressEvent;
  66636. }());
  66637. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66638. var SceneLoader = /** @class */ (function () {
  66639. function SceneLoader() {
  66640. }
  66641. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66642. get: function () {
  66643. return 0;
  66644. },
  66645. enumerable: true,
  66646. configurable: true
  66647. });
  66648. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66649. get: function () {
  66650. return 1;
  66651. },
  66652. enumerable: true,
  66653. configurable: true
  66654. });
  66655. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66656. get: function () {
  66657. return 2;
  66658. },
  66659. enumerable: true,
  66660. configurable: true
  66661. });
  66662. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66663. get: function () {
  66664. return 3;
  66665. },
  66666. enumerable: true,
  66667. configurable: true
  66668. });
  66669. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66670. get: function () {
  66671. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66672. },
  66673. set: function (value) {
  66674. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66675. },
  66676. enumerable: true,
  66677. configurable: true
  66678. });
  66679. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66680. get: function () {
  66681. return SceneLoader._ShowLoadingScreen;
  66682. },
  66683. set: function (value) {
  66684. SceneLoader._ShowLoadingScreen = value;
  66685. },
  66686. enumerable: true,
  66687. configurable: true
  66688. });
  66689. Object.defineProperty(SceneLoader, "loggingLevel", {
  66690. get: function () {
  66691. return SceneLoader._loggingLevel;
  66692. },
  66693. set: function (value) {
  66694. SceneLoader._loggingLevel = value;
  66695. },
  66696. enumerable: true,
  66697. configurable: true
  66698. });
  66699. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66700. get: function () {
  66701. return SceneLoader._CleanBoneMatrixWeights;
  66702. },
  66703. set: function (value) {
  66704. SceneLoader._CleanBoneMatrixWeights = value;
  66705. },
  66706. enumerable: true,
  66707. configurable: true
  66708. });
  66709. SceneLoader._getDefaultPlugin = function () {
  66710. return SceneLoader._registeredPlugins[".babylon"];
  66711. };
  66712. SceneLoader._getPluginForExtension = function (extension) {
  66713. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66714. if (registeredPlugin) {
  66715. return registeredPlugin;
  66716. }
  66717. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  66718. return SceneLoader._getDefaultPlugin();
  66719. };
  66720. SceneLoader._getPluginForDirectLoad = function (data) {
  66721. for (var extension in SceneLoader._registeredPlugins) {
  66722. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66723. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66724. return SceneLoader._registeredPlugins[extension];
  66725. }
  66726. }
  66727. return SceneLoader._getDefaultPlugin();
  66728. };
  66729. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66730. if (sceneFilename.name) {
  66731. sceneFilename = sceneFilename.name;
  66732. }
  66733. var queryStringPosition = sceneFilename.indexOf("?");
  66734. if (queryStringPosition !== -1) {
  66735. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66736. }
  66737. var dotPosition = sceneFilename.lastIndexOf(".");
  66738. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66739. return SceneLoader._getPluginForExtension(extension);
  66740. };
  66741. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66742. SceneLoader._getDirectLoad = function (sceneFilename) {
  66743. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66744. return sceneFilename.substr(5);
  66745. }
  66746. return null;
  66747. };
  66748. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66749. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66750. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66751. var plugin;
  66752. if (registeredPlugin.plugin.createPlugin) {
  66753. plugin = registeredPlugin.plugin.createPlugin();
  66754. }
  66755. else {
  66756. plugin = registeredPlugin.plugin;
  66757. }
  66758. var useArrayBuffer = registeredPlugin.isBinary;
  66759. var database;
  66760. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66761. var dataCallback = function (data, responseURL) {
  66762. if (scene.isDisposed) {
  66763. onError("Scene has been disposed");
  66764. return;
  66765. }
  66766. scene.database = database;
  66767. onSuccess(plugin, data, responseURL);
  66768. };
  66769. var request = null;
  66770. var pluginDisposed = false;
  66771. var onDisposeObservable = plugin.onDisposeObservable;
  66772. if (onDisposeObservable) {
  66773. onDisposeObservable.add(function () {
  66774. pluginDisposed = true;
  66775. if (request) {
  66776. request.abort();
  66777. request = null;
  66778. }
  66779. onDispose();
  66780. });
  66781. }
  66782. var manifestChecked = function () {
  66783. if (pluginDisposed) {
  66784. return;
  66785. }
  66786. var url = rootUrl + sceneFilename;
  66787. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66788. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66789. } : undefined, database, useArrayBuffer, function (request, exception) {
  66790. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66791. });
  66792. };
  66793. if (directLoad) {
  66794. dataCallback(directLoad);
  66795. return plugin;
  66796. }
  66797. if (rootUrl.indexOf("file:") === -1) {
  66798. var engine = scene.getEngine();
  66799. var canUseOfflineSupport = engine.enableOfflineSupport;
  66800. if (canUseOfflineSupport) {
  66801. // Also check for exceptions
  66802. var exceptionFound = false;
  66803. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66804. var regex = _a[_i];
  66805. if (regex.test(rootUrl + sceneFilename)) {
  66806. exceptionFound = true;
  66807. break;
  66808. }
  66809. }
  66810. canUseOfflineSupport = !exceptionFound;
  66811. }
  66812. if (canUseOfflineSupport) {
  66813. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66814. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  66815. }
  66816. else {
  66817. manifestChecked();
  66818. }
  66819. }
  66820. // Loading file from disk via input file or drag'n'drop
  66821. else {
  66822. var fileOrString = sceneFilename;
  66823. if (fileOrString.name) { // File
  66824. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66825. }
  66826. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  66827. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  66828. }
  66829. else {
  66830. onError("Unable to find file named " + sceneFilename);
  66831. }
  66832. }
  66833. return plugin;
  66834. };
  66835. // Public functions
  66836. SceneLoader.GetPluginForExtension = function (extension) {
  66837. return SceneLoader._getPluginForExtension(extension).plugin;
  66838. };
  66839. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  66840. return !!SceneLoader._registeredPlugins[extension];
  66841. };
  66842. SceneLoader.RegisterPlugin = function (plugin) {
  66843. if (typeof plugin.extensions === "string") {
  66844. var extension = plugin.extensions;
  66845. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66846. plugin: plugin,
  66847. isBinary: false
  66848. };
  66849. }
  66850. else {
  66851. var extensions = plugin.extensions;
  66852. Object.keys(extensions).forEach(function (extension) {
  66853. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66854. plugin: plugin,
  66855. isBinary: extensions[extension].isBinary
  66856. };
  66857. });
  66858. }
  66859. };
  66860. /**
  66861. * Import meshes into a scene
  66862. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66863. * @param rootUrl a string that defines the root url for scene and resources
  66864. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66865. * @param scene the instance of BABYLON.Scene to append to
  66866. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  66867. * @param onProgress a callback with a progress event for each file being loaded
  66868. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66869. * @param pluginExtension the extension used to determine the plugin
  66870. * @returns The loaded plugin
  66871. */
  66872. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66873. if (onSuccess === void 0) { onSuccess = null; }
  66874. if (onProgress === void 0) { onProgress = null; }
  66875. if (onError === void 0) { onError = null; }
  66876. if (pluginExtension === void 0) { pluginExtension = null; }
  66877. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66878. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66879. return null;
  66880. }
  66881. var loadingToken = {};
  66882. scene._addPendingData(loadingToken);
  66883. var disposeHandler = function () {
  66884. scene._removePendingData(loadingToken);
  66885. };
  66886. var errorHandler = function (message, exception) {
  66887. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  66888. if (onError) {
  66889. onError(scene, errorMessage, exception);
  66890. }
  66891. else {
  66892. BABYLON.Tools.Error(errorMessage);
  66893. // should the exception be thrown?
  66894. }
  66895. disposeHandler();
  66896. };
  66897. var progressHandler = onProgress ? function (event) {
  66898. try {
  66899. onProgress(event);
  66900. }
  66901. catch (e) {
  66902. errorHandler("Error in onProgress callback", e);
  66903. }
  66904. } : undefined;
  66905. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  66906. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  66907. if (onSuccess) {
  66908. try {
  66909. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  66910. }
  66911. catch (e) {
  66912. errorHandler("Error in onSuccess callback", e);
  66913. }
  66914. }
  66915. scene._removePendingData(loadingToken);
  66916. };
  66917. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66918. if (plugin.rewriteRootURL) {
  66919. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  66920. }
  66921. if (sceneFilename === "") {
  66922. if (sceneFilename === "") {
  66923. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66924. }
  66925. }
  66926. if (plugin.importMesh) {
  66927. var syncedPlugin = plugin;
  66928. var meshes = new Array();
  66929. var particleSystems = new Array();
  66930. var skeletons = new Array();
  66931. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  66932. return;
  66933. }
  66934. scene.loadingPluginName = plugin.name;
  66935. successHandler(meshes, particleSystems, skeletons, []);
  66936. }
  66937. else {
  66938. var asyncedPlugin = plugin;
  66939. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  66940. scene.loadingPluginName = plugin.name;
  66941. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  66942. }).catch(function (error) {
  66943. errorHandler(error.message, error);
  66944. });
  66945. }
  66946. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66947. };
  66948. /**
  66949. * Import meshes into a scene
  66950. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66951. * @param rootUrl a string that defines the root url for scene and resources
  66952. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66953. * @param scene the instance of BABYLON.Scene to append to
  66954. * @param onProgress a callback with a progress event for each file being loaded
  66955. * @param pluginExtension the extension used to determine the plugin
  66956. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  66957. */
  66958. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66959. if (onProgress === void 0) { onProgress = null; }
  66960. if (pluginExtension === void 0) { pluginExtension = null; }
  66961. return new Promise(function (resolve, reject) {
  66962. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  66963. resolve({
  66964. meshes: meshes,
  66965. particleSystems: particleSystems,
  66966. skeletons: skeletons,
  66967. animationGroups: animationGroups
  66968. });
  66969. }, onProgress, function (scene, message, exception) {
  66970. reject(exception || new Error(message));
  66971. });
  66972. });
  66973. };
  66974. /**
  66975. * Load a scene
  66976. * @param rootUrl a string that defines the root url for scene and resources
  66977. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66978. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66979. * @param onSuccess a callback with the scene when import succeeds
  66980. * @param onProgress a callback with a progress event for each file being loaded
  66981. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66982. * @param pluginExtension the extension used to determine the plugin
  66983. * @returns The loaded plugin
  66984. */
  66985. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  66986. if (onSuccess === void 0) { onSuccess = null; }
  66987. if (onProgress === void 0) { onProgress = null; }
  66988. if (onError === void 0) { onError = null; }
  66989. if (pluginExtension === void 0) { pluginExtension = null; }
  66990. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  66991. };
  66992. /**
  66993. * Load a scene
  66994. * @param rootUrl a string that defines the root url for scene and resources
  66995. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66996. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66997. * @param onProgress a callback with a progress event for each file being loaded
  66998. * @param pluginExtension the extension used to determine the plugin
  66999. * @returns The loaded scene
  67000. */
  67001. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67002. if (onProgress === void 0) { onProgress = null; }
  67003. if (pluginExtension === void 0) { pluginExtension = null; }
  67004. return new Promise(function (resolve, reject) {
  67005. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67006. resolve(scene);
  67007. }, onProgress, function (scene, message, exception) {
  67008. reject(exception || new Error(message));
  67009. }, pluginExtension);
  67010. });
  67011. };
  67012. /**
  67013. * Append a scene
  67014. * @param rootUrl a string that defines the root url for scene and resources
  67015. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67016. * @param scene is the instance of BABYLON.Scene to append to
  67017. * @param onSuccess a callback with the scene when import succeeds
  67018. * @param onProgress a callback with a progress event for each file being loaded
  67019. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67020. * @param pluginExtension the extension used to determine the plugin
  67021. * @returns The loaded plugin
  67022. */
  67023. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67024. if (onSuccess === void 0) { onSuccess = null; }
  67025. if (onProgress === void 0) { onProgress = null; }
  67026. if (onError === void 0) { onError = null; }
  67027. if (pluginExtension === void 0) { pluginExtension = null; }
  67028. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67029. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67030. return null;
  67031. }
  67032. if (SceneLoader.ShowLoadingScreen) {
  67033. scene.getEngine().displayLoadingUI();
  67034. }
  67035. var loadingToken = {};
  67036. scene._addPendingData(loadingToken);
  67037. var disposeHandler = function () {
  67038. scene._removePendingData(loadingToken);
  67039. scene.getEngine().hideLoadingUI();
  67040. };
  67041. var errorHandler = function (message, exception) {
  67042. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67043. if (onError) {
  67044. onError(scene, errorMessage, exception);
  67045. }
  67046. else {
  67047. BABYLON.Tools.Error(errorMessage);
  67048. // should the exception be thrown?
  67049. }
  67050. disposeHandler();
  67051. };
  67052. var progressHandler = onProgress ? function (event) {
  67053. try {
  67054. onProgress(event);
  67055. }
  67056. catch (e) {
  67057. errorHandler("Error in onProgress callback", e);
  67058. }
  67059. } : undefined;
  67060. var successHandler = function () {
  67061. if (onSuccess) {
  67062. try {
  67063. onSuccess(scene);
  67064. }
  67065. catch (e) {
  67066. errorHandler("Error in onSuccess callback", e);
  67067. }
  67068. }
  67069. scene._removePendingData(loadingToken);
  67070. };
  67071. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67072. if (sceneFilename === "") {
  67073. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67074. }
  67075. if (plugin.load) {
  67076. var syncedPlugin = plugin;
  67077. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67078. return;
  67079. }
  67080. scene.loadingPluginName = plugin.name;
  67081. successHandler();
  67082. }
  67083. else {
  67084. var asyncedPlugin = plugin;
  67085. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67086. scene.loadingPluginName = plugin.name;
  67087. successHandler();
  67088. }).catch(function (error) {
  67089. errorHandler(error.message, error);
  67090. });
  67091. }
  67092. if (SceneLoader.ShowLoadingScreen) {
  67093. scene.executeWhenReady(function () {
  67094. scene.getEngine().hideLoadingUI();
  67095. });
  67096. }
  67097. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67098. };
  67099. /**
  67100. * Append a scene
  67101. * @param rootUrl a string that defines the root url for scene and resources
  67102. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67103. * @param scene is the instance of BABYLON.Scene to append to
  67104. * @param onProgress a callback with a progress event for each file being loaded
  67105. * @param pluginExtension the extension used to determine the plugin
  67106. * @returns The given scene
  67107. */
  67108. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67109. if (onProgress === void 0) { onProgress = null; }
  67110. if (pluginExtension === void 0) { pluginExtension = null; }
  67111. return new Promise(function (resolve, reject) {
  67112. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67113. resolve(scene);
  67114. }, onProgress, function (scene, message, exception) {
  67115. reject(exception || new Error(message));
  67116. }, pluginExtension);
  67117. });
  67118. };
  67119. /**
  67120. * Load a scene into an asset container
  67121. * @param rootUrl a string that defines the root url for scene and resources
  67122. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67123. * @param scene is the instance of BABYLON.Scene to append to
  67124. * @param onSuccess a callback with the scene when import succeeds
  67125. * @param onProgress a callback with a progress event for each file being loaded
  67126. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67127. * @param pluginExtension the extension used to determine the plugin
  67128. * @returns The loaded plugin
  67129. */
  67130. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67131. if (onSuccess === void 0) { onSuccess = null; }
  67132. if (onProgress === void 0) { onProgress = null; }
  67133. if (onError === void 0) { onError = null; }
  67134. if (pluginExtension === void 0) { pluginExtension = null; }
  67135. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67136. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67137. return null;
  67138. }
  67139. var loadingToken = {};
  67140. scene._addPendingData(loadingToken);
  67141. var disposeHandler = function () {
  67142. scene._removePendingData(loadingToken);
  67143. };
  67144. var errorHandler = function (message, exception) {
  67145. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67146. if (onError) {
  67147. onError(scene, errorMessage, exception);
  67148. }
  67149. else {
  67150. BABYLON.Tools.Error(errorMessage);
  67151. // should the exception be thrown?
  67152. }
  67153. disposeHandler();
  67154. };
  67155. var progressHandler = onProgress ? function (event) {
  67156. try {
  67157. onProgress(event);
  67158. }
  67159. catch (e) {
  67160. errorHandler("Error in onProgress callback", e);
  67161. }
  67162. } : undefined;
  67163. var successHandler = function (assets) {
  67164. if (onSuccess) {
  67165. try {
  67166. onSuccess(assets);
  67167. }
  67168. catch (e) {
  67169. errorHandler("Error in onSuccess callback", e);
  67170. }
  67171. }
  67172. scene._removePendingData(loadingToken);
  67173. };
  67174. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67175. if (plugin.loadAssetContainer) {
  67176. var syncedPlugin = plugin;
  67177. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67178. if (!assetContainer) {
  67179. return;
  67180. }
  67181. scene.loadingPluginName = plugin.name;
  67182. successHandler(assetContainer);
  67183. }
  67184. else if (plugin.loadAssetContainerAsync) {
  67185. var asyncedPlugin = plugin;
  67186. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67187. scene.loadingPluginName = plugin.name;
  67188. successHandler(assetContainer);
  67189. }).catch(function (error) {
  67190. errorHandler(error.message, error);
  67191. });
  67192. }
  67193. else {
  67194. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67195. }
  67196. if (SceneLoader.ShowLoadingScreen) {
  67197. scene.executeWhenReady(function () {
  67198. scene.getEngine().hideLoadingUI();
  67199. });
  67200. }
  67201. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67202. };
  67203. /**
  67204. * Load a scene into an asset container
  67205. * @param rootUrl a string that defines the root url for scene and resources
  67206. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67207. * @param scene is the instance of BABYLON.Scene to append to
  67208. * @param onProgress a callback with a progress event for each file being loaded
  67209. * @param pluginExtension the extension used to determine the plugin
  67210. * @returns The loaded asset container
  67211. */
  67212. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67213. if (onProgress === void 0) { onProgress = null; }
  67214. if (pluginExtension === void 0) { pluginExtension = null; }
  67215. return new Promise(function (resolve, reject) {
  67216. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67217. resolve(assetContainer);
  67218. }, onProgress, function (scene, message, exception) {
  67219. reject(exception || new Error(message));
  67220. }, pluginExtension);
  67221. });
  67222. };
  67223. // Flags
  67224. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67225. SceneLoader._ShowLoadingScreen = true;
  67226. SceneLoader._CleanBoneMatrixWeights = false;
  67227. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67228. // Members
  67229. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67230. SceneLoader._registeredPlugins = {};
  67231. return SceneLoader;
  67232. }());
  67233. BABYLON.SceneLoader = SceneLoader;
  67234. ;
  67235. })(BABYLON || (BABYLON = {}));
  67236. //# sourceMappingURL=babylon.sceneLoader.js.map
  67237. var BABYLON;
  67238. (function (BABYLON) {
  67239. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67240. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67241. var parsedMaterial = parsedData.materials[index];
  67242. if (parsedMaterial.id === id) {
  67243. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67244. }
  67245. }
  67246. return null;
  67247. };
  67248. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67249. for (var i in names) {
  67250. if (mesh.name === names[i]) {
  67251. hierarchyIds.push(mesh.id);
  67252. return true;
  67253. }
  67254. }
  67255. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67256. hierarchyIds.push(mesh.id);
  67257. return true;
  67258. }
  67259. return false;
  67260. };
  67261. var logOperation = function (operation, producer) {
  67262. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67263. };
  67264. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67265. if (addToScene === void 0) { addToScene = false; }
  67266. var container = new BABYLON.AssetContainer(scene);
  67267. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67268. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67269. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67270. // and avoid problems with multiple concurrent .babylon loads.
  67271. var log = "importScene has failed JSON parse";
  67272. try {
  67273. var parsedData = JSON.parse(data);
  67274. log = "";
  67275. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67276. var index;
  67277. var cache;
  67278. // Lights
  67279. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67280. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67281. var parsedLight = parsedData.lights[index];
  67282. var light = BABYLON.Light.Parse(parsedLight, scene);
  67283. if (light) {
  67284. container.lights.push(light);
  67285. log += (index === 0 ? "\n\tLights:" : "");
  67286. log += "\n\t\t" + light.toString(fullDetails);
  67287. }
  67288. }
  67289. }
  67290. // Animations
  67291. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67292. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67293. var parsedAnimation = parsedData.animations[index];
  67294. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67295. scene.animations.push(animation);
  67296. container.animations.push(animation);
  67297. log += (index === 0 ? "\n\tAnimations:" : "");
  67298. log += "\n\t\t" + animation.toString(fullDetails);
  67299. }
  67300. }
  67301. // Materials
  67302. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67303. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67304. var parsedMaterial = parsedData.materials[index];
  67305. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67306. container.materials.push(mat);
  67307. log += (index === 0 ? "\n\tMaterials:" : "");
  67308. log += "\n\t\t" + mat.toString(fullDetails);
  67309. }
  67310. }
  67311. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67312. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67313. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67314. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67315. container.multiMaterials.push(mmat);
  67316. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67317. log += "\n\t\t" + mmat.toString(fullDetails);
  67318. }
  67319. }
  67320. // Morph targets
  67321. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67322. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67323. var managerData = _a[_i];
  67324. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67325. }
  67326. }
  67327. // Skeletons
  67328. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67329. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67330. var parsedSkeleton = parsedData.skeletons[index];
  67331. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67332. container.skeletons.push(skeleton);
  67333. log += (index === 0 ? "\n\tSkeletons:" : "");
  67334. log += "\n\t\t" + skeleton.toString(fullDetails);
  67335. }
  67336. }
  67337. // Geometries
  67338. var geometries = parsedData.geometries;
  67339. if (geometries !== undefined && geometries !== null) {
  67340. var addedGeometry = new Array();
  67341. // Boxes
  67342. var boxes = geometries.boxes;
  67343. if (boxes !== undefined && boxes !== null) {
  67344. for (index = 0, cache = boxes.length; index < cache; index++) {
  67345. var parsedBox = boxes[index];
  67346. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67347. }
  67348. }
  67349. // Spheres
  67350. var spheres = geometries.spheres;
  67351. if (spheres !== undefined && spheres !== null) {
  67352. for (index = 0, cache = spheres.length; index < cache; index++) {
  67353. var parsedSphere = spheres[index];
  67354. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67355. }
  67356. }
  67357. // Cylinders
  67358. var cylinders = geometries.cylinders;
  67359. if (cylinders !== undefined && cylinders !== null) {
  67360. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67361. var parsedCylinder = cylinders[index];
  67362. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67363. }
  67364. }
  67365. // Toruses
  67366. var toruses = geometries.toruses;
  67367. if (toruses !== undefined && toruses !== null) {
  67368. for (index = 0, cache = toruses.length; index < cache; index++) {
  67369. var parsedTorus = toruses[index];
  67370. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67371. }
  67372. }
  67373. // Grounds
  67374. var grounds = geometries.grounds;
  67375. if (grounds !== undefined && grounds !== null) {
  67376. for (index = 0, cache = grounds.length; index < cache; index++) {
  67377. var parsedGround = grounds[index];
  67378. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67379. }
  67380. }
  67381. // Planes
  67382. var planes = geometries.planes;
  67383. if (planes !== undefined && planes !== null) {
  67384. for (index = 0, cache = planes.length; index < cache; index++) {
  67385. var parsedPlane = planes[index];
  67386. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67387. }
  67388. }
  67389. // TorusKnots
  67390. var torusKnots = geometries.torusKnots;
  67391. if (torusKnots !== undefined && torusKnots !== null) {
  67392. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67393. var parsedTorusKnot = torusKnots[index];
  67394. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67395. }
  67396. }
  67397. // VertexData
  67398. var vertexData = geometries.vertexData;
  67399. if (vertexData !== undefined && vertexData !== null) {
  67400. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67401. var parsedVertexData = vertexData[index];
  67402. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67403. }
  67404. }
  67405. addedGeometry.forEach(function (g) {
  67406. if (g) {
  67407. container.geometries.push(g);
  67408. }
  67409. });
  67410. }
  67411. // Transform nodes
  67412. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67413. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67414. var parsedTransformNode = parsedData.transformNodes[index];
  67415. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67416. container.transformNodes.push(node);
  67417. }
  67418. }
  67419. // Meshes
  67420. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67421. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67422. var parsedMesh = parsedData.meshes[index];
  67423. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67424. container.meshes.push(mesh);
  67425. log += (index === 0 ? "\n\tMeshes:" : "");
  67426. log += "\n\t\t" + mesh.toString(fullDetails);
  67427. }
  67428. }
  67429. // Cameras
  67430. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67431. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67432. var parsedCamera = parsedData.cameras[index];
  67433. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67434. container.cameras.push(camera);
  67435. log += (index === 0 ? "\n\tCameras:" : "");
  67436. log += "\n\t\t" + camera.toString(fullDetails);
  67437. }
  67438. }
  67439. // Browsing all the graph to connect the dots
  67440. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67441. var camera = scene.cameras[index];
  67442. if (camera._waitingParentId) {
  67443. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67444. camera._waitingParentId = null;
  67445. }
  67446. }
  67447. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67448. var light_1 = scene.lights[index];
  67449. if (light_1 && light_1._waitingParentId) {
  67450. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67451. light_1._waitingParentId = null;
  67452. }
  67453. }
  67454. // Sounds
  67455. // TODO: add sound
  67456. var loadedSounds = [];
  67457. var loadedSound;
  67458. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67459. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67460. var parsedSound = parsedData.sounds[index];
  67461. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67462. if (!parsedSound.url)
  67463. parsedSound.url = parsedSound.name;
  67464. if (!loadedSounds[parsedSound.url]) {
  67465. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67466. loadedSounds[parsedSound.url] = loadedSound;
  67467. container.sounds.push(loadedSound);
  67468. }
  67469. else {
  67470. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67471. }
  67472. }
  67473. else {
  67474. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67475. }
  67476. }
  67477. }
  67478. loadedSounds = [];
  67479. // Connect parents & children and parse actions
  67480. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67481. var transformNode = scene.transformNodes[index];
  67482. if (transformNode._waitingParentId) {
  67483. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67484. transformNode._waitingParentId = null;
  67485. }
  67486. }
  67487. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67488. var mesh = scene.meshes[index];
  67489. if (mesh._waitingParentId) {
  67490. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67491. mesh._waitingParentId = null;
  67492. }
  67493. if (mesh._waitingActions) {
  67494. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67495. mesh._waitingActions = null;
  67496. }
  67497. }
  67498. // freeze world matrix application
  67499. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67500. var currentMesh = scene.meshes[index];
  67501. if (currentMesh._waitingFreezeWorldMatrix) {
  67502. currentMesh.freezeWorldMatrix();
  67503. currentMesh._waitingFreezeWorldMatrix = null;
  67504. }
  67505. else {
  67506. currentMesh.computeWorldMatrix(true);
  67507. }
  67508. }
  67509. // Particles Systems
  67510. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67511. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67512. var parsedParticleSystem = parsedData.particleSystems[index];
  67513. if (parsedParticleSystem.activeParticleCount) {
  67514. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67515. container.particleSystems.push(ps);
  67516. }
  67517. else {
  67518. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67519. container.particleSystems.push(ps);
  67520. }
  67521. }
  67522. }
  67523. // Lens flares
  67524. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67525. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67526. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67527. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67528. container.lensFlareSystems.push(lf);
  67529. }
  67530. }
  67531. // Shadows
  67532. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67533. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67534. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67535. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67536. container.shadowGenerators.push(sg);
  67537. }
  67538. }
  67539. // Lights exclusions / inclusions
  67540. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67541. var light_2 = scene.lights[index];
  67542. // Excluded check
  67543. if (light_2._excludedMeshesIds.length > 0) {
  67544. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67545. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67546. if (excludedMesh) {
  67547. light_2.excludedMeshes.push(excludedMesh);
  67548. }
  67549. }
  67550. light_2._excludedMeshesIds = [];
  67551. }
  67552. // Included check
  67553. if (light_2._includedOnlyMeshesIds.length > 0) {
  67554. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67555. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67556. if (includedOnlyMesh) {
  67557. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67558. }
  67559. }
  67560. light_2._includedOnlyMeshesIds = [];
  67561. }
  67562. }
  67563. // Effect layers
  67564. if (parsedData.effectLayers) {
  67565. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67566. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67567. container.effectLayers.push(effectLayer);
  67568. }
  67569. }
  67570. // Actions (scene)
  67571. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67572. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67573. }
  67574. if (!addToScene) {
  67575. container.removeAllFromScene();
  67576. }
  67577. }
  67578. catch (err) {
  67579. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67580. if (onError) {
  67581. onError(msg, err);
  67582. }
  67583. else {
  67584. BABYLON.Tools.Log(msg);
  67585. throw err;
  67586. }
  67587. }
  67588. finally {
  67589. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67590. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67591. }
  67592. }
  67593. return container;
  67594. };
  67595. BABYLON.SceneLoader.RegisterPlugin({
  67596. name: "babylon.js",
  67597. extensions: ".babylon",
  67598. canDirectLoad: function (data) {
  67599. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67600. return true;
  67601. }
  67602. return false;
  67603. },
  67604. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67605. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67606. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67607. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67608. // and avoid problems with multiple concurrent .babylon loads.
  67609. var log = "importMesh has failed JSON parse";
  67610. try {
  67611. var parsedData = JSON.parse(data);
  67612. log = "";
  67613. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67614. if (!meshesNames) {
  67615. meshesNames = null;
  67616. }
  67617. else if (!Array.isArray(meshesNames)) {
  67618. meshesNames = [meshesNames];
  67619. }
  67620. var hierarchyIds = new Array();
  67621. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67622. var loadedSkeletonsIds = [];
  67623. var loadedMaterialsIds = [];
  67624. var index;
  67625. var cache;
  67626. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67627. var parsedMesh = parsedData.meshes[index];
  67628. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67629. if (meshesNames !== null) {
  67630. // Remove found mesh name from list.
  67631. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67632. }
  67633. //Geometry?
  67634. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67635. //does the file contain geometries?
  67636. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67637. //find the correct geometry and add it to the scene
  67638. var found = false;
  67639. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67640. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67641. return;
  67642. }
  67643. else {
  67644. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67645. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67646. switch (geometryType) {
  67647. case "boxes":
  67648. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67649. break;
  67650. case "spheres":
  67651. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67652. break;
  67653. case "cylinders":
  67654. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67655. break;
  67656. case "toruses":
  67657. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67658. break;
  67659. case "grounds":
  67660. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67661. break;
  67662. case "planes":
  67663. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67664. break;
  67665. case "torusKnots":
  67666. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67667. break;
  67668. case "vertexData":
  67669. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67670. break;
  67671. }
  67672. found = true;
  67673. }
  67674. });
  67675. }
  67676. });
  67677. if (found === false) {
  67678. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67679. }
  67680. }
  67681. }
  67682. // Material ?
  67683. if (parsedMesh.materialId) {
  67684. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67685. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67686. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67687. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67688. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67689. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67690. var subMatId = parsedMultiMaterial.materials[matIndex];
  67691. loadedMaterialsIds.push(subMatId);
  67692. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67693. if (mat) {
  67694. log += "\n\tMaterial " + mat.toString(fullDetails);
  67695. }
  67696. }
  67697. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67698. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67699. if (mmat) {
  67700. materialFound = true;
  67701. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67702. }
  67703. break;
  67704. }
  67705. }
  67706. }
  67707. if (materialFound === false) {
  67708. loadedMaterialsIds.push(parsedMesh.materialId);
  67709. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67710. if (!mat) {
  67711. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67712. }
  67713. else {
  67714. log += "\n\tMaterial " + mat.toString(fullDetails);
  67715. }
  67716. }
  67717. }
  67718. // Skeleton ?
  67719. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67720. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67721. if (skeletonAlreadyLoaded === false) {
  67722. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67723. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67724. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67725. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67726. skeletons.push(skeleton);
  67727. loadedSkeletonsIds.push(parsedSkeleton.id);
  67728. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67729. }
  67730. }
  67731. }
  67732. }
  67733. // Morph targets ?
  67734. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67735. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67736. var managerData = _a[_i];
  67737. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67738. }
  67739. }
  67740. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67741. meshes.push(mesh);
  67742. log += "\n\tMesh " + mesh.toString(fullDetails);
  67743. }
  67744. }
  67745. // Connecting parents
  67746. var currentMesh;
  67747. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67748. currentMesh = scene.meshes[index];
  67749. if (currentMesh._waitingParentId) {
  67750. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67751. currentMesh._waitingParentId = null;
  67752. }
  67753. }
  67754. // freeze and compute world matrix application
  67755. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67756. currentMesh = scene.meshes[index];
  67757. if (currentMesh._waitingFreezeWorldMatrix) {
  67758. currentMesh.freezeWorldMatrix();
  67759. currentMesh._waitingFreezeWorldMatrix = null;
  67760. }
  67761. else {
  67762. currentMesh.computeWorldMatrix(true);
  67763. }
  67764. }
  67765. }
  67766. // Particles
  67767. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67768. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67769. var parsedParticleSystem = parsedData.particleSystems[index];
  67770. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67771. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67772. }
  67773. }
  67774. }
  67775. return true;
  67776. }
  67777. catch (err) {
  67778. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67779. if (onError) {
  67780. onError(msg, err);
  67781. }
  67782. else {
  67783. BABYLON.Tools.Log(msg);
  67784. throw err;
  67785. }
  67786. }
  67787. finally {
  67788. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67789. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67790. }
  67791. }
  67792. return false;
  67793. },
  67794. load: function (scene, data, rootUrl, onError) {
  67795. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67796. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67797. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67798. // and avoid problems with multiple concurrent .babylon loads.
  67799. var log = "importScene has failed JSON parse";
  67800. try {
  67801. var parsedData = JSON.parse(data);
  67802. log = "";
  67803. // Scene
  67804. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  67805. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  67806. }
  67807. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  67808. scene.autoClear = parsedData.autoClear;
  67809. }
  67810. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  67811. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  67812. }
  67813. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  67814. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  67815. }
  67816. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  67817. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  67818. }
  67819. // Fog
  67820. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  67821. scene.fogMode = parsedData.fogMode;
  67822. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  67823. scene.fogStart = parsedData.fogStart;
  67824. scene.fogEnd = parsedData.fogEnd;
  67825. scene.fogDensity = parsedData.fogDensity;
  67826. log += "\tFog mode for scene: ";
  67827. switch (scene.fogMode) {
  67828. // getters not compiling, so using hardcoded
  67829. case 1:
  67830. log += "exp\n";
  67831. break;
  67832. case 2:
  67833. log += "exp2\n";
  67834. break;
  67835. case 3:
  67836. log += "linear\n";
  67837. break;
  67838. }
  67839. }
  67840. //Physics
  67841. if (parsedData.physicsEnabled) {
  67842. var physicsPlugin;
  67843. if (parsedData.physicsEngine === "cannon") {
  67844. physicsPlugin = new BABYLON.CannonJSPlugin();
  67845. }
  67846. else if (parsedData.physicsEngine === "oimo") {
  67847. physicsPlugin = new BABYLON.OimoJSPlugin();
  67848. }
  67849. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  67850. //else - default engine, which is currently oimo
  67851. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  67852. scene.enablePhysics(physicsGravity, physicsPlugin);
  67853. }
  67854. // Metadata
  67855. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  67856. scene.metadata = parsedData.metadata;
  67857. }
  67858. //collisions, if defined. otherwise, default is true
  67859. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  67860. scene.collisionsEnabled = parsedData.collisionsEnabled;
  67861. }
  67862. scene.workerCollisions = !!parsedData.workerCollisions;
  67863. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  67864. if (!container) {
  67865. return false;
  67866. }
  67867. if (parsedData.autoAnimate) {
  67868. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  67869. }
  67870. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  67871. scene.setActiveCameraByID(parsedData.activeCameraID);
  67872. }
  67873. // Environment texture
  67874. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  67875. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  67876. if (parsedData.createDefaultSkybox === true) {
  67877. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  67878. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  67879. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  67880. }
  67881. }
  67882. // Finish
  67883. return true;
  67884. }
  67885. catch (err) {
  67886. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  67887. if (onError) {
  67888. onError(msg, err);
  67889. }
  67890. else {
  67891. BABYLON.Tools.Log(msg);
  67892. throw err;
  67893. }
  67894. }
  67895. finally {
  67896. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67897. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67898. }
  67899. }
  67900. return false;
  67901. },
  67902. loadAssetContainer: function (scene, data, rootUrl, onError) {
  67903. var container = loadAssetContainer(scene, data, rootUrl, onError);
  67904. return container;
  67905. }
  67906. });
  67907. })(BABYLON || (BABYLON = {}));
  67908. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  67909. var BABYLON;
  67910. (function (BABYLON) {
  67911. var FilesInput = /** @class */ (function () {
  67912. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  67913. this.onProcessFileCallback = function () { return true; };
  67914. this._engine = engine;
  67915. this._currentScene = scene;
  67916. this._sceneLoadedCallback = sceneLoadedCallback;
  67917. this._progressCallback = progressCallback;
  67918. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  67919. this._textureLoadingCallback = textureLoadingCallback;
  67920. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  67921. this._onReloadCallback = onReloadCallback;
  67922. this._errorCallback = errorCallback;
  67923. }
  67924. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  67925. var _this = this;
  67926. if (elementToMonitor) {
  67927. this._elementToMonitor = elementToMonitor;
  67928. this._dragEnterHandler = function (e) { _this.drag(e); };
  67929. this._dragOverHandler = function (e) { _this.drag(e); };
  67930. this._dropHandler = function (e) { _this.drop(e); };
  67931. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  67932. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  67933. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  67934. }
  67935. };
  67936. FilesInput.prototype.dispose = function () {
  67937. if (!this._elementToMonitor) {
  67938. return;
  67939. }
  67940. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  67941. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  67942. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  67943. };
  67944. FilesInput.prototype.renderFunction = function () {
  67945. if (this._additionalRenderLoopLogicCallback) {
  67946. this._additionalRenderLoopLogicCallback();
  67947. }
  67948. if (this._currentScene) {
  67949. if (this._textureLoadingCallback) {
  67950. var remaining = this._currentScene.getWaitingItemsCount();
  67951. if (remaining > 0) {
  67952. this._textureLoadingCallback(remaining);
  67953. }
  67954. }
  67955. this._currentScene.render();
  67956. }
  67957. };
  67958. FilesInput.prototype.drag = function (e) {
  67959. e.stopPropagation();
  67960. e.preventDefault();
  67961. };
  67962. FilesInput.prototype.drop = function (eventDrop) {
  67963. eventDrop.stopPropagation();
  67964. eventDrop.preventDefault();
  67965. this.loadFiles(eventDrop);
  67966. };
  67967. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  67968. var _this = this;
  67969. var reader = folder.createReader();
  67970. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  67971. reader.readEntries(function (entries) {
  67972. remaining.count += entries.length;
  67973. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  67974. var entry = entries_1[_i];
  67975. if (entry.isFile) {
  67976. entry.file(function (file) {
  67977. file.correctName = relativePath + file.name;
  67978. files.push(file);
  67979. if (--remaining.count === 0) {
  67980. callback();
  67981. }
  67982. });
  67983. }
  67984. else if (entry.isDirectory) {
  67985. _this._traverseFolder(entry, files, remaining, callback);
  67986. }
  67987. }
  67988. if (--remaining.count) {
  67989. callback();
  67990. }
  67991. });
  67992. };
  67993. FilesInput.prototype._processFiles = function (files) {
  67994. for (var i = 0; i < files.length; i++) {
  67995. var name = files[i].correctName.toLowerCase();
  67996. var extension = name.split('.').pop();
  67997. if (!this.onProcessFileCallback(files[i], name, extension)) {
  67998. continue;
  67999. }
  68000. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68001. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68002. this._sceneFileToLoad = files[i];
  68003. }
  68004. else {
  68005. FilesInput.FilesToLoad[name] = files[i];
  68006. }
  68007. }
  68008. };
  68009. FilesInput.prototype.loadFiles = function (event) {
  68010. var _this = this;
  68011. if (this._startingProcessingFilesCallback)
  68012. this._startingProcessingFilesCallback();
  68013. // Handling data transfer via drag'n'drop
  68014. if (event && event.dataTransfer && event.dataTransfer.files) {
  68015. this._filesToLoad = event.dataTransfer.files;
  68016. }
  68017. // Handling files from input files
  68018. if (event && event.target && event.target.files) {
  68019. this._filesToLoad = event.target.files;
  68020. }
  68021. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68022. var files_1 = new Array();
  68023. var folders = [];
  68024. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68025. for (var i = 0; i < this._filesToLoad.length; i++) {
  68026. var fileToLoad = this._filesToLoad[i];
  68027. var name_1 = fileToLoad.name.toLowerCase();
  68028. var entry = void 0;
  68029. fileToLoad.correctName = name_1;
  68030. if (items) {
  68031. var item = items[i];
  68032. if (item.getAsEntry) {
  68033. entry = item.getAsEntry();
  68034. }
  68035. else if (item.webkitGetAsEntry) {
  68036. entry = item.webkitGetAsEntry();
  68037. }
  68038. }
  68039. if (!entry) {
  68040. files_1.push(fileToLoad);
  68041. }
  68042. else {
  68043. if (entry.isDirectory) {
  68044. folders.push(entry);
  68045. }
  68046. else {
  68047. files_1.push(fileToLoad);
  68048. }
  68049. }
  68050. }
  68051. if (folders.length === 0) {
  68052. this._processFiles(files_1);
  68053. this._processReload();
  68054. }
  68055. else {
  68056. var remaining = { count: folders.length };
  68057. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68058. var folder = folders_1[_i];
  68059. this._traverseFolder(folder, files_1, remaining, function () {
  68060. _this._processFiles(files_1);
  68061. if (remaining.count === 0) {
  68062. _this._processReload();
  68063. }
  68064. });
  68065. }
  68066. }
  68067. }
  68068. };
  68069. FilesInput.prototype._processReload = function () {
  68070. if (this._onReloadCallback) {
  68071. this._onReloadCallback(this._sceneFileToLoad);
  68072. }
  68073. else {
  68074. this.reload();
  68075. }
  68076. };
  68077. FilesInput.prototype.reload = function () {
  68078. var _this = this;
  68079. // If a scene file has been provided
  68080. if (this._sceneFileToLoad) {
  68081. if (this._currentScene) {
  68082. if (BABYLON.Tools.errorsCount > 0) {
  68083. BABYLON.Tools.ClearLogCache();
  68084. }
  68085. this._engine.stopRenderLoop();
  68086. this._currentScene.dispose();
  68087. }
  68088. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68089. if (_this._progressCallback) {
  68090. _this._progressCallback(progress);
  68091. }
  68092. }).then(function (scene) {
  68093. _this._currentScene = scene;
  68094. if (_this._sceneLoadedCallback) {
  68095. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68096. }
  68097. // Wait for textures and shaders to be ready
  68098. _this._currentScene.executeWhenReady(function () {
  68099. _this._engine.runRenderLoop(function () {
  68100. _this.renderFunction();
  68101. });
  68102. });
  68103. }).catch(function (error) {
  68104. if (_this._errorCallback) {
  68105. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68106. }
  68107. });
  68108. }
  68109. else {
  68110. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68111. }
  68112. };
  68113. FilesInput.FilesToLoad = {};
  68114. return FilesInput;
  68115. }());
  68116. BABYLON.FilesInput = FilesInput;
  68117. })(BABYLON || (BABYLON = {}));
  68118. //# sourceMappingURL=babylon.filesInput.js.map
  68119. var BABYLON;
  68120. (function (BABYLON) {
  68121. /**
  68122. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68123. * The underlying implementation relies on an associative array to ensure the best performances.
  68124. * The value can be anything including 'null' but except 'undefined'
  68125. */
  68126. var StringDictionary = /** @class */ (function () {
  68127. function StringDictionary() {
  68128. this._count = 0;
  68129. this._data = {};
  68130. }
  68131. /**
  68132. * This will clear this dictionary and copy the content from the 'source' one.
  68133. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68134. * @param source the dictionary to take the content from and copy to this dictionary
  68135. */
  68136. StringDictionary.prototype.copyFrom = function (source) {
  68137. var _this = this;
  68138. this.clear();
  68139. source.forEach(function (t, v) { return _this.add(t, v); });
  68140. };
  68141. /**
  68142. * Get a value based from its key
  68143. * @param key the given key to get the matching value from
  68144. * @return the value if found, otherwise undefined is returned
  68145. */
  68146. StringDictionary.prototype.get = function (key) {
  68147. var val = this._data[key];
  68148. if (val !== undefined) {
  68149. return val;
  68150. }
  68151. return undefined;
  68152. };
  68153. /**
  68154. * Get a value from its key or add it if it doesn't exist.
  68155. * This method will ensure you that a given key/data will be present in the dictionary.
  68156. * @param key the given key to get the matching value from
  68157. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68158. * The factory will only be invoked if there's no data for the given key.
  68159. * @return the value corresponding to the key.
  68160. */
  68161. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68162. var val = this.get(key);
  68163. if (val !== undefined) {
  68164. return val;
  68165. }
  68166. val = factory(key);
  68167. if (val) {
  68168. this.add(key, val);
  68169. }
  68170. return val;
  68171. };
  68172. /**
  68173. * Get a value from its key if present in the dictionary otherwise add it
  68174. * @param key the key to get the value from
  68175. * @param val if there's no such key/value pair in the dictionary add it with this value
  68176. * @return the value corresponding to the key
  68177. */
  68178. StringDictionary.prototype.getOrAdd = function (key, val) {
  68179. var curVal = this.get(key);
  68180. if (curVal !== undefined) {
  68181. return curVal;
  68182. }
  68183. this.add(key, val);
  68184. return val;
  68185. };
  68186. /**
  68187. * Check if there's a given key in the dictionary
  68188. * @param key the key to check for
  68189. * @return true if the key is present, false otherwise
  68190. */
  68191. StringDictionary.prototype.contains = function (key) {
  68192. return this._data[key] !== undefined;
  68193. };
  68194. /**
  68195. * Add a new key and its corresponding value
  68196. * @param key the key to add
  68197. * @param value the value corresponding to the key
  68198. * @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
  68199. */
  68200. StringDictionary.prototype.add = function (key, value) {
  68201. if (this._data[key] !== undefined) {
  68202. return false;
  68203. }
  68204. this._data[key] = value;
  68205. ++this._count;
  68206. return true;
  68207. };
  68208. StringDictionary.prototype.set = function (key, value) {
  68209. if (this._data[key] === undefined) {
  68210. return false;
  68211. }
  68212. this._data[key] = value;
  68213. return true;
  68214. };
  68215. /**
  68216. * Get the element of the given key and remove it from the dictionary
  68217. * @param key
  68218. */
  68219. StringDictionary.prototype.getAndRemove = function (key) {
  68220. var val = this.get(key);
  68221. if (val !== undefined) {
  68222. delete this._data[key];
  68223. --this._count;
  68224. return val;
  68225. }
  68226. return null;
  68227. };
  68228. /**
  68229. * Remove a key/value from the dictionary.
  68230. * @param key the key to remove
  68231. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68232. */
  68233. StringDictionary.prototype.remove = function (key) {
  68234. if (this.contains(key)) {
  68235. delete this._data[key];
  68236. --this._count;
  68237. return true;
  68238. }
  68239. return false;
  68240. };
  68241. /**
  68242. * Clear the whole content of the dictionary
  68243. */
  68244. StringDictionary.prototype.clear = function () {
  68245. this._data = {};
  68246. this._count = 0;
  68247. };
  68248. Object.defineProperty(StringDictionary.prototype, "count", {
  68249. get: function () {
  68250. return this._count;
  68251. },
  68252. enumerable: true,
  68253. configurable: true
  68254. });
  68255. /**
  68256. * Execute a callback on each key/val of the dictionary.
  68257. * Note that you can remove any element in this dictionary in the callback implementation
  68258. * @param callback the callback to execute on a given key/value pair
  68259. */
  68260. StringDictionary.prototype.forEach = function (callback) {
  68261. for (var cur in this._data) {
  68262. var val = this._data[cur];
  68263. callback(cur, val);
  68264. }
  68265. };
  68266. /**
  68267. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68268. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68269. * Note that you can remove any element in this dictionary in the callback implementation
  68270. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68271. */
  68272. StringDictionary.prototype.first = function (callback) {
  68273. for (var cur in this._data) {
  68274. var val = this._data[cur];
  68275. var res = callback(cur, val);
  68276. if (res) {
  68277. return res;
  68278. }
  68279. }
  68280. return null;
  68281. };
  68282. return StringDictionary;
  68283. }());
  68284. BABYLON.StringDictionary = StringDictionary;
  68285. })(BABYLON || (BABYLON = {}));
  68286. //# sourceMappingURL=babylon.stringDictionary.js.map
  68287. var BABYLON;
  68288. (function (BABYLON) {
  68289. var Tags = /** @class */ (function () {
  68290. function Tags() {
  68291. }
  68292. Tags.EnableFor = function (obj) {
  68293. obj._tags = obj._tags || {};
  68294. obj.hasTags = function () {
  68295. return Tags.HasTags(obj);
  68296. };
  68297. obj.addTags = function (tagsString) {
  68298. return Tags.AddTagsTo(obj, tagsString);
  68299. };
  68300. obj.removeTags = function (tagsString) {
  68301. return Tags.RemoveTagsFrom(obj, tagsString);
  68302. };
  68303. obj.matchesTagsQuery = function (tagsQuery) {
  68304. return Tags.MatchesQuery(obj, tagsQuery);
  68305. };
  68306. };
  68307. Tags.DisableFor = function (obj) {
  68308. delete obj._tags;
  68309. delete obj.hasTags;
  68310. delete obj.addTags;
  68311. delete obj.removeTags;
  68312. delete obj.matchesTagsQuery;
  68313. };
  68314. Tags.HasTags = function (obj) {
  68315. if (!obj._tags) {
  68316. return false;
  68317. }
  68318. return !BABYLON.Tools.IsEmpty(obj._tags);
  68319. };
  68320. Tags.GetTags = function (obj, asString) {
  68321. if (asString === void 0) { asString = true; }
  68322. if (!obj._tags) {
  68323. return null;
  68324. }
  68325. if (asString) {
  68326. var tagsArray = [];
  68327. for (var tag in obj._tags) {
  68328. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68329. tagsArray.push(tag);
  68330. }
  68331. }
  68332. return tagsArray.join(" ");
  68333. }
  68334. else {
  68335. return obj._tags;
  68336. }
  68337. };
  68338. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68339. // a tag cannot start with '||', '&&', and '!'
  68340. // it cannot contain whitespaces
  68341. Tags.AddTagsTo = function (obj, tagsString) {
  68342. if (!tagsString) {
  68343. return;
  68344. }
  68345. if (typeof tagsString !== "string") {
  68346. return;
  68347. }
  68348. var tags = tagsString.split(" ");
  68349. tags.forEach(function (tag, index, array) {
  68350. Tags._AddTagTo(obj, tag);
  68351. });
  68352. };
  68353. Tags._AddTagTo = function (obj, tag) {
  68354. tag = tag.trim();
  68355. if (tag === "" || tag === "true" || tag === "false") {
  68356. return;
  68357. }
  68358. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68359. return;
  68360. }
  68361. Tags.EnableFor(obj);
  68362. obj._tags[tag] = true;
  68363. };
  68364. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68365. if (!Tags.HasTags(obj)) {
  68366. return;
  68367. }
  68368. var tags = tagsString.split(" ");
  68369. for (var t in tags) {
  68370. Tags._RemoveTagFrom(obj, tags[t]);
  68371. }
  68372. };
  68373. Tags._RemoveTagFrom = function (obj, tag) {
  68374. delete obj._tags[tag];
  68375. };
  68376. Tags.MatchesQuery = function (obj, tagsQuery) {
  68377. if (tagsQuery === undefined) {
  68378. return true;
  68379. }
  68380. if (tagsQuery === "") {
  68381. return Tags.HasTags(obj);
  68382. }
  68383. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68384. };
  68385. return Tags;
  68386. }());
  68387. BABYLON.Tags = Tags;
  68388. })(BABYLON || (BABYLON = {}));
  68389. //# sourceMappingURL=babylon.tags.js.map
  68390. var BABYLON;
  68391. (function (BABYLON) {
  68392. /**
  68393. * Class used to evalaute queries containing `and` and `or` operators
  68394. */
  68395. var AndOrNotEvaluator = /** @class */ (function () {
  68396. function AndOrNotEvaluator() {
  68397. }
  68398. /**
  68399. * Evaluate a query
  68400. * @param query defines the query to evaluate
  68401. * @param evaluateCallback defines the callback used to filter result
  68402. * @returns true if the query matches
  68403. */
  68404. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68405. if (!query.match(/\([^\(\)]*\)/g)) {
  68406. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68407. }
  68408. else {
  68409. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68410. // remove parenthesis
  68411. r = r.slice(1, r.length - 1);
  68412. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68413. });
  68414. }
  68415. if (query === "true") {
  68416. return true;
  68417. }
  68418. if (query === "false") {
  68419. return false;
  68420. }
  68421. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68422. };
  68423. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68424. evaluateCallback = evaluateCallback || (function (r) {
  68425. return r === "true" ? true : false;
  68426. });
  68427. var result;
  68428. var or = parenthesisContent.split("||");
  68429. for (var i in or) {
  68430. if (or.hasOwnProperty(i)) {
  68431. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68432. var and = ori.split("&&");
  68433. if (and.length > 1) {
  68434. for (var j = 0; j < and.length; ++j) {
  68435. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68436. if (andj !== "true" && andj !== "false") {
  68437. if (andj[0] === "!") {
  68438. result = !evaluateCallback(andj.substring(1));
  68439. }
  68440. else {
  68441. result = evaluateCallback(andj);
  68442. }
  68443. }
  68444. else {
  68445. result = andj === "true" ? true : false;
  68446. }
  68447. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68448. ori = "false";
  68449. break;
  68450. }
  68451. }
  68452. }
  68453. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68454. result = true;
  68455. break;
  68456. }
  68457. // result equals false (or undefined)
  68458. if (ori !== "true" && ori !== "false") {
  68459. if (ori[0] === "!") {
  68460. result = !evaluateCallback(ori.substring(1));
  68461. }
  68462. else {
  68463. result = evaluateCallback(ori);
  68464. }
  68465. }
  68466. else {
  68467. result = ori === "true" ? true : false;
  68468. }
  68469. }
  68470. }
  68471. // the whole parenthesis scope is replaced by 'true' or 'false'
  68472. return result ? "true" : "false";
  68473. };
  68474. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68475. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68476. // remove whitespaces
  68477. r = r.replace(/[\s]/g, function () { return ""; });
  68478. return r.length % 2 ? "!" : "";
  68479. });
  68480. booleanString = booleanString.trim();
  68481. if (booleanString === "!true") {
  68482. booleanString = "false";
  68483. }
  68484. else if (booleanString === "!false") {
  68485. booleanString = "true";
  68486. }
  68487. return booleanString;
  68488. };
  68489. return AndOrNotEvaluator;
  68490. }());
  68491. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68492. })(BABYLON || (BABYLON = {}));
  68493. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68494. var BABYLON;
  68495. (function (BABYLON) {
  68496. /**
  68497. * Class used to enable access to IndexedDB
  68498. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68499. */
  68500. var Database = /** @class */ (function () {
  68501. /**
  68502. * Creates a new Database
  68503. * @param urlToScene defines the url to load the scene
  68504. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68505. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68506. */
  68507. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68508. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68509. var _this = this;
  68510. // Handling various flavors of prefixed version of IndexedDB
  68511. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68512. this.callbackManifestChecked = callbackManifestChecked;
  68513. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68514. this.db = null;
  68515. this._enableSceneOffline = false;
  68516. this._enableTexturesOffline = false;
  68517. this.manifestVersionFound = 0;
  68518. this.mustUpdateRessources = false;
  68519. this.hasReachedQuota = false;
  68520. if (!Database.IDBStorageEnabled) {
  68521. this.callbackManifestChecked(true);
  68522. }
  68523. else {
  68524. if (disableManifestCheck) {
  68525. this._enableSceneOffline = true;
  68526. this._enableTexturesOffline = true;
  68527. this.manifestVersionFound = 1;
  68528. BABYLON.Tools.SetImmediate(function () {
  68529. _this.callbackManifestChecked(true);
  68530. });
  68531. }
  68532. else {
  68533. this._checkManifestFile();
  68534. }
  68535. }
  68536. }
  68537. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68538. /**
  68539. * Gets a boolean indicating if scene must be saved in the database
  68540. */
  68541. get: function () {
  68542. return this._enableSceneOffline;
  68543. },
  68544. enumerable: true,
  68545. configurable: true
  68546. });
  68547. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68548. /**
  68549. * Gets a boolean indicating if textures must be saved in the database
  68550. */
  68551. get: function () {
  68552. return this._enableTexturesOffline;
  68553. },
  68554. enumerable: true,
  68555. configurable: true
  68556. });
  68557. Database.prototype._checkManifestFile = function () {
  68558. var _this = this;
  68559. var noManifestFile = function () {
  68560. _this._enableSceneOffline = false;
  68561. _this._enableTexturesOffline = false;
  68562. _this.callbackManifestChecked(false);
  68563. };
  68564. var timeStampUsed = false;
  68565. var manifestURL = this.currentSceneUrl + ".manifest";
  68566. var xhr = new XMLHttpRequest();
  68567. if (navigator.onLine) {
  68568. // Adding a timestamp to by-pass browsers' cache
  68569. timeStampUsed = true;
  68570. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68571. }
  68572. xhr.open("GET", manifestURL, true);
  68573. xhr.addEventListener("load", function () {
  68574. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68575. try {
  68576. var manifestFile = JSON.parse(xhr.response);
  68577. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68578. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68579. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68580. _this.manifestVersionFound = manifestFile.version;
  68581. }
  68582. if (_this.callbackManifestChecked) {
  68583. _this.callbackManifestChecked(true);
  68584. }
  68585. }
  68586. catch (ex) {
  68587. noManifestFile();
  68588. }
  68589. }
  68590. else {
  68591. noManifestFile();
  68592. }
  68593. }, false);
  68594. xhr.addEventListener("error", function (event) {
  68595. if (timeStampUsed) {
  68596. timeStampUsed = false;
  68597. // Let's retry without the timeStamp
  68598. // It could fail when coupled with HTML5 Offline API
  68599. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68600. xhr.open("GET", retryManifestURL, true);
  68601. xhr.send();
  68602. }
  68603. else {
  68604. noManifestFile();
  68605. }
  68606. }, false);
  68607. try {
  68608. xhr.send();
  68609. }
  68610. catch (ex) {
  68611. BABYLON.Tools.Error("Error on XHR send request.");
  68612. this.callbackManifestChecked(false);
  68613. }
  68614. };
  68615. /**
  68616. * Open the database and make it available
  68617. * @param successCallback defines the callback to call on success
  68618. * @param errorCallback defines the callback to call on error
  68619. */
  68620. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68621. var _this = this;
  68622. var handleError = function () {
  68623. _this.isSupported = false;
  68624. if (errorCallback)
  68625. errorCallback();
  68626. };
  68627. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68628. // Your browser doesn't support IndexedDB
  68629. this.isSupported = false;
  68630. if (errorCallback)
  68631. errorCallback();
  68632. }
  68633. else {
  68634. // If the DB hasn't been opened or created yet
  68635. if (!this.db) {
  68636. this.hasReachedQuota = false;
  68637. this.isSupported = true;
  68638. var request = this.idbFactory.open("babylonjs", 1);
  68639. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68640. request.onerror = function (event) {
  68641. handleError();
  68642. };
  68643. // executes when a version change transaction cannot complete due to other active transactions
  68644. request.onblocked = function (event) {
  68645. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68646. handleError();
  68647. };
  68648. // DB has been opened successfully
  68649. request.onsuccess = function (event) {
  68650. _this.db = request.result;
  68651. successCallback();
  68652. };
  68653. // Initialization of the DB. Creating Scenes & Textures stores
  68654. request.onupgradeneeded = function (event) {
  68655. _this.db = (event.target).result;
  68656. if (_this.db) {
  68657. try {
  68658. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68659. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68660. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68661. }
  68662. catch (ex) {
  68663. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68664. handleError();
  68665. }
  68666. }
  68667. };
  68668. }
  68669. // DB has already been created and opened
  68670. else {
  68671. if (successCallback)
  68672. successCallback();
  68673. }
  68674. }
  68675. };
  68676. /**
  68677. * Loads an image from the database
  68678. * @param url defines the url to load from
  68679. * @param image defines the target DOM image
  68680. */
  68681. Database.prototype.loadImageFromDB = function (url, image) {
  68682. var _this = this;
  68683. var completeURL = Database._ReturnFullUrlLocation(url);
  68684. var saveAndLoadImage = function () {
  68685. if (!_this.hasReachedQuota && _this.db !== null) {
  68686. // the texture is not yet in the DB, let's try to save it
  68687. _this._saveImageIntoDBAsync(completeURL, image);
  68688. }
  68689. // If the texture is not in the DB and we've reached the DB quota limit
  68690. // let's load it directly from the web
  68691. else {
  68692. image.src = url;
  68693. }
  68694. };
  68695. if (!this.mustUpdateRessources) {
  68696. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68697. }
  68698. // First time we're download the images or update requested in the manifest file by a version change
  68699. else {
  68700. saveAndLoadImage();
  68701. }
  68702. };
  68703. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68704. if (this.isSupported && this.db !== null) {
  68705. var texture;
  68706. var transaction = this.db.transaction(["textures"]);
  68707. transaction.onabort = function (event) {
  68708. image.src = url;
  68709. };
  68710. transaction.oncomplete = function (event) {
  68711. var blobTextureURL;
  68712. if (texture) {
  68713. var URL = window.URL || window.webkitURL;
  68714. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68715. image.onerror = function () {
  68716. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68717. image.src = url;
  68718. };
  68719. image.src = blobTextureURL;
  68720. }
  68721. else {
  68722. notInDBCallback();
  68723. }
  68724. };
  68725. var getRequest = transaction.objectStore("textures").get(url);
  68726. getRequest.onsuccess = function (event) {
  68727. texture = (event.target).result;
  68728. };
  68729. getRequest.onerror = function (event) {
  68730. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68731. image.src = url;
  68732. };
  68733. }
  68734. else {
  68735. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68736. image.src = url;
  68737. }
  68738. };
  68739. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68740. var _this = this;
  68741. if (this.isSupported) {
  68742. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68743. var generateBlobUrl = function () {
  68744. var blobTextureURL;
  68745. if (blob) {
  68746. var URL = window.URL || window.webkitURL;
  68747. try {
  68748. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68749. }
  68750. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68751. catch (ex) {
  68752. blobTextureURL = URL.createObjectURL(blob);
  68753. }
  68754. }
  68755. if (blobTextureURL) {
  68756. image.src = blobTextureURL;
  68757. }
  68758. };
  68759. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68760. var xhr = new XMLHttpRequest(), blob;
  68761. xhr.open("GET", url, true);
  68762. xhr.responseType = "blob";
  68763. xhr.addEventListener("load", function () {
  68764. if (xhr.status === 200 && _this.db) {
  68765. // Blob as response (XHR2)
  68766. blob = xhr.response;
  68767. var transaction = _this.db.transaction(["textures"], "readwrite");
  68768. // the transaction could abort because of a QuotaExceededError error
  68769. transaction.onabort = function (event) {
  68770. try {
  68771. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68772. var srcElement = (event.srcElement || event.target);
  68773. var error = srcElement.error;
  68774. if (error && error.name === "QuotaExceededError") {
  68775. _this.hasReachedQuota = true;
  68776. }
  68777. }
  68778. catch (ex) { }
  68779. generateBlobUrl();
  68780. };
  68781. transaction.oncomplete = function (event) {
  68782. generateBlobUrl();
  68783. };
  68784. var newTexture = { textureUrl: url, data: blob };
  68785. try {
  68786. // Put the blob into the dabase
  68787. var addRequest = transaction.objectStore("textures").put(newTexture);
  68788. addRequest.onsuccess = function (event) {
  68789. };
  68790. addRequest.onerror = function (event) {
  68791. generateBlobUrl();
  68792. };
  68793. }
  68794. catch (ex) {
  68795. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  68796. if (ex.code === 25) {
  68797. Database.IsUASupportingBlobStorage = false;
  68798. }
  68799. image.src = url;
  68800. }
  68801. }
  68802. else {
  68803. image.src = url;
  68804. }
  68805. }, false);
  68806. xhr.addEventListener("error", function (event) {
  68807. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  68808. image.src = url;
  68809. }, false);
  68810. xhr.send();
  68811. }
  68812. else {
  68813. image.src = url;
  68814. }
  68815. }
  68816. else {
  68817. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68818. image.src = url;
  68819. }
  68820. };
  68821. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  68822. var _this = this;
  68823. var updateVersion = function () {
  68824. // the version is not yet in the DB or we need to update it
  68825. _this._saveVersionIntoDBAsync(url, versionLoaded);
  68826. };
  68827. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  68828. };
  68829. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  68830. var _this = this;
  68831. if (this.isSupported && this.db) {
  68832. var version;
  68833. try {
  68834. var transaction = this.db.transaction(["versions"]);
  68835. transaction.oncomplete = function (event) {
  68836. if (version) {
  68837. // If the version in the JSON file is > than the version in DB
  68838. if (_this.manifestVersionFound > version.data) {
  68839. _this.mustUpdateRessources = true;
  68840. updateInDBCallback();
  68841. }
  68842. else {
  68843. callback(version.data);
  68844. }
  68845. }
  68846. // version was not found in DB
  68847. else {
  68848. _this.mustUpdateRessources = true;
  68849. updateInDBCallback();
  68850. }
  68851. };
  68852. transaction.onabort = function (event) {
  68853. callback(-1);
  68854. };
  68855. var getRequest = transaction.objectStore("versions").get(url);
  68856. getRequest.onsuccess = function (event) {
  68857. version = (event.target).result;
  68858. };
  68859. getRequest.onerror = function (event) {
  68860. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  68861. callback(-1);
  68862. };
  68863. }
  68864. catch (ex) {
  68865. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  68866. callback(-1);
  68867. }
  68868. }
  68869. else {
  68870. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68871. callback(-1);
  68872. }
  68873. };
  68874. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  68875. var _this = this;
  68876. if (this.isSupported && !this.hasReachedQuota && this.db) {
  68877. try {
  68878. // Open a transaction to the database
  68879. var transaction = this.db.transaction(["versions"], "readwrite");
  68880. // the transaction could abort because of a QuotaExceededError error
  68881. transaction.onabort = function (event) {
  68882. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68883. var error = event.srcElement['error'];
  68884. if (error && error.name === "QuotaExceededError") {
  68885. _this.hasReachedQuota = true;
  68886. }
  68887. }
  68888. catch (ex) { }
  68889. callback(-1);
  68890. };
  68891. transaction.oncomplete = function (event) {
  68892. callback(_this.manifestVersionFound);
  68893. };
  68894. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  68895. // Put the scene into the database
  68896. var addRequest = transaction.objectStore("versions").put(newVersion);
  68897. addRequest.onsuccess = function (event) {
  68898. };
  68899. addRequest.onerror = function (event) {
  68900. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  68901. };
  68902. }
  68903. catch (ex) {
  68904. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  68905. callback(-1);
  68906. }
  68907. }
  68908. else {
  68909. callback(-1);
  68910. }
  68911. };
  68912. /**
  68913. * Loads a file from database
  68914. * @param url defines the URL to load from
  68915. * @param sceneLoaded defines a callback to call on success
  68916. * @param progressCallBack defines a callback to call when progress changed
  68917. * @param errorCallback defines a callback to call on error
  68918. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  68919. */
  68920. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  68921. var _this = this;
  68922. var completeUrl = Database._ReturnFullUrlLocation(url);
  68923. var saveAndLoadFile = function () {
  68924. // the scene is not yet in the DB, let's try to save it
  68925. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  68926. };
  68927. this._checkVersionFromDB(completeUrl, function (version) {
  68928. if (version !== -1) {
  68929. if (!_this.mustUpdateRessources) {
  68930. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  68931. }
  68932. else {
  68933. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  68934. }
  68935. }
  68936. else {
  68937. if (errorCallback) {
  68938. errorCallback();
  68939. }
  68940. }
  68941. });
  68942. };
  68943. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  68944. if (this.isSupported && this.db) {
  68945. var targetStore;
  68946. if (url.indexOf(".babylon") !== -1) {
  68947. targetStore = "scenes";
  68948. }
  68949. else {
  68950. targetStore = "textures";
  68951. }
  68952. var file;
  68953. var transaction = this.db.transaction([targetStore]);
  68954. transaction.oncomplete = function (event) {
  68955. if (file) {
  68956. callback(file.data);
  68957. }
  68958. // file was not found in DB
  68959. else {
  68960. notInDBCallback();
  68961. }
  68962. };
  68963. transaction.onabort = function (event) {
  68964. notInDBCallback();
  68965. };
  68966. var getRequest = transaction.objectStore(targetStore).get(url);
  68967. getRequest.onsuccess = function (event) {
  68968. file = (event.target).result;
  68969. };
  68970. getRequest.onerror = function (event) {
  68971. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  68972. notInDBCallback();
  68973. };
  68974. }
  68975. else {
  68976. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68977. callback();
  68978. }
  68979. };
  68980. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  68981. var _this = this;
  68982. if (this.isSupported) {
  68983. var targetStore;
  68984. if (url.indexOf(".babylon") !== -1) {
  68985. targetStore = "scenes";
  68986. }
  68987. else {
  68988. targetStore = "textures";
  68989. }
  68990. // Create XHR
  68991. var xhr = new XMLHttpRequest();
  68992. var fileData;
  68993. xhr.open("GET", url, true);
  68994. if (useArrayBuffer) {
  68995. xhr.responseType = "arraybuffer";
  68996. }
  68997. if (progressCallback) {
  68998. xhr.onprogress = progressCallback;
  68999. }
  69000. xhr.addEventListener("load", function () {
  69001. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69002. // Blob as response (XHR2)
  69003. //fileData = xhr.responseText;
  69004. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69005. if (!_this.hasReachedQuota && _this.db) {
  69006. // Open a transaction to the database
  69007. var transaction = _this.db.transaction([targetStore], "readwrite");
  69008. // the transaction could abort because of a QuotaExceededError error
  69009. transaction.onabort = function (event) {
  69010. try {
  69011. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69012. var error = event.srcElement['error'];
  69013. if (error && error.name === "QuotaExceededError") {
  69014. _this.hasReachedQuota = true;
  69015. }
  69016. }
  69017. catch (ex) { }
  69018. callback(fileData);
  69019. };
  69020. transaction.oncomplete = function (event) {
  69021. callback(fileData);
  69022. };
  69023. var newFile;
  69024. if (targetStore === "scenes") {
  69025. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69026. }
  69027. else {
  69028. newFile = { textureUrl: url, data: fileData };
  69029. }
  69030. try {
  69031. // Put the scene into the database
  69032. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69033. addRequest.onsuccess = function (event) {
  69034. };
  69035. addRequest.onerror = function (event) {
  69036. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69037. };
  69038. }
  69039. catch (ex) {
  69040. callback(fileData);
  69041. }
  69042. }
  69043. else {
  69044. callback(fileData);
  69045. }
  69046. }
  69047. else {
  69048. callback();
  69049. }
  69050. }, false);
  69051. xhr.addEventListener("error", function (event) {
  69052. BABYLON.Tools.Error("error on XHR request.");
  69053. callback();
  69054. }, false);
  69055. xhr.send();
  69056. }
  69057. else {
  69058. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69059. callback();
  69060. }
  69061. };
  69062. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69063. Database.IsUASupportingBlobStorage = true;
  69064. /** Gets a boolean indicating if Database storate is enabled */
  69065. Database.IDBStorageEnabled = true;
  69066. Database._ParseURL = function (url) {
  69067. var a = document.createElement('a');
  69068. a.href = url;
  69069. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69070. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69071. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69072. return absLocation;
  69073. };
  69074. Database._ReturnFullUrlLocation = function (url) {
  69075. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69076. return (Database._ParseURL(window.location.href) + url);
  69077. }
  69078. else {
  69079. return url;
  69080. }
  69081. };
  69082. return Database;
  69083. }());
  69084. BABYLON.Database = Database;
  69085. })(BABYLON || (BABYLON = {}));
  69086. //# sourceMappingURL=babylon.database.js.map
  69087. var BABYLON;
  69088. (function (BABYLON) {
  69089. var FresnelParameters = /** @class */ (function () {
  69090. function FresnelParameters() {
  69091. this._isEnabled = true;
  69092. this.leftColor = BABYLON.Color3.White();
  69093. this.rightColor = BABYLON.Color3.Black();
  69094. this.bias = 0;
  69095. this.power = 1;
  69096. }
  69097. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69098. get: function () {
  69099. return this._isEnabled;
  69100. },
  69101. set: function (value) {
  69102. if (this._isEnabled === value) {
  69103. return;
  69104. }
  69105. this._isEnabled = value;
  69106. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69107. },
  69108. enumerable: true,
  69109. configurable: true
  69110. });
  69111. FresnelParameters.prototype.clone = function () {
  69112. var newFresnelParameters = new FresnelParameters();
  69113. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69114. return newFresnelParameters;
  69115. };
  69116. FresnelParameters.prototype.serialize = function () {
  69117. var serializationObject = {};
  69118. serializationObject.isEnabled = this.isEnabled;
  69119. serializationObject.leftColor = this.leftColor.asArray();
  69120. serializationObject.rightColor = this.rightColor.asArray();
  69121. serializationObject.bias = this.bias;
  69122. serializationObject.power = this.power;
  69123. return serializationObject;
  69124. };
  69125. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69126. var fresnelParameters = new FresnelParameters();
  69127. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69128. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69129. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69130. fresnelParameters.bias = parsedFresnelParameters.bias;
  69131. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69132. return fresnelParameters;
  69133. };
  69134. return FresnelParameters;
  69135. }());
  69136. BABYLON.FresnelParameters = FresnelParameters;
  69137. })(BABYLON || (BABYLON = {}));
  69138. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69139. var BABYLON;
  69140. (function (BABYLON) {
  69141. var MultiMaterial = /** @class */ (function (_super) {
  69142. __extends(MultiMaterial, _super);
  69143. function MultiMaterial(name, scene) {
  69144. var _this = _super.call(this, name, scene, true) || this;
  69145. scene.multiMaterials.push(_this);
  69146. _this.subMaterials = new Array();
  69147. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69148. return _this;
  69149. }
  69150. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69151. get: function () {
  69152. return this._subMaterials;
  69153. },
  69154. set: function (value) {
  69155. this._subMaterials = value;
  69156. this._hookArray(value);
  69157. },
  69158. enumerable: true,
  69159. configurable: true
  69160. });
  69161. MultiMaterial.prototype._hookArray = function (array) {
  69162. var _this = this;
  69163. var oldPush = array.push;
  69164. array.push = function () {
  69165. var items = [];
  69166. for (var _i = 0; _i < arguments.length; _i++) {
  69167. items[_i] = arguments[_i];
  69168. }
  69169. var result = oldPush.apply(array, items);
  69170. _this._markAllSubMeshesAsTexturesDirty();
  69171. return result;
  69172. };
  69173. var oldSplice = array.splice;
  69174. array.splice = function (index, deleteCount) {
  69175. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69176. _this._markAllSubMeshesAsTexturesDirty();
  69177. return deleted;
  69178. };
  69179. };
  69180. // Properties
  69181. MultiMaterial.prototype.getSubMaterial = function (index) {
  69182. if (index < 0 || index >= this.subMaterials.length) {
  69183. return this.getScene().defaultMaterial;
  69184. }
  69185. return this.subMaterials[index];
  69186. };
  69187. MultiMaterial.prototype.getActiveTextures = function () {
  69188. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69189. if (subMaterial) {
  69190. return subMaterial.getActiveTextures();
  69191. }
  69192. else {
  69193. return [];
  69194. }
  69195. }));
  69196. var _a;
  69197. };
  69198. // Methods
  69199. MultiMaterial.prototype.getClassName = function () {
  69200. return "MultiMaterial";
  69201. };
  69202. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69203. for (var index = 0; index < this.subMaterials.length; index++) {
  69204. var subMaterial = this.subMaterials[index];
  69205. if (subMaterial) {
  69206. if (subMaterial.storeEffectOnSubMeshes) {
  69207. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69208. return false;
  69209. }
  69210. continue;
  69211. }
  69212. if (!subMaterial.isReady(mesh)) {
  69213. return false;
  69214. }
  69215. }
  69216. }
  69217. return true;
  69218. };
  69219. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69220. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69221. for (var index = 0; index < this.subMaterials.length; index++) {
  69222. var subMaterial = null;
  69223. var current = this.subMaterials[index];
  69224. if (cloneChildren && current) {
  69225. subMaterial = current.clone(name + "-" + current.name);
  69226. }
  69227. else {
  69228. subMaterial = this.subMaterials[index];
  69229. }
  69230. newMultiMaterial.subMaterials.push(subMaterial);
  69231. }
  69232. return newMultiMaterial;
  69233. };
  69234. MultiMaterial.prototype.serialize = function () {
  69235. var serializationObject = {};
  69236. serializationObject.name = this.name;
  69237. serializationObject.id = this.id;
  69238. if (BABYLON.Tags) {
  69239. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69240. }
  69241. serializationObject.materials = [];
  69242. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69243. var subMat = this.subMaterials[matIndex];
  69244. if (subMat) {
  69245. serializationObject.materials.push(subMat.id);
  69246. }
  69247. else {
  69248. serializationObject.materials.push(null);
  69249. }
  69250. }
  69251. return serializationObject;
  69252. };
  69253. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69254. var scene = this.getScene();
  69255. if (!scene) {
  69256. return;
  69257. }
  69258. var index = scene.multiMaterials.indexOf(this);
  69259. if (index >= 0) {
  69260. scene.multiMaterials.splice(index, 1);
  69261. }
  69262. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69263. };
  69264. return MultiMaterial;
  69265. }(BABYLON.Material));
  69266. BABYLON.MultiMaterial = MultiMaterial;
  69267. })(BABYLON || (BABYLON = {}));
  69268. //# sourceMappingURL=babylon.multiMaterial.js.map
  69269. var BABYLON;
  69270. (function (BABYLON) {
  69271. var FreeCameraTouchInput = /** @class */ (function () {
  69272. function FreeCameraTouchInput() {
  69273. this._offsetX = null;
  69274. this._offsetY = null;
  69275. this._pointerPressed = new Array();
  69276. this.touchAngularSensibility = 200000.0;
  69277. this.touchMoveSensibility = 250.0;
  69278. }
  69279. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69280. var _this = this;
  69281. var previousPosition = null;
  69282. if (this._pointerInput === undefined) {
  69283. this._onLostFocus = function (evt) {
  69284. _this._offsetX = null;
  69285. _this._offsetY = null;
  69286. };
  69287. this._pointerInput = function (p, s) {
  69288. var evt = p.event;
  69289. if (evt.pointerType === "mouse") {
  69290. return;
  69291. }
  69292. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69293. if (!noPreventDefault) {
  69294. evt.preventDefault();
  69295. }
  69296. _this._pointerPressed.push(evt.pointerId);
  69297. if (_this._pointerPressed.length !== 1) {
  69298. return;
  69299. }
  69300. previousPosition = {
  69301. x: evt.clientX,
  69302. y: evt.clientY
  69303. };
  69304. }
  69305. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69306. if (!noPreventDefault) {
  69307. evt.preventDefault();
  69308. }
  69309. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69310. if (index === -1) {
  69311. return;
  69312. }
  69313. _this._pointerPressed.splice(index, 1);
  69314. if (index != 0) {
  69315. return;
  69316. }
  69317. previousPosition = null;
  69318. _this._offsetX = null;
  69319. _this._offsetY = null;
  69320. }
  69321. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69322. if (!noPreventDefault) {
  69323. evt.preventDefault();
  69324. }
  69325. if (!previousPosition) {
  69326. return;
  69327. }
  69328. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69329. if (index != 0) {
  69330. return;
  69331. }
  69332. _this._offsetX = evt.clientX - previousPosition.x;
  69333. _this._offsetY = -(evt.clientY - previousPosition.y);
  69334. }
  69335. };
  69336. }
  69337. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69338. if (this._onLostFocus) {
  69339. element.addEventListener("blur", this._onLostFocus);
  69340. }
  69341. };
  69342. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69343. if (this._pointerInput && element) {
  69344. if (this._observer) {
  69345. this.camera.getScene().onPointerObservable.remove(this._observer);
  69346. this._observer = null;
  69347. }
  69348. if (this._onLostFocus) {
  69349. element.removeEventListener("blur", this._onLostFocus);
  69350. this._onLostFocus = null;
  69351. }
  69352. this._pointerPressed = [];
  69353. this._offsetX = null;
  69354. this._offsetY = null;
  69355. }
  69356. };
  69357. FreeCameraTouchInput.prototype.checkInputs = function () {
  69358. if (this._offsetX && this._offsetY) {
  69359. var camera = this.camera;
  69360. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69361. if (this._pointerPressed.length > 1) {
  69362. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69363. }
  69364. else {
  69365. var speed = camera._computeLocalCameraSpeed();
  69366. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69367. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69368. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69369. }
  69370. }
  69371. };
  69372. FreeCameraTouchInput.prototype.getClassName = function () {
  69373. return "FreeCameraTouchInput";
  69374. };
  69375. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69376. return "touch";
  69377. };
  69378. __decorate([
  69379. BABYLON.serialize()
  69380. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69381. __decorate([
  69382. BABYLON.serialize()
  69383. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69384. return FreeCameraTouchInput;
  69385. }());
  69386. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69387. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69388. })(BABYLON || (BABYLON = {}));
  69389. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69390. var BABYLON;
  69391. (function (BABYLON) {
  69392. // We're mainly based on the logic defined into the FreeCamera code
  69393. var TouchCamera = /** @class */ (function (_super) {
  69394. __extends(TouchCamera, _super);
  69395. //-- end properties for backward compatibility for inputs
  69396. function TouchCamera(name, position, scene) {
  69397. var _this = _super.call(this, name, position, scene) || this;
  69398. _this.inputs.addTouch();
  69399. _this._setupInputs();
  69400. return _this;
  69401. }
  69402. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69403. //-- Begin properties for backward compatibility for inputs
  69404. get: function () {
  69405. var touch = this.inputs.attached["touch"];
  69406. if (touch)
  69407. return touch.touchAngularSensibility;
  69408. return 0;
  69409. },
  69410. set: function (value) {
  69411. var touch = this.inputs.attached["touch"];
  69412. if (touch)
  69413. touch.touchAngularSensibility = value;
  69414. },
  69415. enumerable: true,
  69416. configurable: true
  69417. });
  69418. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69419. get: function () {
  69420. var touch = this.inputs.attached["touch"];
  69421. if (touch)
  69422. return touch.touchMoveSensibility;
  69423. return 0;
  69424. },
  69425. set: function (value) {
  69426. var touch = this.inputs.attached["touch"];
  69427. if (touch)
  69428. touch.touchMoveSensibility = value;
  69429. },
  69430. enumerable: true,
  69431. configurable: true
  69432. });
  69433. TouchCamera.prototype.getClassName = function () {
  69434. return "TouchCamera";
  69435. };
  69436. TouchCamera.prototype._setupInputs = function () {
  69437. var mouse = this.inputs.attached["mouse"];
  69438. if (mouse) {
  69439. mouse.touchEnabled = false;
  69440. }
  69441. };
  69442. return TouchCamera;
  69443. }(BABYLON.FreeCamera));
  69444. BABYLON.TouchCamera = TouchCamera;
  69445. })(BABYLON || (BABYLON = {}));
  69446. //# sourceMappingURL=babylon.touchCamera.js.map
  69447. var BABYLON;
  69448. (function (BABYLON) {
  69449. var ProceduralTexture = /** @class */ (function (_super) {
  69450. __extends(ProceduralTexture, _super);
  69451. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69452. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69453. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69454. if (isCube === void 0) { isCube = false; }
  69455. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69456. _this.isCube = isCube;
  69457. _this.isEnabled = true;
  69458. _this._currentRefreshId = -1;
  69459. _this._refreshRate = 1;
  69460. _this._vertexBuffers = {};
  69461. _this._uniforms = new Array();
  69462. _this._samplers = new Array();
  69463. _this._textures = {};
  69464. _this._floats = {};
  69465. _this._floatsArrays = {};
  69466. _this._colors3 = {};
  69467. _this._colors4 = {};
  69468. _this._vectors2 = {};
  69469. _this._vectors3 = {};
  69470. _this._matrices = {};
  69471. _this._fallbackTextureUsed = false;
  69472. scene.proceduralTextures.push(_this);
  69473. _this._engine = scene.getEngine();
  69474. _this.name = name;
  69475. _this.isRenderTarget = true;
  69476. _this._size = size;
  69477. _this._generateMipMaps = generateMipMaps;
  69478. _this.setFragment(fragment);
  69479. _this._fallbackTexture = fallbackTexture;
  69480. if (isCube) {
  69481. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69482. _this.setFloat("face", 0);
  69483. }
  69484. else {
  69485. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69486. }
  69487. // VBO
  69488. var vertices = [];
  69489. vertices.push(1, 1);
  69490. vertices.push(-1, 1);
  69491. vertices.push(-1, -1);
  69492. vertices.push(1, -1);
  69493. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69494. _this._createIndexBuffer();
  69495. return _this;
  69496. }
  69497. ProceduralTexture.prototype._createIndexBuffer = function () {
  69498. var engine = this._engine;
  69499. // Indices
  69500. var indices = [];
  69501. indices.push(0);
  69502. indices.push(1);
  69503. indices.push(2);
  69504. indices.push(0);
  69505. indices.push(2);
  69506. indices.push(3);
  69507. this._indexBuffer = engine.createIndexBuffer(indices);
  69508. };
  69509. ProceduralTexture.prototype._rebuild = function () {
  69510. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69511. if (vb) {
  69512. vb._rebuild();
  69513. }
  69514. this._createIndexBuffer();
  69515. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69516. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69517. }
  69518. };
  69519. ProceduralTexture.prototype.reset = function () {
  69520. if (this._effect === undefined) {
  69521. return;
  69522. }
  69523. var engine = this._engine;
  69524. engine._releaseEffect(this._effect);
  69525. };
  69526. ProceduralTexture.prototype.isReady = function () {
  69527. var _this = this;
  69528. var engine = this._engine;
  69529. var shaders;
  69530. if (!this._fragment) {
  69531. return false;
  69532. }
  69533. if (this._fallbackTextureUsed) {
  69534. return true;
  69535. }
  69536. if (this._fragment.fragmentElement !== undefined) {
  69537. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69538. }
  69539. else {
  69540. shaders = { vertex: "procedural", fragment: this._fragment };
  69541. }
  69542. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69543. _this.releaseInternalTexture();
  69544. if (_this._fallbackTexture) {
  69545. _this._texture = _this._fallbackTexture._texture;
  69546. if (_this._texture) {
  69547. _this._texture.incrementReferences();
  69548. }
  69549. }
  69550. _this._fallbackTextureUsed = true;
  69551. });
  69552. return this._effect.isReady();
  69553. };
  69554. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69555. this._currentRefreshId = -1;
  69556. };
  69557. ProceduralTexture.prototype.setFragment = function (fragment) {
  69558. this._fragment = fragment;
  69559. };
  69560. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69561. get: function () {
  69562. return this._refreshRate;
  69563. },
  69564. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69565. set: function (value) {
  69566. this._refreshRate = value;
  69567. this.resetRefreshCounter();
  69568. },
  69569. enumerable: true,
  69570. configurable: true
  69571. });
  69572. ProceduralTexture.prototype._shouldRender = function () {
  69573. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69574. return false;
  69575. }
  69576. if (this._fallbackTextureUsed) {
  69577. return false;
  69578. }
  69579. if (this._currentRefreshId === -1) { // At least render once
  69580. this._currentRefreshId = 1;
  69581. return true;
  69582. }
  69583. if (this.refreshRate === this._currentRefreshId) {
  69584. this._currentRefreshId = 1;
  69585. return true;
  69586. }
  69587. this._currentRefreshId++;
  69588. return false;
  69589. };
  69590. ProceduralTexture.prototype.getRenderSize = function () {
  69591. return this._size;
  69592. };
  69593. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69594. if (this._fallbackTextureUsed) {
  69595. return;
  69596. }
  69597. this.releaseInternalTexture();
  69598. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69599. };
  69600. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69601. if (this._uniforms.indexOf(uniformName) === -1) {
  69602. this._uniforms.push(uniformName);
  69603. }
  69604. };
  69605. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69606. if (this._samplers.indexOf(name) === -1) {
  69607. this._samplers.push(name);
  69608. }
  69609. this._textures[name] = texture;
  69610. return this;
  69611. };
  69612. ProceduralTexture.prototype.setFloat = function (name, value) {
  69613. this._checkUniform(name);
  69614. this._floats[name] = value;
  69615. return this;
  69616. };
  69617. ProceduralTexture.prototype.setFloats = function (name, value) {
  69618. this._checkUniform(name);
  69619. this._floatsArrays[name] = value;
  69620. return this;
  69621. };
  69622. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69623. this._checkUniform(name);
  69624. this._colors3[name] = value;
  69625. return this;
  69626. };
  69627. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69628. this._checkUniform(name);
  69629. this._colors4[name] = value;
  69630. return this;
  69631. };
  69632. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69633. this._checkUniform(name);
  69634. this._vectors2[name] = value;
  69635. return this;
  69636. };
  69637. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69638. this._checkUniform(name);
  69639. this._vectors3[name] = value;
  69640. return this;
  69641. };
  69642. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69643. this._checkUniform(name);
  69644. this._matrices[name] = value;
  69645. return this;
  69646. };
  69647. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69648. var scene = this.getScene();
  69649. if (!scene) {
  69650. return;
  69651. }
  69652. var engine = this._engine;
  69653. // Render
  69654. engine.enableEffect(this._effect);
  69655. engine.setState(false);
  69656. // Texture
  69657. for (var name in this._textures) {
  69658. this._effect.setTexture(name, this._textures[name]);
  69659. }
  69660. // Float
  69661. for (name in this._floats) {
  69662. this._effect.setFloat(name, this._floats[name]);
  69663. }
  69664. // Floats
  69665. for (name in this._floatsArrays) {
  69666. this._effect.setArray(name, this._floatsArrays[name]);
  69667. }
  69668. // Color3
  69669. for (name in this._colors3) {
  69670. this._effect.setColor3(name, this._colors3[name]);
  69671. }
  69672. // Color4
  69673. for (name in this._colors4) {
  69674. var color = this._colors4[name];
  69675. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69676. }
  69677. // Vector2
  69678. for (name in this._vectors2) {
  69679. this._effect.setVector2(name, this._vectors2[name]);
  69680. }
  69681. // Vector3
  69682. for (name in this._vectors3) {
  69683. this._effect.setVector3(name, this._vectors3[name]);
  69684. }
  69685. // Matrix
  69686. for (name in this._matrices) {
  69687. this._effect.setMatrix(name, this._matrices[name]);
  69688. }
  69689. if (!this._texture) {
  69690. return;
  69691. }
  69692. if (this.isCube) {
  69693. for (var face = 0; face < 6; face++) {
  69694. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69695. // VBOs
  69696. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69697. this._effect.setFloat("face", face);
  69698. // Clear
  69699. engine.clear(scene.clearColor, true, true, true);
  69700. // Draw order
  69701. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69702. // Mipmaps
  69703. if (face === 5) {
  69704. engine.generateMipMapsForCubemap(this._texture);
  69705. }
  69706. }
  69707. }
  69708. else {
  69709. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69710. // VBOs
  69711. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69712. // Clear
  69713. engine.clear(scene.clearColor, true, true, true);
  69714. // Draw order
  69715. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69716. }
  69717. // Unbind
  69718. engine.unBindFramebuffer(this._texture, this.isCube);
  69719. if (this.onGenerated) {
  69720. this.onGenerated();
  69721. }
  69722. };
  69723. ProceduralTexture.prototype.clone = function () {
  69724. var textureSize = this.getSize();
  69725. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69726. // Base texture
  69727. newTexture.hasAlpha = this.hasAlpha;
  69728. newTexture.level = this.level;
  69729. // RenderTarget Texture
  69730. newTexture.coordinatesMode = this.coordinatesMode;
  69731. return newTexture;
  69732. };
  69733. ProceduralTexture.prototype.dispose = function () {
  69734. var scene = this.getScene();
  69735. if (!scene) {
  69736. return;
  69737. }
  69738. var index = scene.proceduralTextures.indexOf(this);
  69739. if (index >= 0) {
  69740. scene.proceduralTextures.splice(index, 1);
  69741. }
  69742. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69743. if (vertexBuffer) {
  69744. vertexBuffer.dispose();
  69745. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69746. }
  69747. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69748. this._indexBuffer = null;
  69749. }
  69750. _super.prototype.dispose.call(this);
  69751. };
  69752. return ProceduralTexture;
  69753. }(BABYLON.Texture));
  69754. BABYLON.ProceduralTexture = ProceduralTexture;
  69755. })(BABYLON || (BABYLON = {}));
  69756. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69757. var BABYLON;
  69758. (function (BABYLON) {
  69759. var CustomProceduralTexture = /** @class */ (function (_super) {
  69760. __extends(CustomProceduralTexture, _super);
  69761. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69762. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69763. _this._animate = true;
  69764. _this._time = 0;
  69765. _this._texturePath = texturePath;
  69766. //Try to load json
  69767. _this.loadJson(texturePath);
  69768. _this.refreshRate = 1;
  69769. return _this;
  69770. }
  69771. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  69772. var _this = this;
  69773. var noConfigFile = function () {
  69774. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  69775. try {
  69776. _this.setFragment(_this._texturePath);
  69777. }
  69778. catch (ex) {
  69779. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  69780. }
  69781. };
  69782. var configFileUrl = jsonUrl + "/config.json";
  69783. var xhr = new XMLHttpRequest();
  69784. xhr.open("GET", configFileUrl, true);
  69785. xhr.addEventListener("load", function () {
  69786. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69787. try {
  69788. _this._config = JSON.parse(xhr.response);
  69789. _this.updateShaderUniforms();
  69790. _this.updateTextures();
  69791. _this.setFragment(_this._texturePath + "/custom");
  69792. _this._animate = _this._config.animate;
  69793. _this.refreshRate = _this._config.refreshrate;
  69794. }
  69795. catch (ex) {
  69796. noConfigFile();
  69797. }
  69798. }
  69799. else {
  69800. noConfigFile();
  69801. }
  69802. }, false);
  69803. xhr.addEventListener("error", function () {
  69804. noConfigFile();
  69805. }, false);
  69806. try {
  69807. xhr.send();
  69808. }
  69809. catch (ex) {
  69810. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  69811. }
  69812. };
  69813. CustomProceduralTexture.prototype.isReady = function () {
  69814. if (!_super.prototype.isReady.call(this)) {
  69815. return false;
  69816. }
  69817. for (var name in this._textures) {
  69818. var texture = this._textures[name];
  69819. if (!texture.isReady()) {
  69820. return false;
  69821. }
  69822. }
  69823. return true;
  69824. };
  69825. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69826. var scene = this.getScene();
  69827. if (this._animate && scene) {
  69828. this._time += scene.getAnimationRatio() * 0.03;
  69829. this.updateShaderUniforms();
  69830. }
  69831. _super.prototype.render.call(this, useCameraPostProcess);
  69832. };
  69833. CustomProceduralTexture.prototype.updateTextures = function () {
  69834. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  69835. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  69836. }
  69837. };
  69838. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  69839. if (this._config) {
  69840. for (var j = 0; j < this._config.uniforms.length; j++) {
  69841. var uniform = this._config.uniforms[j];
  69842. switch (uniform.type) {
  69843. case "float":
  69844. this.setFloat(uniform.name, uniform.value);
  69845. break;
  69846. case "color3":
  69847. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  69848. break;
  69849. case "color4":
  69850. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  69851. break;
  69852. case "vector2":
  69853. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  69854. break;
  69855. case "vector3":
  69856. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  69857. break;
  69858. }
  69859. }
  69860. }
  69861. this.setFloat("time", this._time);
  69862. };
  69863. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  69864. get: function () {
  69865. return this._animate;
  69866. },
  69867. set: function (value) {
  69868. this._animate = value;
  69869. },
  69870. enumerable: true,
  69871. configurable: true
  69872. });
  69873. return CustomProceduralTexture;
  69874. }(BABYLON.ProceduralTexture));
  69875. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  69876. })(BABYLON || (BABYLON = {}));
  69877. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  69878. var BABYLON;
  69879. (function (BABYLON) {
  69880. var FreeCameraGamepadInput = /** @class */ (function () {
  69881. function FreeCameraGamepadInput() {
  69882. this.gamepadAngularSensibility = 200;
  69883. this.gamepadMoveSensibility = 40;
  69884. // private members
  69885. this._cameraTransform = BABYLON.Matrix.Identity();
  69886. this._deltaTransform = BABYLON.Vector3.Zero();
  69887. this._vector3 = BABYLON.Vector3.Zero();
  69888. this._vector2 = BABYLON.Vector2.Zero();
  69889. }
  69890. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69891. var _this = this;
  69892. var manager = this.camera.getScene().gamepadManager;
  69893. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69894. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69895. // prioritize XBOX gamepads.
  69896. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69897. _this.gamepad = gamepad;
  69898. }
  69899. }
  69900. });
  69901. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69902. if (_this.gamepad === gamepad) {
  69903. _this.gamepad = null;
  69904. }
  69905. });
  69906. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69907. };
  69908. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  69909. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69910. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69911. this.gamepad = null;
  69912. };
  69913. FreeCameraGamepadInput.prototype.checkInputs = function () {
  69914. if (this.gamepad && this.gamepad.leftStick) {
  69915. var camera = this.camera;
  69916. var LSValues = this.gamepad.leftStick;
  69917. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  69918. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69919. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  69920. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  69921. var RSValues = this.gamepad.rightStick;
  69922. if (RSValues) {
  69923. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  69924. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  69925. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  69926. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  69927. }
  69928. else {
  69929. RSValues = { x: 0, y: 0 };
  69930. }
  69931. if (!camera.rotationQuaternion) {
  69932. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  69933. }
  69934. else {
  69935. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  69936. }
  69937. var speed = camera._computeLocalCameraSpeed() * 50.0;
  69938. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  69939. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  69940. camera.cameraDirection.addInPlace(this._deltaTransform);
  69941. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  69942. camera.cameraRotation.addInPlace(this._vector2);
  69943. }
  69944. };
  69945. FreeCameraGamepadInput.prototype.getClassName = function () {
  69946. return "FreeCameraGamepadInput";
  69947. };
  69948. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  69949. return "gamepad";
  69950. };
  69951. __decorate([
  69952. BABYLON.serialize()
  69953. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  69954. __decorate([
  69955. BABYLON.serialize()
  69956. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69957. return FreeCameraGamepadInput;
  69958. }());
  69959. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  69960. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  69961. })(BABYLON || (BABYLON = {}));
  69962. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  69963. var BABYLON;
  69964. (function (BABYLON) {
  69965. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  69966. function ArcRotateCameraGamepadInput() {
  69967. this.gamepadRotationSensibility = 80;
  69968. this.gamepadMoveSensibility = 40;
  69969. }
  69970. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69971. var _this = this;
  69972. var manager = this.camera.getScene().gamepadManager;
  69973. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69974. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69975. // prioritize XBOX gamepads.
  69976. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69977. _this.gamepad = gamepad;
  69978. }
  69979. }
  69980. });
  69981. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69982. if (_this.gamepad === gamepad) {
  69983. _this.gamepad = null;
  69984. }
  69985. });
  69986. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69987. };
  69988. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  69989. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69990. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69991. this.gamepad = null;
  69992. };
  69993. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  69994. if (this.gamepad) {
  69995. var camera = this.camera;
  69996. var RSValues = this.gamepad.rightStick;
  69997. if (RSValues) {
  69998. if (RSValues.x != 0) {
  69999. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70000. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70001. camera.inertialAlphaOffset += normalizedRX;
  70002. }
  70003. }
  70004. if (RSValues.y != 0) {
  70005. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70006. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70007. camera.inertialBetaOffset += normalizedRY;
  70008. }
  70009. }
  70010. }
  70011. var LSValues = this.gamepad.leftStick;
  70012. if (LSValues && LSValues.y != 0) {
  70013. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70014. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70015. this.camera.inertialRadiusOffset -= normalizedLY;
  70016. }
  70017. }
  70018. }
  70019. };
  70020. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70021. return "ArcRotateCameraGamepadInput";
  70022. };
  70023. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70024. return "gamepad";
  70025. };
  70026. __decorate([
  70027. BABYLON.serialize()
  70028. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70029. __decorate([
  70030. BABYLON.serialize()
  70031. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70032. return ArcRotateCameraGamepadInput;
  70033. }());
  70034. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70035. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70036. })(BABYLON || (BABYLON = {}));
  70037. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70038. var BABYLON;
  70039. (function (BABYLON) {
  70040. var GamepadManager = /** @class */ (function () {
  70041. function GamepadManager(_scene) {
  70042. var _this = this;
  70043. this._scene = _scene;
  70044. this._babylonGamepads = [];
  70045. this._oneGamepadConnected = false;
  70046. this._isMonitoring = false;
  70047. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70048. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70049. this._gamepadEventSupported = false;
  70050. }
  70051. else {
  70052. this._gamepadEventSupported = 'GamepadEvent' in window;
  70053. this._gamepadSupport = (navigator.getGamepads ||
  70054. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70055. }
  70056. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70057. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70058. for (var i in _this._babylonGamepads) {
  70059. var gamepad = _this._babylonGamepads[i];
  70060. if (gamepad && gamepad._isConnected) {
  70061. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70062. }
  70063. }
  70064. });
  70065. this._onGamepadConnectedEvent = function (evt) {
  70066. var gamepad = evt.gamepad;
  70067. if (gamepad.index in _this._babylonGamepads) {
  70068. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70069. return;
  70070. }
  70071. }
  70072. var newGamepad;
  70073. if (_this._babylonGamepads[gamepad.index]) {
  70074. newGamepad = _this._babylonGamepads[gamepad.index];
  70075. newGamepad.browserGamepad = gamepad;
  70076. newGamepad._isConnected = true;
  70077. }
  70078. else {
  70079. newGamepad = _this._addNewGamepad(gamepad);
  70080. }
  70081. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70082. _this._startMonitoringGamepads();
  70083. };
  70084. this._onGamepadDisconnectedEvent = function (evt) {
  70085. var gamepad = evt.gamepad;
  70086. // Remove the gamepad from the list of gamepads to monitor.
  70087. for (var i in _this._babylonGamepads) {
  70088. if (_this._babylonGamepads[i].index === gamepad.index) {
  70089. var disconnectedGamepad = _this._babylonGamepads[i];
  70090. disconnectedGamepad._isConnected = false;
  70091. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70092. break;
  70093. }
  70094. }
  70095. };
  70096. if (this._gamepadSupport) {
  70097. //first add already-connected gamepads
  70098. this._updateGamepadObjects();
  70099. if (this._babylonGamepads.length) {
  70100. this._startMonitoringGamepads();
  70101. }
  70102. // Checking if the gamepad connected event is supported (like in Firefox)
  70103. if (this._gamepadEventSupported) {
  70104. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70105. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70106. }
  70107. else {
  70108. this._startMonitoringGamepads();
  70109. }
  70110. }
  70111. }
  70112. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70113. get: function () {
  70114. return this._babylonGamepads;
  70115. },
  70116. enumerable: true,
  70117. configurable: true
  70118. });
  70119. GamepadManager.prototype.getGamepadByType = function (type) {
  70120. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70121. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70122. var gamepad = _a[_i];
  70123. if (gamepad && gamepad.type === type) {
  70124. return gamepad;
  70125. }
  70126. }
  70127. return null;
  70128. };
  70129. GamepadManager.prototype.dispose = function () {
  70130. if (this._gamepadEventSupported) {
  70131. if (this._onGamepadConnectedEvent) {
  70132. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70133. }
  70134. if (this._onGamepadDisconnectedEvent) {
  70135. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70136. }
  70137. this._onGamepadConnectedEvent = null;
  70138. this._onGamepadDisconnectedEvent = null;
  70139. }
  70140. this._babylonGamepads.forEach(function (gamepad) {
  70141. gamepad.dispose();
  70142. });
  70143. this.onGamepadConnectedObservable.clear();
  70144. this.onGamepadDisconnectedObservable.clear();
  70145. this._oneGamepadConnected = false;
  70146. this._stopMonitoringGamepads();
  70147. this._babylonGamepads = [];
  70148. };
  70149. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70150. if (!this._oneGamepadConnected) {
  70151. this._oneGamepadConnected = true;
  70152. }
  70153. var newGamepad;
  70154. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70155. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70156. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70157. }
  70158. // if pose is supported, use the (WebVR) pose enabled controller
  70159. else if (gamepad.pose) {
  70160. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70161. }
  70162. else {
  70163. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70164. }
  70165. this._babylonGamepads[newGamepad.index] = newGamepad;
  70166. return newGamepad;
  70167. };
  70168. GamepadManager.prototype._startMonitoringGamepads = function () {
  70169. if (!this._isMonitoring) {
  70170. this._isMonitoring = true;
  70171. //back-comp
  70172. if (!this._scene) {
  70173. this._checkGamepadsStatus();
  70174. }
  70175. }
  70176. };
  70177. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70178. this._isMonitoring = false;
  70179. };
  70180. GamepadManager.prototype._checkGamepadsStatus = function () {
  70181. var _this = this;
  70182. // Hack to be compatible Chrome
  70183. this._updateGamepadObjects();
  70184. for (var i in this._babylonGamepads) {
  70185. var gamepad = this._babylonGamepads[i];
  70186. if (!gamepad || !gamepad.isConnected) {
  70187. continue;
  70188. }
  70189. gamepad.update();
  70190. }
  70191. if (this._isMonitoring && !this._scene) {
  70192. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70193. }
  70194. };
  70195. // This function is called only on Chrome, which does not properly support
  70196. // connection/disconnection events and forces you to recopy again the gamepad object
  70197. GamepadManager.prototype._updateGamepadObjects = function () {
  70198. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70199. for (var i = 0; i < gamepads.length; i++) {
  70200. var gamepad = gamepads[i];
  70201. if (gamepad) {
  70202. if (!this._babylonGamepads[gamepad.index]) {
  70203. var newGamepad = this._addNewGamepad(gamepad);
  70204. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70205. }
  70206. else {
  70207. // Forced to copy again this object for Chrome for unknown reason
  70208. this._babylonGamepads[i].browserGamepad = gamepad;
  70209. if (!this._babylonGamepads[i].isConnected) {
  70210. this._babylonGamepads[i]._isConnected = true;
  70211. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70212. }
  70213. }
  70214. }
  70215. }
  70216. };
  70217. return GamepadManager;
  70218. }());
  70219. BABYLON.GamepadManager = GamepadManager;
  70220. })(BABYLON || (BABYLON = {}));
  70221. //# sourceMappingURL=babylon.gamepadManager.js.map
  70222. var BABYLON;
  70223. (function (BABYLON) {
  70224. var StickValues = /** @class */ (function () {
  70225. function StickValues(x, y) {
  70226. this.x = x;
  70227. this.y = y;
  70228. }
  70229. return StickValues;
  70230. }());
  70231. BABYLON.StickValues = StickValues;
  70232. var Gamepad = /** @class */ (function () {
  70233. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70234. if (leftStickX === void 0) { leftStickX = 0; }
  70235. if (leftStickY === void 0) { leftStickY = 1; }
  70236. if (rightStickX === void 0) { rightStickX = 2; }
  70237. if (rightStickY === void 0) { rightStickY = 3; }
  70238. this.id = id;
  70239. this.index = index;
  70240. this.browserGamepad = browserGamepad;
  70241. this._isConnected = true;
  70242. this._invertLeftStickY = false;
  70243. this.type = Gamepad.GAMEPAD;
  70244. this._leftStickAxisX = leftStickX;
  70245. this._leftStickAxisY = leftStickY;
  70246. this._rightStickAxisX = rightStickX;
  70247. this._rightStickAxisY = rightStickY;
  70248. if (this.browserGamepad.axes.length >= 2) {
  70249. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70250. }
  70251. if (this.browserGamepad.axes.length >= 4) {
  70252. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70253. }
  70254. }
  70255. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70256. get: function () {
  70257. return this._isConnected;
  70258. },
  70259. enumerable: true,
  70260. configurable: true
  70261. });
  70262. Gamepad.prototype.onleftstickchanged = function (callback) {
  70263. this._onleftstickchanged = callback;
  70264. };
  70265. Gamepad.prototype.onrightstickchanged = function (callback) {
  70266. this._onrightstickchanged = callback;
  70267. };
  70268. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70269. get: function () {
  70270. return this._leftStick;
  70271. },
  70272. set: function (newValues) {
  70273. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70274. this._onleftstickchanged(newValues);
  70275. }
  70276. this._leftStick = newValues;
  70277. },
  70278. enumerable: true,
  70279. configurable: true
  70280. });
  70281. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70282. get: function () {
  70283. return this._rightStick;
  70284. },
  70285. set: function (newValues) {
  70286. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70287. this._onrightstickchanged(newValues);
  70288. }
  70289. this._rightStick = newValues;
  70290. },
  70291. enumerable: true,
  70292. configurable: true
  70293. });
  70294. Gamepad.prototype.update = function () {
  70295. if (this._leftStick) {
  70296. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70297. if (this._invertLeftStickY) {
  70298. this.leftStick.y *= -1;
  70299. }
  70300. }
  70301. if (this._rightStick) {
  70302. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70303. }
  70304. };
  70305. Gamepad.prototype.dispose = function () {
  70306. };
  70307. Gamepad.GAMEPAD = 0;
  70308. Gamepad.GENERIC = 1;
  70309. Gamepad.XBOX = 2;
  70310. Gamepad.POSE_ENABLED = 3;
  70311. return Gamepad;
  70312. }());
  70313. BABYLON.Gamepad = Gamepad;
  70314. var GenericPad = /** @class */ (function (_super) {
  70315. __extends(GenericPad, _super);
  70316. function GenericPad(id, index, browserGamepad) {
  70317. var _this = _super.call(this, id, index, browserGamepad) || this;
  70318. _this.onButtonDownObservable = new BABYLON.Observable();
  70319. _this.onButtonUpObservable = new BABYLON.Observable();
  70320. _this.type = Gamepad.GENERIC;
  70321. _this._buttons = new Array(browserGamepad.buttons.length);
  70322. return _this;
  70323. }
  70324. GenericPad.prototype.onbuttondown = function (callback) {
  70325. this._onbuttondown = callback;
  70326. };
  70327. GenericPad.prototype.onbuttonup = function (callback) {
  70328. this._onbuttonup = callback;
  70329. };
  70330. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70331. if (newValue !== currentValue) {
  70332. if (newValue === 1) {
  70333. if (this._onbuttondown) {
  70334. this._onbuttondown(buttonIndex);
  70335. }
  70336. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70337. }
  70338. if (newValue === 0) {
  70339. if (this._onbuttonup) {
  70340. this._onbuttonup(buttonIndex);
  70341. }
  70342. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70343. }
  70344. }
  70345. return newValue;
  70346. };
  70347. GenericPad.prototype.update = function () {
  70348. _super.prototype.update.call(this);
  70349. for (var index = 0; index < this._buttons.length; index++) {
  70350. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70351. }
  70352. };
  70353. GenericPad.prototype.dispose = function () {
  70354. _super.prototype.dispose.call(this);
  70355. this.onButtonDownObservable.clear();
  70356. this.onButtonUpObservable.clear();
  70357. };
  70358. return GenericPad;
  70359. }(Gamepad));
  70360. BABYLON.GenericPad = GenericPad;
  70361. })(BABYLON || (BABYLON = {}));
  70362. //# sourceMappingURL=babylon.gamepad.js.map
  70363. var BABYLON;
  70364. (function (BABYLON) {
  70365. /**
  70366. * Defines supported buttons for XBox360 compatible gamepads
  70367. */
  70368. var Xbox360Button;
  70369. (function (Xbox360Button) {
  70370. /** A */
  70371. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70372. /** B */
  70373. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70374. /** X */
  70375. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70376. /** Y */
  70377. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70378. /** Start */
  70379. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70380. /** Back */
  70381. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70382. /** Left button */
  70383. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70384. /** Right button */
  70385. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70386. /** Left stick */
  70387. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70388. /** Right stick */
  70389. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70390. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70391. /** Defines values for XBox360 DPad */
  70392. var Xbox360Dpad;
  70393. (function (Xbox360Dpad) {
  70394. /** Up */
  70395. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70396. /** Down */
  70397. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70398. /** Left */
  70399. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70400. /** Right */
  70401. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70402. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70403. /**
  70404. * Defines a XBox360 gamepad
  70405. */
  70406. var Xbox360Pad = /** @class */ (function (_super) {
  70407. __extends(Xbox360Pad, _super);
  70408. /**
  70409. * Creates a new XBox360 gamepad object
  70410. * @param id defines the id of this gamepad
  70411. * @param index defines its index
  70412. * @param gamepad defines the internal HTML gamepad object
  70413. * @param xboxOne defines if it is a XBox One gamepad
  70414. */
  70415. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70416. if (xboxOne === void 0) { xboxOne = false; }
  70417. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70418. _this._leftTrigger = 0;
  70419. _this._rightTrigger = 0;
  70420. /** Observable raised when a button is pressed */
  70421. _this.onButtonDownObservable = new BABYLON.Observable();
  70422. /** Observable raised when a button is released */
  70423. _this.onButtonUpObservable = new BABYLON.Observable();
  70424. /** Observable raised when a pad is pressed */
  70425. _this.onPadDownObservable = new BABYLON.Observable();
  70426. /** Observable raised when a pad is released */
  70427. _this.onPadUpObservable = new BABYLON.Observable();
  70428. _this._buttonA = 0;
  70429. _this._buttonB = 0;
  70430. _this._buttonX = 0;
  70431. _this._buttonY = 0;
  70432. _this._buttonBack = 0;
  70433. _this._buttonStart = 0;
  70434. _this._buttonLB = 0;
  70435. _this._buttonRB = 0;
  70436. _this._buttonLeftStick = 0;
  70437. _this._buttonRightStick = 0;
  70438. _this._dPadUp = 0;
  70439. _this._dPadDown = 0;
  70440. _this._dPadLeft = 0;
  70441. _this._dPadRight = 0;
  70442. _this._isXboxOnePad = false;
  70443. _this.type = BABYLON.Gamepad.XBOX;
  70444. _this._isXboxOnePad = xboxOne;
  70445. return _this;
  70446. }
  70447. /**
  70448. * Defines the callback to call when left trigger is pressed
  70449. * @param callback defines the callback to use
  70450. */
  70451. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70452. this._onlefttriggerchanged = callback;
  70453. };
  70454. /**
  70455. * Defines the callback to call when right trigger is pressed
  70456. * @param callback defines the callback to use
  70457. */
  70458. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70459. this._onrighttriggerchanged = callback;
  70460. };
  70461. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70462. /**
  70463. * Gets or sets left trigger value
  70464. */
  70465. get: function () {
  70466. return this._leftTrigger;
  70467. },
  70468. set: function (newValue) {
  70469. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70470. this._onlefttriggerchanged(newValue);
  70471. }
  70472. this._leftTrigger = newValue;
  70473. },
  70474. enumerable: true,
  70475. configurable: true
  70476. });
  70477. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70478. /**
  70479. * Gets or sets right trigger value
  70480. */
  70481. get: function () {
  70482. return this._rightTrigger;
  70483. },
  70484. set: function (newValue) {
  70485. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70486. this._onrighttriggerchanged(newValue);
  70487. }
  70488. this._rightTrigger = newValue;
  70489. },
  70490. enumerable: true,
  70491. configurable: true
  70492. });
  70493. /**
  70494. * Defines the callback to call when a button is pressed
  70495. * @param callback defines the callback to use
  70496. */
  70497. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70498. this._onbuttondown = callback;
  70499. };
  70500. /**
  70501. * Defines the callback to call when a button is released
  70502. * @param callback defines the callback to use
  70503. */
  70504. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70505. this._onbuttonup = callback;
  70506. };
  70507. /**
  70508. * Defines the callback to call when a pad is pressed
  70509. * @param callback defines the callback to use
  70510. */
  70511. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70512. this._ondpaddown = callback;
  70513. };
  70514. /**
  70515. * Defines the callback to call when a pad is released
  70516. * @param callback defines the callback to use
  70517. */
  70518. Xbox360Pad.prototype.ondpadup = function (callback) {
  70519. this._ondpadup = callback;
  70520. };
  70521. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70522. if (newValue !== currentValue) {
  70523. if (newValue === 1) {
  70524. if (this._onbuttondown) {
  70525. this._onbuttondown(buttonType);
  70526. }
  70527. this.onButtonDownObservable.notifyObservers(buttonType);
  70528. }
  70529. if (newValue === 0) {
  70530. if (this._onbuttonup) {
  70531. this._onbuttonup(buttonType);
  70532. }
  70533. this.onButtonUpObservable.notifyObservers(buttonType);
  70534. }
  70535. }
  70536. return newValue;
  70537. };
  70538. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70539. if (newValue !== currentValue) {
  70540. if (newValue === 1) {
  70541. if (this._ondpaddown) {
  70542. this._ondpaddown(buttonType);
  70543. }
  70544. this.onPadDownObservable.notifyObservers(buttonType);
  70545. }
  70546. if (newValue === 0) {
  70547. if (this._ondpadup) {
  70548. this._ondpadup(buttonType);
  70549. }
  70550. this.onPadUpObservable.notifyObservers(buttonType);
  70551. }
  70552. }
  70553. return newValue;
  70554. };
  70555. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70556. /** Gets or sets value of A button */
  70557. get: function () {
  70558. return this._buttonA;
  70559. },
  70560. set: function (value) {
  70561. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70562. },
  70563. enumerable: true,
  70564. configurable: true
  70565. });
  70566. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70567. /** Gets or sets value of B button */
  70568. get: function () {
  70569. return this._buttonB;
  70570. },
  70571. set: function (value) {
  70572. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70573. },
  70574. enumerable: true,
  70575. configurable: true
  70576. });
  70577. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70578. /** Gets or sets value of X button */
  70579. get: function () {
  70580. return this._buttonX;
  70581. },
  70582. set: function (value) {
  70583. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70584. },
  70585. enumerable: true,
  70586. configurable: true
  70587. });
  70588. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70589. /** Gets or sets value of Y button */
  70590. get: function () {
  70591. return this._buttonY;
  70592. },
  70593. set: function (value) {
  70594. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70595. },
  70596. enumerable: true,
  70597. configurable: true
  70598. });
  70599. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70600. /** Gets or sets value of Start button */
  70601. get: function () {
  70602. return this._buttonStart;
  70603. },
  70604. set: function (value) {
  70605. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70606. },
  70607. enumerable: true,
  70608. configurable: true
  70609. });
  70610. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70611. /** Gets or sets value of Back button */
  70612. get: function () {
  70613. return this._buttonBack;
  70614. },
  70615. set: function (value) {
  70616. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70617. },
  70618. enumerable: true,
  70619. configurable: true
  70620. });
  70621. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70622. /** Gets or sets value of Left button */
  70623. get: function () {
  70624. return this._buttonLB;
  70625. },
  70626. set: function (value) {
  70627. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70628. },
  70629. enumerable: true,
  70630. configurable: true
  70631. });
  70632. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70633. /** Gets or sets value of Right button */
  70634. get: function () {
  70635. return this._buttonRB;
  70636. },
  70637. set: function (value) {
  70638. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70639. },
  70640. enumerable: true,
  70641. configurable: true
  70642. });
  70643. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70644. /** Gets or sets value of left stick */
  70645. get: function () {
  70646. return this._buttonLeftStick;
  70647. },
  70648. set: function (value) {
  70649. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70650. },
  70651. enumerable: true,
  70652. configurable: true
  70653. });
  70654. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70655. /** Gets or sets value of right stick */
  70656. get: function () {
  70657. return this._buttonRightStick;
  70658. },
  70659. set: function (value) {
  70660. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70661. },
  70662. enumerable: true,
  70663. configurable: true
  70664. });
  70665. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70666. /** Gets or sets value of DPad up */
  70667. get: function () {
  70668. return this._dPadUp;
  70669. },
  70670. set: function (value) {
  70671. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70672. },
  70673. enumerable: true,
  70674. configurable: true
  70675. });
  70676. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70677. /** Gets or sets value of DPad down */
  70678. get: function () {
  70679. return this._dPadDown;
  70680. },
  70681. set: function (value) {
  70682. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70683. },
  70684. enumerable: true,
  70685. configurable: true
  70686. });
  70687. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70688. /** Gets or sets value of DPad left */
  70689. get: function () {
  70690. return this._dPadLeft;
  70691. },
  70692. set: function (value) {
  70693. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70694. },
  70695. enumerable: true,
  70696. configurable: true
  70697. });
  70698. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70699. /** Gets or sets value of DPad right */
  70700. get: function () {
  70701. return this._dPadRight;
  70702. },
  70703. set: function (value) {
  70704. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70705. },
  70706. enumerable: true,
  70707. configurable: true
  70708. });
  70709. /**
  70710. * Force the gamepad to synchronize with device values
  70711. */
  70712. Xbox360Pad.prototype.update = function () {
  70713. _super.prototype.update.call(this);
  70714. if (this._isXboxOnePad) {
  70715. this.buttonA = this.browserGamepad.buttons[0].value;
  70716. this.buttonB = this.browserGamepad.buttons[1].value;
  70717. this.buttonX = this.browserGamepad.buttons[2].value;
  70718. this.buttonY = this.browserGamepad.buttons[3].value;
  70719. this.buttonLB = this.browserGamepad.buttons[4].value;
  70720. this.buttonRB = this.browserGamepad.buttons[5].value;
  70721. this.leftTrigger = this.browserGamepad.axes[2];
  70722. this.rightTrigger = this.browserGamepad.axes[5];
  70723. this.buttonBack = this.browserGamepad.buttons[9].value;
  70724. this.buttonStart = this.browserGamepad.buttons[8].value;
  70725. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70726. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70727. this.dPadUp = this.browserGamepad.buttons[11].value;
  70728. this.dPadDown = this.browserGamepad.buttons[12].value;
  70729. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70730. this.dPadRight = this.browserGamepad.buttons[14].value;
  70731. }
  70732. else {
  70733. this.buttonA = this.browserGamepad.buttons[0].value;
  70734. this.buttonB = this.browserGamepad.buttons[1].value;
  70735. this.buttonX = this.browserGamepad.buttons[2].value;
  70736. this.buttonY = this.browserGamepad.buttons[3].value;
  70737. this.buttonLB = this.browserGamepad.buttons[4].value;
  70738. this.buttonRB = this.browserGamepad.buttons[5].value;
  70739. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70740. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70741. this.buttonBack = this.browserGamepad.buttons[8].value;
  70742. this.buttonStart = this.browserGamepad.buttons[9].value;
  70743. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70744. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70745. this.dPadUp = this.browserGamepad.buttons[12].value;
  70746. this.dPadDown = this.browserGamepad.buttons[13].value;
  70747. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70748. this.dPadRight = this.browserGamepad.buttons[15].value;
  70749. }
  70750. };
  70751. Xbox360Pad.prototype.dispose = function () {
  70752. _super.prototype.dispose.call(this);
  70753. this.onButtonDownObservable.clear();
  70754. this.onButtonUpObservable.clear();
  70755. this.onPadDownObservable.clear();
  70756. this.onPadUpObservable.clear();
  70757. };
  70758. return Xbox360Pad;
  70759. }(BABYLON.Gamepad));
  70760. BABYLON.Xbox360Pad = Xbox360Pad;
  70761. })(BABYLON || (BABYLON = {}));
  70762. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70763. var BABYLON;
  70764. (function (BABYLON) {
  70765. /**
  70766. * Defines the types of pose enabled controllers that are supported
  70767. */
  70768. var PoseEnabledControllerType;
  70769. (function (PoseEnabledControllerType) {
  70770. /**
  70771. * HTC Vive
  70772. */
  70773. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  70774. /**
  70775. * Oculus Rift
  70776. */
  70777. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  70778. /**
  70779. * Windows mixed reality
  70780. */
  70781. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  70782. /**
  70783. * Samsung gear VR
  70784. */
  70785. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  70786. /**
  70787. * Google Daydream
  70788. */
  70789. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  70790. /**
  70791. * Generic
  70792. */
  70793. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  70794. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  70795. /**
  70796. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70797. */
  70798. var PoseEnabledControllerHelper = /** @class */ (function () {
  70799. function PoseEnabledControllerHelper() {
  70800. }
  70801. /**
  70802. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70803. * @param vrGamepad the gamepad to initialized
  70804. * @returns a vr controller of the type the gamepad identified as
  70805. */
  70806. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  70807. // Oculus Touch
  70808. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  70809. return new BABYLON.OculusTouchController(vrGamepad);
  70810. }
  70811. // Windows Mixed Reality controllers
  70812. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  70813. return new BABYLON.WindowsMotionController(vrGamepad);
  70814. }
  70815. // HTC Vive
  70816. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  70817. return new BABYLON.ViveController(vrGamepad);
  70818. }
  70819. // Samsung/Oculus Gear VR
  70820. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  70821. return new BABYLON.GearVRController(vrGamepad);
  70822. }
  70823. // Google Daydream
  70824. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  70825. return new BABYLON.DaydreamController(vrGamepad);
  70826. }
  70827. // Generic
  70828. else {
  70829. return new BABYLON.GenericController(vrGamepad);
  70830. }
  70831. };
  70832. return PoseEnabledControllerHelper;
  70833. }());
  70834. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  70835. /**
  70836. * Defines the PoseEnabledController object that contains state of a vr capable controller
  70837. */
  70838. var PoseEnabledController = /** @class */ (function (_super) {
  70839. __extends(PoseEnabledController, _super);
  70840. /**
  70841. * Creates a new PoseEnabledController from a gamepad
  70842. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  70843. */
  70844. function PoseEnabledController(browserGamepad) {
  70845. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  70846. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  70847. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  70848. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  70849. /**
  70850. * The device position in babylon space
  70851. */
  70852. _this.devicePosition = BABYLON.Vector3.Zero();
  70853. /**
  70854. * The device rotation in babylon space
  70855. */
  70856. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70857. /**
  70858. * The scale factor of the device in babylon space
  70859. */
  70860. _this.deviceScaleFactor = 1;
  70861. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  70862. /**
  70863. * Internal, matrix used to convert room space to babylon space
  70864. */
  70865. _this._deviceToWorld = BABYLON.Matrix.Identity();
  70866. /**
  70867. * Node to be used when casting a ray from the controller
  70868. */
  70869. _this._pointingPoseNode = null;
  70870. _this._workingMatrix = BABYLON.Matrix.Identity();
  70871. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  70872. _this.controllerType = PoseEnabledControllerType.GENERIC;
  70873. _this.position = BABYLON.Vector3.Zero();
  70874. _this.rotationQuaternion = new BABYLON.Quaternion();
  70875. _this._calculatedPosition = BABYLON.Vector3.Zero();
  70876. _this._calculatedRotation = new BABYLON.Quaternion();
  70877. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  70878. return _this;
  70879. }
  70880. /**
  70881. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  70882. */
  70883. PoseEnabledController.prototype.update = function () {
  70884. _super.prototype.update.call(this);
  70885. var pose = this.browserGamepad.pose;
  70886. this.updateFromDevice(pose);
  70887. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  70888. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  70889. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  70890. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  70891. if (this._mesh) {
  70892. this._mesh.position.copyFrom(this.devicePosition);
  70893. if (this._mesh.rotationQuaternion) {
  70894. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70895. }
  70896. }
  70897. };
  70898. /**
  70899. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  70900. * @param poseData raw pose fromthe device
  70901. */
  70902. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  70903. if (poseData) {
  70904. this.rawPose = poseData;
  70905. if (poseData.position) {
  70906. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  70907. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  70908. this._deviceRoomPosition.z *= -1;
  70909. }
  70910. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  70911. this._calculatedPosition.addInPlace(this.position);
  70912. }
  70913. var pose = this.rawPose;
  70914. if (poseData.orientation && pose.orientation) {
  70915. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  70916. if (this._mesh) {
  70917. if (this._mesh.getScene().useRightHandedSystem) {
  70918. this._deviceRoomRotationQuaternion.z *= -1;
  70919. this._deviceRoomRotationQuaternion.w *= -1;
  70920. }
  70921. else {
  70922. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  70923. }
  70924. }
  70925. // if the camera is set, rotate to the camera's rotation
  70926. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  70927. }
  70928. }
  70929. };
  70930. /**
  70931. * Attaches a mesh to the controller
  70932. * @param mesh the mesh to be attached
  70933. */
  70934. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  70935. if (this._mesh) {
  70936. this._mesh.parent = null;
  70937. }
  70938. this._mesh = mesh;
  70939. if (this._poseControlledCamera) {
  70940. this._mesh.parent = this._poseControlledCamera;
  70941. }
  70942. if (!this._mesh.rotationQuaternion) {
  70943. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  70944. }
  70945. };
  70946. /**
  70947. * Attaches the controllers mesh to a camera
  70948. * @param camera the camera the mesh should be attached to
  70949. */
  70950. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  70951. this._poseControlledCamera = camera;
  70952. if (this._mesh) {
  70953. this._mesh.parent = this._poseControlledCamera;
  70954. }
  70955. };
  70956. /**
  70957. * Disposes of the controller
  70958. */
  70959. PoseEnabledController.prototype.dispose = function () {
  70960. if (this._mesh) {
  70961. this._mesh.dispose();
  70962. }
  70963. this._mesh = null;
  70964. _super.prototype.dispose.call(this);
  70965. };
  70966. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  70967. /**
  70968. * The mesh that is attached to the controller
  70969. */
  70970. get: function () {
  70971. return this._mesh;
  70972. },
  70973. enumerable: true,
  70974. configurable: true
  70975. });
  70976. /**
  70977. * Gets the ray of the controller in the direction the controller is pointing
  70978. * @param length the length the resulting ray should be
  70979. * @returns a ray in the direction the controller is pointing
  70980. */
  70981. PoseEnabledController.prototype.getForwardRay = function (length) {
  70982. if (length === void 0) { length = 100; }
  70983. if (!this.mesh) {
  70984. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  70985. }
  70986. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  70987. var origin = m.getTranslation();
  70988. var forward = new BABYLON.Vector3(0, 0, -1);
  70989. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  70990. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  70991. return new BABYLON.Ray(origin, direction, length);
  70992. };
  70993. /**
  70994. * Name of the child mesh that can be used to cast a ray from the controller
  70995. */
  70996. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  70997. return PoseEnabledController;
  70998. }(BABYLON.Gamepad));
  70999. BABYLON.PoseEnabledController = PoseEnabledController;
  71000. })(BABYLON || (BABYLON = {}));
  71001. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71002. var BABYLON;
  71003. (function (BABYLON) {
  71004. /**
  71005. * Defines the WebVRController object that represents controllers tracked in 3D space
  71006. */
  71007. var WebVRController = /** @class */ (function (_super) {
  71008. __extends(WebVRController, _super);
  71009. /**
  71010. * Creates a new WebVRController from a gamepad
  71011. * @param vrGamepad the gamepad that the WebVRController should be created from
  71012. */
  71013. function WebVRController(vrGamepad) {
  71014. var _this = _super.call(this, vrGamepad) || this;
  71015. // Observables
  71016. /**
  71017. * Fired when the trigger state has changed
  71018. */
  71019. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71020. /**
  71021. * Fired when the main button state has changed
  71022. */
  71023. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71024. /**
  71025. * Fired when the secondary button state has changed
  71026. */
  71027. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71028. /**
  71029. * Fired when the pad state has changed
  71030. */
  71031. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71032. /**
  71033. * Fired when controllers stick values have changed
  71034. */
  71035. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71036. /**
  71037. * X and Y axis corrisponding to the controllers joystick
  71038. */
  71039. _this.pad = { x: 0, y: 0 };
  71040. // avoid GC, store state in a tmp object
  71041. _this._changes = {
  71042. pressChanged: false,
  71043. touchChanged: false,
  71044. valueChanged: false,
  71045. changed: false
  71046. };
  71047. _this._buttons = new Array(vrGamepad.buttons.length);
  71048. _this.hand = vrGamepad.hand;
  71049. return _this;
  71050. }
  71051. /**
  71052. * Fired when a controller button's state has changed
  71053. * @param callback the callback containing the button that was modified
  71054. */
  71055. WebVRController.prototype.onButtonStateChange = function (callback) {
  71056. this._onButtonStateChange = callback;
  71057. };
  71058. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71059. /**
  71060. * The default controller model for the controller
  71061. */
  71062. get: function () {
  71063. return this._defaultModel;
  71064. },
  71065. enumerable: true,
  71066. configurable: true
  71067. });
  71068. /**
  71069. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71070. */
  71071. WebVRController.prototype.update = function () {
  71072. _super.prototype.update.call(this);
  71073. for (var index = 0; index < this._buttons.length; index++) {
  71074. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71075. }
  71076. ;
  71077. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71078. this.pad.x = this.leftStick.x;
  71079. this.pad.y = this.leftStick.y;
  71080. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71081. }
  71082. };
  71083. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71084. if (!newState) {
  71085. newState = {
  71086. pressed: false,
  71087. touched: false,
  71088. value: 0
  71089. };
  71090. }
  71091. if (!currentState) {
  71092. this._buttons[buttonIndex] = {
  71093. pressed: newState.pressed,
  71094. touched: newState.touched,
  71095. value: newState.value
  71096. };
  71097. return;
  71098. }
  71099. this._checkChanges(newState, currentState);
  71100. if (this._changes.changed) {
  71101. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71102. this._handleButtonChange(buttonIndex, newState, this._changes);
  71103. }
  71104. this._buttons[buttonIndex].pressed = newState.pressed;
  71105. this._buttons[buttonIndex].touched = newState.touched;
  71106. // oculus triggers are never 0, thou not touched.
  71107. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71108. };
  71109. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71110. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71111. this._changes.touchChanged = newState.touched !== currentState.touched;
  71112. this._changes.valueChanged = newState.value !== currentState.value;
  71113. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71114. return this._changes;
  71115. };
  71116. /**
  71117. * Disposes of th webVRCOntroller
  71118. */
  71119. WebVRController.prototype.dispose = function () {
  71120. _super.prototype.dispose.call(this);
  71121. this.onTriggerStateChangedObservable.clear();
  71122. this.onMainButtonStateChangedObservable.clear();
  71123. this.onSecondaryButtonStateChangedObservable.clear();
  71124. this.onPadStateChangedObservable.clear();
  71125. this.onPadValuesChangedObservable.clear();
  71126. };
  71127. return WebVRController;
  71128. }(BABYLON.PoseEnabledController));
  71129. BABYLON.WebVRController = WebVRController;
  71130. })(BABYLON || (BABYLON = {}));
  71131. //# sourceMappingURL=babylon.webVRController.js.map
  71132. var BABYLON;
  71133. (function (BABYLON) {
  71134. /**
  71135. * Oculus Touch Controller
  71136. */
  71137. var OculusTouchController = /** @class */ (function (_super) {
  71138. __extends(OculusTouchController, _super);
  71139. /**
  71140. * Creates a new OculusTouchController from a gamepad
  71141. * @param vrGamepad the gamepad that the controller should be created from
  71142. */
  71143. function OculusTouchController(vrGamepad) {
  71144. var _this = _super.call(this, vrGamepad) || this;
  71145. /**
  71146. * Fired when the secondary trigger on this controller is modified
  71147. */
  71148. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71149. /**
  71150. * Fired when the thumb rest on this controller is modified
  71151. */
  71152. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71153. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71154. return _this;
  71155. }
  71156. /**
  71157. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71158. * @param scene scene in which to add meshes
  71159. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71160. */
  71161. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71162. var _this = this;
  71163. var meshName;
  71164. // Hand
  71165. if (this.hand === 'left') {
  71166. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71167. }
  71168. else { // Right is the default if no hand is specified
  71169. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71170. }
  71171. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71172. /*
  71173. Parent Mesh name: oculus_touch_left
  71174. - body
  71175. - trigger
  71176. - thumbstick
  71177. - grip
  71178. - button_y
  71179. - button_x
  71180. - button_enter
  71181. */
  71182. _this._defaultModel = newMeshes[1];
  71183. _this.attachToMesh(_this._defaultModel);
  71184. if (meshLoaded) {
  71185. meshLoaded(_this._defaultModel);
  71186. }
  71187. });
  71188. };
  71189. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71190. /**
  71191. * Fired when the A button on this controller is modified
  71192. */
  71193. get: function () {
  71194. if (this.hand === 'right') {
  71195. return this.onMainButtonStateChangedObservable;
  71196. }
  71197. else {
  71198. throw new Error('No A button on left hand');
  71199. }
  71200. },
  71201. enumerable: true,
  71202. configurable: true
  71203. });
  71204. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71205. /**
  71206. * Fired when the B button on this controller is modified
  71207. */
  71208. get: function () {
  71209. if (this.hand === 'right') {
  71210. return this.onSecondaryButtonStateChangedObservable;
  71211. }
  71212. else {
  71213. throw new Error('No B button on left hand');
  71214. }
  71215. },
  71216. enumerable: true,
  71217. configurable: true
  71218. });
  71219. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71220. /**
  71221. * Fired when the X button on this controller is modified
  71222. */
  71223. get: function () {
  71224. if (this.hand === 'left') {
  71225. return this.onMainButtonStateChangedObservable;
  71226. }
  71227. else {
  71228. throw new Error('No X button on right hand');
  71229. }
  71230. },
  71231. enumerable: true,
  71232. configurable: true
  71233. });
  71234. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71235. /**
  71236. * Fired when the Y button on this controller is modified
  71237. */
  71238. get: function () {
  71239. if (this.hand === 'left') {
  71240. return this.onSecondaryButtonStateChangedObservable;
  71241. }
  71242. else {
  71243. throw new Error('No Y button on right hand');
  71244. }
  71245. },
  71246. enumerable: true,
  71247. configurable: true
  71248. });
  71249. /**
  71250. * Called once for each button that changed state since the last frame
  71251. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71252. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71253. * 2) secondary trigger (same)
  71254. * 3) A (right) X (left), touch, pressed = value
  71255. * 4) B / Y
  71256. * 5) thumb rest
  71257. * @param buttonIdx Which button index changed
  71258. * @param state New state of the button
  71259. * @param changes Which properties on the state changed since last frame
  71260. */
  71261. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71262. var notifyObject = state; //{ state: state, changes: changes };
  71263. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71264. switch (buttonIdx) {
  71265. case 0:
  71266. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71267. return;
  71268. case 1: // index trigger
  71269. if (this._defaultModel) {
  71270. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71271. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71272. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71273. }
  71274. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71275. return;
  71276. case 2: // secondary trigger
  71277. if (this._defaultModel) {
  71278. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71279. }
  71280. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71281. return;
  71282. case 3:
  71283. if (this._defaultModel) {
  71284. if (notifyObject.pressed) {
  71285. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71286. }
  71287. else {
  71288. (this._defaultModel.getChildren()[1]).position.y = 0;
  71289. }
  71290. }
  71291. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71292. return;
  71293. case 4:
  71294. if (this._defaultModel) {
  71295. if (notifyObject.pressed) {
  71296. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71297. }
  71298. else {
  71299. (this._defaultModel.getChildren()[2]).position.y = 0;
  71300. }
  71301. }
  71302. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71303. return;
  71304. case 5:
  71305. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71306. return;
  71307. }
  71308. };
  71309. /**
  71310. * Base Url for the controller model.
  71311. */
  71312. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71313. /**
  71314. * File name for the left controller model.
  71315. */
  71316. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71317. /**
  71318. * File name for the right controller model.
  71319. */
  71320. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71321. return OculusTouchController;
  71322. }(BABYLON.WebVRController));
  71323. BABYLON.OculusTouchController = OculusTouchController;
  71324. })(BABYLON || (BABYLON = {}));
  71325. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71326. var BABYLON;
  71327. (function (BABYLON) {
  71328. /**
  71329. * Vive Controller
  71330. */
  71331. var ViveController = /** @class */ (function (_super) {
  71332. __extends(ViveController, _super);
  71333. /**
  71334. * Creates a new ViveController from a gamepad
  71335. * @param vrGamepad the gamepad that the controller should be created from
  71336. */
  71337. function ViveController(vrGamepad) {
  71338. var _this = _super.call(this, vrGamepad) || this;
  71339. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71340. _this._invertLeftStickY = true;
  71341. return _this;
  71342. }
  71343. /**
  71344. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71345. * @param scene scene in which to add meshes
  71346. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71347. */
  71348. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71349. var _this = this;
  71350. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71351. /*
  71352. Parent Mesh name: ViveWand
  71353. - body
  71354. - r_gripper
  71355. - l_gripper
  71356. - menu_button
  71357. - system_button
  71358. - trackpad
  71359. - trigger
  71360. - LED
  71361. */
  71362. _this._defaultModel = newMeshes[1];
  71363. _this.attachToMesh(_this._defaultModel);
  71364. if (meshLoaded) {
  71365. meshLoaded(_this._defaultModel);
  71366. }
  71367. });
  71368. };
  71369. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71370. /**
  71371. * Fired when the left button on this controller is modified
  71372. */
  71373. get: function () {
  71374. return this.onMainButtonStateChangedObservable;
  71375. },
  71376. enumerable: true,
  71377. configurable: true
  71378. });
  71379. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71380. /**
  71381. * Fired when the right button on this controller is modified
  71382. */
  71383. get: function () {
  71384. return this.onMainButtonStateChangedObservable;
  71385. },
  71386. enumerable: true,
  71387. configurable: true
  71388. });
  71389. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71390. /**
  71391. * Fired when the menu button on this controller is modified
  71392. */
  71393. get: function () {
  71394. return this.onSecondaryButtonStateChangedObservable;
  71395. },
  71396. enumerable: true,
  71397. configurable: true
  71398. });
  71399. /**
  71400. * Called once for each button that changed state since the last frame
  71401. * Vive mapping:
  71402. * 0: touchpad
  71403. * 1: trigger
  71404. * 2: left AND right buttons
  71405. * 3: menu button
  71406. * @param buttonIdx Which button index changed
  71407. * @param state New state of the button
  71408. * @param changes Which properties on the state changed since last frame
  71409. */
  71410. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71411. var notifyObject = state; //{ state: state, changes: changes };
  71412. switch (buttonIdx) {
  71413. case 0:
  71414. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71415. return;
  71416. case 1: // index trigger
  71417. if (this._defaultModel) {
  71418. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71419. }
  71420. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71421. return;
  71422. case 2: // left AND right button
  71423. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71424. return;
  71425. case 3:
  71426. if (this._defaultModel) {
  71427. if (notifyObject.pressed) {
  71428. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71429. }
  71430. else {
  71431. (this._defaultModel.getChildren()[2]).position.y = 0;
  71432. }
  71433. }
  71434. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71435. return;
  71436. }
  71437. };
  71438. /**
  71439. * Base Url for the controller model.
  71440. */
  71441. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71442. /**
  71443. * File name for the controller model.
  71444. */
  71445. ViveController.MODEL_FILENAME = 'wand.babylon';
  71446. return ViveController;
  71447. }(BABYLON.WebVRController));
  71448. BABYLON.ViveController = ViveController;
  71449. })(BABYLON || (BABYLON = {}));
  71450. //# sourceMappingURL=babylon.viveController.js.map
  71451. var BABYLON;
  71452. (function (BABYLON) {
  71453. /**
  71454. * Generic Controller
  71455. */
  71456. var GenericController = /** @class */ (function (_super) {
  71457. __extends(GenericController, _super);
  71458. /**
  71459. * Creates a new GenericController from a gamepad
  71460. * @param vrGamepad the gamepad that the controller should be created from
  71461. */
  71462. function GenericController(vrGamepad) {
  71463. return _super.call(this, vrGamepad) || this;
  71464. }
  71465. /**
  71466. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71467. * @param scene scene in which to add meshes
  71468. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71469. */
  71470. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71471. var _this = this;
  71472. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71473. _this._defaultModel = newMeshes[1];
  71474. _this.attachToMesh(_this._defaultModel);
  71475. if (meshLoaded) {
  71476. meshLoaded(_this._defaultModel);
  71477. }
  71478. });
  71479. };
  71480. /**
  71481. * Called once for each button that changed state since the last frame
  71482. * @param buttonIdx Which button index changed
  71483. * @param state New state of the button
  71484. * @param changes Which properties on the state changed since last frame
  71485. */
  71486. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71487. console.log("Button id: " + buttonIdx + "state: ");
  71488. console.dir(state);
  71489. };
  71490. /**
  71491. * Base Url for the controller model.
  71492. */
  71493. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71494. /**
  71495. * File name for the controller model.
  71496. */
  71497. GenericController.MODEL_FILENAME = 'generic.babylon';
  71498. return GenericController;
  71499. }(BABYLON.WebVRController));
  71500. BABYLON.GenericController = GenericController;
  71501. })(BABYLON || (BABYLON = {}));
  71502. //# sourceMappingURL=babylon.genericController.js.map
  71503. var BABYLON;
  71504. (function (BABYLON) {
  71505. /**
  71506. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71507. */
  71508. var LoadedMeshInfo = /** @class */ (function () {
  71509. function LoadedMeshInfo() {
  71510. /**
  71511. * Map of the button meshes contained in the controller
  71512. */
  71513. this.buttonMeshes = {};
  71514. /**
  71515. * Map of the axis meshes contained in the controller
  71516. */
  71517. this.axisMeshes = {};
  71518. }
  71519. return LoadedMeshInfo;
  71520. }());
  71521. /**
  71522. * Defines the WindowsMotionController object that the state of the windows motion controller
  71523. */
  71524. var WindowsMotionController = /** @class */ (function (_super) {
  71525. __extends(WindowsMotionController, _super);
  71526. /**
  71527. * Creates a new WindowsMotionController from a gamepad
  71528. * @param vrGamepad the gamepad that the controller should be created from
  71529. */
  71530. function WindowsMotionController(vrGamepad) {
  71531. var _this = _super.call(this, vrGamepad) || this;
  71532. _this._mapping = {
  71533. // Semantic button names
  71534. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71535. // A mapping of the button name to glTF model node name
  71536. // that should be transformed by button value.
  71537. buttonMeshNames: {
  71538. 'trigger': 'SELECT',
  71539. 'menu': 'MENU',
  71540. 'grip': 'GRASP',
  71541. 'thumbstick': 'THUMBSTICK_PRESS',
  71542. 'trackpad': 'TOUCHPAD_PRESS'
  71543. },
  71544. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71545. buttonObservableNames: {
  71546. 'trigger': 'onTriggerStateChangedObservable',
  71547. 'menu': 'onSecondaryButtonStateChangedObservable',
  71548. 'grip': 'onMainButtonStateChangedObservable',
  71549. 'thumbstick': 'onPadStateChangedObservable',
  71550. 'trackpad': 'onTrackpadChangedObservable'
  71551. },
  71552. // A mapping of the axis name to glTF model node name
  71553. // that should be transformed by axis value.
  71554. // This array mirrors the browserGamepad.axes array, such that
  71555. // the mesh corresponding to axis 0 is in this array index 0.
  71556. axisMeshNames: [
  71557. 'THUMBSTICK_X',
  71558. 'THUMBSTICK_Y',
  71559. 'TOUCHPAD_TOUCH_X',
  71560. 'TOUCHPAD_TOUCH_Y'
  71561. ],
  71562. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71563. };
  71564. /**
  71565. * Fired when the trackpad on this controller is clicked
  71566. */
  71567. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71568. /**
  71569. * Fired when the trackpad on this controller is modified
  71570. */
  71571. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71572. /**
  71573. * The current x and y values of this controller's trackpad
  71574. */
  71575. _this.trackpad = { x: 0, y: 0 };
  71576. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71577. _this._loadedMeshInfo = null;
  71578. return _this;
  71579. }
  71580. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71581. /**
  71582. * Fired when the trigger on this controller is modified
  71583. */
  71584. get: function () {
  71585. return this.onTriggerStateChangedObservable;
  71586. },
  71587. enumerable: true,
  71588. configurable: true
  71589. });
  71590. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71591. /**
  71592. * Fired when the menu button on this controller is modified
  71593. */
  71594. get: function () {
  71595. return this.onSecondaryButtonStateChangedObservable;
  71596. },
  71597. enumerable: true,
  71598. configurable: true
  71599. });
  71600. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71601. /**
  71602. * Fired when the grip button on this controller is modified
  71603. */
  71604. get: function () {
  71605. return this.onMainButtonStateChangedObservable;
  71606. },
  71607. enumerable: true,
  71608. configurable: true
  71609. });
  71610. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71611. /**
  71612. * Fired when the thumbstick button on this controller is modified
  71613. */
  71614. get: function () {
  71615. return this.onPadStateChangedObservable;
  71616. },
  71617. enumerable: true,
  71618. configurable: true
  71619. });
  71620. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71621. /**
  71622. * Fired when the touchpad button on this controller is modified
  71623. */
  71624. get: function () {
  71625. return this.onTrackpadChangedObservable;
  71626. },
  71627. enumerable: true,
  71628. configurable: true
  71629. });
  71630. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71631. /**
  71632. * Fired when the touchpad values on this controller are modified
  71633. */
  71634. get: function () {
  71635. return this.onTrackpadValuesChangedObservable;
  71636. },
  71637. enumerable: true,
  71638. configurable: true
  71639. });
  71640. /**
  71641. * Called once per frame by the engine.
  71642. */
  71643. WindowsMotionController.prototype.update = function () {
  71644. _super.prototype.update.call(this);
  71645. if (this.browserGamepad.axes) {
  71646. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  71647. this.trackpad.x = this.browserGamepad["axes"][2];
  71648. this.trackpad.y = this.browserGamepad["axes"][3];
  71649. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71650. }
  71651. // Only need to animate axes if there is a loaded mesh
  71652. if (this._loadedMeshInfo) {
  71653. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71654. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71655. }
  71656. }
  71657. }
  71658. };
  71659. /**
  71660. * Called once for each button that changed state since the last frame
  71661. * @param buttonIdx Which button index changed
  71662. * @param state New state of the button
  71663. * @param changes Which properties on the state changed since last frame
  71664. */
  71665. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71666. var buttonName = this._mapping.buttons[buttonIdx];
  71667. if (!buttonName) {
  71668. return;
  71669. }
  71670. // Only emit events for buttons that we know how to map from index to name
  71671. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71672. if (observable) {
  71673. observable.notifyObservers(state);
  71674. }
  71675. this._lerpButtonTransform(buttonName, state.value);
  71676. };
  71677. /**
  71678. * Moves the buttons on the controller mesh based on their current state
  71679. * @param buttonName the name of the button to move
  71680. * @param buttonValue the value of the button which determines the buttons new position
  71681. */
  71682. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71683. // If there is no loaded mesh, there is nothing to transform.
  71684. if (!this._loadedMeshInfo) {
  71685. return;
  71686. }
  71687. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71688. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71689. return;
  71690. }
  71691. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71692. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71693. };
  71694. /**
  71695. * Moves the axis on the controller mesh based on its current state
  71696. * @param axis the index of the axis
  71697. * @param axisValue the value of the axis which determines the meshes new position
  71698. * @hidden
  71699. */
  71700. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71701. if (!this._loadedMeshInfo) {
  71702. return;
  71703. }
  71704. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71705. if (!meshInfo) {
  71706. return;
  71707. }
  71708. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71709. return;
  71710. }
  71711. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71712. var lerpValue = axisValue * 0.5 + 0.5;
  71713. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71714. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71715. };
  71716. /**
  71717. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71718. * @param scene scene in which to add meshes
  71719. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71720. */
  71721. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71722. var _this = this;
  71723. if (forceDefault === void 0) { forceDefault = false; }
  71724. var path;
  71725. var filename;
  71726. // Checking if GLB loader is present
  71727. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71728. // Determine the device specific folder based on the ID suffix
  71729. var device = 'default';
  71730. if (this.id && !forceDefault) {
  71731. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71732. device = ((match && match[0]) || device);
  71733. }
  71734. // Hand
  71735. if (this.hand === 'left') {
  71736. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71737. }
  71738. else { // Right is the default if no hand is specified
  71739. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71740. }
  71741. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71742. }
  71743. else {
  71744. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71745. path = BABYLON.GenericController.MODEL_BASE_URL;
  71746. filename = BABYLON.GenericController.MODEL_FILENAME;
  71747. }
  71748. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71749. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71750. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71751. if (!_this._loadedMeshInfo) {
  71752. return;
  71753. }
  71754. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71755. _this.attachToMesh(_this._defaultModel);
  71756. if (meshLoaded) {
  71757. meshLoaded(_this._defaultModel);
  71758. }
  71759. }, null, function (scene, message) {
  71760. BABYLON.Tools.Log(message);
  71761. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71762. if (!forceDefault) {
  71763. _this.initControllerMesh(scene, meshLoaded, true);
  71764. }
  71765. });
  71766. };
  71767. /**
  71768. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  71769. * can be transformed by button presses and axes values, based on this._mapping.
  71770. *
  71771. * @param scene scene in which the meshes exist
  71772. * @param meshes list of meshes that make up the controller model to process
  71773. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  71774. */
  71775. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  71776. var loadedMeshInfo = null;
  71777. // Create a new mesh to contain the glTF hierarchy
  71778. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  71779. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  71780. var childMesh = null;
  71781. for (var i = 0; i < meshes.length; i++) {
  71782. var mesh = meshes[i];
  71783. if (!mesh.parent) {
  71784. // Exclude controller meshes from picking results
  71785. mesh.isPickable = false;
  71786. // Handle root node, attach to the new parentMesh
  71787. childMesh = mesh;
  71788. break;
  71789. }
  71790. }
  71791. if (childMesh) {
  71792. childMesh.setParent(parentMesh);
  71793. // Create our mesh info. Note that this method will always return non-null.
  71794. loadedMeshInfo = this.createMeshInfo(parentMesh);
  71795. }
  71796. else {
  71797. BABYLON.Tools.Warn('Could not find root node in model file.');
  71798. }
  71799. return loadedMeshInfo;
  71800. };
  71801. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  71802. var loadedMeshInfo = new LoadedMeshInfo();
  71803. var i;
  71804. loadedMeshInfo.rootNode = rootNode;
  71805. // Reset the caches
  71806. loadedMeshInfo.buttonMeshes = {};
  71807. loadedMeshInfo.axisMeshes = {};
  71808. // Button Meshes
  71809. for (i = 0; i < this._mapping.buttons.length; i++) {
  71810. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  71811. if (!buttonMeshName) {
  71812. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  71813. continue;
  71814. }
  71815. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  71816. if (!buttonMesh) {
  71817. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  71818. continue;
  71819. }
  71820. var buttonMeshInfo = {
  71821. index: i,
  71822. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  71823. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  71824. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  71825. };
  71826. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  71827. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  71828. }
  71829. else {
  71830. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  71831. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  71832. '(VALUE: ' + !!buttonMeshInfo.value +
  71833. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  71834. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  71835. ')');
  71836. }
  71837. }
  71838. // Axis Meshes
  71839. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  71840. var axisMeshName = this._mapping.axisMeshNames[i];
  71841. if (!axisMeshName) {
  71842. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  71843. continue;
  71844. }
  71845. var axisMesh = getChildByName(rootNode, axisMeshName);
  71846. if (!axisMesh) {
  71847. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  71848. continue;
  71849. }
  71850. var axisMeshInfo = {
  71851. index: i,
  71852. value: getImmediateChildByName(axisMesh, 'VALUE'),
  71853. min: getImmediateChildByName(axisMesh, 'MIN'),
  71854. max: getImmediateChildByName(axisMesh, 'MAX')
  71855. };
  71856. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  71857. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  71858. }
  71859. else {
  71860. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  71861. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  71862. '(VALUE: ' + !!axisMeshInfo.value +
  71863. ', MIN: ' + !!axisMeshInfo.min +
  71864. ', MAX:' + !!axisMeshInfo.max +
  71865. ')');
  71866. }
  71867. }
  71868. // Pointing Ray
  71869. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  71870. if (!loadedMeshInfo.pointingPoseNode) {
  71871. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  71872. }
  71873. return loadedMeshInfo;
  71874. // Look through all children recursively. This will return null if no mesh exists with the given name.
  71875. function getChildByName(node, name) {
  71876. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  71877. }
  71878. // Look through only immediate children. This will return null if no mesh exists with the given name.
  71879. function getImmediateChildByName(node, name) {
  71880. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  71881. }
  71882. };
  71883. /**
  71884. * Gets the ray of the controller in the direction the controller is pointing
  71885. * @param length the length the resulting ray should be
  71886. * @returns a ray in the direction the controller is pointing
  71887. */
  71888. WindowsMotionController.prototype.getForwardRay = function (length) {
  71889. if (length === void 0) { length = 100; }
  71890. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  71891. return _super.prototype.getForwardRay.call(this, length);
  71892. }
  71893. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  71894. var origin = m.getTranslation();
  71895. var forward = new BABYLON.Vector3(0, 0, -1);
  71896. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71897. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71898. return new BABYLON.Ray(origin, direction, length);
  71899. };
  71900. /**
  71901. * Disposes of the controller
  71902. */
  71903. WindowsMotionController.prototype.dispose = function () {
  71904. _super.prototype.dispose.call(this);
  71905. this.onTrackpadChangedObservable.clear();
  71906. };
  71907. /**
  71908. * The base url used to load the left and right controller models
  71909. */
  71910. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  71911. /**
  71912. * The name of the left controller model file
  71913. */
  71914. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  71915. /**
  71916. * The name of the right controller model file
  71917. */
  71918. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  71919. /**
  71920. * The controller name prefix for this controller type
  71921. */
  71922. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  71923. /**
  71924. * The controller id pattern for this controller type
  71925. */
  71926. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  71927. return WindowsMotionController;
  71928. }(BABYLON.WebVRController));
  71929. BABYLON.WindowsMotionController = WindowsMotionController;
  71930. })(BABYLON || (BABYLON = {}));
  71931. //# sourceMappingURL=babylon.windowsMotionController.js.map
  71932. var BABYLON;
  71933. (function (BABYLON) {
  71934. /**
  71935. * Gear VR Controller
  71936. */
  71937. var GearVRController = /** @class */ (function (_super) {
  71938. __extends(GearVRController, _super);
  71939. /**
  71940. * Creates a new GearVRController from a gamepad
  71941. * @param vrGamepad the gamepad that the controller should be created from
  71942. */
  71943. function GearVRController(vrGamepad) {
  71944. var _this = _super.call(this, vrGamepad) || this;
  71945. _this._buttonIndexToObservableNameMap = [
  71946. 'onTrackpadChangedObservable',
  71947. 'onTriggerStateChangedObservable' // Trigger
  71948. ];
  71949. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  71950. return _this;
  71951. }
  71952. /**
  71953. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71954. * @param scene scene in which to add meshes
  71955. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71956. */
  71957. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71958. var _this = this;
  71959. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  71960. _this._defaultModel = newMeshes[1];
  71961. _this.attachToMesh(_this._defaultModel);
  71962. if (meshLoaded) {
  71963. meshLoaded(_this._defaultModel);
  71964. }
  71965. });
  71966. };
  71967. /**
  71968. * Called once for each button that changed state since the last frame
  71969. * @param buttonIdx Which button index changed
  71970. * @param state New state of the button
  71971. * @param changes Which properties on the state changed since last frame
  71972. */
  71973. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71974. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  71975. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  71976. // Only emit events for buttons that we know how to map from index to observable
  71977. var observable = this[observableName];
  71978. if (observable) {
  71979. observable.notifyObservers(state);
  71980. }
  71981. }
  71982. };
  71983. /**
  71984. * Base Url for the controller model.
  71985. */
  71986. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71987. /**
  71988. * File name for the controller model.
  71989. */
  71990. GearVRController.MODEL_FILENAME = 'generic.babylon';
  71991. /**
  71992. * Gamepad Id prefix used to identify this controller.
  71993. */
  71994. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  71995. return GearVRController;
  71996. }(BABYLON.WebVRController));
  71997. BABYLON.GearVRController = GearVRController;
  71998. })(BABYLON || (BABYLON = {}));
  71999. //# sourceMappingURL=babylon.gearVRController.js.map
  72000. var BABYLON;
  72001. (function (BABYLON) {
  72002. /**
  72003. * Google Daydream controller
  72004. */
  72005. var DaydreamController = /** @class */ (function (_super) {
  72006. __extends(DaydreamController, _super);
  72007. /**
  72008. * Creates a new DaydreamController from a gamepad
  72009. * @param vrGamepad the gamepad that the controller should be created from
  72010. */
  72011. function DaydreamController(vrGamepad) {
  72012. var _this = _super.call(this, vrGamepad) || this;
  72013. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72014. return _this;
  72015. }
  72016. /**
  72017. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72018. * @param scene scene in which to add meshes
  72019. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72020. */
  72021. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72022. var _this = this;
  72023. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72024. _this._defaultModel = newMeshes[1];
  72025. _this.attachToMesh(_this._defaultModel);
  72026. if (meshLoaded) {
  72027. meshLoaded(_this._defaultModel);
  72028. }
  72029. });
  72030. };
  72031. /**
  72032. * Called once for each button that changed state since the last frame
  72033. * @param buttonIdx Which button index changed
  72034. * @param state New state of the button
  72035. * @param changes Which properties on the state changed since last frame
  72036. */
  72037. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72038. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72039. if (buttonIdx === 0) {
  72040. var observable = this.onTriggerStateChangedObservable;
  72041. if (observable) {
  72042. observable.notifyObservers(state);
  72043. }
  72044. }
  72045. else {
  72046. // If the app or home buttons are ever made available
  72047. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72048. }
  72049. };
  72050. /**
  72051. * Base Url for the controller model.
  72052. */
  72053. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72054. /**
  72055. * File name for the controller model.
  72056. */
  72057. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72058. /**
  72059. * Gamepad Id prefix used to identify Daydream Controller.
  72060. */
  72061. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72062. return DaydreamController;
  72063. }(BABYLON.WebVRController));
  72064. BABYLON.DaydreamController = DaydreamController;
  72065. })(BABYLON || (BABYLON = {}));
  72066. //# sourceMappingURL=babylon.daydreamController.js.map
  72067. var BABYLON;
  72068. (function (BABYLON) {
  72069. var FollowCamera = /** @class */ (function (_super) {
  72070. __extends(FollowCamera, _super);
  72071. function FollowCamera(name, position, scene, lockedTarget) {
  72072. if (lockedTarget === void 0) { lockedTarget = null; }
  72073. var _this = _super.call(this, name, position, scene) || this;
  72074. _this.radius = 12;
  72075. _this.rotationOffset = 0;
  72076. _this.heightOffset = 4;
  72077. _this.cameraAcceleration = 0.05;
  72078. _this.maxCameraSpeed = 20;
  72079. _this.lockedTarget = lockedTarget;
  72080. return _this;
  72081. }
  72082. FollowCamera.prototype.getRadians = function (degrees) {
  72083. return degrees * Math.PI / 180;
  72084. };
  72085. FollowCamera.prototype.follow = function (cameraTarget) {
  72086. if (!cameraTarget)
  72087. return;
  72088. var yRotation;
  72089. if (cameraTarget.rotationQuaternion) {
  72090. var rotMatrix = new BABYLON.Matrix();
  72091. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72092. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72093. }
  72094. else {
  72095. yRotation = cameraTarget.rotation.y;
  72096. }
  72097. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72098. var targetPosition = cameraTarget.getAbsolutePosition();
  72099. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72100. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72101. var dx = targetX - this.position.x;
  72102. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72103. var dz = (targetZ) - this.position.z;
  72104. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72105. var vy = dy * this.cameraAcceleration;
  72106. var vz = dz * this.cameraAcceleration * 2;
  72107. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72108. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72109. }
  72110. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72111. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72112. }
  72113. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72114. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72115. }
  72116. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72117. this.setTarget(targetPosition);
  72118. };
  72119. FollowCamera.prototype._checkInputs = function () {
  72120. _super.prototype._checkInputs.call(this);
  72121. if (this.lockedTarget) {
  72122. this.follow(this.lockedTarget);
  72123. }
  72124. };
  72125. FollowCamera.prototype.getClassName = function () {
  72126. return "FollowCamera";
  72127. };
  72128. __decorate([
  72129. BABYLON.serialize()
  72130. ], FollowCamera.prototype, "radius", void 0);
  72131. __decorate([
  72132. BABYLON.serialize()
  72133. ], FollowCamera.prototype, "rotationOffset", void 0);
  72134. __decorate([
  72135. BABYLON.serialize()
  72136. ], FollowCamera.prototype, "heightOffset", void 0);
  72137. __decorate([
  72138. BABYLON.serialize()
  72139. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72140. __decorate([
  72141. BABYLON.serialize()
  72142. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72143. __decorate([
  72144. BABYLON.serializeAsMeshReference("lockedTargetId")
  72145. ], FollowCamera.prototype, "lockedTarget", void 0);
  72146. return FollowCamera;
  72147. }(BABYLON.TargetCamera));
  72148. BABYLON.FollowCamera = FollowCamera;
  72149. var ArcFollowCamera = /** @class */ (function (_super) {
  72150. __extends(ArcFollowCamera, _super);
  72151. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72152. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72153. _this.alpha = alpha;
  72154. _this.beta = beta;
  72155. _this.radius = radius;
  72156. _this.target = target;
  72157. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72158. _this.follow();
  72159. return _this;
  72160. }
  72161. ArcFollowCamera.prototype.follow = function () {
  72162. if (!this.target) {
  72163. return;
  72164. }
  72165. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72166. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72167. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72168. var targetPosition = this.target.getAbsolutePosition();
  72169. this.position = targetPosition.add(this._cartesianCoordinates);
  72170. this.setTarget(targetPosition);
  72171. };
  72172. ArcFollowCamera.prototype._checkInputs = function () {
  72173. _super.prototype._checkInputs.call(this);
  72174. this.follow();
  72175. };
  72176. ArcFollowCamera.prototype.getClassName = function () {
  72177. return "ArcFollowCamera";
  72178. };
  72179. return ArcFollowCamera;
  72180. }(BABYLON.TargetCamera));
  72181. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72182. })(BABYLON || (BABYLON = {}));
  72183. //# sourceMappingURL=babylon.followCamera.js.map
  72184. var BABYLON;
  72185. (function (BABYLON) {
  72186. // We're mainly based on the logic defined into the FreeCamera code
  72187. var UniversalCamera = /** @class */ (function (_super) {
  72188. __extends(UniversalCamera, _super);
  72189. //-- end properties for backward compatibility for inputs
  72190. function UniversalCamera(name, position, scene) {
  72191. var _this = _super.call(this, name, position, scene) || this;
  72192. _this.inputs.addGamepad();
  72193. return _this;
  72194. }
  72195. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72196. //-- Begin properties for backward compatibility for inputs
  72197. get: function () {
  72198. var gamepad = this.inputs.attached["gamepad"];
  72199. if (gamepad)
  72200. return gamepad.gamepadAngularSensibility;
  72201. return 0;
  72202. },
  72203. set: function (value) {
  72204. var gamepad = this.inputs.attached["gamepad"];
  72205. if (gamepad)
  72206. gamepad.gamepadAngularSensibility = value;
  72207. },
  72208. enumerable: true,
  72209. configurable: true
  72210. });
  72211. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72212. get: function () {
  72213. var gamepad = this.inputs.attached["gamepad"];
  72214. if (gamepad)
  72215. return gamepad.gamepadMoveSensibility;
  72216. return 0;
  72217. },
  72218. set: function (value) {
  72219. var gamepad = this.inputs.attached["gamepad"];
  72220. if (gamepad)
  72221. gamepad.gamepadMoveSensibility = value;
  72222. },
  72223. enumerable: true,
  72224. configurable: true
  72225. });
  72226. UniversalCamera.prototype.getClassName = function () {
  72227. return "UniversalCamera";
  72228. };
  72229. return UniversalCamera;
  72230. }(BABYLON.TouchCamera));
  72231. BABYLON.UniversalCamera = UniversalCamera;
  72232. })(BABYLON || (BABYLON = {}));
  72233. //# sourceMappingURL=babylon.universalCamera.js.map
  72234. var BABYLON;
  72235. (function (BABYLON) {
  72236. // We're mainly based on the logic defined into the FreeCamera code
  72237. var GamepadCamera = /** @class */ (function (_super) {
  72238. __extends(GamepadCamera, _super);
  72239. //-- end properties for backward compatibility for inputs
  72240. function GamepadCamera(name, position, scene) {
  72241. return _super.call(this, name, position, scene) || this;
  72242. }
  72243. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72244. //-- Begin properties for backward compatibility for inputs
  72245. get: function () {
  72246. var gamepad = this.inputs.attached["gamepad"];
  72247. if (gamepad)
  72248. return gamepad.gamepadAngularSensibility;
  72249. return 0;
  72250. },
  72251. set: function (value) {
  72252. var gamepad = this.inputs.attached["gamepad"];
  72253. if (gamepad)
  72254. gamepad.gamepadAngularSensibility = value;
  72255. },
  72256. enumerable: true,
  72257. configurable: true
  72258. });
  72259. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72260. get: function () {
  72261. var gamepad = this.inputs.attached["gamepad"];
  72262. if (gamepad)
  72263. return gamepad.gamepadMoveSensibility;
  72264. return 0;
  72265. },
  72266. set: function (value) {
  72267. var gamepad = this.inputs.attached["gamepad"];
  72268. if (gamepad)
  72269. gamepad.gamepadMoveSensibility = value;
  72270. },
  72271. enumerable: true,
  72272. configurable: true
  72273. });
  72274. GamepadCamera.prototype.getClassName = function () {
  72275. return "GamepadCamera";
  72276. };
  72277. return GamepadCamera;
  72278. }(BABYLON.UniversalCamera));
  72279. BABYLON.GamepadCamera = GamepadCamera;
  72280. })(BABYLON || (BABYLON = {}));
  72281. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72282. var BABYLON;
  72283. (function (BABYLON) {
  72284. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72285. function PostProcessRenderPipelineManager() {
  72286. this._renderPipelines = {};
  72287. }
  72288. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72289. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72290. };
  72291. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72292. if (unique === void 0) { unique = false; }
  72293. var renderPipeline = this._renderPipelines[renderPipelineName];
  72294. if (!renderPipeline) {
  72295. return;
  72296. }
  72297. renderPipeline._attachCameras(cameras, unique);
  72298. };
  72299. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72300. var renderPipeline = this._renderPipelines[renderPipelineName];
  72301. if (!renderPipeline) {
  72302. return;
  72303. }
  72304. renderPipeline._detachCameras(cameras);
  72305. };
  72306. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72307. var renderPipeline = this._renderPipelines[renderPipelineName];
  72308. if (!renderPipeline) {
  72309. return;
  72310. }
  72311. renderPipeline._enableEffect(renderEffectName, cameras);
  72312. };
  72313. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72314. var renderPipeline = this._renderPipelines[renderPipelineName];
  72315. if (!renderPipeline) {
  72316. return;
  72317. }
  72318. renderPipeline._disableEffect(renderEffectName, cameras);
  72319. };
  72320. PostProcessRenderPipelineManager.prototype.update = function () {
  72321. for (var renderPipelineName in this._renderPipelines) {
  72322. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72323. var pipeline = this._renderPipelines[renderPipelineName];
  72324. if (!pipeline.isSupported) {
  72325. pipeline.dispose();
  72326. delete this._renderPipelines[renderPipelineName];
  72327. }
  72328. else {
  72329. pipeline._update();
  72330. }
  72331. }
  72332. }
  72333. };
  72334. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72335. for (var renderPipelineName in this._renderPipelines) {
  72336. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72337. var pipeline = this._renderPipelines[renderPipelineName];
  72338. pipeline._rebuild();
  72339. }
  72340. }
  72341. };
  72342. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72343. for (var renderPipelineName in this._renderPipelines) {
  72344. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72345. var pipeline = this._renderPipelines[renderPipelineName];
  72346. pipeline.dispose();
  72347. }
  72348. }
  72349. };
  72350. return PostProcessRenderPipelineManager;
  72351. }());
  72352. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72353. })(BABYLON || (BABYLON = {}));
  72354. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72355. var BABYLON;
  72356. (function (BABYLON) {
  72357. /**
  72358. * This represents a set of one or more post processes in Babylon.
  72359. * A post process can be used to apply a shader to a texture after it is rendered.
  72360. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72361. */
  72362. var PostProcessRenderEffect = /** @class */ (function () {
  72363. /**
  72364. * Instantiates a post process render effect.
  72365. * A post process can be used to apply a shader to a texture after it is rendered.
  72366. * @param engine The engine the effect is tied to
  72367. * @param name The name of the effect
  72368. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72369. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72370. */
  72371. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72372. this._name = name;
  72373. this._singleInstance = singleInstance || true;
  72374. this._getPostProcesses = getPostProcesses;
  72375. this._cameras = {};
  72376. this._indicesForCamera = {};
  72377. this._postProcesses = {};
  72378. }
  72379. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72380. /**
  72381. * Checks if all the post processes in the effect are supported.
  72382. */
  72383. get: function () {
  72384. for (var index in this._postProcesses) {
  72385. if (this._postProcesses.hasOwnProperty(index)) {
  72386. var pps = this._postProcesses[index];
  72387. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72388. if (!pps[ppIndex].isSupported) {
  72389. return false;
  72390. }
  72391. }
  72392. }
  72393. }
  72394. return true;
  72395. },
  72396. enumerable: true,
  72397. configurable: true
  72398. });
  72399. /**
  72400. * Updates the current state of the effect
  72401. */
  72402. PostProcessRenderEffect.prototype._update = function () {
  72403. };
  72404. /**
  72405. * Attaches the effect on cameras
  72406. * @param cameras The camera to attach to.
  72407. */
  72408. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72409. var _this = this;
  72410. var cameraKey;
  72411. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72412. if (!cams) {
  72413. return;
  72414. }
  72415. for (var i = 0; i < cams.length; i++) {
  72416. var camera = cams[i];
  72417. var cameraName = camera.name;
  72418. if (this._singleInstance) {
  72419. cameraKey = 0;
  72420. }
  72421. else {
  72422. cameraKey = cameraName;
  72423. }
  72424. if (!this._postProcesses[cameraKey]) {
  72425. var postProcess = this._getPostProcesses();
  72426. if (postProcess) {
  72427. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72428. }
  72429. }
  72430. if (!this._indicesForCamera[cameraName]) {
  72431. this._indicesForCamera[cameraName] = [];
  72432. }
  72433. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72434. var index = camera.attachPostProcess(postProcess);
  72435. _this._indicesForCamera[cameraName].push(index);
  72436. });
  72437. if (!this._cameras[cameraName]) {
  72438. this._cameras[cameraName] = camera;
  72439. }
  72440. }
  72441. };
  72442. /**
  72443. * Detatches the effect on cameras
  72444. * @param cameras The camera to detatch from.
  72445. */
  72446. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72447. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72448. if (!cams) {
  72449. return;
  72450. }
  72451. for (var i = 0; i < cams.length; i++) {
  72452. var camera = cams[i];
  72453. var cameraName = camera.name;
  72454. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72455. camera.detachPostProcess(postProcess);
  72456. });
  72457. if (this._cameras[cameraName]) {
  72458. //this._indicesForCamera.splice(index, 1);
  72459. this._cameras[cameraName] = null;
  72460. }
  72461. }
  72462. };
  72463. /**
  72464. * Enables the effect on given cameras
  72465. * @param cameras The camera to enable.
  72466. */
  72467. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72468. var _this = this;
  72469. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72470. if (!cams) {
  72471. return;
  72472. }
  72473. for (var i = 0; i < cams.length; i++) {
  72474. var camera = cams[i];
  72475. var cameraName = camera.name;
  72476. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72477. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72478. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72479. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72480. });
  72481. }
  72482. }
  72483. }
  72484. };
  72485. /**
  72486. * Disables the effect on the given cameras
  72487. * @param cameras The camera to disable.
  72488. */
  72489. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72490. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72491. if (!cams) {
  72492. return;
  72493. }
  72494. for (var i = 0; i < cams.length; i++) {
  72495. var camera = cams[i];
  72496. var cameraName = camera.name;
  72497. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72498. camera.detachPostProcess(postProcess);
  72499. });
  72500. }
  72501. };
  72502. /**
  72503. * Gets a list of the post processes contained in the effect.
  72504. * @param camera The camera to get the post processes on.
  72505. * @returns The list of the post processes in the effect.
  72506. */
  72507. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72508. if (this._singleInstance) {
  72509. return this._postProcesses[0];
  72510. }
  72511. else {
  72512. if (!camera) {
  72513. return null;
  72514. }
  72515. return this._postProcesses[camera.name];
  72516. }
  72517. };
  72518. return PostProcessRenderEffect;
  72519. }());
  72520. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72521. })(BABYLON || (BABYLON = {}));
  72522. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72523. var BABYLON;
  72524. (function (BABYLON) {
  72525. var PostProcessRenderPipeline = /** @class */ (function () {
  72526. function PostProcessRenderPipeline(engine, name) {
  72527. this.engine = engine;
  72528. this._name = name;
  72529. this._renderEffects = {};
  72530. this._renderEffectsForIsolatedPass = new Array();
  72531. this._cameras = [];
  72532. }
  72533. PostProcessRenderPipeline.prototype.getClassName = function () {
  72534. return "PostProcessRenderPipeline";
  72535. };
  72536. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72537. get: function () {
  72538. for (var renderEffectName in this._renderEffects) {
  72539. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72540. if (!this._renderEffects[renderEffectName].isSupported) {
  72541. return false;
  72542. }
  72543. }
  72544. }
  72545. return true;
  72546. },
  72547. enumerable: true,
  72548. configurable: true
  72549. });
  72550. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72551. this._renderEffects[renderEffect._name] = renderEffect;
  72552. };
  72553. // private
  72554. PostProcessRenderPipeline.prototype._rebuild = function () {
  72555. };
  72556. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72557. var renderEffects = this._renderEffects[renderEffectName];
  72558. if (!renderEffects) {
  72559. return;
  72560. }
  72561. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72562. };
  72563. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72564. var renderEffects = this._renderEffects[renderEffectName];
  72565. if (!renderEffects) {
  72566. return;
  72567. }
  72568. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72569. };
  72570. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72571. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72572. if (!cams) {
  72573. return;
  72574. }
  72575. var indicesToDelete = [];
  72576. var i;
  72577. for (i = 0; i < cams.length; i++) {
  72578. var camera = cams[i];
  72579. var cameraName = camera.name;
  72580. if (this._cameras.indexOf(camera) === -1) {
  72581. this._cameras[cameraName] = camera;
  72582. }
  72583. else if (unique) {
  72584. indicesToDelete.push(i);
  72585. }
  72586. }
  72587. for (i = 0; i < indicesToDelete.length; i++) {
  72588. cameras.splice(indicesToDelete[i], 1);
  72589. }
  72590. for (var renderEffectName in this._renderEffects) {
  72591. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72592. this._renderEffects[renderEffectName]._attachCameras(cams);
  72593. }
  72594. }
  72595. };
  72596. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72597. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72598. if (!cams) {
  72599. return;
  72600. }
  72601. for (var renderEffectName in this._renderEffects) {
  72602. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72603. this._renderEffects[renderEffectName]._detachCameras(cams);
  72604. }
  72605. }
  72606. for (var i = 0; i < cams.length; i++) {
  72607. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72608. }
  72609. };
  72610. PostProcessRenderPipeline.prototype._update = function () {
  72611. for (var renderEffectName in this._renderEffects) {
  72612. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72613. this._renderEffects[renderEffectName]._update();
  72614. }
  72615. }
  72616. for (var i = 0; i < this._cameras.length; i++) {
  72617. var cameraName = this._cameras[i].name;
  72618. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72619. this._renderEffectsForIsolatedPass[cameraName]._update();
  72620. }
  72621. }
  72622. };
  72623. PostProcessRenderPipeline.prototype._reset = function () {
  72624. this._renderEffects = {};
  72625. this._renderEffectsForIsolatedPass = new Array();
  72626. };
  72627. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72628. // 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)
  72629. var effectKeys = Object.keys(this._renderEffects);
  72630. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72631. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72632. if (postProcesses) {
  72633. postProcesses[0].samples = sampleCount;
  72634. return true;
  72635. }
  72636. }
  72637. return false;
  72638. };
  72639. PostProcessRenderPipeline.prototype.dispose = function () {
  72640. // Must be implemented by children
  72641. };
  72642. __decorate([
  72643. BABYLON.serialize()
  72644. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72645. return PostProcessRenderPipeline;
  72646. }());
  72647. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72648. })(BABYLON || (BABYLON = {}));
  72649. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72650. var BABYLON;
  72651. (function (BABYLON) {
  72652. /**
  72653. * This represents a depth renderer in Babylon.
  72654. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72655. */
  72656. var DepthRenderer = /** @class */ (function () {
  72657. /**
  72658. * Instantiates a depth renderer
  72659. * @param scene The scene the renderer belongs to
  72660. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72661. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72662. */
  72663. function DepthRenderer(scene, type, camera) {
  72664. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72665. if (camera === void 0) { camera = null; }
  72666. var _this = this;
  72667. this._scene = scene;
  72668. this._camera = camera;
  72669. var engine = scene.getEngine();
  72670. // Render target
  72671. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72672. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72673. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72674. this._depthMap.refreshRate = 1;
  72675. this._depthMap.renderParticles = false;
  72676. this._depthMap.renderList = null;
  72677. // Camera to get depth map from to support multiple concurrent cameras
  72678. this._depthMap.activeCamera = this._camera;
  72679. this._depthMap.ignoreCameraViewport = true;
  72680. this._depthMap.useCameraPostProcesses = false;
  72681. // set default depth value to 1.0 (far away)
  72682. this._depthMap.onClearObservable.add(function (engine) {
  72683. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72684. });
  72685. // Custom render function
  72686. var renderSubMesh = function (subMesh) {
  72687. var mesh = subMesh.getRenderingMesh();
  72688. var scene = _this._scene;
  72689. var engine = scene.getEngine();
  72690. var material = subMesh.getMaterial();
  72691. if (!material) {
  72692. return;
  72693. }
  72694. // Culling and reverse (right handed system)
  72695. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72696. // Managing instances
  72697. var batch = mesh._getInstancesRenderList(subMesh._id);
  72698. if (batch.mustReturn) {
  72699. return;
  72700. }
  72701. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72702. var camera = _this._camera || scene.activeCamera;
  72703. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72704. engine.enableEffect(_this._effect);
  72705. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72706. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72707. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72708. // Alpha test
  72709. if (material && material.needAlphaTesting()) {
  72710. var alphaTexture = material.getAlphaTestTexture();
  72711. if (alphaTexture) {
  72712. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72713. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72714. }
  72715. }
  72716. // Bones
  72717. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72718. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72719. }
  72720. // Draw
  72721. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72722. }
  72723. };
  72724. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72725. var index;
  72726. if (depthOnlySubMeshes.length) {
  72727. engine.setColorWrite(false);
  72728. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72729. renderSubMesh(depthOnlySubMeshes.data[index]);
  72730. }
  72731. engine.setColorWrite(true);
  72732. }
  72733. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72734. renderSubMesh(opaqueSubMeshes.data[index]);
  72735. }
  72736. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72737. renderSubMesh(alphaTestSubMeshes.data[index]);
  72738. }
  72739. };
  72740. }
  72741. /**
  72742. * Creates the depth rendering effect and checks if the effect is ready.
  72743. * @param subMesh The submesh to be used to render the depth map of
  72744. * @param useInstances If multiple world instances should be used
  72745. * @returns if the depth renderer is ready to render the depth map
  72746. */
  72747. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72748. var material = subMesh.getMaterial();
  72749. if (material.disableDepthWrite) {
  72750. return false;
  72751. }
  72752. var defines = [];
  72753. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72754. var mesh = subMesh.getMesh();
  72755. // Alpha test
  72756. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72757. defines.push("#define ALPHATEST");
  72758. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72759. attribs.push(BABYLON.VertexBuffer.UVKind);
  72760. defines.push("#define UV1");
  72761. }
  72762. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72763. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72764. defines.push("#define UV2");
  72765. }
  72766. }
  72767. // Bones
  72768. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72769. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72770. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72771. if (mesh.numBoneInfluencers > 4) {
  72772. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72773. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72774. }
  72775. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72776. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72777. }
  72778. else {
  72779. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72780. }
  72781. // Instances
  72782. if (useInstances) {
  72783. defines.push("#define INSTANCES");
  72784. attribs.push("world0");
  72785. attribs.push("world1");
  72786. attribs.push("world2");
  72787. attribs.push("world3");
  72788. }
  72789. // Get correct effect
  72790. var join = defines.join("\n");
  72791. if (this._cachedDefines !== join) {
  72792. this._cachedDefines = join;
  72793. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  72794. }
  72795. return this._effect.isReady();
  72796. };
  72797. /**
  72798. * Gets the texture which the depth map will be written to.
  72799. * @returns The depth map texture
  72800. */
  72801. DepthRenderer.prototype.getDepthMap = function () {
  72802. return this._depthMap;
  72803. };
  72804. /**
  72805. * Disposes of the depth renderer.
  72806. */
  72807. DepthRenderer.prototype.dispose = function () {
  72808. this._depthMap.dispose();
  72809. };
  72810. return DepthRenderer;
  72811. }());
  72812. BABYLON.DepthRenderer = DepthRenderer;
  72813. })(BABYLON || (BABYLON = {}));
  72814. //# sourceMappingURL=babylon.depthRenderer.js.map
  72815. var BABYLON;
  72816. (function (BABYLON) {
  72817. var SSAORenderingPipeline = /** @class */ (function (_super) {
  72818. __extends(SSAORenderingPipeline, _super);
  72819. /**
  72820. * @constructor
  72821. * @param {string} name - The rendering pipeline name
  72822. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72823. * @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 }
  72824. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72825. */
  72826. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  72827. var _this = _super.call(this, scene.getEngine(), name) || this;
  72828. // Members
  72829. /**
  72830. * The PassPostProcess id in the pipeline that contains the original scene color
  72831. */
  72832. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72833. /**
  72834. * The SSAO PostProcess id in the pipeline
  72835. */
  72836. _this.SSAORenderEffect = "SSAORenderEffect";
  72837. /**
  72838. * The horizontal blur PostProcess id in the pipeline
  72839. */
  72840. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72841. /**
  72842. * The vertical blur PostProcess id in the pipeline
  72843. */
  72844. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72845. /**
  72846. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72847. */
  72848. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72849. /**
  72850. * The output strength of the SSAO post-process. Default value is 1.0.
  72851. */
  72852. _this.totalStrength = 1.0;
  72853. /**
  72854. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  72855. */
  72856. _this.radius = 0.0001;
  72857. /**
  72858. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  72859. * Must not be equal to fallOff and superior to fallOff.
  72860. * Default value is 0.975
  72861. */
  72862. _this.area = 0.0075;
  72863. /**
  72864. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  72865. * Must not be equal to area and inferior to area.
  72866. * Default value is 0.0
  72867. */
  72868. _this.fallOff = 0.000001;
  72869. /**
  72870. * The base color of the SSAO post-process
  72871. * The final result is "base + ssao" between [0, 1]
  72872. */
  72873. _this.base = 0.5;
  72874. _this._firstUpdate = true;
  72875. _this._scene = scene;
  72876. // Set up assets
  72877. _this._createRandomTexture();
  72878. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72879. var ssaoRatio = ratio.ssaoRatio || ratio;
  72880. var combineRatio = ratio.combineRatio || ratio;
  72881. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72882. _this._createSSAOPostProcess(ssaoRatio);
  72883. _this._createBlurPostProcess(ssaoRatio);
  72884. _this._createSSAOCombinePostProcess(combineRatio);
  72885. // Set up pipeline
  72886. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72887. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72888. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72889. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72890. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72891. // Finish
  72892. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72893. if (cameras)
  72894. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72895. return _this;
  72896. }
  72897. // Public Methods
  72898. /**
  72899. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72900. */
  72901. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72902. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72903. for (var i = 0; i < this._scene.cameras.length; i++) {
  72904. var camera = this._scene.cameras[i];
  72905. this._originalColorPostProcess.dispose(camera);
  72906. this._ssaoPostProcess.dispose(camera);
  72907. this._blurHPostProcess.dispose(camera);
  72908. this._blurVPostProcess.dispose(camera);
  72909. this._ssaoCombinePostProcess.dispose(camera);
  72910. }
  72911. this._randomTexture.dispose();
  72912. if (disableDepthRender)
  72913. this._scene.disableDepthRenderer();
  72914. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72915. _super.prototype.dispose.call(this);
  72916. };
  72917. // Private Methods
  72918. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  72919. var _this = this;
  72920. var size = 16;
  72921. 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);
  72922. 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);
  72923. this._blurHPostProcess.onActivateObservable.add(function () {
  72924. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  72925. _this._blurHPostProcess.kernel = size * dw;
  72926. });
  72927. this._blurVPostProcess.onActivateObservable.add(function () {
  72928. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  72929. _this._blurVPostProcess.kernel = size * dw;
  72930. });
  72931. };
  72932. SSAORenderingPipeline.prototype._rebuild = function () {
  72933. this._firstUpdate = true;
  72934. _super.prototype._rebuild.call(this);
  72935. };
  72936. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72937. var _this = this;
  72938. var numSamples = 16;
  72939. var sampleSphere = [
  72940. 0.5381, 0.1856, -0.4319,
  72941. 0.1379, 0.2486, 0.4430,
  72942. 0.3371, 0.5679, -0.0057,
  72943. -0.6999, -0.0451, -0.0019,
  72944. 0.0689, -0.1598, -0.8547,
  72945. 0.0560, 0.0069, -0.1843,
  72946. -0.0146, 0.1402, 0.0762,
  72947. 0.0100, -0.1924, -0.0344,
  72948. -0.3577, -0.5301, -0.4358,
  72949. -0.3169, 0.1063, 0.0158,
  72950. 0.0103, -0.5869, 0.0046,
  72951. -0.0897, -0.4940, 0.3287,
  72952. 0.7119, -0.0154, -0.0918,
  72953. -0.0533, 0.0596, -0.5411,
  72954. 0.0352, -0.0631, 0.5460,
  72955. -0.4776, 0.2847, -0.0271
  72956. ];
  72957. var samplesFactor = 1.0 / numSamples;
  72958. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  72959. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72960. "area", "fallOff", "base", "range", "viewport"
  72961. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72962. this._ssaoPostProcess.onApply = function (effect) {
  72963. if (_this._firstUpdate) {
  72964. effect.setArray3("sampleSphere", sampleSphere);
  72965. effect.setFloat("samplesFactor", samplesFactor);
  72966. effect.setFloat("randTextureTiles", 4.0);
  72967. }
  72968. effect.setFloat("totalStrength", _this.totalStrength);
  72969. effect.setFloat("radius", _this.radius);
  72970. effect.setFloat("area", _this.area);
  72971. effect.setFloat("fallOff", _this.fallOff);
  72972. effect.setFloat("base", _this.base);
  72973. effect.setTexture("textureSampler", _this._depthTexture);
  72974. effect.setTexture("randomSampler", _this._randomTexture);
  72975. };
  72976. };
  72977. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  72978. var _this = this;
  72979. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72980. this._ssaoCombinePostProcess.onApply = function (effect) {
  72981. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  72982. };
  72983. };
  72984. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  72985. var size = 512;
  72986. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72987. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72988. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72989. var context = this._randomTexture.getContext();
  72990. var rand = function (min, max) {
  72991. return Math.random() * (max - min) + min;
  72992. };
  72993. var randVector = BABYLON.Vector3.Zero();
  72994. for (var x = 0; x < size; x++) {
  72995. for (var y = 0; y < size; y++) {
  72996. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  72997. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  72998. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  72999. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73000. context.fillRect(x, y, 1, 1);
  73001. }
  73002. }
  73003. this._randomTexture.update(false);
  73004. };
  73005. __decorate([
  73006. BABYLON.serialize()
  73007. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73008. __decorate([
  73009. BABYLON.serialize()
  73010. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73011. __decorate([
  73012. BABYLON.serialize()
  73013. ], SSAORenderingPipeline.prototype, "area", void 0);
  73014. __decorate([
  73015. BABYLON.serialize()
  73016. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73017. __decorate([
  73018. BABYLON.serialize()
  73019. ], SSAORenderingPipeline.prototype, "base", void 0);
  73020. return SSAORenderingPipeline;
  73021. }(BABYLON.PostProcessRenderPipeline));
  73022. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73023. })(BABYLON || (BABYLON = {}));
  73024. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73025. var BABYLON;
  73026. (function (BABYLON) {
  73027. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73028. __extends(SSAO2RenderingPipeline, _super);
  73029. /**
  73030. * @constructor
  73031. * @param {string} name - The rendering pipeline name
  73032. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73033. * @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 }
  73034. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73035. */
  73036. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73037. var _this = _super.call(this, scene.getEngine(), name) || this;
  73038. // Members
  73039. /**
  73040. * The PassPostProcess id in the pipeline that contains the original scene color
  73041. */
  73042. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73043. /**
  73044. * The SSAO PostProcess id in the pipeline
  73045. */
  73046. _this.SSAORenderEffect = "SSAORenderEffect";
  73047. /**
  73048. * The horizontal blur PostProcess id in the pipeline
  73049. */
  73050. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73051. /**
  73052. * The vertical blur PostProcess id in the pipeline
  73053. */
  73054. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73055. /**
  73056. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73057. */
  73058. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73059. /**
  73060. * The output strength of the SSAO post-process. Default value is 1.0.
  73061. */
  73062. _this.totalStrength = 1.0;
  73063. /**
  73064. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73065. */
  73066. _this.maxZ = 100.0;
  73067. /**
  73068. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73069. */
  73070. _this.minZAspect = 0.2;
  73071. /**
  73072. * Number of samples used for the SSAO calculations. Default value is 8
  73073. */
  73074. _this._samples = 8;
  73075. /**
  73076. * Are we using bilateral blur ?
  73077. */
  73078. _this._expensiveBlur = true;
  73079. /**
  73080. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73081. */
  73082. _this.radius = 2.0;
  73083. /**
  73084. * The base color of the SSAO post-process
  73085. * The final result is "base + ssao" between [0, 1]
  73086. */
  73087. _this.base = 0.1;
  73088. _this._firstUpdate = true;
  73089. _this._scene = scene;
  73090. if (!_this.isSupported) {
  73091. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73092. return _this;
  73093. }
  73094. var ssaoRatio = ratio.ssaoRatio || ratio;
  73095. var blurRatio = ratio.blurRatio || ratio;
  73096. // Set up assets
  73097. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73098. _this._createRandomTexture();
  73099. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73100. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73101. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73102. _this._createSSAOPostProcess(1.0);
  73103. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73104. _this._createSSAOCombinePostProcess(blurRatio);
  73105. // Set up pipeline
  73106. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73107. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73108. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73109. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73110. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73111. // Finish
  73112. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73113. if (cameras)
  73114. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73115. return _this;
  73116. }
  73117. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73118. get: function () {
  73119. return this._samples;
  73120. },
  73121. set: function (n) {
  73122. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73123. this._samples = n;
  73124. this._sampleSphere = this._generateHemisphere();
  73125. this._firstUpdate = true;
  73126. },
  73127. enumerable: true,
  73128. configurable: true
  73129. });
  73130. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73131. get: function () {
  73132. return this._expensiveBlur;
  73133. },
  73134. set: function (b) {
  73135. 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"]);
  73136. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73137. this._expensiveBlur = b;
  73138. this._firstUpdate = true;
  73139. },
  73140. enumerable: true,
  73141. configurable: true
  73142. });
  73143. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73144. /**
  73145. * Support test.
  73146. */
  73147. get: function () {
  73148. var engine = BABYLON.Engine.LastCreatedEngine;
  73149. if (!engine) {
  73150. return false;
  73151. }
  73152. return engine.getCaps().drawBuffersExtension;
  73153. },
  73154. enumerable: true,
  73155. configurable: true
  73156. });
  73157. // Public Methods
  73158. /**
  73159. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73160. */
  73161. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73162. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73163. for (var i = 0; i < this._scene.cameras.length; i++) {
  73164. var camera = this._scene.cameras[i];
  73165. this._originalColorPostProcess.dispose(camera);
  73166. this._ssaoPostProcess.dispose(camera);
  73167. this._blurHPostProcess.dispose(camera);
  73168. this._blurVPostProcess.dispose(camera);
  73169. this._ssaoCombinePostProcess.dispose(camera);
  73170. }
  73171. this._randomTexture.dispose();
  73172. if (disableGeometryBufferRenderer)
  73173. this._scene.disableGeometryBufferRenderer();
  73174. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73175. _super.prototype.dispose.call(this);
  73176. };
  73177. // Private Methods
  73178. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73179. var _this = this;
  73180. this._samplerOffsets = [];
  73181. var expensive = this.expensiveBlur;
  73182. for (var i = -8; i < 8; i++) {
  73183. this._samplerOffsets.push(i * 2 + 0.5);
  73184. }
  73185. 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");
  73186. this._blurHPostProcess.onApply = function (effect) {
  73187. if (!_this._scene.activeCamera) {
  73188. return;
  73189. }
  73190. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73191. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73192. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73193. effect.setFloat("radius", _this.radius);
  73194. effect.setTexture("depthSampler", _this._depthTexture);
  73195. if (_this._firstUpdate) {
  73196. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73197. }
  73198. };
  73199. 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");
  73200. this._blurVPostProcess.onApply = function (effect) {
  73201. if (!_this._scene.activeCamera) {
  73202. return;
  73203. }
  73204. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73205. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73206. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73207. effect.setFloat("radius", _this.radius);
  73208. effect.setTexture("depthSampler", _this._depthTexture);
  73209. if (_this._firstUpdate) {
  73210. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73211. _this._firstUpdate = false;
  73212. }
  73213. };
  73214. };
  73215. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73216. this._firstUpdate = true;
  73217. _super.prototype._rebuild.call(this);
  73218. };
  73219. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73220. var numSamples = this.samples;
  73221. var result = [];
  73222. var vector, scale;
  73223. var rand = function (min, max) {
  73224. return Math.random() * (max - min) + min;
  73225. };
  73226. var i = 0;
  73227. while (i < numSamples) {
  73228. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73229. vector.normalize();
  73230. scale = i / numSamples;
  73231. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73232. vector.scaleInPlace(scale);
  73233. result.push(vector.x, vector.y, vector.z);
  73234. i++;
  73235. }
  73236. return result;
  73237. };
  73238. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73239. var _this = this;
  73240. var numSamples = this.samples;
  73241. this._sampleSphere = this._generateHemisphere();
  73242. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73243. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73244. "base", "range", "projection", "near", "far", "texelSize",
  73245. "xViewport", "yViewport", "maxZ", "minZAspect"
  73246. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73247. this._ssaoPostProcess.onApply = function (effect) {
  73248. if (_this._firstUpdate) {
  73249. effect.setArray3("sampleSphere", _this._sampleSphere);
  73250. effect.setFloat("randTextureTiles", 4.0);
  73251. }
  73252. if (!_this._scene.activeCamera) {
  73253. return;
  73254. }
  73255. effect.setFloat("samplesFactor", 1 / _this.samples);
  73256. effect.setFloat("totalStrength", _this.totalStrength);
  73257. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73258. effect.setFloat("radius", _this.radius);
  73259. effect.setFloat("maxZ", _this.maxZ);
  73260. effect.setFloat("minZAspect", _this.minZAspect);
  73261. effect.setFloat("base", _this.base);
  73262. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73263. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73264. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73265. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73266. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73267. effect.setTexture("textureSampler", _this._depthTexture);
  73268. effect.setTexture("normalSampler", _this._normalTexture);
  73269. effect.setTexture("randomSampler", _this._randomTexture);
  73270. };
  73271. };
  73272. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73273. var _this = this;
  73274. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73275. this._ssaoCombinePostProcess.onApply = function (effect) {
  73276. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73277. };
  73278. };
  73279. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73280. var size = 512;
  73281. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73282. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73283. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73284. var context = this._randomTexture.getContext();
  73285. var rand = function (min, max) {
  73286. return Math.random() * (max - min) + min;
  73287. };
  73288. var randVector = BABYLON.Vector3.Zero();
  73289. for (var x = 0; x < size; x++) {
  73290. for (var y = 0; y < size; y++) {
  73291. randVector.x = rand(0.0, 1.0);
  73292. randVector.y = rand(0.0, 1.0);
  73293. randVector.z = 0.0;
  73294. randVector.normalize();
  73295. randVector.scaleInPlace(255);
  73296. randVector.x = Math.floor(randVector.x);
  73297. randVector.y = Math.floor(randVector.y);
  73298. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73299. context.fillRect(x, y, 1, 1);
  73300. }
  73301. }
  73302. this._randomTexture.update(false);
  73303. };
  73304. __decorate([
  73305. BABYLON.serialize()
  73306. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73307. __decorate([
  73308. BABYLON.serialize()
  73309. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73310. __decorate([
  73311. BABYLON.serialize()
  73312. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73313. __decorate([
  73314. BABYLON.serialize("samples")
  73315. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73316. __decorate([
  73317. BABYLON.serialize("expensiveBlur")
  73318. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73319. __decorate([
  73320. BABYLON.serialize()
  73321. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73322. __decorate([
  73323. BABYLON.serialize()
  73324. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73325. return SSAO2RenderingPipeline;
  73326. }(BABYLON.PostProcessRenderPipeline));
  73327. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73328. })(BABYLON || (BABYLON = {}));
  73329. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73330. // BABYLON.JS Chromatic Aberration GLSL Shader
  73331. // Author: Olivier Guyot
  73332. // Separates very slightly R, G and B colors on the edges of the screen
  73333. // Inspired by Francois Tarlier & Martins Upitis
  73334. var BABYLON;
  73335. (function (BABYLON) {
  73336. var LensRenderingPipeline = /** @class */ (function (_super) {
  73337. __extends(LensRenderingPipeline, _super);
  73338. /**
  73339. * @constructor
  73340. *
  73341. * Effect parameters are as follow:
  73342. * {
  73343. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73344. * edge_blur: number; // from 0 to x (1 for realism)
  73345. * distortion: number; // from 0 to x (1 for realism)
  73346. * grain_amount: number; // from 0 to 1
  73347. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73348. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73349. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73350. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73351. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73352. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73353. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73354. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73355. * }
  73356. * Note: if an effect parameter is unset, effect is disabled
  73357. *
  73358. * @param {string} name - The rendering pipeline name
  73359. * @param {object} parameters - An object containing all parameters (see above)
  73360. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73361. * @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)
  73362. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73363. */
  73364. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73365. if (ratio === void 0) { ratio = 1.0; }
  73366. var _this = _super.call(this, scene.getEngine(), name) || this;
  73367. // Lens effects can be of the following:
  73368. // - chromatic aberration (slight shift of RGB colors)
  73369. // - blur on the edge of the lens
  73370. // - lens distortion
  73371. // - depth-of-field blur & highlights enhancing
  73372. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73373. // - grain effect (noise or custom texture)
  73374. // Two additional texture samplers are needed:
  73375. // - depth map (for depth-of-field)
  73376. // - grain texture
  73377. /**
  73378. * The chromatic aberration PostProcess id in the pipeline
  73379. */
  73380. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73381. /**
  73382. * The highlights enhancing PostProcess id in the pipeline
  73383. */
  73384. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73385. /**
  73386. * The depth-of-field PostProcess id in the pipeline
  73387. */
  73388. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73389. _this._scene = scene;
  73390. // Fetch texture samplers
  73391. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73392. if (parameters.grain_texture) {
  73393. _this._grainTexture = parameters.grain_texture;
  73394. }
  73395. else {
  73396. _this._createGrainTexture();
  73397. }
  73398. // save parameters
  73399. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73400. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73401. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73402. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73403. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73404. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73405. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73406. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73407. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73408. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73409. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73410. // Create effects
  73411. _this._createChromaticAberrationPostProcess(ratio);
  73412. _this._createHighlightsPostProcess(ratio);
  73413. _this._createDepthOfFieldPostProcess(ratio / 4);
  73414. // Set up pipeline
  73415. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73416. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73417. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73418. if (_this._highlightsGain === -1) {
  73419. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73420. }
  73421. // Finish
  73422. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73423. if (cameras) {
  73424. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73425. }
  73426. return _this;
  73427. }
  73428. // public methods (self explanatory)
  73429. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73430. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73431. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73432. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73433. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73434. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73435. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73436. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73437. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73438. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73439. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73440. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73441. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73442. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73443. };
  73444. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73445. this._highlightsPostProcess.updateEffect();
  73446. };
  73447. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73448. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73449. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73450. this._highlightsGain = amount;
  73451. };
  73452. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73453. if (this._highlightsGain === -1) {
  73454. this._highlightsGain = 1.0;
  73455. }
  73456. this._highlightsThreshold = amount;
  73457. };
  73458. LensRenderingPipeline.prototype.disableHighlights = function () {
  73459. this._highlightsGain = -1;
  73460. };
  73461. /**
  73462. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73463. */
  73464. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73465. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73466. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73467. this._chromaticAberrationPostProcess = null;
  73468. this._highlightsPostProcess = null;
  73469. this._depthOfFieldPostProcess = null;
  73470. this._grainTexture.dispose();
  73471. if (disableDepthRender)
  73472. this._scene.disableDepthRenderer();
  73473. };
  73474. // colors shifting and distortion
  73475. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73476. var _this = this;
  73477. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73478. [], // samplers
  73479. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73480. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73481. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73482. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73483. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73484. effect.setFloat('radialIntensity', 1);
  73485. effect.setFloat2('direction', 17, 17);
  73486. effect.setFloat2('centerPosition', 0.5, 0.5);
  73487. };
  73488. };
  73489. // highlights enhancing
  73490. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73491. var _this = this;
  73492. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73493. [], // samplers
  73494. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73495. this._highlightsPostProcess.onApply = function (effect) {
  73496. effect.setFloat('gain', _this._highlightsGain);
  73497. effect.setFloat('threshold', _this._highlightsThreshold);
  73498. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73499. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73500. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73501. };
  73502. };
  73503. // colors shifting and distortion
  73504. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73505. var _this = this;
  73506. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73507. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73508. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73509. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73510. this._depthOfFieldPostProcess.onApply = function (effect) {
  73511. effect.setTexture("depthSampler", _this._depthTexture);
  73512. effect.setTexture("grainSampler", _this._grainTexture);
  73513. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73514. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73515. effect.setFloat('grain_amount', _this._grainAmount);
  73516. effect.setBool('blur_noise', _this._blurNoise);
  73517. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73518. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73519. effect.setFloat('distortion', _this._distortion);
  73520. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73521. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73522. effect.setFloat('aperture', _this._dofAperture);
  73523. effect.setFloat('darken', _this._dofDarken);
  73524. effect.setFloat('edge_blur', _this._edgeBlur);
  73525. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73526. if (_this._scene.activeCamera) {
  73527. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73528. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73529. }
  73530. };
  73531. };
  73532. // creates a black and white random noise texture, 512x512
  73533. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73534. var size = 512;
  73535. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73536. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73537. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73538. var context = this._grainTexture.getContext();
  73539. var rand = function (min, max) {
  73540. return Math.random() * (max - min) + min;
  73541. };
  73542. var value;
  73543. for (var x = 0; x < size; x++) {
  73544. for (var y = 0; y < size; y++) {
  73545. value = Math.floor(rand(0.42, 0.58) * 255);
  73546. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73547. context.fillRect(x, y, 1, 1);
  73548. }
  73549. }
  73550. this._grainTexture.update(false);
  73551. };
  73552. return LensRenderingPipeline;
  73553. }(BABYLON.PostProcessRenderPipeline));
  73554. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73555. })(BABYLON || (BABYLON = {}));
  73556. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73557. var BABYLON;
  73558. (function (BABYLON) {
  73559. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73560. __extends(StandardRenderingPipeline, _super);
  73561. /**
  73562. * @constructor
  73563. * @param {string} name - The rendering pipeline name
  73564. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73565. * @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)
  73566. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73567. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73568. */
  73569. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73570. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73571. var _this = _super.call(this, scene.getEngine(), name) || this;
  73572. _this.downSampleX4PostProcess = null;
  73573. _this.brightPassPostProcess = null;
  73574. _this.blurHPostProcesses = [];
  73575. _this.blurVPostProcesses = [];
  73576. _this.textureAdderPostProcess = null;
  73577. _this.volumetricLightPostProcess = null;
  73578. _this.volumetricLightSmoothXPostProcess = null;
  73579. _this.volumetricLightSmoothYPostProcess = null;
  73580. _this.volumetricLightMergePostProces = null;
  73581. _this.volumetricLightFinalPostProcess = null;
  73582. _this.luminancePostProcess = null;
  73583. _this.luminanceDownSamplePostProcesses = [];
  73584. _this.hdrPostProcess = null;
  73585. _this.textureAdderFinalPostProcess = null;
  73586. _this.lensFlareFinalPostProcess = null;
  73587. _this.hdrFinalPostProcess = null;
  73588. _this.lensFlarePostProcess = null;
  73589. _this.lensFlareComposePostProcess = null;
  73590. _this.motionBlurPostProcess = null;
  73591. _this.depthOfFieldPostProcess = null;
  73592. // Values
  73593. _this.brightThreshold = 1.0;
  73594. _this.blurWidth = 512.0;
  73595. _this.horizontalBlur = false;
  73596. _this.exposure = 1.0;
  73597. _this.lensTexture = null;
  73598. _this.volumetricLightCoefficient = 0.2;
  73599. _this.volumetricLightPower = 4.0;
  73600. _this.volumetricLightBlurScale = 64.0;
  73601. _this.sourceLight = null;
  73602. _this.hdrMinimumLuminance = 1.0;
  73603. _this.hdrDecreaseRate = 0.5;
  73604. _this.hdrIncreaseRate = 0.5;
  73605. _this.lensColorTexture = null;
  73606. _this.lensFlareStrength = 20.0;
  73607. _this.lensFlareGhostDispersal = 1.4;
  73608. _this.lensFlareHaloWidth = 0.7;
  73609. _this.lensFlareDistortionStrength = 16.0;
  73610. _this.lensStarTexture = null;
  73611. _this.lensFlareDirtTexture = null;
  73612. _this.depthOfFieldDistance = 10.0;
  73613. _this.depthOfFieldBlurWidth = 64.0;
  73614. _this.motionStrength = 1.0;
  73615. // IAnimatable
  73616. _this.animations = [];
  73617. _this._currentDepthOfFieldSource = null;
  73618. _this._hdrCurrentLuminance = 1.0;
  73619. // Getters and setters
  73620. _this._bloomEnabled = true;
  73621. _this._depthOfFieldEnabled = false;
  73622. _this._vlsEnabled = false;
  73623. _this._lensFlareEnabled = false;
  73624. _this._hdrEnabled = false;
  73625. _this._motionBlurEnabled = false;
  73626. _this._motionBlurSamples = 64.0;
  73627. _this._volumetricLightStepsCount = 50.0;
  73628. _this._cameras = cameras || [];
  73629. // Initialize
  73630. _this._scene = scene;
  73631. _this._basePostProcess = originalPostProcess;
  73632. _this._ratio = ratio;
  73633. // Misc
  73634. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73635. // Finish
  73636. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73637. _this._buildPipeline();
  73638. return _this;
  73639. }
  73640. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73641. get: function () {
  73642. return this._bloomEnabled;
  73643. },
  73644. set: function (enabled) {
  73645. if (this._bloomEnabled === enabled) {
  73646. return;
  73647. }
  73648. this._bloomEnabled = enabled;
  73649. this._buildPipeline();
  73650. },
  73651. enumerable: true,
  73652. configurable: true
  73653. });
  73654. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73655. get: function () {
  73656. return this._depthOfFieldEnabled;
  73657. },
  73658. set: function (enabled) {
  73659. if (this._depthOfFieldEnabled === enabled) {
  73660. return;
  73661. }
  73662. this._depthOfFieldEnabled = enabled;
  73663. this._buildPipeline();
  73664. },
  73665. enumerable: true,
  73666. configurable: true
  73667. });
  73668. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73669. get: function () {
  73670. return this._lensFlareEnabled;
  73671. },
  73672. set: function (enabled) {
  73673. if (this._lensFlareEnabled === enabled) {
  73674. return;
  73675. }
  73676. this._lensFlareEnabled = enabled;
  73677. this._buildPipeline();
  73678. },
  73679. enumerable: true,
  73680. configurable: true
  73681. });
  73682. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73683. get: function () {
  73684. return this._hdrEnabled;
  73685. },
  73686. set: function (enabled) {
  73687. if (this._hdrEnabled === enabled) {
  73688. return;
  73689. }
  73690. this._hdrEnabled = enabled;
  73691. this._buildPipeline();
  73692. },
  73693. enumerable: true,
  73694. configurable: true
  73695. });
  73696. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73697. get: function () {
  73698. return this._vlsEnabled;
  73699. },
  73700. set: function (enabled) {
  73701. if (this._vlsEnabled === enabled) {
  73702. return;
  73703. }
  73704. if (enabled) {
  73705. var geometry = this._scene.enableGeometryBufferRenderer();
  73706. if (!geometry) {
  73707. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73708. return;
  73709. }
  73710. }
  73711. this._vlsEnabled = enabled;
  73712. this._buildPipeline();
  73713. },
  73714. enumerable: true,
  73715. configurable: true
  73716. });
  73717. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73718. get: function () {
  73719. return this._motionBlurEnabled;
  73720. },
  73721. set: function (enabled) {
  73722. if (this._motionBlurEnabled === enabled) {
  73723. return;
  73724. }
  73725. this._motionBlurEnabled = enabled;
  73726. this._buildPipeline();
  73727. },
  73728. enumerable: true,
  73729. configurable: true
  73730. });
  73731. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73732. get: function () {
  73733. return this._volumetricLightStepsCount;
  73734. },
  73735. set: function (count) {
  73736. if (this.volumetricLightPostProcess) {
  73737. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73738. }
  73739. this._volumetricLightStepsCount = count;
  73740. },
  73741. enumerable: true,
  73742. configurable: true
  73743. });
  73744. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  73745. get: function () {
  73746. return this._motionBlurSamples;
  73747. },
  73748. set: function (samples) {
  73749. if (this.motionBlurPostProcess) {
  73750. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  73751. }
  73752. this._motionBlurSamples = samples;
  73753. },
  73754. enumerable: true,
  73755. configurable: true
  73756. });
  73757. StandardRenderingPipeline.prototype._buildPipeline = function () {
  73758. var _this = this;
  73759. var ratio = this._ratio;
  73760. var scene = this._scene;
  73761. this._disposePostProcesses();
  73762. this._reset();
  73763. // Create pass post-process
  73764. if (!this._basePostProcess) {
  73765. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  73766. this.originalPostProcess.onApply = function (effect) {
  73767. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  73768. };
  73769. }
  73770. else {
  73771. this.originalPostProcess = this._basePostProcess;
  73772. }
  73773. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  73774. this._currentDepthOfFieldSource = this.originalPostProcess;
  73775. if (this._vlsEnabled) {
  73776. // Create volumetric light
  73777. this._createVolumetricLightPostProcess(scene, ratio);
  73778. // Create volumetric light final post-process
  73779. 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);
  73780. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  73781. }
  73782. if (this._bloomEnabled) {
  73783. // Create down sample X4 post-process
  73784. this._createDownSampleX4PostProcess(scene, ratio / 2);
  73785. // Create bright pass post-process
  73786. this._createBrightPassPostProcess(scene, ratio / 2);
  73787. // Create gaussian blur post-processes (down sampling blurs)
  73788. this._createBlurPostProcesses(scene, ratio / 4, 1);
  73789. // Create texture adder post-process
  73790. this._createTextureAdderPostProcess(scene, ratio);
  73791. // Create depth-of-field source post-process
  73792. 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);
  73793. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  73794. }
  73795. if (this._lensFlareEnabled) {
  73796. // Create lens flare post-process
  73797. this._createLensFlarePostProcess(scene, ratio);
  73798. // Create depth-of-field source post-process post lens-flare and disable it now
  73799. 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);
  73800. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  73801. }
  73802. if (this._hdrEnabled) {
  73803. // Create luminance
  73804. this._createLuminancePostProcesses(scene, this._floatTextureType);
  73805. // Create HDR
  73806. this._createHdrPostProcess(scene, ratio);
  73807. // Create depth-of-field source post-process post hdr and disable it now
  73808. 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);
  73809. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  73810. }
  73811. if (this._depthOfFieldEnabled) {
  73812. // Create gaussian blur used by depth-of-field
  73813. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  73814. // Create depth-of-field post-process
  73815. this._createDepthOfFieldPostProcess(scene, ratio);
  73816. }
  73817. if (this._motionBlurEnabled) {
  73818. // Create motion blur post-process
  73819. this._createMotionBlurPostProcess(scene, ratio);
  73820. }
  73821. if (this._cameras !== null) {
  73822. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73823. }
  73824. };
  73825. // Down Sample X4 Post-Processs
  73826. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  73827. var _this = this;
  73828. var downSampleX4Offsets = new Array(32);
  73829. 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);
  73830. this.downSampleX4PostProcess.onApply = function (effect) {
  73831. var id = 0;
  73832. var width = _this.downSampleX4PostProcess.width;
  73833. var height = _this.downSampleX4PostProcess.height;
  73834. for (var i = -2; i < 2; i++) {
  73835. for (var j = -2; j < 2; j++) {
  73836. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  73837. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  73838. id += 2;
  73839. }
  73840. }
  73841. effect.setArray2("dsOffsets", downSampleX4Offsets);
  73842. };
  73843. // Add to pipeline
  73844. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  73845. };
  73846. // Brightpass Post-Process
  73847. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  73848. var _this = this;
  73849. var brightOffsets = new Array(8);
  73850. 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);
  73851. this.brightPassPostProcess.onApply = function (effect) {
  73852. var sU = (1.0 / _this.brightPassPostProcess.width);
  73853. var sV = (1.0 / _this.brightPassPostProcess.height);
  73854. brightOffsets[0] = -0.5 * sU;
  73855. brightOffsets[1] = 0.5 * sV;
  73856. brightOffsets[2] = 0.5 * sU;
  73857. brightOffsets[3] = 0.5 * sV;
  73858. brightOffsets[4] = -0.5 * sU;
  73859. brightOffsets[5] = -0.5 * sV;
  73860. brightOffsets[6] = 0.5 * sU;
  73861. brightOffsets[7] = -0.5 * sV;
  73862. effect.setArray2("dsOffsets", brightOffsets);
  73863. effect.setFloat("brightThreshold", _this.brightThreshold);
  73864. };
  73865. // Add to pipeline
  73866. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  73867. };
  73868. // Create blur H&V post-processes
  73869. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  73870. var _this = this;
  73871. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  73872. var engine = scene.getEngine();
  73873. 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);
  73874. 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);
  73875. blurX.onActivateObservable.add(function () {
  73876. var dw = blurX.width / engine.getRenderWidth();
  73877. blurX.kernel = _this[blurWidthKey] * dw;
  73878. });
  73879. blurY.onActivateObservable.add(function () {
  73880. var dw = blurY.height / engine.getRenderHeight();
  73881. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  73882. });
  73883. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  73884. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  73885. this.blurHPostProcesses.push(blurX);
  73886. this.blurVPostProcesses.push(blurY);
  73887. };
  73888. // Create texture adder post-process
  73889. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  73890. var _this = this;
  73891. 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);
  73892. this.textureAdderPostProcess.onApply = function (effect) {
  73893. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  73894. effect.setTexture("lensSampler", _this.lensTexture);
  73895. effect.setFloat("exposure", _this.exposure);
  73896. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  73897. };
  73898. // Add to pipeline
  73899. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  73900. };
  73901. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  73902. var _this = this;
  73903. var geometryRenderer = scene.enableGeometryBufferRenderer();
  73904. geometryRenderer.enablePosition = true;
  73905. var geometry = geometryRenderer.getGBuffer();
  73906. // Base post-process
  73907. 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));
  73908. var depthValues = BABYLON.Vector2.Zero();
  73909. this.volumetricLightPostProcess.onApply = function (effect) {
  73910. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  73911. var generator = _this.sourceLight.getShadowGenerator();
  73912. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  73913. effect.setTexture("positionSampler", geometry.textures[2]);
  73914. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  73915. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  73916. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  73917. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  73918. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  73919. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  73920. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  73921. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  73922. effect.setVector2("depthValues", depthValues);
  73923. }
  73924. };
  73925. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  73926. // Smooth
  73927. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  73928. // Merge
  73929. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  73930. this.volumetricLightMergePostProces.onApply = function (effect) {
  73931. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  73932. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  73933. };
  73934. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  73935. };
  73936. // Create luminance
  73937. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  73938. var _this = this;
  73939. // Create luminance
  73940. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  73941. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  73942. var offsets = [];
  73943. this.luminancePostProcess.onApply = function (effect) {
  73944. var sU = (1.0 / _this.luminancePostProcess.width);
  73945. var sV = (1.0 / _this.luminancePostProcess.height);
  73946. offsets[0] = -0.5 * sU;
  73947. offsets[1] = 0.5 * sV;
  73948. offsets[2] = 0.5 * sU;
  73949. offsets[3] = 0.5 * sV;
  73950. offsets[4] = -0.5 * sU;
  73951. offsets[5] = -0.5 * sV;
  73952. offsets[6] = 0.5 * sU;
  73953. offsets[7] = -0.5 * sV;
  73954. effect.setArray2("lumOffsets", offsets);
  73955. };
  73956. // Add to pipeline
  73957. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  73958. // Create down sample luminance
  73959. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  73960. var size = Math.pow(3, i);
  73961. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  73962. if (i === 0) {
  73963. defines += "#define FINAL_DOWN_SAMPLER";
  73964. }
  73965. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  73966. this.luminanceDownSamplePostProcesses.push(postProcess);
  73967. }
  73968. // Create callbacks and add effects
  73969. var lastLuminance = this.luminancePostProcess;
  73970. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  73971. var downSampleOffsets = new Array(18);
  73972. pp.onApply = function (effect) {
  73973. if (!lastLuminance) {
  73974. return;
  73975. }
  73976. var id = 0;
  73977. for (var x = -1; x < 2; x++) {
  73978. for (var y = -1; y < 2; y++) {
  73979. downSampleOffsets[id] = x / lastLuminance.width;
  73980. downSampleOffsets[id + 1] = y / lastLuminance.height;
  73981. id += 2;
  73982. }
  73983. }
  73984. effect.setArray2("dsOffsets", downSampleOffsets);
  73985. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  73986. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  73987. lastLuminance = _this.luminancePostProcess;
  73988. }
  73989. else {
  73990. lastLuminance = pp;
  73991. }
  73992. };
  73993. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  73994. pp.onAfterRender = function (effect) {
  73995. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  73996. 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);
  73997. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  73998. };
  73999. }
  74000. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74001. });
  74002. };
  74003. // Create HDR post-process
  74004. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74005. var _this = this;
  74006. 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);
  74007. var outputLiminance = 1;
  74008. var time = 0;
  74009. var lastTime = 0;
  74010. this.hdrPostProcess.onApply = function (effect) {
  74011. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74012. time += scene.getEngine().getDeltaTime();
  74013. if (outputLiminance < 0) {
  74014. outputLiminance = _this._hdrCurrentLuminance;
  74015. }
  74016. else {
  74017. var dt = (lastTime - time) / 1000.0;
  74018. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74019. outputLiminance += _this.hdrDecreaseRate * dt;
  74020. }
  74021. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74022. outputLiminance -= _this.hdrIncreaseRate * dt;
  74023. }
  74024. else {
  74025. outputLiminance = _this._hdrCurrentLuminance;
  74026. }
  74027. }
  74028. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74029. effect.setFloat("averageLuminance", outputLiminance);
  74030. lastTime = time;
  74031. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74032. };
  74033. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74034. };
  74035. // Create lens flare post-process
  74036. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74037. var _this = this;
  74038. 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);
  74039. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74040. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74041. 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);
  74042. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74043. var resolution = new BABYLON.Vector2(0, 0);
  74044. // Lens flare
  74045. this.lensFlarePostProcess.onApply = function (effect) {
  74046. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74047. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74048. effect.setFloat("strength", _this.lensFlareStrength);
  74049. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74050. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74051. // Shift
  74052. resolution.x = _this.lensFlarePostProcess.width;
  74053. resolution.y = _this.lensFlarePostProcess.height;
  74054. effect.setVector2("resolution", resolution);
  74055. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74056. };
  74057. // Compose
  74058. 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);
  74059. 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);
  74060. this.lensFlareComposePostProcess.onApply = function (effect) {
  74061. if (!_this._scene.activeCamera) {
  74062. return;
  74063. }
  74064. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74065. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74066. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74067. // Lens start rotation matrix
  74068. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74069. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74070. 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));
  74071. camRot *= 4.0;
  74072. 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);
  74073. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74074. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74075. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74076. };
  74077. };
  74078. // Create depth-of-field post-process
  74079. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74080. var _this = this;
  74081. 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);
  74082. this.depthOfFieldPostProcess.onApply = function (effect) {
  74083. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74084. effect.setTexture("depthSampler", _this._getDepthTexture());
  74085. effect.setFloat("distance", _this.depthOfFieldDistance);
  74086. };
  74087. // Add to pipeline
  74088. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74089. };
  74090. // Create motion blur post-process
  74091. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74092. var _this = this;
  74093. 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);
  74094. var motionScale = 0;
  74095. var prevViewProjection = BABYLON.Matrix.Identity();
  74096. var invViewProjection = BABYLON.Matrix.Identity();
  74097. var viewProjection = BABYLON.Matrix.Identity();
  74098. var screenSize = BABYLON.Vector2.Zero();
  74099. this.motionBlurPostProcess.onApply = function (effect) {
  74100. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74101. viewProjection.invertToRef(invViewProjection);
  74102. effect.setMatrix("inverseViewProjection", invViewProjection);
  74103. effect.setMatrix("prevViewProjection", prevViewProjection);
  74104. prevViewProjection = viewProjection;
  74105. screenSize.x = _this.motionBlurPostProcess.width;
  74106. screenSize.y = _this.motionBlurPostProcess.height;
  74107. effect.setVector2("screenSize", screenSize);
  74108. motionScale = scene.getEngine().getFps() / 60.0;
  74109. effect.setFloat("motionScale", motionScale);
  74110. effect.setFloat("motionStrength", _this.motionStrength);
  74111. effect.setTexture("depthSampler", _this._getDepthTexture());
  74112. };
  74113. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74114. };
  74115. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74116. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74117. var renderer = this._scene.enableGeometryBufferRenderer();
  74118. return renderer.getGBuffer().textures[0];
  74119. }
  74120. return this._scene.enableDepthRenderer().getDepthMap();
  74121. };
  74122. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74123. for (var i = 0; i < this._cameras.length; i++) {
  74124. var camera = this._cameras[i];
  74125. if (this.originalPostProcess) {
  74126. this.originalPostProcess.dispose(camera);
  74127. }
  74128. if (this.downSampleX4PostProcess) {
  74129. this.downSampleX4PostProcess.dispose(camera);
  74130. }
  74131. if (this.brightPassPostProcess) {
  74132. this.brightPassPostProcess.dispose(camera);
  74133. }
  74134. if (this.textureAdderPostProcess) {
  74135. this.textureAdderPostProcess.dispose(camera);
  74136. }
  74137. if (this.textureAdderFinalPostProcess) {
  74138. this.textureAdderFinalPostProcess.dispose(camera);
  74139. }
  74140. if (this.volumetricLightPostProcess) {
  74141. this.volumetricLightPostProcess.dispose(camera);
  74142. }
  74143. if (this.volumetricLightSmoothXPostProcess) {
  74144. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74145. }
  74146. if (this.volumetricLightSmoothYPostProcess) {
  74147. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74148. }
  74149. if (this.volumetricLightMergePostProces) {
  74150. this.volumetricLightMergePostProces.dispose(camera);
  74151. }
  74152. if (this.volumetricLightFinalPostProcess) {
  74153. this.volumetricLightFinalPostProcess.dispose(camera);
  74154. }
  74155. if (this.lensFlarePostProcess) {
  74156. this.lensFlarePostProcess.dispose(camera);
  74157. }
  74158. if (this.lensFlareComposePostProcess) {
  74159. this.lensFlareComposePostProcess.dispose(camera);
  74160. }
  74161. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74162. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74163. }
  74164. if (this.luminancePostProcess) {
  74165. this.luminancePostProcess.dispose(camera);
  74166. }
  74167. if (this.hdrPostProcess) {
  74168. this.hdrPostProcess.dispose(camera);
  74169. }
  74170. if (this.hdrFinalPostProcess) {
  74171. this.hdrFinalPostProcess.dispose(camera);
  74172. }
  74173. if (this.depthOfFieldPostProcess) {
  74174. this.depthOfFieldPostProcess.dispose(camera);
  74175. }
  74176. if (this.motionBlurPostProcess) {
  74177. this.motionBlurPostProcess.dispose(camera);
  74178. }
  74179. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74180. this.blurHPostProcesses[j].dispose(camera);
  74181. }
  74182. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74183. this.blurVPostProcesses[j].dispose(camera);
  74184. }
  74185. }
  74186. this.originalPostProcess = null;
  74187. this.downSampleX4PostProcess = null;
  74188. this.brightPassPostProcess = null;
  74189. this.textureAdderPostProcess = null;
  74190. this.textureAdderFinalPostProcess = null;
  74191. this.volumetricLightPostProcess = null;
  74192. this.volumetricLightSmoothXPostProcess = null;
  74193. this.volumetricLightSmoothYPostProcess = null;
  74194. this.volumetricLightMergePostProces = null;
  74195. this.volumetricLightFinalPostProcess = null;
  74196. this.lensFlarePostProcess = null;
  74197. this.lensFlareComposePostProcess = null;
  74198. this.luminancePostProcess = null;
  74199. this.hdrPostProcess = null;
  74200. this.hdrFinalPostProcess = null;
  74201. this.depthOfFieldPostProcess = null;
  74202. this.motionBlurPostProcess = null;
  74203. this.luminanceDownSamplePostProcesses = [];
  74204. this.blurHPostProcesses = [];
  74205. this.blurVPostProcesses = [];
  74206. };
  74207. // Dispose
  74208. StandardRenderingPipeline.prototype.dispose = function () {
  74209. this._disposePostProcesses();
  74210. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74211. _super.prototype.dispose.call(this);
  74212. };
  74213. // Serialize rendering pipeline
  74214. StandardRenderingPipeline.prototype.serialize = function () {
  74215. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74216. serializationObject.customType = "StandardRenderingPipeline";
  74217. return serializationObject;
  74218. };
  74219. /**
  74220. * Static members
  74221. */
  74222. // Parse serialized pipeline
  74223. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74224. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74225. };
  74226. // Luminance steps
  74227. StandardRenderingPipeline.LuminanceSteps = 6;
  74228. __decorate([
  74229. BABYLON.serialize()
  74230. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74231. __decorate([
  74232. BABYLON.serialize()
  74233. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74234. __decorate([
  74235. BABYLON.serialize()
  74236. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74237. __decorate([
  74238. BABYLON.serialize()
  74239. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74240. __decorate([
  74241. BABYLON.serializeAsTexture("lensTexture")
  74242. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74243. __decorate([
  74244. BABYLON.serialize()
  74245. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74246. __decorate([
  74247. BABYLON.serialize()
  74248. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74249. __decorate([
  74250. BABYLON.serialize()
  74251. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74252. __decorate([
  74253. BABYLON.serialize()
  74254. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74255. __decorate([
  74256. BABYLON.serialize()
  74257. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74258. __decorate([
  74259. BABYLON.serialize()
  74260. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74261. __decorate([
  74262. BABYLON.serializeAsTexture("lensColorTexture")
  74263. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74264. __decorate([
  74265. BABYLON.serialize()
  74266. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74267. __decorate([
  74268. BABYLON.serialize()
  74269. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74270. __decorate([
  74271. BABYLON.serialize()
  74272. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74273. __decorate([
  74274. BABYLON.serialize()
  74275. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74276. __decorate([
  74277. BABYLON.serializeAsTexture("lensStarTexture")
  74278. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74279. __decorate([
  74280. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74281. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74282. __decorate([
  74283. BABYLON.serialize()
  74284. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74285. __decorate([
  74286. BABYLON.serialize()
  74287. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74288. __decorate([
  74289. BABYLON.serialize()
  74290. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74291. __decorate([
  74292. BABYLON.serialize()
  74293. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74294. __decorate([
  74295. BABYLON.serialize()
  74296. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74297. __decorate([
  74298. BABYLON.serialize()
  74299. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74300. __decorate([
  74301. BABYLON.serialize()
  74302. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74303. __decorate([
  74304. BABYLON.serialize()
  74305. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74306. __decorate([
  74307. BABYLON.serialize()
  74308. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74309. __decorate([
  74310. BABYLON.serialize()
  74311. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74312. __decorate([
  74313. BABYLON.serialize()
  74314. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74315. __decorate([
  74316. BABYLON.serialize()
  74317. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74318. return StandardRenderingPipeline;
  74319. }(BABYLON.PostProcessRenderPipeline));
  74320. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74321. })(BABYLON || (BABYLON = {}));
  74322. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74323. var BABYLON;
  74324. (function (BABYLON) {
  74325. var FxaaPostProcess = /** @class */ (function (_super) {
  74326. __extends(FxaaPostProcess, _super);
  74327. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74328. if (camera === void 0) { camera = null; }
  74329. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74330. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  74331. _this.onApplyObservable.add(function (effect) {
  74332. var texelSize = _this.texelSize;
  74333. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74334. });
  74335. return _this;
  74336. }
  74337. return FxaaPostProcess;
  74338. }(BABYLON.PostProcess));
  74339. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74340. })(BABYLON || (BABYLON = {}));
  74341. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74342. var BABYLON;
  74343. (function (BABYLON) {
  74344. /**
  74345. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74346. */
  74347. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74348. __extends(ChromaticAberrationPostProcess, _super);
  74349. /**
  74350. * Creates a new instance ChromaticAberrationPostProcess
  74351. * @param name The name of the effect.
  74352. * @param screenWidth The width of the screen to apply the effect on.
  74353. * @param screenHeight The height of the screen to apply the effect on.
  74354. * @param options The required width/height ratio to downsize to before computing the render pass.
  74355. * @param camera The camera to apply the render pass to.
  74356. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74357. * @param engine The engine which the post process will be applied. (default: current engine)
  74358. * @param reusable If the post process can be reused on the same frame. (default: false)
  74359. * @param textureType Type of textures used when performing the post process. (default: 0)
  74360. * @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)
  74361. */
  74362. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74363. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74364. if (blockCompilation === void 0) { blockCompilation = false; }
  74365. 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;
  74366. /**
  74367. * The amount of seperation of rgb channels (default: 30)
  74368. */
  74369. _this.aberrationAmount = 30;
  74370. /**
  74371. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74372. */
  74373. _this.radialIntensity = 0;
  74374. /**
  74375. * 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))
  74376. */
  74377. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74378. /**
  74379. * 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))
  74380. */
  74381. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74382. _this.onApplyObservable.add(function (effect) {
  74383. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74384. effect.setFloat('screen_width', screenWidth);
  74385. effect.setFloat('screen_height', screenHeight);
  74386. effect.setFloat('radialIntensity', _this.radialIntensity);
  74387. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74388. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74389. });
  74390. return _this;
  74391. }
  74392. return ChromaticAberrationPostProcess;
  74393. }(BABYLON.PostProcess));
  74394. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74395. })(BABYLON || (BABYLON = {}));
  74396. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74397. var BABYLON;
  74398. (function (BABYLON) {
  74399. /**
  74400. * The GrainPostProcess adds noise to the image at mid luminance levels
  74401. */
  74402. var GrainPostProcess = /** @class */ (function (_super) {
  74403. __extends(GrainPostProcess, _super);
  74404. /**
  74405. * Creates a new instance of @see GrainPostProcess
  74406. * @param name The name of the effect.
  74407. * @param options The required width/height ratio to downsize to before computing the render pass.
  74408. * @param camera The camera to apply the render pass to.
  74409. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74410. * @param engine The engine which the post process will be applied. (default: current engine)
  74411. * @param reusable If the post process can be reused on the same frame. (default: false)
  74412. * @param textureType Type of textures used when performing the post process. (default: 0)
  74413. * @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)
  74414. */
  74415. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74416. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74417. if (blockCompilation === void 0) { blockCompilation = false; }
  74418. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74419. /**
  74420. * The intensity of the grain added (default: 30)
  74421. */
  74422. _this.intensity = 30;
  74423. /**
  74424. * If the grain should be randomized on every frame
  74425. */
  74426. _this.animated = false;
  74427. _this.onApplyObservable.add(function (effect) {
  74428. effect.setFloat('intensity', _this.intensity);
  74429. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74430. });
  74431. return _this;
  74432. }
  74433. return GrainPostProcess;
  74434. }(BABYLON.PostProcess));
  74435. BABYLON.GrainPostProcess = GrainPostProcess;
  74436. })(BABYLON || (BABYLON = {}));
  74437. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74438. var BABYLON;
  74439. (function (BABYLON) {
  74440. /**
  74441. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74442. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74443. */
  74444. var SharpenPostProcess = /** @class */ (function (_super) {
  74445. __extends(SharpenPostProcess, _super);
  74446. /**
  74447. * Creates a new instance ConvolutionPostProcess
  74448. * @param name The name of the effect.
  74449. * @param options The required width/height ratio to downsize to before computing the render pass.
  74450. * @param camera The camera to apply the render pass to.
  74451. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74452. * @param engine The engine which the post process will be applied. (default: current engine)
  74453. * @param reusable If the post process can be reused on the same frame. (default: false)
  74454. * @param textureType Type of textures used when performing the post process. (default: 0)
  74455. * @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)
  74456. */
  74457. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74458. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74459. if (blockCompilation === void 0) { blockCompilation = false; }
  74460. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74461. /**
  74462. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74463. */
  74464. _this.colorAmount = 1.0;
  74465. /**
  74466. * How much sharpness should be applied (default: 0.3)
  74467. */
  74468. _this.edgeAmount = 0.3;
  74469. _this.onApply = function (effect) {
  74470. effect.setFloat2("screenSize", _this.width, _this.height);
  74471. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74472. };
  74473. return _this;
  74474. }
  74475. return SharpenPostProcess;
  74476. }(BABYLON.PostProcess));
  74477. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74478. })(BABYLON || (BABYLON = {}));
  74479. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74480. var BABYLON;
  74481. (function (BABYLON) {
  74482. /**
  74483. * The Blur Post Process which blurs an image based on a kernel and direction.
  74484. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74485. */
  74486. var BlurPostProcess = /** @class */ (function (_super) {
  74487. __extends(BlurPostProcess, _super);
  74488. /**
  74489. * Creates a new instance BlurPostProcess
  74490. * @param name The name of the effect.
  74491. * @param direction The direction in which to blur the image.
  74492. * @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.
  74493. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74494. * @param camera The camera to apply the render pass to.
  74495. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74496. * @param engine The engine which the post process will be applied. (default: current engine)
  74497. * @param reusable If the post process can be reused on the same frame. (default: false)
  74498. * @param textureType Type of textures used when performing the post process. (default: 0)
  74499. * @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)
  74500. */
  74501. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74502. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74503. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74504. if (defines === void 0) { defines = ""; }
  74505. if (blockCompilation === void 0) { blockCompilation = false; }
  74506. 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;
  74507. _this.direction = direction;
  74508. _this.blockCompilation = blockCompilation;
  74509. _this._packedFloat = false;
  74510. _this._staticDefines = "";
  74511. _this._staticDefines = defines;
  74512. _this.onApplyObservable.add(function (effect) {
  74513. if (_this._outputTexture) {
  74514. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74515. }
  74516. else {
  74517. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74518. }
  74519. });
  74520. _this.kernel = kernel;
  74521. return _this;
  74522. }
  74523. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74524. /**
  74525. * Gets the length in pixels of the blur sample region
  74526. */
  74527. get: function () {
  74528. return this._idealKernel;
  74529. },
  74530. /**
  74531. * Sets the length in pixels of the blur sample region
  74532. */
  74533. set: function (v) {
  74534. if (this._idealKernel === v) {
  74535. return;
  74536. }
  74537. v = Math.max(v, 1);
  74538. this._idealKernel = v;
  74539. this._kernel = this._nearestBestKernel(v);
  74540. if (!this.blockCompilation) {
  74541. this._updateParameters();
  74542. }
  74543. },
  74544. enumerable: true,
  74545. configurable: true
  74546. });
  74547. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74548. /**
  74549. * Gets wether or not the blur is unpacking/repacking floats
  74550. */
  74551. get: function () {
  74552. return this._packedFloat;
  74553. },
  74554. /**
  74555. * Sets wether or not the blur needs to unpack/repack floats
  74556. */
  74557. set: function (v) {
  74558. if (this._packedFloat === v) {
  74559. return;
  74560. }
  74561. this._packedFloat = v;
  74562. if (!this.blockCompilation) {
  74563. this._updateParameters();
  74564. }
  74565. },
  74566. enumerable: true,
  74567. configurable: true
  74568. });
  74569. /**
  74570. * Updates the effect with the current post process compile time values and recompiles the shader.
  74571. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74572. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74573. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74574. * @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
  74575. * @param onCompiled Called when the shader has been compiled.
  74576. * @param onError Called if there is an error when compiling a shader.
  74577. */
  74578. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74579. if (defines === void 0) { defines = null; }
  74580. if (uniforms === void 0) { uniforms = null; }
  74581. if (samplers === void 0) { samplers = null; }
  74582. this._updateParameters(onCompiled, onError);
  74583. };
  74584. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74585. // Generate sampling offsets and weights
  74586. var N = this._kernel;
  74587. var centerIndex = (N - 1) / 2;
  74588. // Generate Gaussian sampling weights over kernel
  74589. var offsets = [];
  74590. var weights = [];
  74591. var totalWeight = 0;
  74592. for (var i = 0; i < N; i++) {
  74593. var u = i / (N - 1);
  74594. var w = this._gaussianWeight(u * 2.0 - 1);
  74595. offsets[i] = (i - centerIndex);
  74596. weights[i] = w;
  74597. totalWeight += w;
  74598. }
  74599. // Normalize weights
  74600. for (var i = 0; i < weights.length; i++) {
  74601. weights[i] /= totalWeight;
  74602. }
  74603. // Optimize: combine samples to take advantage of hardware linear sampling
  74604. // Walk from left to center, combining pairs (symmetrically)
  74605. var linearSamplingWeights = [];
  74606. var linearSamplingOffsets = [];
  74607. var linearSamplingMap = [];
  74608. for (var i = 0; i <= centerIndex; i += 2) {
  74609. var j = Math.min(i + 1, Math.floor(centerIndex));
  74610. var singleCenterSample = i === j;
  74611. if (singleCenterSample) {
  74612. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74613. }
  74614. else {
  74615. var sharedCell = j === centerIndex;
  74616. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74617. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74618. if (offsetLinear === 0) {
  74619. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74620. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74621. }
  74622. else {
  74623. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74624. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74625. }
  74626. }
  74627. }
  74628. for (var i = 0; i < linearSamplingMap.length; i++) {
  74629. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74630. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74631. }
  74632. // Replace with optimized
  74633. offsets = linearSamplingOffsets;
  74634. weights = linearSamplingWeights;
  74635. // Generate shaders
  74636. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74637. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74638. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74639. var defines = "";
  74640. defines += this._staticDefines;
  74641. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74642. if (this._staticDefines.indexOf("DOF") != -1) {
  74643. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74644. varyingCount--;
  74645. }
  74646. for (var i = 0; i < varyingCount; i++) {
  74647. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74648. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74649. }
  74650. var depCount = 0;
  74651. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74652. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74653. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74654. depCount++;
  74655. }
  74656. if (this.packedFloat) {
  74657. defines += "#define PACKEDFLOAT 1";
  74658. }
  74659. this.blockCompilation = false;
  74660. _super.prototype.updateEffect.call(this, defines, null, null, {
  74661. varyingCount: varyingCount,
  74662. depCount: depCount
  74663. }, onCompiled, onError);
  74664. };
  74665. /**
  74666. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74667. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74668. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74669. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74670. * The gaps between physical kernels are compensated for in the weighting of the samples
  74671. * @param idealKernel Ideal blur kernel.
  74672. * @return Nearest best kernel.
  74673. */
  74674. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74675. var v = Math.round(idealKernel);
  74676. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74677. var k = _a[_i];
  74678. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74679. return Math.max(k, 3);
  74680. }
  74681. }
  74682. return Math.max(v, 3);
  74683. };
  74684. /**
  74685. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74686. * @param x The point on the Gaussian distribution to sample.
  74687. * @return the value of the Gaussian function at x.
  74688. */
  74689. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74690. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74691. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74692. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74693. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74694. // truncated at around 1.3% of peak strength.
  74695. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74696. var sigma = (1 / 3);
  74697. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74698. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74699. var weight = (1.0 / denominator) * Math.exp(exponent);
  74700. return weight;
  74701. };
  74702. /**
  74703. * Generates a string that can be used as a floating point number in GLSL.
  74704. * @param x Value to print.
  74705. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74706. * @return GLSL float string.
  74707. */
  74708. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74709. if (decimalFigures === void 0) { decimalFigures = 8; }
  74710. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74711. };
  74712. return BlurPostProcess;
  74713. }(BABYLON.PostProcess));
  74714. BABYLON.BlurPostProcess = BlurPostProcess;
  74715. })(BABYLON || (BABYLON = {}));
  74716. //# sourceMappingURL=babylon.blurPostProcess.js.map
  74717. var BABYLON;
  74718. (function (BABYLON) {
  74719. /**
  74720. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  74721. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  74722. * based on samples that have a large difference in distance than the center pixel.
  74723. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74724. */
  74725. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  74726. __extends(DepthOfFieldBlurPostProcess, _super);
  74727. /**
  74728. * Creates a new instance CircleOfConfusionPostProcess
  74729. * @param name The name of the effect.
  74730. * @param scene The scene the effect belongs to.
  74731. * @param direction The direction the blur should be applied.
  74732. * @param kernel The size of the kernel used to blur.
  74733. * @param options The required width/height ratio to downsize to before computing the render pass.
  74734. * @param camera The camera to apply the render pass to.
  74735. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  74736. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  74737. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74738. * @param engine The engine which the post process will be applied. (default: current engine)
  74739. * @param reusable If the post process can be reused on the same frame. (default: false)
  74740. * @param textureType Type of textures used when performing the post process. (default: 0)
  74741. * @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)
  74742. */
  74743. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  74744. if (imageToBlur === void 0) { imageToBlur = null; }
  74745. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74746. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74747. if (blockCompilation === void 0) { blockCompilation = false; }
  74748. 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;
  74749. _this.direction = direction;
  74750. _this.onApplyObservable.add(function (effect) {
  74751. if (imageToBlur != null) {
  74752. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  74753. }
  74754. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74755. if (scene.activeCamera) {
  74756. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74757. }
  74758. });
  74759. return _this;
  74760. }
  74761. return DepthOfFieldBlurPostProcess;
  74762. }(BABYLON.BlurPostProcess));
  74763. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  74764. })(BABYLON || (BABYLON = {}));
  74765. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  74766. var BABYLON;
  74767. (function (BABYLON) {
  74768. /**
  74769. * Options to be set when merging outputs from the default pipeline.
  74770. */
  74771. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  74772. function DepthOfFieldMergePostProcessOptions() {
  74773. }
  74774. return DepthOfFieldMergePostProcessOptions;
  74775. }());
  74776. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  74777. /**
  74778. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74779. */
  74780. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  74781. __extends(DepthOfFieldMergePostProcess, _super);
  74782. /**
  74783. * Creates a new instance of DepthOfFieldMergePostProcess
  74784. * @param name The name of the effect.
  74785. * @param originalFromInput Post process which's input will be used for the merge.
  74786. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  74787. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  74788. * @param options The required width/height ratio to downsize to before computing the render pass.
  74789. * @param camera The camera to apply the render pass to.
  74790. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74791. * @param engine The engine which the post process will be applied. (default: current engine)
  74792. * @param reusable If the post process can be reused on the same frame. (default: false)
  74793. * @param textureType Type of textures used when performing the post process. (default: 0)
  74794. * @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)
  74795. */
  74796. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74797. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74798. if (blockCompilation === void 0) { blockCompilation = false; }
  74799. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74800. _this.blurSteps = blurSteps;
  74801. _this.onApplyObservable.add(function (effect) {
  74802. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74803. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74804. blurSteps.forEach(function (step, index) {
  74805. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  74806. });
  74807. });
  74808. if (!blockCompilation) {
  74809. _this.updateEffect();
  74810. }
  74811. return _this;
  74812. }
  74813. /**
  74814. * Updates the effect with the current post process compile time values and recompiles the shader.
  74815. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74816. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74817. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74818. * @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
  74819. * @param onCompiled Called when the shader has been compiled.
  74820. * @param onError Called if there is an error when compiling a shader.
  74821. */
  74822. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74823. if (defines === void 0) { defines = null; }
  74824. if (uniforms === void 0) { uniforms = null; }
  74825. if (samplers === void 0) { samplers = null; }
  74826. if (!defines) {
  74827. defines = "";
  74828. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  74829. }
  74830. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  74831. };
  74832. return DepthOfFieldMergePostProcess;
  74833. }(BABYLON.PostProcess));
  74834. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  74835. })(BABYLON || (BABYLON = {}));
  74836. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  74837. var BABYLON;
  74838. (function (BABYLON) {
  74839. /**
  74840. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  74841. */
  74842. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  74843. __extends(CircleOfConfusionPostProcess, _super);
  74844. /**
  74845. * Creates a new instance CircleOfConfusionPostProcess
  74846. * @param name The name of the effect.
  74847. * @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.
  74848. * @param options The required width/height ratio to downsize to before computing the render pass.
  74849. * @param camera The camera to apply the render pass to.
  74850. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74851. * @param engine The engine which the post process will be applied. (default: current engine)
  74852. * @param reusable If the post process can be reused on the same frame. (default: false)
  74853. * @param textureType Type of textures used when performing the post process. (default: 0)
  74854. * @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)
  74855. */
  74856. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74857. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74858. if (blockCompilation === void 0) { blockCompilation = false; }
  74859. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74860. /**
  74861. * 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.
  74862. */
  74863. _this.lensSize = 50;
  74864. /**
  74865. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74866. */
  74867. _this.fStop = 1.4;
  74868. /**
  74869. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74870. */
  74871. _this.focusDistance = 2000;
  74872. /**
  74873. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  74874. */
  74875. _this.focalLength = 50;
  74876. _this._depthTexture = null;
  74877. _this._depthTexture = depthTexture;
  74878. _this.onApplyObservable.add(function (effect) {
  74879. if (!_this._depthTexture) {
  74880. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  74881. return;
  74882. }
  74883. effect.setTexture("depthSampler", _this._depthTexture);
  74884. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  74885. var aperture = _this.lensSize / _this.fStop;
  74886. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  74887. effect.setFloat('focusDistance', _this.focusDistance);
  74888. effect.setFloat('cocPrecalculation', cocPrecalculation);
  74889. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  74890. });
  74891. return _this;
  74892. }
  74893. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  74894. /**
  74895. * 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.
  74896. */
  74897. set: function (value) {
  74898. this._depthTexture = value;
  74899. },
  74900. enumerable: true,
  74901. configurable: true
  74902. });
  74903. return CircleOfConfusionPostProcess;
  74904. }(BABYLON.PostProcess));
  74905. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  74906. })(BABYLON || (BABYLON = {}));
  74907. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  74908. var BABYLON;
  74909. (function (BABYLON) {
  74910. /**
  74911. * Specifies the level of max blur that should be applied when using the depth of field effect
  74912. */
  74913. var DepthOfFieldEffectBlurLevel;
  74914. (function (DepthOfFieldEffectBlurLevel) {
  74915. /**
  74916. * Subtle blur
  74917. */
  74918. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  74919. /**
  74920. * Medium blur
  74921. */
  74922. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  74923. /**
  74924. * Large blur
  74925. */
  74926. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  74927. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  74928. ;
  74929. /**
  74930. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  74931. */
  74932. var DepthOfFieldEffect = /** @class */ (function (_super) {
  74933. __extends(DepthOfFieldEffect, _super);
  74934. /**
  74935. * Creates a new instance DepthOfFieldEffect
  74936. * @param scene The scene the effect belongs to.
  74937. * @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.
  74938. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  74939. * @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)
  74940. */
  74941. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  74942. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  74943. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  74944. if (blockCompilation === void 0) { blockCompilation = false; }
  74945. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  74946. return _this._effects;
  74947. }, true) || this;
  74948. /**
  74949. * Internal post processes in depth of field effect
  74950. */
  74951. _this._effects = [];
  74952. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  74953. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74954. // 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)
  74955. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  74956. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74957. _this._depthOfFieldBlurY = [];
  74958. _this._depthOfFieldBlurX = [];
  74959. var blurCount = 1;
  74960. var kernelSize = 15;
  74961. switch (blurLevel) {
  74962. case DepthOfFieldEffectBlurLevel.High: {
  74963. blurCount = 3;
  74964. kernelSize = 51;
  74965. break;
  74966. }
  74967. case DepthOfFieldEffectBlurLevel.Medium: {
  74968. blurCount = 2;
  74969. kernelSize = 31;
  74970. break;
  74971. }
  74972. default: {
  74973. kernelSize = 15;
  74974. blurCount = 1;
  74975. break;
  74976. }
  74977. }
  74978. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  74979. var ratio = 1.0;
  74980. for (var i = 0; i < blurCount; i++) {
  74981. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74982. blurY.autoClear = false;
  74983. ratio = 0.75 / Math.pow(2, i);
  74984. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74985. blurX.autoClear = false;
  74986. _this._depthOfFieldBlurY.push(blurY);
  74987. _this._depthOfFieldBlurX.push(blurX);
  74988. }
  74989. // Set all post processes on the effect.
  74990. _this._effects = [_this._circleOfConfusion];
  74991. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  74992. _this._effects.push(_this._depthOfFieldBlurY[i]);
  74993. _this._effects.push(_this._depthOfFieldBlurX[i]);
  74994. }
  74995. // Merge blurred images with original image based on circleOfConfusion
  74996. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74997. _this._dofMerge.autoClear = false;
  74998. _this._effects.push(_this._dofMerge);
  74999. return _this;
  75000. }
  75001. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75002. get: function () {
  75003. return this._circleOfConfusion.focalLength;
  75004. },
  75005. /**
  75006. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75007. */
  75008. set: function (value) {
  75009. this._circleOfConfusion.focalLength = value;
  75010. },
  75011. enumerable: true,
  75012. configurable: true
  75013. });
  75014. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75015. get: function () {
  75016. return this._circleOfConfusion.fStop;
  75017. },
  75018. /**
  75019. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75020. */
  75021. set: function (value) {
  75022. this._circleOfConfusion.fStop = value;
  75023. },
  75024. enumerable: true,
  75025. configurable: true
  75026. });
  75027. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75028. get: function () {
  75029. return this._circleOfConfusion.focusDistance;
  75030. },
  75031. /**
  75032. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75033. */
  75034. set: function (value) {
  75035. this._circleOfConfusion.focusDistance = value;
  75036. },
  75037. enumerable: true,
  75038. configurable: true
  75039. });
  75040. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75041. get: function () {
  75042. return this._circleOfConfusion.lensSize;
  75043. },
  75044. /**
  75045. * 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.
  75046. */
  75047. set: function (value) {
  75048. this._circleOfConfusion.lensSize = value;
  75049. },
  75050. enumerable: true,
  75051. configurable: true
  75052. });
  75053. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75054. /**
  75055. * 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.
  75056. */
  75057. set: function (value) {
  75058. this._circleOfConfusion.depthTexture = value;
  75059. },
  75060. enumerable: true,
  75061. configurable: true
  75062. });
  75063. /**
  75064. * Disposes each of the internal effects for a given camera.
  75065. * @param camera The camera to dispose the effect on.
  75066. */
  75067. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75068. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75069. this._effects[effectIndex].dispose(camera);
  75070. }
  75071. };
  75072. /**
  75073. * Internal
  75074. */
  75075. DepthOfFieldEffect.prototype._updateEffects = function () {
  75076. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75077. this._effects[effectIndex].updateEffect();
  75078. }
  75079. };
  75080. /**
  75081. * Internal
  75082. * @returns if all the contained post processes are ready.
  75083. */
  75084. DepthOfFieldEffect.prototype._isReady = function () {
  75085. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75086. if (!this._effects[effectIndex].isReady()) {
  75087. return false;
  75088. }
  75089. }
  75090. return true;
  75091. };
  75092. return DepthOfFieldEffect;
  75093. }(BABYLON.PostProcessRenderEffect));
  75094. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75095. })(BABYLON || (BABYLON = {}));
  75096. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75097. var BABYLON;
  75098. (function (BABYLON) {
  75099. /**
  75100. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75101. */
  75102. var BloomMergePostProcess = /** @class */ (function (_super) {
  75103. __extends(BloomMergePostProcess, _super);
  75104. /**
  75105. * Creates a new instance of @see BloomMergePostProcess
  75106. * @param name The name of the effect.
  75107. * @param originalFromInput Post process which's input will be used for the merge.
  75108. * @param blurred Blurred highlights post process which's output will be used.
  75109. * @param weight Weight of the bloom to be added to the original input.
  75110. * @param options The required width/height ratio to downsize to before computing the render pass.
  75111. * @param camera The camera to apply the render pass to.
  75112. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75113. * @param engine The engine which the post process will be applied. (default: current engine)
  75114. * @param reusable If the post process can be reused on the same frame. (default: false)
  75115. * @param textureType Type of textures used when performing the post process. (default: 0)
  75116. * @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)
  75117. */
  75118. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75119. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75120. if (blockCompilation === void 0) { blockCompilation = false; }
  75121. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75122. _this.weight = weight;
  75123. _this.onApplyObservable.add(function (effect) {
  75124. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75125. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75126. effect.setFloat("bloomWeight", _this.weight);
  75127. });
  75128. if (!blockCompilation) {
  75129. _this.updateEffect();
  75130. }
  75131. return _this;
  75132. }
  75133. return BloomMergePostProcess;
  75134. }(BABYLON.PostProcess));
  75135. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75136. })(BABYLON || (BABYLON = {}));
  75137. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75138. var BABYLON;
  75139. (function (BABYLON) {
  75140. /**
  75141. * The extract highlights post process sets all pixels to black except pixels above the specified luminance threshold. Used as the first step for a bloom effect.
  75142. */
  75143. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75144. __extends(ExtractHighlightsPostProcess, _super);
  75145. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75146. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75147. if (blockCompilation === void 0) { blockCompilation = false; }
  75148. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75149. /**
  75150. * The luminance threshold, pixels below this value will be set to black.
  75151. */
  75152. _this.threshold = 0.9;
  75153. /**
  75154. * Internal
  75155. */
  75156. _this._exposure = 1;
  75157. /**
  75158. * Post process which has the input texture to be used when performing highlight extraction
  75159. */
  75160. _this._inputPostProcess = null;
  75161. _this.onApplyObservable.add(function (effect) {
  75162. if (_this._inputPostProcess) {
  75163. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75164. }
  75165. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75166. effect.setFloat('exposure', _this._exposure);
  75167. });
  75168. return _this;
  75169. }
  75170. return ExtractHighlightsPostProcess;
  75171. }(BABYLON.PostProcess));
  75172. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75173. })(BABYLON || (BABYLON = {}));
  75174. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75175. var BABYLON;
  75176. (function (BABYLON) {
  75177. /**
  75178. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75179. */
  75180. var BloomEffect = /** @class */ (function (_super) {
  75181. __extends(BloomEffect, _super);
  75182. /**
  75183. * Creates a new instance of @see BloomEffect
  75184. * @param scene The scene the effect belongs to.
  75185. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75186. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75187. * @param bloomWeight The the strength of bloom.
  75188. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75189. * @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)
  75190. */
  75191. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75192. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75193. if (blockCompilation === void 0) { blockCompilation = false; }
  75194. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75195. return _this._effects;
  75196. }, true) || this;
  75197. _this.bloomScale = bloomScale;
  75198. /**
  75199. * Internal
  75200. */
  75201. _this._effects = [];
  75202. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75203. _this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  75204. _this._blurX.alwaysForcePOT = true;
  75205. _this._blurX.autoClear = false;
  75206. _this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
  75207. _this._blurY.alwaysForcePOT = true;
  75208. _this._blurY.autoClear = false;
  75209. _this.kernel = bloomKernel;
  75210. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75211. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75212. _this._merge.autoClear = false;
  75213. _this._effects.push(_this._merge);
  75214. return _this;
  75215. }
  75216. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75217. /**
  75218. * The luminance threshold to find bright areas of the image to bloom.
  75219. */
  75220. get: function () {
  75221. return this._downscale.threshold;
  75222. },
  75223. set: function (value) {
  75224. this._downscale.threshold = value;
  75225. },
  75226. enumerable: true,
  75227. configurable: true
  75228. });
  75229. Object.defineProperty(BloomEffect.prototype, "weight", {
  75230. /**
  75231. * The strength of the bloom.
  75232. */
  75233. get: function () {
  75234. return this._merge.weight;
  75235. },
  75236. set: function (value) {
  75237. this._merge.weight = value;
  75238. },
  75239. enumerable: true,
  75240. configurable: true
  75241. });
  75242. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75243. /**
  75244. * Specifies the size of the bloom blur kernel, relative to the final output size
  75245. */
  75246. get: function () {
  75247. return this._blurX.kernel / this.bloomScale;
  75248. },
  75249. set: function (value) {
  75250. this._blurX.kernel = value * this.bloomScale;
  75251. this._blurY.kernel = value * this.bloomScale;
  75252. },
  75253. enumerable: true,
  75254. configurable: true
  75255. });
  75256. /**
  75257. * Disposes each of the internal effects for a given camera.
  75258. * @param camera The camera to dispose the effect on.
  75259. */
  75260. BloomEffect.prototype.disposeEffects = function (camera) {
  75261. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75262. this._effects[effectIndex].dispose(camera);
  75263. }
  75264. };
  75265. /**
  75266. * Internal
  75267. */
  75268. BloomEffect.prototype._updateEffects = function () {
  75269. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75270. this._effects[effectIndex].updateEffect();
  75271. }
  75272. };
  75273. /**
  75274. * Internal
  75275. * @returns if all the contained post processes are ready.
  75276. */
  75277. BloomEffect.prototype._isReady = function () {
  75278. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75279. if (!this._effects[effectIndex].isReady()) {
  75280. return false;
  75281. }
  75282. }
  75283. return true;
  75284. };
  75285. return BloomEffect;
  75286. }(BABYLON.PostProcessRenderEffect));
  75287. BABYLON.BloomEffect = BloomEffect;
  75288. })(BABYLON || (BABYLON = {}));
  75289. //# sourceMappingURL=babylon.bloomEffect.js.map
  75290. var BABYLON;
  75291. (function (BABYLON) {
  75292. /**
  75293. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75294. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75295. */
  75296. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75297. __extends(DefaultRenderingPipeline, _super);
  75298. /**
  75299. * @constructor
  75300. * @param {string} name - The rendering pipeline name
  75301. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75302. * @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)
  75303. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75304. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  75305. */
  75306. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75307. if (automaticBuild === void 0) { automaticBuild = true; }
  75308. var _this = _super.call(this, scene.getEngine(), name) || this;
  75309. _this._originalCameras = [];
  75310. /**
  75311. * ID of the sharpen post process,
  75312. */
  75313. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75314. /**
  75315. * ID of the image processing post process;
  75316. */
  75317. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75318. /**
  75319. * ID of the Fast Approximate Anti-Aliasing post process;
  75320. */
  75321. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75322. /**
  75323. * ID of the chromatic aberration post process,
  75324. */
  75325. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75326. /**
  75327. * ID of the grain post process
  75328. */
  75329. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75330. /**
  75331. * Animations which can be used to tweak settings over a period of time
  75332. */
  75333. _this.animations = [];
  75334. _this._imageProcessingConfigurationObserver = null;
  75335. // Values
  75336. _this._sharpenEnabled = false;
  75337. _this._bloomEnabled = false;
  75338. _this._depthOfFieldEnabled = false;
  75339. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75340. _this._fxaaEnabled = false;
  75341. _this._imageProcessingEnabled = true;
  75342. _this._bloomScale = 0.5;
  75343. _this._chromaticAberrationEnabled = false;
  75344. _this._grainEnabled = false;
  75345. _this._buildAllowed = true;
  75346. _this._resizeObserver = null;
  75347. _this._hardwareScaleLevel = 1.0;
  75348. _this._bloomKernel = 64;
  75349. /**
  75350. * Specifies the weight of the bloom in the final rendering
  75351. */
  75352. _this._bloomWeight = 0.15;
  75353. /**
  75354. * Specifies the luma threshold for the area that will be blurred by the bloom
  75355. */
  75356. _this._bloomThreshold = 0.9;
  75357. _this._samples = 1;
  75358. _this._hasCleared = false;
  75359. _this._prevPostProcess = null;
  75360. _this._prevPrevPostProcess = null;
  75361. _this._cameras = cameras || [];
  75362. _this._originalCameras = _this._cameras.slice();
  75363. _this._buildAllowed = automaticBuild;
  75364. // Initialize
  75365. _this._scene = scene;
  75366. var caps = _this._scene.getEngine().getCaps();
  75367. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75368. // Misc
  75369. if (_this._hdr) {
  75370. if (caps.textureHalfFloatRender) {
  75371. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75372. }
  75373. else if (caps.textureFloatRender) {
  75374. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75375. }
  75376. }
  75377. else {
  75378. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75379. }
  75380. // Attach
  75381. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75382. var engine = _this._scene.getEngine();
  75383. // Create post processes before hand so they can be modified before enabled.
  75384. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75385. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75386. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75387. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75388. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75389. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75390. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75391. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75392. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75393. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75394. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75395. _this.bloomKernel = _this.bloomKernel;
  75396. });
  75397. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75398. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75399. });
  75400. _this._buildPipeline();
  75401. return _this;
  75402. }
  75403. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75404. get: function () {
  75405. return this._sharpenEnabled;
  75406. },
  75407. /**
  75408. * Enable or disable the sharpen process from the pipeline
  75409. */
  75410. set: function (enabled) {
  75411. if (this._sharpenEnabled === enabled) {
  75412. return;
  75413. }
  75414. this._sharpenEnabled = enabled;
  75415. this._buildPipeline();
  75416. },
  75417. enumerable: true,
  75418. configurable: true
  75419. });
  75420. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75421. /**
  75422. * Specifies the size of the bloom blur kernel, relative to the final output size
  75423. */
  75424. get: function () {
  75425. return this._bloomKernel;
  75426. },
  75427. set: function (value) {
  75428. this._bloomKernel = value;
  75429. this.bloom.kernel = value / this._hardwareScaleLevel;
  75430. },
  75431. enumerable: true,
  75432. configurable: true
  75433. });
  75434. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75435. get: function () {
  75436. return this._bloomWeight;
  75437. },
  75438. /**
  75439. * The strength of the bloom.
  75440. */
  75441. set: function (value) {
  75442. if (this._bloomWeight === value) {
  75443. return;
  75444. }
  75445. this.bloom.weight = value;
  75446. this._bloomWeight = value;
  75447. },
  75448. enumerable: true,
  75449. configurable: true
  75450. });
  75451. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75452. get: function () {
  75453. return this._bloomThreshold;
  75454. },
  75455. /**
  75456. * The strength of the bloom.
  75457. */
  75458. set: function (value) {
  75459. if (this._bloomThreshold === value) {
  75460. return;
  75461. }
  75462. this.bloom.threshold = value;
  75463. this._bloomThreshold = value;
  75464. },
  75465. enumerable: true,
  75466. configurable: true
  75467. });
  75468. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75469. get: function () {
  75470. return this._bloomScale;
  75471. },
  75472. /**
  75473. * The scale of the bloom, lower value will provide better performance.
  75474. */
  75475. set: function (value) {
  75476. if (this._bloomScale === value) {
  75477. return;
  75478. }
  75479. this._bloomScale = value;
  75480. // recreate bloom and dispose old as this setting is not dynamic
  75481. this._rebuildBloom();
  75482. this._buildPipeline();
  75483. },
  75484. enumerable: true,
  75485. configurable: true
  75486. });
  75487. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75488. get: function () {
  75489. return this._bloomEnabled;
  75490. },
  75491. /**
  75492. * Enable or disable the bloom from the pipeline
  75493. */
  75494. set: function (enabled) {
  75495. if (this._bloomEnabled === enabled) {
  75496. return;
  75497. }
  75498. this._bloomEnabled = enabled;
  75499. this._buildPipeline();
  75500. },
  75501. enumerable: true,
  75502. configurable: true
  75503. });
  75504. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75505. // recreate bloom and dispose old as this setting is not dynamic
  75506. var oldBloom = this.bloom;
  75507. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75508. this.bloom.threshold = oldBloom.threshold;
  75509. for (var i = 0; i < this._cameras.length; i++) {
  75510. oldBloom.disposeEffects(this._cameras[i]);
  75511. }
  75512. };
  75513. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75514. /**
  75515. * If the depth of field is enabled.
  75516. */
  75517. get: function () {
  75518. return this._depthOfFieldEnabled;
  75519. },
  75520. set: function (enabled) {
  75521. if (this._depthOfFieldEnabled === enabled) {
  75522. return;
  75523. }
  75524. this._depthOfFieldEnabled = enabled;
  75525. this._buildPipeline();
  75526. },
  75527. enumerable: true,
  75528. configurable: true
  75529. });
  75530. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75531. /**
  75532. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75533. */
  75534. get: function () {
  75535. return this._depthOfFieldBlurLevel;
  75536. },
  75537. set: function (value) {
  75538. if (this._depthOfFieldBlurLevel === value) {
  75539. return;
  75540. }
  75541. this._depthOfFieldBlurLevel = value;
  75542. // recreate dof and dispose old as this setting is not dynamic
  75543. var oldDof = this.depthOfField;
  75544. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75545. this.depthOfField.focalLength = oldDof.focalLength;
  75546. this.depthOfField.focusDistance = oldDof.focusDistance;
  75547. this.depthOfField.fStop = oldDof.fStop;
  75548. this.depthOfField.lensSize = oldDof.lensSize;
  75549. for (var i = 0; i < this._cameras.length; i++) {
  75550. oldDof.disposeEffects(this._cameras[i]);
  75551. }
  75552. this._buildPipeline();
  75553. },
  75554. enumerable: true,
  75555. configurable: true
  75556. });
  75557. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75558. get: function () {
  75559. return this._fxaaEnabled;
  75560. },
  75561. /**
  75562. * If the anti aliasing is enabled.
  75563. */
  75564. set: function (enabled) {
  75565. if (this._fxaaEnabled === enabled) {
  75566. return;
  75567. }
  75568. this._fxaaEnabled = enabled;
  75569. this._buildPipeline();
  75570. },
  75571. enumerable: true,
  75572. configurable: true
  75573. });
  75574. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75575. get: function () {
  75576. return this._samples;
  75577. },
  75578. /**
  75579. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75580. */
  75581. set: function (sampleCount) {
  75582. if (this._samples === sampleCount) {
  75583. return;
  75584. }
  75585. this._samples = sampleCount;
  75586. this._buildPipeline();
  75587. },
  75588. enumerable: true,
  75589. configurable: true
  75590. });
  75591. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75592. get: function () {
  75593. return this._imageProcessingEnabled;
  75594. },
  75595. /**
  75596. * If image processing is enabled.
  75597. */
  75598. set: function (enabled) {
  75599. if (this._imageProcessingEnabled === enabled) {
  75600. return;
  75601. }
  75602. this._imageProcessingEnabled = enabled;
  75603. this._buildPipeline();
  75604. },
  75605. enumerable: true,
  75606. configurable: true
  75607. });
  75608. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75609. get: function () {
  75610. return this._chromaticAberrationEnabled;
  75611. },
  75612. /**
  75613. * Enable or disable the chromaticAberration process from the pipeline
  75614. */
  75615. set: function (enabled) {
  75616. if (this._chromaticAberrationEnabled === enabled) {
  75617. return;
  75618. }
  75619. this._chromaticAberrationEnabled = enabled;
  75620. this._buildPipeline();
  75621. },
  75622. enumerable: true,
  75623. configurable: true
  75624. });
  75625. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75626. get: function () {
  75627. return this._grainEnabled;
  75628. },
  75629. /**
  75630. * Enable or disable the grain process from the pipeline
  75631. */
  75632. set: function (enabled) {
  75633. if (this._grainEnabled === enabled) {
  75634. return;
  75635. }
  75636. this._grainEnabled = enabled;
  75637. this._buildPipeline();
  75638. },
  75639. enumerable: true,
  75640. configurable: true
  75641. });
  75642. /**
  75643. * Force the compilation of the entire pipeline.
  75644. */
  75645. DefaultRenderingPipeline.prototype.prepare = function () {
  75646. var previousState = this._buildAllowed;
  75647. this._buildAllowed = true;
  75648. this._buildPipeline();
  75649. this._buildAllowed = previousState;
  75650. };
  75651. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75652. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75653. if (this._hasCleared) {
  75654. postProcess.autoClear = false;
  75655. }
  75656. else {
  75657. postProcess.autoClear = true;
  75658. this._scene.autoClear = false;
  75659. this._hasCleared = true;
  75660. }
  75661. if (!skipTextureSharing) {
  75662. if (this._prevPrevPostProcess) {
  75663. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75664. }
  75665. else {
  75666. postProcess.useOwnOutput();
  75667. }
  75668. if (this._prevPostProcess) {
  75669. this._prevPrevPostProcess = this._prevPostProcess;
  75670. }
  75671. this._prevPostProcess = postProcess;
  75672. }
  75673. };
  75674. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75675. var _this = this;
  75676. if (!this._buildAllowed) {
  75677. return;
  75678. }
  75679. this._scene.autoClear = true;
  75680. var engine = this._scene.getEngine();
  75681. this._disposePostProcesses();
  75682. if (this._cameras !== null) {
  75683. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75684. // get back cameras to be used to reattach pipeline
  75685. this._cameras = this._originalCameras.slice();
  75686. }
  75687. this._reset();
  75688. this._prevPostProcess = null;
  75689. this._prevPrevPostProcess = null;
  75690. this._hasCleared = false;
  75691. if (this.depthOfFieldEnabled) {
  75692. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  75693. this.depthOfField.depthTexture = depthTexture;
  75694. if (!this.depthOfField._isReady()) {
  75695. this.depthOfField._updateEffects();
  75696. }
  75697. this.addEffect(this.depthOfField);
  75698. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  75699. }
  75700. if (this.bloomEnabled) {
  75701. if (!this.bloom._isReady()) {
  75702. this.bloom._updateEffects();
  75703. }
  75704. this.addEffect(this.bloom);
  75705. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  75706. }
  75707. if (this._imageProcessingEnabled) {
  75708. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75709. if (this._hdr) {
  75710. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  75711. this._setAutoClearAndTextureSharing(this.imageProcessing);
  75712. }
  75713. else {
  75714. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  75715. }
  75716. }
  75717. if (this.sharpenEnabled) {
  75718. if (!this.sharpen.isReady()) {
  75719. this.sharpen.updateEffect();
  75720. }
  75721. this.addEffect(this._sharpenEffect);
  75722. this._setAutoClearAndTextureSharing(this.sharpen);
  75723. }
  75724. if (this.grainEnabled) {
  75725. if (!this.grain.isReady()) {
  75726. this.grain.updateEffect();
  75727. }
  75728. this.addEffect(this._grainEffect);
  75729. this._setAutoClearAndTextureSharing(this.grain);
  75730. }
  75731. if (this.chromaticAberrationEnabled) {
  75732. if (!this.chromaticAberration.isReady()) {
  75733. this.chromaticAberration.updateEffect();
  75734. }
  75735. this.addEffect(this._chromaticAberrationEffect);
  75736. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  75737. }
  75738. if (this.fxaaEnabled) {
  75739. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75740. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  75741. this._setAutoClearAndTextureSharing(this.fxaa, true);
  75742. }
  75743. if (this._cameras !== null) {
  75744. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75745. }
  75746. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  75747. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  75748. }
  75749. };
  75750. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  75751. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  75752. for (var i = 0; i < this._cameras.length; i++) {
  75753. var camera = this._cameras[i];
  75754. if (this.imageProcessing) {
  75755. this.imageProcessing.dispose(camera);
  75756. }
  75757. if (this.fxaa) {
  75758. this.fxaa.dispose(camera);
  75759. }
  75760. // These are created in the constructor and should not be disposed on every pipeline change
  75761. if (disposeNonRecreated) {
  75762. if (this.sharpen) {
  75763. this.sharpen.dispose(camera);
  75764. }
  75765. if (this.depthOfField) {
  75766. this.depthOfField.disposeEffects(camera);
  75767. }
  75768. if (this.bloom) {
  75769. this.bloom.disposeEffects(camera);
  75770. }
  75771. if (this.chromaticAberration) {
  75772. this.chromaticAberration.dispose(camera);
  75773. }
  75774. if (this.grain) {
  75775. this.grain.dispose(camera);
  75776. }
  75777. }
  75778. }
  75779. this.imageProcessing = null;
  75780. this.fxaa = null;
  75781. if (disposeNonRecreated) {
  75782. this.sharpen = null;
  75783. this._sharpenEffect = null;
  75784. this.depthOfField = null;
  75785. this.bloom = null;
  75786. this.chromaticAberration = null;
  75787. this._chromaticAberrationEffect = null;
  75788. this.grain = null;
  75789. this._grainEffect = null;
  75790. }
  75791. };
  75792. /**
  75793. * Dispose of the pipeline and stop all post processes
  75794. */
  75795. DefaultRenderingPipeline.prototype.dispose = function () {
  75796. this._disposePostProcesses(true);
  75797. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75798. this._scene.autoClear = true;
  75799. if (this._resizeObserver) {
  75800. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  75801. this._resizeObserver = null;
  75802. }
  75803. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  75804. _super.prototype.dispose.call(this);
  75805. };
  75806. /**
  75807. * Serialize the rendering pipeline (Used when exporting)
  75808. * @returns the serialized object
  75809. */
  75810. DefaultRenderingPipeline.prototype.serialize = function () {
  75811. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75812. serializationObject.customType = "DefaultRenderingPipeline";
  75813. return serializationObject;
  75814. };
  75815. /**
  75816. * Parse the serialized pipeline
  75817. * @param source Source pipeline.
  75818. * @param scene The scene to load the pipeline to.
  75819. * @param rootUrl The URL of the serialized pipeline.
  75820. * @returns An instantiated pipeline from the serialized object.
  75821. */
  75822. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75823. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  75824. };
  75825. __decorate([
  75826. BABYLON.serialize()
  75827. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  75828. __decorate([
  75829. BABYLON.serialize()
  75830. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  75831. __decorate([
  75832. BABYLON.serialize()
  75833. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  75834. __decorate([
  75835. BABYLON.serialize()
  75836. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  75837. __decorate([
  75838. BABYLON.serialize()
  75839. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  75840. __decorate([
  75841. BABYLON.serialize()
  75842. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  75843. __decorate([
  75844. BABYLON.serialize()
  75845. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  75846. __decorate([
  75847. BABYLON.serialize()
  75848. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  75849. __decorate([
  75850. BABYLON.serialize()
  75851. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  75852. __decorate([
  75853. BABYLON.serialize()
  75854. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  75855. __decorate([
  75856. BABYLON.serialize()
  75857. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  75858. __decorate([
  75859. BABYLON.serialize()
  75860. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  75861. __decorate([
  75862. BABYLON.serialize()
  75863. ], DefaultRenderingPipeline.prototype, "samples", null);
  75864. __decorate([
  75865. BABYLON.serialize()
  75866. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  75867. __decorate([
  75868. BABYLON.serialize()
  75869. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  75870. __decorate([
  75871. BABYLON.serialize()
  75872. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  75873. return DefaultRenderingPipeline;
  75874. }(BABYLON.PostProcessRenderPipeline));
  75875. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  75876. })(BABYLON || (BABYLON = {}));
  75877. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  75878. var BABYLON;
  75879. (function (BABYLON) {
  75880. /**
  75881. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  75882. */
  75883. var GeometryBufferRenderer = /** @class */ (function () {
  75884. /**
  75885. * Creates a new G Buffer for the scene
  75886. * @param scene The scene the buffer belongs to
  75887. * @param ratio How big is the buffer related to the main canvas.
  75888. */
  75889. function GeometryBufferRenderer(scene, ratio) {
  75890. if (ratio === void 0) { ratio = 1; }
  75891. this._enablePosition = false;
  75892. this._scene = scene;
  75893. this._ratio = ratio;
  75894. // Render target
  75895. this._createRenderTargets();
  75896. }
  75897. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  75898. /**
  75899. * Set the render list (meshes to be rendered) used in the G buffer.
  75900. */
  75901. set: function (meshes) {
  75902. this._multiRenderTarget.renderList = meshes;
  75903. },
  75904. enumerable: true,
  75905. configurable: true
  75906. });
  75907. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  75908. /**
  75909. * Gets wether or not G buffer are supported by the running hardware.
  75910. * This requires draw buffer supports
  75911. */
  75912. get: function () {
  75913. return this._multiRenderTarget.isSupported;
  75914. },
  75915. enumerable: true,
  75916. configurable: true
  75917. });
  75918. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  75919. /**
  75920. * Gets wether or not position are enabled for the G buffer.
  75921. */
  75922. get: function () {
  75923. return this._enablePosition;
  75924. },
  75925. /**
  75926. * Sets wether or not position are enabled for the G buffer.
  75927. */
  75928. set: function (enable) {
  75929. this._enablePosition = enable;
  75930. this.dispose();
  75931. this._createRenderTargets();
  75932. },
  75933. enumerable: true,
  75934. configurable: true
  75935. });
  75936. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  75937. /**
  75938. * Gets the scene associated with the buffer.
  75939. */
  75940. get: function () {
  75941. return this._scene;
  75942. },
  75943. enumerable: true,
  75944. configurable: true
  75945. });
  75946. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  75947. /**
  75948. * Gets the ratio used by the buffer during its creation.
  75949. * How big is the buffer related to the main canvas.
  75950. */
  75951. get: function () {
  75952. return this._ratio;
  75953. },
  75954. enumerable: true,
  75955. configurable: true
  75956. });
  75957. /**
  75958. * Checks wether everything is ready to render a submesh to the G buffer.
  75959. * @param subMesh the submesh to check readiness for
  75960. * @param useInstances is the mesh drawn using instance or not
  75961. * @returns true if ready otherwise false
  75962. */
  75963. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  75964. var material = subMesh.getMaterial();
  75965. if (material && material.disableDepthWrite) {
  75966. return false;
  75967. }
  75968. var defines = [];
  75969. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  75970. var mesh = subMesh.getMesh();
  75971. // Alpha test
  75972. if (material && material.needAlphaTesting()) {
  75973. defines.push("#define ALPHATEST");
  75974. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75975. attribs.push(BABYLON.VertexBuffer.UVKind);
  75976. defines.push("#define UV1");
  75977. }
  75978. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75979. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75980. defines.push("#define UV2");
  75981. }
  75982. }
  75983. // Buffers
  75984. if (this._enablePosition) {
  75985. defines.push("#define POSITION");
  75986. }
  75987. // Bones
  75988. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75989. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75990. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75991. if (mesh.numBoneInfluencers > 4) {
  75992. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75993. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75994. }
  75995. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75996. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  75997. }
  75998. else {
  75999. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76000. }
  76001. // Instances
  76002. if (useInstances) {
  76003. defines.push("#define INSTANCES");
  76004. attribs.push("world0");
  76005. attribs.push("world1");
  76006. attribs.push("world2");
  76007. attribs.push("world3");
  76008. }
  76009. // Get correct effect
  76010. var join = defines.join("\n");
  76011. if (this._cachedDefines !== join) {
  76012. this._cachedDefines = join;
  76013. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76014. }
  76015. return this._effect.isReady();
  76016. };
  76017. /**
  76018. * Gets the current underlying G Buffer.
  76019. * @returns the buffer
  76020. */
  76021. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76022. return this._multiRenderTarget;
  76023. };
  76024. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76025. /**
  76026. * Gets the number of samples used to render the buffer (anti aliasing).
  76027. */
  76028. get: function () {
  76029. return this._multiRenderTarget.samples;
  76030. },
  76031. /**
  76032. * Sets the number of samples used to render the buffer (anti aliasing).
  76033. */
  76034. set: function (value) {
  76035. this._multiRenderTarget.samples = value;
  76036. },
  76037. enumerable: true,
  76038. configurable: true
  76039. });
  76040. /**
  76041. * Disposes the renderer and frees up associated resources.
  76042. */
  76043. GeometryBufferRenderer.prototype.dispose = function () {
  76044. this.getGBuffer().dispose();
  76045. };
  76046. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76047. var _this = this;
  76048. var engine = this._scene.getEngine();
  76049. var count = this._enablePosition ? 3 : 2;
  76050. 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 });
  76051. if (!this.isSupported) {
  76052. return;
  76053. }
  76054. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76055. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76056. this._multiRenderTarget.refreshRate = 1;
  76057. this._multiRenderTarget.renderParticles = false;
  76058. this._multiRenderTarget.renderList = null;
  76059. // set default depth value to 1.0 (far away)
  76060. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76061. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76062. });
  76063. // Custom render function
  76064. var renderSubMesh = function (subMesh) {
  76065. var mesh = subMesh.getRenderingMesh();
  76066. var scene = _this._scene;
  76067. var engine = scene.getEngine();
  76068. var material = subMesh.getMaterial();
  76069. if (!material) {
  76070. return;
  76071. }
  76072. // Culling
  76073. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76074. // Managing instances
  76075. var batch = mesh._getInstancesRenderList(subMesh._id);
  76076. if (batch.mustReturn) {
  76077. return;
  76078. }
  76079. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76080. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76081. engine.enableEffect(_this._effect);
  76082. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76083. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76084. _this._effect.setMatrix("view", scene.getViewMatrix());
  76085. // Alpha test
  76086. if (material && material.needAlphaTesting()) {
  76087. var alphaTexture = material.getAlphaTestTexture();
  76088. if (alphaTexture) {
  76089. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76090. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76091. }
  76092. }
  76093. // Bones
  76094. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76095. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76096. }
  76097. // Draw
  76098. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76099. }
  76100. };
  76101. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76102. var index;
  76103. if (depthOnlySubMeshes.length) {
  76104. engine.setColorWrite(false);
  76105. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76106. renderSubMesh(depthOnlySubMeshes.data[index]);
  76107. }
  76108. engine.setColorWrite(true);
  76109. }
  76110. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76111. renderSubMesh(opaqueSubMeshes.data[index]);
  76112. }
  76113. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76114. renderSubMesh(alphaTestSubMeshes.data[index]);
  76115. }
  76116. };
  76117. };
  76118. return GeometryBufferRenderer;
  76119. }());
  76120. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76121. })(BABYLON || (BABYLON = {}));
  76122. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76123. var BABYLON;
  76124. (function (BABYLON) {
  76125. var RefractionPostProcess = /** @class */ (function (_super) {
  76126. __extends(RefractionPostProcess, _super);
  76127. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76128. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76129. _this.color = color;
  76130. _this.depth = depth;
  76131. _this.colorLevel = colorLevel;
  76132. _this._ownRefractionTexture = true;
  76133. _this.onActivateObservable.add(function (cam) {
  76134. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76135. });
  76136. _this.onApplyObservable.add(function (effect) {
  76137. effect.setColor3("baseColor", _this.color);
  76138. effect.setFloat("depth", _this.depth);
  76139. effect.setFloat("colorLevel", _this.colorLevel);
  76140. effect.setTexture("refractionSampler", _this._refTexture);
  76141. });
  76142. return _this;
  76143. }
  76144. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76145. /**
  76146. * Gets or sets the refraction texture
  76147. * Please note that you are responsible for disposing the texture if you set it manually
  76148. */
  76149. get: function () {
  76150. return this._refTexture;
  76151. },
  76152. set: function (value) {
  76153. if (this._refTexture && this._ownRefractionTexture) {
  76154. this._refTexture.dispose();
  76155. }
  76156. this._refTexture = value;
  76157. this._ownRefractionTexture = false;
  76158. },
  76159. enumerable: true,
  76160. configurable: true
  76161. });
  76162. // Methods
  76163. RefractionPostProcess.prototype.dispose = function (camera) {
  76164. if (this._refTexture && this._ownRefractionTexture) {
  76165. this._refTexture.dispose();
  76166. this._refTexture = null;
  76167. }
  76168. _super.prototype.dispose.call(this, camera);
  76169. };
  76170. return RefractionPostProcess;
  76171. }(BABYLON.PostProcess));
  76172. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76173. })(BABYLON || (BABYLON = {}));
  76174. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76175. var BABYLON;
  76176. (function (BABYLON) {
  76177. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76178. __extends(BlackAndWhitePostProcess, _super);
  76179. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76180. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76181. _this.degree = 1;
  76182. _this.onApplyObservable.add(function (effect) {
  76183. effect.setFloat("degree", _this.degree);
  76184. });
  76185. return _this;
  76186. }
  76187. return BlackAndWhitePostProcess;
  76188. }(BABYLON.PostProcess));
  76189. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76190. })(BABYLON || (BABYLON = {}));
  76191. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76192. var BABYLON;
  76193. (function (BABYLON) {
  76194. /**
  76195. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76196. * input texture to perform effects such as edge detection or sharpening
  76197. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76198. */
  76199. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76200. __extends(ConvolutionPostProcess, _super);
  76201. /**
  76202. * Creates a new instance ConvolutionPostProcess
  76203. * @param name The name of the effect.
  76204. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76205. * @param options The required width/height ratio to downsize to before computing the render pass.
  76206. * @param camera The camera to apply the render pass to.
  76207. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76208. * @param engine The engine which the post process will be applied. (default: current engine)
  76209. * @param reusable If the post process can be reused on the same frame. (default: false)
  76210. * @param textureType Type of textures used when performing the post process. (default: 0)
  76211. */
  76212. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76213. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76214. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76215. _this.kernel = kernel;
  76216. _this.onApply = function (effect) {
  76217. effect.setFloat2("screenSize", _this.width, _this.height);
  76218. effect.setArray("kernel", _this.kernel);
  76219. };
  76220. return _this;
  76221. }
  76222. // Statics
  76223. /**
  76224. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76225. */
  76226. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  76227. /**
  76228. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76229. */
  76230. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  76231. /**
  76232. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76233. */
  76234. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  76235. /**
  76236. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76237. */
  76238. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  76239. /**
  76240. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76241. */
  76242. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  76243. /**
  76244. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76245. */
  76246. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  76247. return ConvolutionPostProcess;
  76248. }(BABYLON.PostProcess));
  76249. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  76250. })(BABYLON || (BABYLON = {}));
  76251. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  76252. var BABYLON;
  76253. (function (BABYLON) {
  76254. var FilterPostProcess = /** @class */ (function (_super) {
  76255. __extends(FilterPostProcess, _super);
  76256. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  76257. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  76258. _this.kernelMatrix = kernelMatrix;
  76259. _this.onApply = function (effect) {
  76260. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  76261. };
  76262. return _this;
  76263. }
  76264. return FilterPostProcess;
  76265. }(BABYLON.PostProcess));
  76266. BABYLON.FilterPostProcess = FilterPostProcess;
  76267. })(BABYLON || (BABYLON = {}));
  76268. //# sourceMappingURL=babylon.filterPostProcess.js.map
  76269. var BABYLON;
  76270. (function (BABYLON) {
  76271. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  76272. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  76273. __extends(VolumetricLightScatteringPostProcess, _super);
  76274. /**
  76275. * @constructor
  76276. * @param {string} name - The post-process name
  76277. * @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)
  76278. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  76279. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  76280. * @param {number} samples - The post-process quality, default 100
  76281. * @param {number} samplingMode - The post-process filtering mode
  76282. * @param {BABYLON.Engine} engine - The babylon engine
  76283. * @param {boolean} reusable - If the post-process is reusable
  76284. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  76285. */
  76286. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  76287. if (samples === void 0) { samples = 100; }
  76288. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76289. 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;
  76290. _this._screenCoordinates = BABYLON.Vector2.Zero();
  76291. /**
  76292. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  76293. */
  76294. _this.customMeshPosition = BABYLON.Vector3.Zero();
  76295. /**
  76296. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  76297. */
  76298. _this.useCustomMeshPosition = false;
  76299. /**
  76300. * If the post-process should inverse the light scattering direction
  76301. */
  76302. _this.invert = true;
  76303. /**
  76304. * Array containing the excluded meshes not rendered in the internal pass
  76305. */
  76306. _this.excludedMeshes = new Array();
  76307. /**
  76308. * Controls the overall intensity of the post-process
  76309. */
  76310. _this.exposure = 0.3;
  76311. /**
  76312. * Dissipates each sample's contribution in range [0, 1]
  76313. */
  76314. _this.decay = 0.96815;
  76315. /**
  76316. * Controls the overall intensity of each sample
  76317. */
  76318. _this.weight = 0.58767;
  76319. /**
  76320. * Controls the density of each sample
  76321. */
  76322. _this.density = 0.926;
  76323. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  76324. engine = scene.getEngine();
  76325. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  76326. // Configure mesh
  76327. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  76328. // Configure
  76329. _this._createPass(scene, ratio.passRatio || ratio);
  76330. _this.onActivate = function (camera) {
  76331. if (!_this.isSupported) {
  76332. _this.dispose(camera);
  76333. }
  76334. _this.onActivate = null;
  76335. };
  76336. _this.onApplyObservable.add(function (effect) {
  76337. _this._updateMeshScreenCoordinates(scene);
  76338. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  76339. effect.setFloat("exposure", _this.exposure);
  76340. effect.setFloat("decay", _this.decay);
  76341. effect.setFloat("weight", _this.weight);
  76342. effect.setFloat("density", _this.density);
  76343. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  76344. });
  76345. return _this;
  76346. }
  76347. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  76348. get: function () {
  76349. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76350. return false;
  76351. },
  76352. set: function (useDiffuseColor) {
  76353. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76354. },
  76355. enumerable: true,
  76356. configurable: true
  76357. });
  76358. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  76359. return "VolumetricLightScatteringPostProcess";
  76360. };
  76361. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  76362. var mesh = subMesh.getMesh();
  76363. // Render this.mesh as default
  76364. if (mesh === this.mesh && mesh.material) {
  76365. return mesh.material.isReady(mesh);
  76366. }
  76367. var defines = [];
  76368. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76369. var material = subMesh.getMaterial();
  76370. // Alpha test
  76371. if (material) {
  76372. if (material.needAlphaTesting()) {
  76373. defines.push("#define ALPHATEST");
  76374. }
  76375. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76376. attribs.push(BABYLON.VertexBuffer.UVKind);
  76377. defines.push("#define UV1");
  76378. }
  76379. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76380. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76381. defines.push("#define UV2");
  76382. }
  76383. }
  76384. // Bones
  76385. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76386. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76387. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76388. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76389. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  76390. }
  76391. else {
  76392. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76393. }
  76394. // Instances
  76395. if (useInstances) {
  76396. defines.push("#define INSTANCES");
  76397. attribs.push("world0");
  76398. attribs.push("world1");
  76399. attribs.push("world2");
  76400. attribs.push("world3");
  76401. }
  76402. // Get correct effect
  76403. var join = defines.join("\n");
  76404. if (this._cachedDefines !== join) {
  76405. this._cachedDefines = join;
  76406. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  76407. }
  76408. return this._volumetricLightScatteringPass.isReady();
  76409. };
  76410. /**
  76411. * Sets the new light position for light scattering effect
  76412. * @param {BABYLON.Vector3} The new custom light position
  76413. */
  76414. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  76415. this.customMeshPosition = position;
  76416. };
  76417. /**
  76418. * Returns the light position for light scattering effect
  76419. * @return {BABYLON.Vector3} The custom light position
  76420. */
  76421. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  76422. return this.customMeshPosition;
  76423. };
  76424. /**
  76425. * Disposes the internal assets and detaches the post-process from the camera
  76426. */
  76427. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  76428. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  76429. if (rttIndex !== -1) {
  76430. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  76431. }
  76432. this._volumetricLightScatteringRTT.dispose();
  76433. _super.prototype.dispose.call(this, camera);
  76434. };
  76435. /**
  76436. * Returns the render target texture used by the post-process
  76437. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  76438. */
  76439. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  76440. return this._volumetricLightScatteringRTT;
  76441. };
  76442. // Private methods
  76443. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  76444. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  76445. return true;
  76446. }
  76447. return false;
  76448. };
  76449. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  76450. var _this = this;
  76451. var engine = scene.getEngine();
  76452. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76453. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76454. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76455. this._volumetricLightScatteringRTT.renderList = null;
  76456. this._volumetricLightScatteringRTT.renderParticles = false;
  76457. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  76458. var camera = this.getCamera();
  76459. if (camera) {
  76460. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76461. }
  76462. else {
  76463. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76464. }
  76465. // Custom render function for submeshes
  76466. var renderSubMesh = function (subMesh) {
  76467. var mesh = subMesh.getRenderingMesh();
  76468. if (_this._meshExcluded(mesh)) {
  76469. return;
  76470. }
  76471. var material = subMesh.getMaterial();
  76472. if (!material) {
  76473. return;
  76474. }
  76475. var scene = mesh.getScene();
  76476. var engine = scene.getEngine();
  76477. // Culling
  76478. engine.setState(material.backFaceCulling);
  76479. // Managing instances
  76480. var batch = mesh._getInstancesRenderList(subMesh._id);
  76481. if (batch.mustReturn) {
  76482. return;
  76483. }
  76484. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76485. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  76486. var effect = _this._volumetricLightScatteringPass;
  76487. if (mesh === _this.mesh) {
  76488. if (subMesh.effect) {
  76489. effect = subMesh.effect;
  76490. }
  76491. else {
  76492. effect = material.getEffect();
  76493. }
  76494. }
  76495. engine.enableEffect(effect);
  76496. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  76497. if (mesh === _this.mesh) {
  76498. material.bind(mesh.getWorldMatrix(), mesh);
  76499. }
  76500. else {
  76501. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  76502. // Alpha test
  76503. if (material && material.needAlphaTesting()) {
  76504. var alphaTexture = material.getAlphaTestTexture();
  76505. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  76506. if (alphaTexture) {
  76507. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76508. }
  76509. }
  76510. // Bones
  76511. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76512. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76513. }
  76514. }
  76515. // Draw
  76516. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  76517. }
  76518. };
  76519. // Render target texture callbacks
  76520. var savedSceneClearColor;
  76521. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  76522. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  76523. savedSceneClearColor = scene.clearColor;
  76524. scene.clearColor = sceneClearColor;
  76525. });
  76526. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  76527. scene.clearColor = savedSceneClearColor;
  76528. });
  76529. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76530. var engine = scene.getEngine();
  76531. var index;
  76532. if (depthOnlySubMeshes.length) {
  76533. engine.setColorWrite(false);
  76534. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76535. renderSubMesh(depthOnlySubMeshes.data[index]);
  76536. }
  76537. engine.setColorWrite(true);
  76538. }
  76539. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76540. renderSubMesh(opaqueSubMeshes.data[index]);
  76541. }
  76542. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76543. renderSubMesh(alphaTestSubMeshes.data[index]);
  76544. }
  76545. if (transparentSubMeshes.length) {
  76546. // Sort sub meshes
  76547. for (index = 0; index < transparentSubMeshes.length; index++) {
  76548. var submesh = transparentSubMeshes.data[index];
  76549. var boundingInfo = submesh.getBoundingInfo();
  76550. if (boundingInfo && scene.activeCamera) {
  76551. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  76552. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  76553. }
  76554. }
  76555. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  76556. sortedArray.sort(function (a, b) {
  76557. // Alpha index first
  76558. if (a._alphaIndex > b._alphaIndex) {
  76559. return 1;
  76560. }
  76561. if (a._alphaIndex < b._alphaIndex) {
  76562. return -1;
  76563. }
  76564. // Then distance to camera
  76565. if (a._distanceToCamera < b._distanceToCamera) {
  76566. return 1;
  76567. }
  76568. if (a._distanceToCamera > b._distanceToCamera) {
  76569. return -1;
  76570. }
  76571. return 0;
  76572. });
  76573. // Render sub meshes
  76574. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  76575. for (index = 0; index < sortedArray.length; index++) {
  76576. renderSubMesh(sortedArray[index]);
  76577. }
  76578. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76579. }
  76580. };
  76581. };
  76582. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  76583. var transform = scene.getTransformMatrix();
  76584. var meshPosition;
  76585. if (this.useCustomMeshPosition) {
  76586. meshPosition = this.customMeshPosition;
  76587. }
  76588. else if (this.attachedNode) {
  76589. meshPosition = this.attachedNode.position;
  76590. }
  76591. else {
  76592. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  76593. }
  76594. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  76595. this._screenCoordinates.x = pos.x / this._viewPort.width;
  76596. this._screenCoordinates.y = pos.y / this._viewPort.height;
  76597. if (this.invert)
  76598. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  76599. };
  76600. // Static methods
  76601. /**
  76602. * Creates a default mesh for the Volumeric Light Scattering post-process
  76603. * @param {string} The mesh name
  76604. * @param {BABYLON.Scene} The scene where to create the mesh
  76605. * @return {BABYLON.Mesh} the default mesh
  76606. */
  76607. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  76608. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  76609. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  76610. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  76611. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  76612. mesh.material = material;
  76613. return mesh;
  76614. };
  76615. __decorate([
  76616. BABYLON.serializeAsVector3()
  76617. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  76618. __decorate([
  76619. BABYLON.serialize()
  76620. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  76621. __decorate([
  76622. BABYLON.serialize()
  76623. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  76624. __decorate([
  76625. BABYLON.serializeAsMeshReference()
  76626. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  76627. __decorate([
  76628. BABYLON.serialize()
  76629. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  76630. __decorate([
  76631. BABYLON.serialize()
  76632. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  76633. __decorate([
  76634. BABYLON.serialize()
  76635. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  76636. __decorate([
  76637. BABYLON.serialize()
  76638. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  76639. __decorate([
  76640. BABYLON.serialize()
  76641. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  76642. return VolumetricLightScatteringPostProcess;
  76643. }(BABYLON.PostProcess));
  76644. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  76645. })(BABYLON || (BABYLON = {}));
  76646. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  76647. //
  76648. // This post-process allows the modification of rendered colors by using
  76649. // a 'look-up table' (LUT). This effect is also called Color Grading.
  76650. //
  76651. // The object needs to be provided an url to a texture containing the color
  76652. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  76653. // Use an image editing software to tweak the LUT to match your needs.
  76654. //
  76655. // For an example of a color LUT, see here:
  76656. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  76657. // For explanations on color grading, see here:
  76658. // http://udn.epicgames.com/Three/ColorGrading.html
  76659. //
  76660. var BABYLON;
  76661. (function (BABYLON) {
  76662. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  76663. __extends(ColorCorrectionPostProcess, _super);
  76664. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  76665. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  76666. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76667. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  76668. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76669. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76670. _this.onApply = function (effect) {
  76671. effect.setTexture("colorTable", _this._colorTableTexture);
  76672. };
  76673. return _this;
  76674. }
  76675. return ColorCorrectionPostProcess;
  76676. }(BABYLON.PostProcess));
  76677. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  76678. })(BABYLON || (BABYLON = {}));
  76679. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  76680. var BABYLON;
  76681. (function (BABYLON) {
  76682. /** Defines operator used for tonemapping */
  76683. var TonemappingOperator;
  76684. (function (TonemappingOperator) {
  76685. /** Hable */
  76686. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  76687. /** Reinhard */
  76688. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  76689. /** HejiDawson */
  76690. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  76691. /** Photographic */
  76692. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  76693. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  76694. ;
  76695. /**
  76696. * Defines a post process to apply tone mapping
  76697. */
  76698. var TonemapPostProcess = /** @class */ (function (_super) {
  76699. __extends(TonemapPostProcess, _super);
  76700. /**
  76701. * Creates a new TonemapPostProcess
  76702. * @param name defines the name of the postprocess
  76703. * @param _operator defines the operator to use
  76704. * @param exposureAdjustment defines the required exposure adjustement
  76705. * @param camera defines the camera to use (can be null)
  76706. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  76707. * @param engine defines the hosting engine (can be ignore if camera is set)
  76708. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  76709. */
  76710. function TonemapPostProcess(name, _operator,
  76711. /** Defines the required exposure adjustement */
  76712. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  76713. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76714. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76715. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  76716. _this._operator = _operator;
  76717. _this.exposureAdjustment = exposureAdjustment;
  76718. var defines = "#define ";
  76719. if (_this._operator === TonemappingOperator.Hable)
  76720. defines += "HABLE_TONEMAPPING";
  76721. else if (_this._operator === TonemappingOperator.Reinhard)
  76722. defines += "REINHARD_TONEMAPPING";
  76723. else if (_this._operator === TonemappingOperator.HejiDawson)
  76724. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  76725. else if (_this._operator === TonemappingOperator.Photographic)
  76726. defines += "PHOTOGRAPHIC_TONEMAPPING";
  76727. //sadly a second call to create the effect.
  76728. _this.updateEffect(defines);
  76729. _this.onApply = function (effect) {
  76730. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  76731. };
  76732. return _this;
  76733. }
  76734. return TonemapPostProcess;
  76735. }(BABYLON.PostProcess));
  76736. BABYLON.TonemapPostProcess = TonemapPostProcess;
  76737. })(BABYLON || (BABYLON = {}));
  76738. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  76739. var BABYLON;
  76740. (function (BABYLON) {
  76741. var DisplayPassPostProcess = /** @class */ (function (_super) {
  76742. __extends(DisplayPassPostProcess, _super);
  76743. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  76744. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  76745. }
  76746. return DisplayPassPostProcess;
  76747. }(BABYLON.PostProcess));
  76748. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  76749. })(BABYLON || (BABYLON = {}));
  76750. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  76751. var BABYLON;
  76752. (function (BABYLON) {
  76753. var HighlightsPostProcess = /** @class */ (function (_super) {
  76754. __extends(HighlightsPostProcess, _super);
  76755. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76756. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76757. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76758. }
  76759. return HighlightsPostProcess;
  76760. }(BABYLON.PostProcess));
  76761. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  76762. })(BABYLON || (BABYLON = {}));
  76763. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  76764. var BABYLON;
  76765. (function (BABYLON) {
  76766. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  76767. __extends(ImageProcessingPostProcess, _super);
  76768. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  76769. if (camera === void 0) { camera = null; }
  76770. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76771. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  76772. _this._fromLinearSpace = true;
  76773. /**
  76774. * Defines cache preventing GC.
  76775. */
  76776. _this._defines = {
  76777. IMAGEPROCESSING: false,
  76778. VIGNETTE: false,
  76779. VIGNETTEBLENDMODEMULTIPLY: false,
  76780. VIGNETTEBLENDMODEOPAQUE: false,
  76781. TONEMAPPING: false,
  76782. CONTRAST: false,
  76783. COLORCURVES: false,
  76784. COLORGRADING: false,
  76785. COLORGRADING3D: false,
  76786. FROMLINEARSPACE: false,
  76787. SAMPLER3DGREENDEPTH: false,
  76788. SAMPLER3DBGRMAP: false,
  76789. IMAGEPROCESSINGPOSTPROCESS: false,
  76790. EXPOSURE: false,
  76791. };
  76792. // Setup the configuration as forced by the constructor. This would then not force the
  76793. // scene materials output in linear space and let untouched the default forward pass.
  76794. if (imageProcessingConfiguration) {
  76795. imageProcessingConfiguration.applyByPostProcess = true;
  76796. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  76797. // This will cause the shader to be compiled
  76798. _this.fromLinearSpace = false;
  76799. }
  76800. // Setup the default processing configuration to the scene.
  76801. else {
  76802. _this._attachImageProcessingConfiguration(null, true);
  76803. _this.imageProcessingConfiguration.applyByPostProcess = true;
  76804. }
  76805. _this.onApply = function (effect) {
  76806. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  76807. };
  76808. return _this;
  76809. }
  76810. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  76811. /**
  76812. * Gets the image processing configuration used either in this material.
  76813. */
  76814. get: function () {
  76815. return this._imageProcessingConfiguration;
  76816. },
  76817. /**
  76818. * Sets the Default image processing configuration used either in the this material.
  76819. *
  76820. * If sets to null, the scene one is in use.
  76821. */
  76822. set: function (value) {
  76823. this._attachImageProcessingConfiguration(value);
  76824. },
  76825. enumerable: true,
  76826. configurable: true
  76827. });
  76828. /**
  76829. * Attaches a new image processing configuration to the PBR Material.
  76830. * @param configuration
  76831. */
  76832. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  76833. var _this = this;
  76834. if (doNotBuild === void 0) { doNotBuild = false; }
  76835. if (configuration === this._imageProcessingConfiguration) {
  76836. return;
  76837. }
  76838. // Detaches observer.
  76839. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76840. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76841. }
  76842. // Pick the scene configuration if needed.
  76843. if (!configuration) {
  76844. var scene = null;
  76845. var engine = this.getEngine();
  76846. var camera = this.getCamera();
  76847. if (camera) {
  76848. scene = camera.getScene();
  76849. }
  76850. else if (engine && engine.scenes) {
  76851. var scenes = engine.scenes;
  76852. scene = scenes[scenes.length - 1];
  76853. }
  76854. else {
  76855. scene = BABYLON.Engine.LastCreatedScene;
  76856. }
  76857. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  76858. }
  76859. else {
  76860. this._imageProcessingConfiguration = configuration;
  76861. }
  76862. // Attaches observer.
  76863. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  76864. _this._updateParameters();
  76865. });
  76866. // Ensure the effect will be rebuilt.
  76867. if (!doNotBuild) {
  76868. this._updateParameters();
  76869. }
  76870. };
  76871. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  76872. /**
  76873. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76874. */
  76875. get: function () {
  76876. return this.imageProcessingConfiguration.colorCurves;
  76877. },
  76878. /**
  76879. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76880. */
  76881. set: function (value) {
  76882. this.imageProcessingConfiguration.colorCurves = value;
  76883. },
  76884. enumerable: true,
  76885. configurable: true
  76886. });
  76887. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  76888. /**
  76889. * Gets wether the color curves effect is enabled.
  76890. */
  76891. get: function () {
  76892. return this.imageProcessingConfiguration.colorCurvesEnabled;
  76893. },
  76894. /**
  76895. * Sets wether the color curves effect is enabled.
  76896. */
  76897. set: function (value) {
  76898. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  76899. },
  76900. enumerable: true,
  76901. configurable: true
  76902. });
  76903. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  76904. /**
  76905. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76906. */
  76907. get: function () {
  76908. return this.imageProcessingConfiguration.colorGradingTexture;
  76909. },
  76910. /**
  76911. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76912. */
  76913. set: function (value) {
  76914. this.imageProcessingConfiguration.colorGradingTexture = value;
  76915. },
  76916. enumerable: true,
  76917. configurable: true
  76918. });
  76919. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  76920. /**
  76921. * Gets wether the color grading effect is enabled.
  76922. */
  76923. get: function () {
  76924. return this.imageProcessingConfiguration.colorGradingEnabled;
  76925. },
  76926. /**
  76927. * Gets wether the color grading effect is enabled.
  76928. */
  76929. set: function (value) {
  76930. this.imageProcessingConfiguration.colorGradingEnabled = value;
  76931. },
  76932. enumerable: true,
  76933. configurable: true
  76934. });
  76935. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  76936. /**
  76937. * Gets exposure used in the effect.
  76938. */
  76939. get: function () {
  76940. return this.imageProcessingConfiguration.exposure;
  76941. },
  76942. /**
  76943. * Sets exposure used in the effect.
  76944. */
  76945. set: function (value) {
  76946. this.imageProcessingConfiguration.exposure = value;
  76947. },
  76948. enumerable: true,
  76949. configurable: true
  76950. });
  76951. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  76952. /**
  76953. * Gets wether tonemapping is enabled or not.
  76954. */
  76955. get: function () {
  76956. return this._imageProcessingConfiguration.toneMappingEnabled;
  76957. },
  76958. /**
  76959. * Sets wether tonemapping is enabled or not
  76960. */
  76961. set: function (value) {
  76962. this._imageProcessingConfiguration.toneMappingEnabled = value;
  76963. },
  76964. enumerable: true,
  76965. configurable: true
  76966. });
  76967. ;
  76968. ;
  76969. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  76970. /**
  76971. * Gets contrast used in the effect.
  76972. */
  76973. get: function () {
  76974. return this.imageProcessingConfiguration.contrast;
  76975. },
  76976. /**
  76977. * Sets contrast used in the effect.
  76978. */
  76979. set: function (value) {
  76980. this.imageProcessingConfiguration.contrast = value;
  76981. },
  76982. enumerable: true,
  76983. configurable: true
  76984. });
  76985. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  76986. /**
  76987. * Gets Vignette stretch size.
  76988. */
  76989. get: function () {
  76990. return this.imageProcessingConfiguration.vignetteStretch;
  76991. },
  76992. /**
  76993. * Sets Vignette stretch size.
  76994. */
  76995. set: function (value) {
  76996. this.imageProcessingConfiguration.vignetteStretch = value;
  76997. },
  76998. enumerable: true,
  76999. configurable: true
  77000. });
  77001. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77002. /**
  77003. * Gets Vignette centre X Offset.
  77004. */
  77005. get: function () {
  77006. return this.imageProcessingConfiguration.vignetteCentreX;
  77007. },
  77008. /**
  77009. * Sets Vignette centre X Offset.
  77010. */
  77011. set: function (value) {
  77012. this.imageProcessingConfiguration.vignetteCentreX = value;
  77013. },
  77014. enumerable: true,
  77015. configurable: true
  77016. });
  77017. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77018. /**
  77019. * Gets Vignette centre Y Offset.
  77020. */
  77021. get: function () {
  77022. return this.imageProcessingConfiguration.vignetteCentreY;
  77023. },
  77024. /**
  77025. * Sets Vignette centre Y Offset.
  77026. */
  77027. set: function (value) {
  77028. this.imageProcessingConfiguration.vignetteCentreY = value;
  77029. },
  77030. enumerable: true,
  77031. configurable: true
  77032. });
  77033. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77034. /**
  77035. * Gets Vignette weight or intensity of the vignette effect.
  77036. */
  77037. get: function () {
  77038. return this.imageProcessingConfiguration.vignetteWeight;
  77039. },
  77040. /**
  77041. * Sets Vignette weight or intensity of the vignette effect.
  77042. */
  77043. set: function (value) {
  77044. this.imageProcessingConfiguration.vignetteWeight = value;
  77045. },
  77046. enumerable: true,
  77047. configurable: true
  77048. });
  77049. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77050. /**
  77051. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77052. * if vignetteEnabled is set to true.
  77053. */
  77054. get: function () {
  77055. return this.imageProcessingConfiguration.vignetteColor;
  77056. },
  77057. /**
  77058. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77059. * if vignetteEnabled is set to true.
  77060. */
  77061. set: function (value) {
  77062. this.imageProcessingConfiguration.vignetteColor = value;
  77063. },
  77064. enumerable: true,
  77065. configurable: true
  77066. });
  77067. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77068. /**
  77069. * Gets Camera field of view used by the Vignette effect.
  77070. */
  77071. get: function () {
  77072. return this.imageProcessingConfiguration.vignetteCameraFov;
  77073. },
  77074. /**
  77075. * Sets Camera field of view used by the Vignette effect.
  77076. */
  77077. set: function (value) {
  77078. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77079. },
  77080. enumerable: true,
  77081. configurable: true
  77082. });
  77083. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77084. /**
  77085. * Gets the vignette blend mode allowing different kind of effect.
  77086. */
  77087. get: function () {
  77088. return this.imageProcessingConfiguration.vignetteBlendMode;
  77089. },
  77090. /**
  77091. * Sets the vignette blend mode allowing different kind of effect.
  77092. */
  77093. set: function (value) {
  77094. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77095. },
  77096. enumerable: true,
  77097. configurable: true
  77098. });
  77099. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77100. /**
  77101. * Gets wether the vignette effect is enabled.
  77102. */
  77103. get: function () {
  77104. return this.imageProcessingConfiguration.vignetteEnabled;
  77105. },
  77106. /**
  77107. * Sets wether the vignette effect is enabled.
  77108. */
  77109. set: function (value) {
  77110. this.imageProcessingConfiguration.vignetteEnabled = value;
  77111. },
  77112. enumerable: true,
  77113. configurable: true
  77114. });
  77115. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77116. /**
  77117. * Gets wether the input of the processing is in Gamma or Linear Space.
  77118. */
  77119. get: function () {
  77120. return this._fromLinearSpace;
  77121. },
  77122. /**
  77123. * Sets wether the input of the processing is in Gamma or Linear Space.
  77124. */
  77125. set: function (value) {
  77126. if (this._fromLinearSpace === value) {
  77127. return;
  77128. }
  77129. this._fromLinearSpace = value;
  77130. this._updateParameters();
  77131. },
  77132. enumerable: true,
  77133. configurable: true
  77134. });
  77135. ImageProcessingPostProcess.prototype.getClassName = function () {
  77136. return "ImageProcessingPostProcess";
  77137. };
  77138. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77139. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77140. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77141. var defines = "";
  77142. for (var define in this._defines) {
  77143. if (this._defines[define]) {
  77144. defines += "#define " + define + ";\r\n";
  77145. }
  77146. }
  77147. var samplers = ["textureSampler"];
  77148. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77149. var uniforms = ["scale"];
  77150. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77151. this.updateEffect(defines, uniforms, samplers);
  77152. };
  77153. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77154. _super.prototype.dispose.call(this, camera);
  77155. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77156. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77157. }
  77158. this.imageProcessingConfiguration.applyByPostProcess = false;
  77159. };
  77160. __decorate([
  77161. BABYLON.serialize()
  77162. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77163. return ImageProcessingPostProcess;
  77164. }(BABYLON.PostProcess));
  77165. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77166. })(BABYLON || (BABYLON = {}));
  77167. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77168. var BABYLON;
  77169. (function (BABYLON) {
  77170. /**
  77171. * Class used to store bone information
  77172. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77173. */
  77174. var Bone = /** @class */ (function (_super) {
  77175. __extends(Bone, _super);
  77176. /**
  77177. * Create a new bone
  77178. * @param name defines the bone name
  77179. * @param skeleton defines the parent skeleton
  77180. * @param parentBone defines the parent (can be null if the bone is the root)
  77181. * @param localMatrix defines the local matrix
  77182. * @param restPose defines the rest pose matrix
  77183. * @param baseMatrix defines the base matrix
  77184. * @param index defines index of the bone in the hiearchy
  77185. */
  77186. function Bone(
  77187. /**
  77188. * defines the bone name
  77189. */
  77190. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77191. if (parentBone === void 0) { parentBone = null; }
  77192. if (localMatrix === void 0) { localMatrix = null; }
  77193. if (restPose === void 0) { restPose = null; }
  77194. if (baseMatrix === void 0) { baseMatrix = null; }
  77195. if (index === void 0) { index = null; }
  77196. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77197. _this.name = name;
  77198. /**
  77199. * Gets the list of child bones
  77200. */
  77201. _this.children = new Array();
  77202. /** Gets the animations associated with this bone */
  77203. _this.animations = new Array();
  77204. /**
  77205. * @hidden Internal only
  77206. * Set this value to map this bone to a different index in the transform matrices
  77207. * Set this value to -1 to exclude the bone from the transform matrices
  77208. */
  77209. _this._index = null;
  77210. _this._absoluteTransform = new BABYLON.Matrix();
  77211. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77212. _this._scalingDeterminant = 1;
  77213. _this._worldTransform = new BABYLON.Matrix();
  77214. _this._needToDecompose = true;
  77215. _this._needToCompose = false;
  77216. _this._skeleton = skeleton;
  77217. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77218. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77219. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77220. _this._index = index;
  77221. skeleton.bones.push(_this);
  77222. _this.setParent(parentBone, false);
  77223. if (baseMatrix || localMatrix) {
  77224. _this._updateDifferenceMatrix();
  77225. }
  77226. return _this;
  77227. }
  77228. Object.defineProperty(Bone.prototype, "_matrix", {
  77229. /** @hidden */
  77230. get: function () {
  77231. this._compose();
  77232. return this._localMatrix;
  77233. },
  77234. /** @hidden */
  77235. set: function (value) {
  77236. this._localMatrix.copyFrom(value);
  77237. this._needToDecompose = true;
  77238. },
  77239. enumerable: true,
  77240. configurable: true
  77241. });
  77242. // Members
  77243. /**
  77244. * Gets the parent skeleton
  77245. * @returns a skeleton
  77246. */
  77247. Bone.prototype.getSkeleton = function () {
  77248. return this._skeleton;
  77249. };
  77250. /**
  77251. * Gets parent bone
  77252. * @returns a bone or null if the bone is the root of the bone hierarchy
  77253. */
  77254. Bone.prototype.getParent = function () {
  77255. return this._parent;
  77256. };
  77257. /**
  77258. * Sets the parent bone
  77259. * @param parent defines the parent (can be null if the bone is the root)
  77260. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77261. */
  77262. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  77263. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77264. if (this._parent === parent) {
  77265. return;
  77266. }
  77267. if (this._parent) {
  77268. var index = this._parent.children.indexOf(this);
  77269. if (index !== -1) {
  77270. this._parent.children.splice(index, 1);
  77271. }
  77272. }
  77273. this._parent = parent;
  77274. if (this._parent) {
  77275. this._parent.children.push(this);
  77276. }
  77277. if (updateDifferenceMatrix) {
  77278. this._updateDifferenceMatrix();
  77279. }
  77280. this.markAsDirty();
  77281. };
  77282. /**
  77283. * Gets the local matrix
  77284. * @returns a matrix
  77285. */
  77286. Bone.prototype.getLocalMatrix = function () {
  77287. this._compose();
  77288. return this._localMatrix;
  77289. };
  77290. /**
  77291. * Gets the base matrix (initial matrix which remains unchanged)
  77292. * @returns a matrix
  77293. */
  77294. Bone.prototype.getBaseMatrix = function () {
  77295. return this._baseMatrix;
  77296. };
  77297. /**
  77298. * Gets the rest pose matrix
  77299. * @returns a matrix
  77300. */
  77301. Bone.prototype.getRestPose = function () {
  77302. return this._restPose;
  77303. };
  77304. /**
  77305. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  77306. */
  77307. Bone.prototype.getWorldMatrix = function () {
  77308. return this._worldTransform;
  77309. };
  77310. /**
  77311. * Sets the local matrix to rest pose matrix
  77312. */
  77313. Bone.prototype.returnToRest = function () {
  77314. this.updateMatrix(this._restPose.clone());
  77315. };
  77316. /**
  77317. * Gets the inverse of the absolute transform matrix.
  77318. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  77319. * @returns a matrix
  77320. */
  77321. Bone.prototype.getInvertedAbsoluteTransform = function () {
  77322. return this._invertedAbsoluteTransform;
  77323. };
  77324. /**
  77325. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  77326. * @returns a matrix
  77327. */
  77328. Bone.prototype.getAbsoluteTransform = function () {
  77329. return this._absoluteTransform;
  77330. };
  77331. Object.defineProperty(Bone.prototype, "position", {
  77332. // Properties (matches AbstractMesh properties)
  77333. /** Gets or sets current position (in local space) */
  77334. get: function () {
  77335. this._decompose();
  77336. return this._localPosition;
  77337. },
  77338. set: function (newPosition) {
  77339. this._decompose();
  77340. this._localPosition.copyFrom(newPosition);
  77341. this._markAsDirtyAndCompose();
  77342. },
  77343. enumerable: true,
  77344. configurable: true
  77345. });
  77346. Object.defineProperty(Bone.prototype, "rotation", {
  77347. /** Gets or sets current rotation (in local space) */
  77348. get: function () {
  77349. return this.getRotation();
  77350. },
  77351. set: function (newRotation) {
  77352. this.setRotation(newRotation);
  77353. },
  77354. enumerable: true,
  77355. configurable: true
  77356. });
  77357. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  77358. /** Gets or sets current rotation quaternion (in local space) */
  77359. get: function () {
  77360. this._decompose();
  77361. return this._localRotation;
  77362. },
  77363. set: function (newRotation) {
  77364. this.setRotationQuaternion(newRotation);
  77365. },
  77366. enumerable: true,
  77367. configurable: true
  77368. });
  77369. Object.defineProperty(Bone.prototype, "scaling", {
  77370. /** Gets or sets current scaling (in local space) */
  77371. get: function () {
  77372. return this.getScale();
  77373. },
  77374. set: function (newScaling) {
  77375. this.setScale(newScaling);
  77376. },
  77377. enumerable: true,
  77378. configurable: true
  77379. });
  77380. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  77381. /**
  77382. * Gets the animation properties override
  77383. */
  77384. get: function () {
  77385. return this._skeleton.animationPropertiesOverride;
  77386. },
  77387. enumerable: true,
  77388. configurable: true
  77389. });
  77390. // Methods
  77391. Bone.prototype._decompose = function () {
  77392. if (!this._needToDecompose) {
  77393. return;
  77394. }
  77395. this._needToDecompose = false;
  77396. if (!this._localScaling) {
  77397. this._localScaling = BABYLON.Vector3.Zero();
  77398. this._localRotation = BABYLON.Quaternion.Zero();
  77399. this._localPosition = BABYLON.Vector3.Zero();
  77400. }
  77401. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  77402. };
  77403. Bone.prototype._compose = function () {
  77404. if (!this._needToCompose) {
  77405. return;
  77406. }
  77407. this._needToCompose = false;
  77408. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  77409. };
  77410. /**
  77411. * Update the base and local matrices
  77412. * @param matrix defines the new base or local matrix
  77413. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77414. * @param updateLocalMatrix defines if the local matrix should be updated
  77415. */
  77416. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  77417. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77418. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  77419. this._baseMatrix.copyFrom(matrix);
  77420. if (updateDifferenceMatrix) {
  77421. this._updateDifferenceMatrix();
  77422. }
  77423. if (updateLocalMatrix) {
  77424. this._localMatrix.copyFrom(matrix);
  77425. this._markAsDirtyAndDecompose();
  77426. }
  77427. else {
  77428. this.markAsDirty();
  77429. }
  77430. };
  77431. /** @hidden */
  77432. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  77433. if (updateChildren === void 0) { updateChildren = true; }
  77434. if (!rootMatrix) {
  77435. rootMatrix = this._baseMatrix;
  77436. }
  77437. if (this._parent) {
  77438. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77439. }
  77440. else {
  77441. this._absoluteTransform.copyFrom(rootMatrix);
  77442. }
  77443. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  77444. if (updateChildren) {
  77445. for (var index = 0; index < this.children.length; index++) {
  77446. this.children[index]._updateDifferenceMatrix();
  77447. }
  77448. }
  77449. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  77450. };
  77451. /**
  77452. * Flag the bone as dirty (Forcing it to update everything)
  77453. */
  77454. Bone.prototype.markAsDirty = function () {
  77455. this._currentRenderId++;
  77456. this._childRenderId++;
  77457. this._skeleton._markAsDirty();
  77458. };
  77459. Bone.prototype._markAsDirtyAndCompose = function () {
  77460. this.markAsDirty();
  77461. this._needToCompose = true;
  77462. };
  77463. Bone.prototype._markAsDirtyAndDecompose = function () {
  77464. this.markAsDirty();
  77465. this._needToDecompose = true;
  77466. };
  77467. /**
  77468. * Copy an animation range from another bone
  77469. * @param source defines the source bone
  77470. * @param rangeName defines the range name to copy
  77471. * @param frameOffset defines the frame offset
  77472. * @param rescaleAsRequired defines if rescaling must be applied if required
  77473. * @param skelDimensionsRatio defines the scaling ratio
  77474. * @returns true if operation was successful
  77475. */
  77476. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  77477. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77478. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  77479. // all animation may be coming from a library skeleton, so may need to create animation
  77480. if (this.animations.length === 0) {
  77481. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  77482. this.animations[0].setKeys([]);
  77483. }
  77484. // get animation info / verify there is such a range from the source bone
  77485. var sourceRange = source.animations[0].getRange(rangeName);
  77486. if (!sourceRange) {
  77487. return false;
  77488. }
  77489. var from = sourceRange.from;
  77490. var to = sourceRange.to;
  77491. var sourceKeys = source.animations[0].getKeys();
  77492. // rescaling prep
  77493. var sourceBoneLength = source.length;
  77494. var sourceParent = source.getParent();
  77495. var parent = this.getParent();
  77496. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  77497. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  77498. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  77499. var destKeys = this.animations[0].getKeys();
  77500. // loop vars declaration
  77501. var orig;
  77502. var origTranslation;
  77503. var mat;
  77504. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  77505. orig = sourceKeys[key];
  77506. if (orig.frame >= from && orig.frame <= to) {
  77507. if (rescaleAsRequired) {
  77508. mat = orig.value.clone();
  77509. // scale based on parent ratio, when bone has parent
  77510. if (parentScalingReqd) {
  77511. origTranslation = mat.getTranslation();
  77512. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  77513. // scale based on skeleton dimension ratio when root bone, and value is passed
  77514. }
  77515. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  77516. origTranslation = mat.getTranslation();
  77517. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  77518. // use original when root bone, and no data for skelDimensionsRatio
  77519. }
  77520. else {
  77521. mat = orig.value;
  77522. }
  77523. }
  77524. else {
  77525. mat = orig.value;
  77526. }
  77527. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  77528. }
  77529. }
  77530. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  77531. return true;
  77532. };
  77533. /**
  77534. * Translate the bone in local or world space
  77535. * @param vec The amount to translate the bone
  77536. * @param space The space that the translation is in
  77537. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77538. */
  77539. Bone.prototype.translate = function (vec, space, mesh) {
  77540. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77541. var lm = this.getLocalMatrix();
  77542. if (space == BABYLON.Space.LOCAL) {
  77543. lm.m[12] += vec.x;
  77544. lm.m[13] += vec.y;
  77545. lm.m[14] += vec.z;
  77546. }
  77547. else {
  77548. var wm = null;
  77549. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77550. if (mesh) {
  77551. wm = mesh.getWorldMatrix();
  77552. }
  77553. this._skeleton.computeAbsoluteTransforms();
  77554. var tmat = Bone._tmpMats[0];
  77555. var tvec = Bone._tmpVecs[0];
  77556. if (this._parent) {
  77557. if (mesh && wm) {
  77558. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77559. tmat.multiplyToRef(wm, tmat);
  77560. }
  77561. else {
  77562. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77563. }
  77564. }
  77565. tmat.m[12] = 0;
  77566. tmat.m[13] = 0;
  77567. tmat.m[14] = 0;
  77568. tmat.invert();
  77569. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  77570. lm.m[12] += tvec.x;
  77571. lm.m[13] += tvec.y;
  77572. lm.m[14] += tvec.z;
  77573. }
  77574. this._markAsDirtyAndDecompose();
  77575. };
  77576. /**
  77577. * Set the postion of the bone in local or world space
  77578. * @param position The position to set the bone
  77579. * @param space The space that the position is in
  77580. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77581. */
  77582. Bone.prototype.setPosition = function (position, space, mesh) {
  77583. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77584. var lm = this.getLocalMatrix();
  77585. if (space == BABYLON.Space.LOCAL) {
  77586. lm.m[12] = position.x;
  77587. lm.m[13] = position.y;
  77588. lm.m[14] = position.z;
  77589. }
  77590. else {
  77591. var wm = null;
  77592. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77593. if (mesh) {
  77594. wm = mesh.getWorldMatrix();
  77595. }
  77596. this._skeleton.computeAbsoluteTransforms();
  77597. var tmat = Bone._tmpMats[0];
  77598. var vec = Bone._tmpVecs[0];
  77599. if (this._parent) {
  77600. if (mesh && wm) {
  77601. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77602. tmat.multiplyToRef(wm, tmat);
  77603. }
  77604. else {
  77605. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77606. }
  77607. }
  77608. tmat.invert();
  77609. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  77610. lm.m[12] = vec.x;
  77611. lm.m[13] = vec.y;
  77612. lm.m[14] = vec.z;
  77613. }
  77614. this._markAsDirtyAndDecompose();
  77615. };
  77616. /**
  77617. * Set the absolute position of the bone (world space)
  77618. * @param position The position to set the bone
  77619. * @param mesh The mesh that this bone is attached to
  77620. */
  77621. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  77622. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  77623. };
  77624. /**
  77625. * Scale the bone on the x, y and z axes (in local space)
  77626. * @param x The amount to scale the bone on the x axis
  77627. * @param y The amount to scale the bone on the y axis
  77628. * @param z The amount to scale the bone on the z axis
  77629. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  77630. */
  77631. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  77632. if (scaleChildren === void 0) { scaleChildren = false; }
  77633. var locMat = this.getLocalMatrix();
  77634. // Apply new scaling on top of current local matrix
  77635. var scaleMat = Bone._tmpMats[0];
  77636. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  77637. scaleMat.multiplyToRef(locMat, locMat);
  77638. // Invert scaling matrix and apply the inverse to all children
  77639. scaleMat.invert();
  77640. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  77641. var child = _a[_i];
  77642. var cm = child.getLocalMatrix();
  77643. cm.multiplyToRef(scaleMat, cm);
  77644. cm.m[12] *= x;
  77645. cm.m[13] *= y;
  77646. cm.m[14] *= z;
  77647. child._markAsDirtyAndDecompose();
  77648. }
  77649. this._markAsDirtyAndDecompose();
  77650. if (scaleChildren) {
  77651. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  77652. var child = _c[_b];
  77653. child.scale(x, y, z, scaleChildren);
  77654. }
  77655. }
  77656. };
  77657. /**
  77658. * Set the bone scaling in local space
  77659. * @param scale defines the scaling vector
  77660. */
  77661. Bone.prototype.setScale = function (scale) {
  77662. this._decompose();
  77663. this._localScaling.copyFrom(scale);
  77664. this._markAsDirtyAndCompose();
  77665. };
  77666. /**
  77667. * Gets the current scaling in local space
  77668. * @returns the current scaling vector
  77669. */
  77670. Bone.prototype.getScale = function () {
  77671. this._decompose();
  77672. return this._localScaling;
  77673. };
  77674. /**
  77675. * Gets the current scaling in local space and stores it in a target vector
  77676. * @param result defines the target vector
  77677. */
  77678. Bone.prototype.getScaleToRef = function (result) {
  77679. this._decompose();
  77680. result.copyFrom(this._localScaling);
  77681. };
  77682. /**
  77683. * Set the yaw, pitch, and roll of the bone in local or world space
  77684. * @param yaw The rotation of the bone on the y axis
  77685. * @param pitch The rotation of the bone on the x axis
  77686. * @param roll The rotation of the bone on the z axis
  77687. * @param space The space that the axes of rotation are in
  77688. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77689. */
  77690. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  77691. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77692. if (space === BABYLON.Space.LOCAL) {
  77693. var quat = Bone._tmpQuat;
  77694. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  77695. this.setRotationQuaternion(quat, space, mesh);
  77696. return;
  77697. }
  77698. var rotMatInv = Bone._tmpMats[0];
  77699. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77700. return;
  77701. }
  77702. var rotMat = Bone._tmpMats[1];
  77703. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  77704. rotMatInv.multiplyToRef(rotMat, rotMat);
  77705. this._rotateWithMatrix(rotMat, space, mesh);
  77706. };
  77707. /**
  77708. * Add a rotation to the bone on an axis in local or world space
  77709. * @param axis The axis to rotate the bone on
  77710. * @param amount The amount to rotate the bone
  77711. * @param space The space that the axis is in
  77712. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77713. */
  77714. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  77715. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77716. var rmat = Bone._tmpMats[0];
  77717. rmat.m[12] = 0;
  77718. rmat.m[13] = 0;
  77719. rmat.m[14] = 0;
  77720. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  77721. this._rotateWithMatrix(rmat, space, mesh);
  77722. };
  77723. /**
  77724. * Set the rotation of the bone to a particular axis angle in local or world space
  77725. * @param axis The axis to rotate the bone on
  77726. * @param angle The angle that the bone should be rotated to
  77727. * @param space The space that the axis is in
  77728. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77729. */
  77730. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  77731. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77732. if (space === BABYLON.Space.LOCAL) {
  77733. var quat = Bone._tmpQuat;
  77734. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  77735. this.setRotationQuaternion(quat, space, mesh);
  77736. return;
  77737. }
  77738. var rotMatInv = Bone._tmpMats[0];
  77739. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77740. return;
  77741. }
  77742. var rotMat = Bone._tmpMats[1];
  77743. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  77744. rotMatInv.multiplyToRef(rotMat, rotMat);
  77745. this._rotateWithMatrix(rotMat, space, mesh);
  77746. };
  77747. /**
  77748. * Set the euler rotation of the bone in local of world space
  77749. * @param rotation The euler rotation that the bone should be set to
  77750. * @param space The space that the rotation is in
  77751. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77752. */
  77753. Bone.prototype.setRotation = function (rotation, space, mesh) {
  77754. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77755. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  77756. };
  77757. /**
  77758. * Set the quaternion rotation of the bone in local of world space
  77759. * @param quat The quaternion rotation that the bone should be set to
  77760. * @param space The space that the rotation is in
  77761. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77762. */
  77763. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  77764. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77765. if (space === BABYLON.Space.LOCAL) {
  77766. this._decompose();
  77767. this._localRotation.copyFrom(quat);
  77768. this._markAsDirtyAndCompose();
  77769. return;
  77770. }
  77771. var rotMatInv = Bone._tmpMats[0];
  77772. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77773. return;
  77774. }
  77775. var rotMat = Bone._tmpMats[1];
  77776. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  77777. rotMatInv.multiplyToRef(rotMat, rotMat);
  77778. this._rotateWithMatrix(rotMat, space, mesh);
  77779. };
  77780. /**
  77781. * Set the rotation matrix of the bone in local of world space
  77782. * @param rotMat The rotation matrix that the bone should be set to
  77783. * @param space The space that the rotation is in
  77784. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77785. */
  77786. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  77787. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77788. if (space === BABYLON.Space.LOCAL) {
  77789. var quat = Bone._tmpQuat;
  77790. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  77791. this.setRotationQuaternion(quat, space, mesh);
  77792. return;
  77793. }
  77794. var rotMatInv = Bone._tmpMats[0];
  77795. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77796. return;
  77797. }
  77798. var rotMat2 = Bone._tmpMats[1];
  77799. rotMat2.copyFrom(rotMat);
  77800. rotMatInv.multiplyToRef(rotMat, rotMat2);
  77801. this._rotateWithMatrix(rotMat2, space, mesh);
  77802. };
  77803. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  77804. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77805. var lmat = this.getLocalMatrix();
  77806. var lx = lmat.m[12];
  77807. var ly = lmat.m[13];
  77808. var lz = lmat.m[14];
  77809. var parent = this.getParent();
  77810. var parentScale = Bone._tmpMats[3];
  77811. var parentScaleInv = Bone._tmpMats[4];
  77812. if (parent && space == BABYLON.Space.WORLD) {
  77813. if (mesh) {
  77814. parentScale.copyFrom(mesh.getWorldMatrix());
  77815. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  77816. }
  77817. else {
  77818. parentScale.copyFrom(parent.getAbsoluteTransform());
  77819. }
  77820. parentScaleInv.copyFrom(parentScale);
  77821. parentScaleInv.invert();
  77822. lmat.multiplyToRef(parentScale, lmat);
  77823. lmat.multiplyToRef(rmat, lmat);
  77824. lmat.multiplyToRef(parentScaleInv, lmat);
  77825. }
  77826. else {
  77827. if (space == BABYLON.Space.WORLD && mesh) {
  77828. parentScale.copyFrom(mesh.getWorldMatrix());
  77829. parentScaleInv.copyFrom(parentScale);
  77830. parentScaleInv.invert();
  77831. lmat.multiplyToRef(parentScale, lmat);
  77832. lmat.multiplyToRef(rmat, lmat);
  77833. lmat.multiplyToRef(parentScaleInv, lmat);
  77834. }
  77835. else {
  77836. lmat.multiplyToRef(rmat, lmat);
  77837. }
  77838. }
  77839. lmat.m[12] = lx;
  77840. lmat.m[13] = ly;
  77841. lmat.m[14] = lz;
  77842. this.computeAbsoluteTransforms();
  77843. this._markAsDirtyAndDecompose();
  77844. };
  77845. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  77846. var scaleMatrix = Bone._tmpMats[2];
  77847. rotMatInv.copyFrom(this.getAbsoluteTransform());
  77848. if (mesh) {
  77849. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  77850. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  77851. }
  77852. rotMatInv.invert();
  77853. if (isNaN(rotMatInv.m[0])) {
  77854. // Matrix failed to invert.
  77855. // This can happen if scale is zero for example.
  77856. return false;
  77857. }
  77858. scaleMatrix.m[0] *= this._scalingDeterminant;
  77859. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  77860. return true;
  77861. };
  77862. /**
  77863. * Get the position of the bone in local or world space
  77864. * @param space The space that the returned position is in
  77865. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77866. * @returns The position of the bone
  77867. */
  77868. Bone.prototype.getPosition = function (space, mesh) {
  77869. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77870. if (mesh === void 0) { mesh = null; }
  77871. var pos = BABYLON.Vector3.Zero();
  77872. this.getPositionToRef(space, mesh, pos);
  77873. return pos;
  77874. };
  77875. /**
  77876. * Copy the position of the bone to a vector3 in local or world space
  77877. * @param space The space that the returned position is in
  77878. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77879. * @param result The vector3 to copy the position to
  77880. */
  77881. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  77882. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77883. if (space == BABYLON.Space.LOCAL) {
  77884. var lm = this.getLocalMatrix();
  77885. result.x = lm.m[12];
  77886. result.y = lm.m[13];
  77887. result.z = lm.m[14];
  77888. }
  77889. else {
  77890. var wm = null;
  77891. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77892. if (mesh) {
  77893. wm = mesh.getWorldMatrix();
  77894. }
  77895. this._skeleton.computeAbsoluteTransforms();
  77896. var tmat = Bone._tmpMats[0];
  77897. if (mesh && wm) {
  77898. tmat.copyFrom(this.getAbsoluteTransform());
  77899. tmat.multiplyToRef(wm, tmat);
  77900. }
  77901. else {
  77902. tmat = this.getAbsoluteTransform();
  77903. }
  77904. result.x = tmat.m[12];
  77905. result.y = tmat.m[13];
  77906. result.z = tmat.m[14];
  77907. }
  77908. };
  77909. /**
  77910. * Get the absolute position of the bone (world space)
  77911. * @param mesh The mesh that this bone is attached to
  77912. * @returns The absolute position of the bone
  77913. */
  77914. Bone.prototype.getAbsolutePosition = function (mesh) {
  77915. if (mesh === void 0) { mesh = null; }
  77916. var pos = BABYLON.Vector3.Zero();
  77917. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  77918. return pos;
  77919. };
  77920. /**
  77921. * Copy the absolute position of the bone (world space) to the result param
  77922. * @param mesh The mesh that this bone is attached to
  77923. * @param result The vector3 to copy the absolute position to
  77924. */
  77925. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  77926. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  77927. };
  77928. /**
  77929. * Compute the absolute transforms of this bone and its children
  77930. */
  77931. Bone.prototype.computeAbsoluteTransforms = function () {
  77932. this._compose();
  77933. if (this._parent) {
  77934. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77935. }
  77936. else {
  77937. this._absoluteTransform.copyFrom(this._localMatrix);
  77938. var poseMatrix = this._skeleton.getPoseMatrix();
  77939. if (poseMatrix) {
  77940. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  77941. }
  77942. }
  77943. var children = this.children;
  77944. var len = children.length;
  77945. for (var i = 0; i < len; i++) {
  77946. children[i].computeAbsoluteTransforms();
  77947. }
  77948. };
  77949. /**
  77950. * Get the world direction from an axis that is in the local space of the bone
  77951. * @param localAxis The local direction that is used to compute the world direction
  77952. * @param mesh The mesh that this bone is attached to
  77953. * @returns The world direction
  77954. */
  77955. Bone.prototype.getDirection = function (localAxis, mesh) {
  77956. if (mesh === void 0) { mesh = null; }
  77957. var result = BABYLON.Vector3.Zero();
  77958. this.getDirectionToRef(localAxis, mesh, result);
  77959. return result;
  77960. };
  77961. /**
  77962. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  77963. * @param localAxis The local direction that is used to compute the world direction
  77964. * @param mesh The mesh that this bone is attached to
  77965. * @param result The vector3 that the world direction will be copied to
  77966. */
  77967. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  77968. if (mesh === void 0) { mesh = null; }
  77969. var wm = null;
  77970. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77971. if (mesh) {
  77972. wm = mesh.getWorldMatrix();
  77973. }
  77974. this._skeleton.computeAbsoluteTransforms();
  77975. var mat = Bone._tmpMats[0];
  77976. mat.copyFrom(this.getAbsoluteTransform());
  77977. if (mesh && wm) {
  77978. mat.multiplyToRef(wm, mat);
  77979. }
  77980. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  77981. result.normalize();
  77982. };
  77983. /**
  77984. * Get the euler rotation of the bone in local or world space
  77985. * @param space The space that the rotation should be in
  77986. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77987. * @returns The euler rotation
  77988. */
  77989. Bone.prototype.getRotation = function (space, mesh) {
  77990. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77991. if (mesh === void 0) { mesh = null; }
  77992. var result = BABYLON.Vector3.Zero();
  77993. this.getRotationToRef(space, mesh, result);
  77994. return result;
  77995. };
  77996. /**
  77997. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  77998. * @param space The space that the rotation should be in
  77999. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78000. * @param result The vector3 that the rotation should be copied to
  78001. */
  78002. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78003. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78004. if (mesh === void 0) { mesh = null; }
  78005. var quat = Bone._tmpQuat;
  78006. this.getRotationQuaternionToRef(space, mesh, quat);
  78007. quat.toEulerAnglesToRef(result);
  78008. };
  78009. /**
  78010. * Get the quaternion rotation of the bone in either local or world space
  78011. * @param space The space that the rotation should be in
  78012. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78013. * @returns The quaternion rotation
  78014. */
  78015. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78016. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78017. if (mesh === void 0) { mesh = null; }
  78018. var result = BABYLON.Quaternion.Identity();
  78019. this.getRotationQuaternionToRef(space, mesh, result);
  78020. return result;
  78021. };
  78022. /**
  78023. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78024. * @param space The space that the rotation should be in
  78025. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78026. * @param result The quaternion that the rotation should be copied to
  78027. */
  78028. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78029. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78030. if (mesh === void 0) { mesh = null; }
  78031. if (space == BABYLON.Space.LOCAL) {
  78032. this._decompose();
  78033. result.copyFrom(this._localRotation);
  78034. }
  78035. else {
  78036. var mat = Bone._tmpMats[0];
  78037. var amat = this.getAbsoluteTransform();
  78038. if (mesh) {
  78039. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78040. }
  78041. else {
  78042. mat.copyFrom(amat);
  78043. }
  78044. mat.m[0] *= this._scalingDeterminant;
  78045. mat.m[1] *= this._scalingDeterminant;
  78046. mat.m[2] *= this._scalingDeterminant;
  78047. mat.decompose(undefined, result, undefined);
  78048. }
  78049. };
  78050. /**
  78051. * Get the rotation matrix of the bone in local or world space
  78052. * @param space The space that the rotation should be in
  78053. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78054. * @returns The rotation matrix
  78055. */
  78056. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78057. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78058. var result = BABYLON.Matrix.Identity();
  78059. this.getRotationMatrixToRef(space, mesh, result);
  78060. return result;
  78061. };
  78062. /**
  78063. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78064. * @param space The space that the rotation should be in
  78065. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78066. * @param result The quaternion that the rotation should be copied to
  78067. */
  78068. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78069. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78070. if (space == BABYLON.Space.LOCAL) {
  78071. this.getLocalMatrix().getRotationMatrixToRef(result);
  78072. }
  78073. else {
  78074. var mat = Bone._tmpMats[0];
  78075. var amat = this.getAbsoluteTransform();
  78076. if (mesh) {
  78077. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78078. }
  78079. else {
  78080. mat.copyFrom(amat);
  78081. }
  78082. mat.m[0] *= this._scalingDeterminant;
  78083. mat.m[1] *= this._scalingDeterminant;
  78084. mat.m[2] *= this._scalingDeterminant;
  78085. mat.getRotationMatrixToRef(result);
  78086. }
  78087. };
  78088. /**
  78089. * Get the world position of a point that is in the local space of the bone
  78090. * @param position The local position
  78091. * @param mesh The mesh that this bone is attached to
  78092. * @returns The world position
  78093. */
  78094. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78095. if (mesh === void 0) { mesh = null; }
  78096. var result = BABYLON.Vector3.Zero();
  78097. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78098. return result;
  78099. };
  78100. /**
  78101. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78102. * @param position The local position
  78103. * @param mesh The mesh that this bone is attached to
  78104. * @param result The vector3 that the world position should be copied to
  78105. */
  78106. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78107. if (mesh === void 0) { mesh = null; }
  78108. var wm = null;
  78109. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78110. if (mesh) {
  78111. wm = mesh.getWorldMatrix();
  78112. }
  78113. this._skeleton.computeAbsoluteTransforms();
  78114. var tmat = Bone._tmpMats[0];
  78115. if (mesh && wm) {
  78116. tmat.copyFrom(this.getAbsoluteTransform());
  78117. tmat.multiplyToRef(wm, tmat);
  78118. }
  78119. else {
  78120. tmat = this.getAbsoluteTransform();
  78121. }
  78122. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78123. };
  78124. /**
  78125. * Get the local position of a point that is in world space
  78126. * @param position The world position
  78127. * @param mesh The mesh that this bone is attached to
  78128. * @returns The local position
  78129. */
  78130. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78131. if (mesh === void 0) { mesh = null; }
  78132. var result = BABYLON.Vector3.Zero();
  78133. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78134. return result;
  78135. };
  78136. /**
  78137. * Get the local position of a point that is in world space and copy it to the result param
  78138. * @param position The world position
  78139. * @param mesh The mesh that this bone is attached to
  78140. * @param result The vector3 that the local position should be copied to
  78141. */
  78142. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78143. if (mesh === void 0) { mesh = null; }
  78144. var wm = null;
  78145. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78146. if (mesh) {
  78147. wm = mesh.getWorldMatrix();
  78148. }
  78149. this._skeleton.computeAbsoluteTransforms();
  78150. var tmat = Bone._tmpMats[0];
  78151. tmat.copyFrom(this.getAbsoluteTransform());
  78152. if (mesh && wm) {
  78153. tmat.multiplyToRef(wm, tmat);
  78154. }
  78155. tmat.invert();
  78156. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78157. };
  78158. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78159. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78160. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78161. return Bone;
  78162. }(BABYLON.Node));
  78163. BABYLON.Bone = Bone;
  78164. })(BABYLON || (BABYLON = {}));
  78165. //# sourceMappingURL=babylon.bone.js.map
  78166. var BABYLON;
  78167. (function (BABYLON) {
  78168. /**
  78169. * Class used to apply inverse kinematics to bones
  78170. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78171. */
  78172. var BoneIKController = /** @class */ (function () {
  78173. /**
  78174. * Creates a new BoneIKController
  78175. * @param mesh defines the mesh to control
  78176. * @param bone defines the bone to control
  78177. * @param options defines options to set up the controller
  78178. */
  78179. function BoneIKController(mesh, bone, options) {
  78180. /**
  78181. * Gets or sets the target position
  78182. */
  78183. this.targetPosition = BABYLON.Vector3.Zero();
  78184. /**
  78185. * Gets or sets the pole target position
  78186. */
  78187. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78188. /**
  78189. * Gets or sets the pole target local offset
  78190. */
  78191. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78192. /**
  78193. * Gets or sets the pole angle
  78194. */
  78195. this.poleAngle = 0;
  78196. /**
  78197. * 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)
  78198. */
  78199. this.slerpAmount = 1;
  78200. this._bone1Quat = BABYLON.Quaternion.Identity();
  78201. this._bone1Mat = BABYLON.Matrix.Identity();
  78202. this._bone2Ang = Math.PI;
  78203. this._maxAngle = Math.PI;
  78204. this._rightHandedSystem = false;
  78205. this._bendAxis = BABYLON.Vector3.Right();
  78206. this._slerping = false;
  78207. this._adjustRoll = 0;
  78208. this._bone2 = bone;
  78209. this._bone1 = bone.getParent();
  78210. if (!this._bone1) {
  78211. return;
  78212. }
  78213. this.mesh = mesh;
  78214. var bonePos = bone.getPosition();
  78215. if (bone.getAbsoluteTransform().determinant() > 0) {
  78216. this._rightHandedSystem = true;
  78217. this._bendAxis.x = 0;
  78218. this._bendAxis.y = 0;
  78219. this._bendAxis.z = -1;
  78220. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78221. this._adjustRoll = Math.PI * .5;
  78222. this._bendAxis.z = 1;
  78223. }
  78224. }
  78225. if (this._bone1.length) {
  78226. var boneScale1 = this._bone1.getScale();
  78227. var boneScale2 = this._bone2.getScale();
  78228. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  78229. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  78230. }
  78231. else if (this._bone1.children[0]) {
  78232. mesh.computeWorldMatrix(true);
  78233. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  78234. var pos2 = this._bone2.getAbsolutePosition(mesh);
  78235. var pos3 = this._bone1.getAbsolutePosition(mesh);
  78236. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  78237. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  78238. }
  78239. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  78240. this.maxAngle = Math.PI;
  78241. if (options) {
  78242. if (options.targetMesh) {
  78243. this.targetMesh = options.targetMesh;
  78244. this.targetMesh.computeWorldMatrix(true);
  78245. }
  78246. if (options.poleTargetMesh) {
  78247. this.poleTargetMesh = options.poleTargetMesh;
  78248. this.poleTargetMesh.computeWorldMatrix(true);
  78249. }
  78250. else if (options.poleTargetBone) {
  78251. this.poleTargetBone = options.poleTargetBone;
  78252. }
  78253. else if (this._bone1.getParent()) {
  78254. this.poleTargetBone = this._bone1.getParent();
  78255. }
  78256. if (options.poleTargetLocalOffset) {
  78257. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  78258. }
  78259. if (options.poleAngle) {
  78260. this.poleAngle = options.poleAngle;
  78261. }
  78262. if (options.bendAxis) {
  78263. this._bendAxis.copyFrom(options.bendAxis);
  78264. }
  78265. if (options.maxAngle) {
  78266. this.maxAngle = options.maxAngle;
  78267. }
  78268. if (options.slerpAmount) {
  78269. this.slerpAmount = options.slerpAmount;
  78270. }
  78271. }
  78272. }
  78273. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  78274. /**
  78275. * Gets or sets maximum allowed angle
  78276. */
  78277. get: function () {
  78278. return this._maxAngle;
  78279. },
  78280. set: function (value) {
  78281. this._setMaxAngle(value);
  78282. },
  78283. enumerable: true,
  78284. configurable: true
  78285. });
  78286. BoneIKController.prototype._setMaxAngle = function (ang) {
  78287. if (ang < 0) {
  78288. ang = 0;
  78289. }
  78290. if (ang > Math.PI || ang == undefined) {
  78291. ang = Math.PI;
  78292. }
  78293. this._maxAngle = ang;
  78294. var a = this._bone1Length;
  78295. var b = this._bone2Length;
  78296. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  78297. };
  78298. /**
  78299. * Force the controller to update the bones
  78300. */
  78301. BoneIKController.prototype.update = function () {
  78302. var bone1 = this._bone1;
  78303. if (!bone1) {
  78304. return;
  78305. }
  78306. var target = this.targetPosition;
  78307. var poleTarget = this.poleTargetPosition;
  78308. var mat1 = BoneIKController._tmpMats[0];
  78309. var mat2 = BoneIKController._tmpMats[1];
  78310. if (this.targetMesh) {
  78311. target.copyFrom(this.targetMesh.getAbsolutePosition());
  78312. }
  78313. if (this.poleTargetBone) {
  78314. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  78315. }
  78316. else if (this.poleTargetMesh) {
  78317. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  78318. }
  78319. var bonePos = BoneIKController._tmpVecs[0];
  78320. var zaxis = BoneIKController._tmpVecs[1];
  78321. var xaxis = BoneIKController._tmpVecs[2];
  78322. var yaxis = BoneIKController._tmpVecs[3];
  78323. var upAxis = BoneIKController._tmpVecs[4];
  78324. var _tmpQuat = BoneIKController._tmpQuat;
  78325. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  78326. poleTarget.subtractToRef(bonePos, upAxis);
  78327. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  78328. upAxis.y = 1;
  78329. }
  78330. else {
  78331. upAxis.normalize();
  78332. }
  78333. target.subtractToRef(bonePos, yaxis);
  78334. yaxis.normalize();
  78335. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  78336. zaxis.normalize();
  78337. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  78338. xaxis.normalize();
  78339. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  78340. var a = this._bone1Length;
  78341. var b = this._bone2Length;
  78342. var c = BABYLON.Vector3.Distance(bonePos, target);
  78343. if (this._maxReach > 0) {
  78344. c = Math.min(this._maxReach, c);
  78345. }
  78346. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  78347. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  78348. if (acosa > 1) {
  78349. acosa = 1;
  78350. }
  78351. if (acosb > 1) {
  78352. acosb = 1;
  78353. }
  78354. if (acosa < -1) {
  78355. acosa = -1;
  78356. }
  78357. if (acosb < -1) {
  78358. acosb = -1;
  78359. }
  78360. var angA = Math.acos(acosa);
  78361. var angB = Math.acos(acosb);
  78362. var angC = -angA - angB;
  78363. if (this._rightHandedSystem) {
  78364. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  78365. mat2.multiplyToRef(mat1, mat1);
  78366. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  78367. mat2.multiplyToRef(mat1, mat1);
  78368. }
  78369. else {
  78370. var _tmpVec = BoneIKController._tmpVecs[5];
  78371. _tmpVec.copyFrom(this._bendAxis);
  78372. _tmpVec.x *= -1;
  78373. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  78374. mat2.multiplyToRef(mat1, mat1);
  78375. }
  78376. if (this.poleAngle) {
  78377. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  78378. mat1.multiplyToRef(mat2, mat1);
  78379. }
  78380. if (this._bone1) {
  78381. if (this.slerpAmount < 1) {
  78382. if (!this._slerping) {
  78383. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  78384. }
  78385. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  78386. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  78387. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  78388. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  78389. this._slerping = true;
  78390. }
  78391. else {
  78392. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  78393. this._bone1Mat.copyFrom(mat1);
  78394. this._slerping = false;
  78395. }
  78396. }
  78397. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  78398. this._bone2Ang = angC;
  78399. };
  78400. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78401. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  78402. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78403. return BoneIKController;
  78404. }());
  78405. BABYLON.BoneIKController = BoneIKController;
  78406. })(BABYLON || (BABYLON = {}));
  78407. //# sourceMappingURL=babylon.boneIKController.js.map
  78408. var BABYLON;
  78409. (function (BABYLON) {
  78410. /**
  78411. * Class used to make a bone look toward a point in space
  78412. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  78413. */
  78414. var BoneLookController = /** @class */ (function () {
  78415. /**
  78416. * Create a BoneLookController
  78417. * @param mesh the mesh that the bone belongs to
  78418. * @param bone the bone that will be looking to the target
  78419. * @param target the target Vector3 to look at
  78420. * @param settings optional settings:
  78421. * * maxYaw: the maximum angle the bone will yaw to
  78422. * * minYaw: the minimum angle the bone will yaw to
  78423. * * maxPitch: the maximum angle the bone will pitch to
  78424. * * minPitch: the minimum angle the bone will yaw to
  78425. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  78426. * * upAxis: the up axis of the coordinate system
  78427. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  78428. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  78429. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  78430. * * adjustYaw: used to make an adjustment to the yaw of the bone
  78431. * * adjustPitch: used to make an adjustment to the pitch of the bone
  78432. * * adjustRoll: used to make an adjustment to the roll of the bone
  78433. **/
  78434. function BoneLookController(mesh, bone, target, options) {
  78435. /**
  78436. * The up axis of the coordinate system that is used when the bone is rotated
  78437. */
  78438. this.upAxis = BABYLON.Vector3.Up();
  78439. /**
  78440. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  78441. */
  78442. this.upAxisSpace = BABYLON.Space.LOCAL;
  78443. /**
  78444. * Used to make an adjustment to the yaw of the bone
  78445. */
  78446. this.adjustYaw = 0;
  78447. /**
  78448. * Used to make an adjustment to the pitch of the bone
  78449. */
  78450. this.adjustPitch = 0;
  78451. /**
  78452. * Used to make an adjustment to the roll of the bone
  78453. */
  78454. this.adjustRoll = 0;
  78455. /**
  78456. * 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)
  78457. */
  78458. this.slerpAmount = 1;
  78459. this._boneQuat = BABYLON.Quaternion.Identity();
  78460. this._slerping = false;
  78461. this._firstFrameSkipped = false;
  78462. this._fowardAxis = BABYLON.Vector3.Forward();
  78463. this.mesh = mesh;
  78464. this.bone = bone;
  78465. this.target = target;
  78466. if (options) {
  78467. if (options.adjustYaw) {
  78468. this.adjustYaw = options.adjustYaw;
  78469. }
  78470. if (options.adjustPitch) {
  78471. this.adjustPitch = options.adjustPitch;
  78472. }
  78473. if (options.adjustRoll) {
  78474. this.adjustRoll = options.adjustRoll;
  78475. }
  78476. if (options.maxYaw != null) {
  78477. this.maxYaw = options.maxYaw;
  78478. }
  78479. else {
  78480. this.maxYaw = Math.PI;
  78481. }
  78482. if (options.minYaw != null) {
  78483. this.minYaw = options.minYaw;
  78484. }
  78485. else {
  78486. this.minYaw = -Math.PI;
  78487. }
  78488. if (options.maxPitch != null) {
  78489. this.maxPitch = options.maxPitch;
  78490. }
  78491. else {
  78492. this.maxPitch = Math.PI;
  78493. }
  78494. if (options.minPitch != null) {
  78495. this.minPitch = options.minPitch;
  78496. }
  78497. else {
  78498. this.minPitch = -Math.PI;
  78499. }
  78500. if (options.slerpAmount != null) {
  78501. this.slerpAmount = options.slerpAmount;
  78502. }
  78503. if (options.upAxis != null) {
  78504. this.upAxis = options.upAxis;
  78505. }
  78506. if (options.upAxisSpace != null) {
  78507. this.upAxisSpace = options.upAxisSpace;
  78508. }
  78509. if (options.yawAxis != null || options.pitchAxis != null) {
  78510. var newYawAxis = BABYLON.Axis.Y;
  78511. var newPitchAxis = BABYLON.Axis.X;
  78512. if (options.yawAxis != null) {
  78513. newYawAxis = options.yawAxis.clone();
  78514. newYawAxis.normalize();
  78515. }
  78516. if (options.pitchAxis != null) {
  78517. newPitchAxis = options.pitchAxis.clone();
  78518. newPitchAxis.normalize();
  78519. }
  78520. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  78521. this._transformYawPitch = BABYLON.Matrix.Identity();
  78522. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  78523. this._transformYawPitchInv = this._transformYawPitch.clone();
  78524. this._transformYawPitch.invert();
  78525. }
  78526. }
  78527. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  78528. this.upAxisSpace = BABYLON.Space.LOCAL;
  78529. }
  78530. }
  78531. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  78532. /**
  78533. * Gets or sets the minimum yaw angle that the bone can look to
  78534. */
  78535. get: function () {
  78536. return this._minYaw;
  78537. },
  78538. set: function (value) {
  78539. this._minYaw = value;
  78540. this._minYawSin = Math.sin(value);
  78541. this._minYawCos = Math.cos(value);
  78542. if (this._maxYaw != null) {
  78543. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78544. this._yawRange = this._maxYaw - this._minYaw;
  78545. }
  78546. },
  78547. enumerable: true,
  78548. configurable: true
  78549. });
  78550. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  78551. /**
  78552. * Gets or sets the maximum yaw angle that the bone can look to
  78553. */
  78554. get: function () {
  78555. return this._maxYaw;
  78556. },
  78557. set: function (value) {
  78558. this._maxYaw = value;
  78559. this._maxYawSin = Math.sin(value);
  78560. this._maxYawCos = Math.cos(value);
  78561. if (this._minYaw != null) {
  78562. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78563. this._yawRange = this._maxYaw - this._minYaw;
  78564. }
  78565. },
  78566. enumerable: true,
  78567. configurable: true
  78568. });
  78569. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  78570. /**
  78571. * Gets or sets the minimum pitch angle that the bone can look to
  78572. */
  78573. get: function () {
  78574. return this._minPitch;
  78575. },
  78576. set: function (value) {
  78577. this._minPitch = value;
  78578. this._minPitchTan = Math.tan(value);
  78579. },
  78580. enumerable: true,
  78581. configurable: true
  78582. });
  78583. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  78584. /**
  78585. * Gets or sets the maximum pitch angle that the bone can look to
  78586. */
  78587. get: function () {
  78588. return this._maxPitch;
  78589. },
  78590. set: function (value) {
  78591. this._maxPitch = value;
  78592. this._maxPitchTan = Math.tan(value);
  78593. },
  78594. enumerable: true,
  78595. configurable: true
  78596. });
  78597. /**
  78598. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  78599. */
  78600. BoneLookController.prototype.update = function () {
  78601. //skip the first frame when slerping so that the mesh rotation is correct
  78602. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  78603. this._firstFrameSkipped = true;
  78604. return;
  78605. }
  78606. var bone = this.bone;
  78607. var bonePos = BoneLookController._tmpVecs[0];
  78608. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  78609. var target = this.target;
  78610. var _tmpMat1 = BoneLookController._tmpMats[0];
  78611. var _tmpMat2 = BoneLookController._tmpMats[1];
  78612. var mesh = this.mesh;
  78613. var parentBone = bone.getParent();
  78614. var upAxis = BoneLookController._tmpVecs[1];
  78615. upAxis.copyFrom(this.upAxis);
  78616. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  78617. if (this._transformYawPitch) {
  78618. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  78619. }
  78620. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  78621. }
  78622. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  78623. mesh.getDirectionToRef(upAxis, upAxis);
  78624. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  78625. upAxis.normalize();
  78626. }
  78627. }
  78628. var checkYaw = false;
  78629. var checkPitch = false;
  78630. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  78631. checkYaw = true;
  78632. }
  78633. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  78634. checkPitch = true;
  78635. }
  78636. if (checkYaw || checkPitch) {
  78637. var spaceMat = BoneLookController._tmpMats[2];
  78638. var spaceMatInv = BoneLookController._tmpMats[3];
  78639. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  78640. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  78641. }
  78642. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  78643. spaceMat.copyFrom(mesh.getWorldMatrix());
  78644. }
  78645. else {
  78646. var forwardAxis = BoneLookController._tmpVecs[2];
  78647. forwardAxis.copyFrom(this._fowardAxis);
  78648. if (this._transformYawPitch) {
  78649. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  78650. }
  78651. if (parentBone) {
  78652. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  78653. }
  78654. else {
  78655. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  78656. }
  78657. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  78658. rightAxis.normalize();
  78659. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  78660. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  78661. }
  78662. spaceMat.invertToRef(spaceMatInv);
  78663. var xzlen = null;
  78664. if (checkPitch) {
  78665. var localTarget = BoneLookController._tmpVecs[3];
  78666. target.subtractToRef(bonePos, localTarget);
  78667. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78668. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78669. var pitch = Math.atan2(localTarget.y, xzlen);
  78670. var newPitch = pitch;
  78671. if (pitch > this._maxPitch) {
  78672. localTarget.y = this._maxPitchTan * xzlen;
  78673. newPitch = this._maxPitch;
  78674. }
  78675. else if (pitch < this._minPitch) {
  78676. localTarget.y = this._minPitchTan * xzlen;
  78677. newPitch = this._minPitch;
  78678. }
  78679. if (pitch != newPitch) {
  78680. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78681. localTarget.addInPlace(bonePos);
  78682. target = localTarget;
  78683. }
  78684. }
  78685. if (checkYaw) {
  78686. var localTarget = BoneLookController._tmpVecs[4];
  78687. target.subtractToRef(bonePos, localTarget);
  78688. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78689. var yaw = Math.atan2(localTarget.x, localTarget.z);
  78690. var newYaw = yaw;
  78691. if (yaw > this._maxYaw || yaw < this._minYaw) {
  78692. if (xzlen == null) {
  78693. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78694. }
  78695. if (this._yawRange > Math.PI) {
  78696. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  78697. localTarget.z = this._maxYawCos * xzlen;
  78698. localTarget.x = this._maxYawSin * xzlen;
  78699. newYaw = this._maxYaw;
  78700. }
  78701. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  78702. localTarget.z = this._minYawCos * xzlen;
  78703. localTarget.x = this._minYawSin * xzlen;
  78704. newYaw = this._minYaw;
  78705. }
  78706. }
  78707. else {
  78708. if (yaw > this._maxYaw) {
  78709. localTarget.z = this._maxYawCos * xzlen;
  78710. localTarget.x = this._maxYawSin * xzlen;
  78711. newYaw = this._maxYaw;
  78712. }
  78713. else if (yaw < this._minYaw) {
  78714. localTarget.z = this._minYawCos * xzlen;
  78715. localTarget.x = this._minYawSin * xzlen;
  78716. newYaw = this._minYaw;
  78717. }
  78718. }
  78719. }
  78720. if (this._slerping && this._yawRange > Math.PI) {
  78721. //are we going to be crossing into the min/max region?
  78722. var boneFwd = BoneLookController._tmpVecs[8];
  78723. boneFwd.copyFrom(BABYLON.Axis.Z);
  78724. if (this._transformYawPitch) {
  78725. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  78726. }
  78727. var boneRotMat = BoneLookController._tmpMats[4];
  78728. this._boneQuat.toRotationMatrix(boneRotMat);
  78729. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  78730. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  78731. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  78732. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  78733. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  78734. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  78735. if (angBtwTar > angBtwMidYaw) {
  78736. if (xzlen == null) {
  78737. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78738. }
  78739. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  78740. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  78741. if (angBtwMin < angBtwMax) {
  78742. newYaw = boneYaw + Math.PI * .75;
  78743. localTarget.z = Math.cos(newYaw) * xzlen;
  78744. localTarget.x = Math.sin(newYaw) * xzlen;
  78745. }
  78746. else {
  78747. newYaw = boneYaw - Math.PI * .75;
  78748. localTarget.z = Math.cos(newYaw) * xzlen;
  78749. localTarget.x = Math.sin(newYaw) * xzlen;
  78750. }
  78751. }
  78752. }
  78753. if (yaw != newYaw) {
  78754. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78755. localTarget.addInPlace(bonePos);
  78756. target = localTarget;
  78757. }
  78758. }
  78759. }
  78760. var zaxis = BoneLookController._tmpVecs[5];
  78761. var xaxis = BoneLookController._tmpVecs[6];
  78762. var yaxis = BoneLookController._tmpVecs[7];
  78763. var _tmpQuat = BoneLookController._tmpQuat;
  78764. target.subtractToRef(bonePos, zaxis);
  78765. zaxis.normalize();
  78766. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  78767. xaxis.normalize();
  78768. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  78769. yaxis.normalize();
  78770. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  78771. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  78772. return;
  78773. }
  78774. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  78775. return;
  78776. }
  78777. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  78778. return;
  78779. }
  78780. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  78781. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  78782. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  78783. }
  78784. if (this.slerpAmount < 1) {
  78785. if (!this._slerping) {
  78786. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  78787. }
  78788. if (this._transformYawPitch) {
  78789. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78790. }
  78791. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  78792. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  78793. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  78794. this._slerping = true;
  78795. }
  78796. else {
  78797. if (this._transformYawPitch) {
  78798. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78799. }
  78800. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  78801. this._slerping = false;
  78802. }
  78803. };
  78804. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  78805. var angDiff = ang2 - ang1;
  78806. angDiff %= Math.PI * 2;
  78807. if (angDiff > Math.PI) {
  78808. angDiff -= Math.PI * 2;
  78809. }
  78810. else if (angDiff < -Math.PI) {
  78811. angDiff += Math.PI * 2;
  78812. }
  78813. return angDiff;
  78814. };
  78815. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  78816. ang1 %= (2 * Math.PI);
  78817. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78818. ang2 %= (2 * Math.PI);
  78819. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78820. var ab = 0;
  78821. if (ang1 < ang2) {
  78822. ab = ang2 - ang1;
  78823. }
  78824. else {
  78825. ab = ang1 - ang2;
  78826. }
  78827. if (ab > Math.PI) {
  78828. ab = Math.PI * 2 - ab;
  78829. }
  78830. return ab;
  78831. };
  78832. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  78833. ang %= (2 * Math.PI);
  78834. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  78835. ang1 %= (2 * Math.PI);
  78836. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78837. ang2 %= (2 * Math.PI);
  78838. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78839. if (ang1 < ang2) {
  78840. if (ang > ang1 && ang < ang2) {
  78841. return true;
  78842. }
  78843. }
  78844. else {
  78845. if (ang > ang2 && ang < ang1) {
  78846. return true;
  78847. }
  78848. }
  78849. return false;
  78850. };
  78851. 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()];
  78852. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  78853. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78854. return BoneLookController;
  78855. }());
  78856. BABYLON.BoneLookController = BoneLookController;
  78857. })(BABYLON || (BABYLON = {}));
  78858. //# sourceMappingURL=babylon.boneLookController.js.map
  78859. var BABYLON;
  78860. (function (BABYLON) {
  78861. /**
  78862. * Class used to handle skinning animations
  78863. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78864. */
  78865. var Skeleton = /** @class */ (function () {
  78866. /**
  78867. * Creates a new skeleton
  78868. * @param name defines the skeleton name
  78869. * @param id defines the skeleton Id
  78870. * @param scene defines the hosting scene
  78871. */
  78872. function Skeleton(
  78873. /** defines the skeleton name */
  78874. name,
  78875. /** defines the skeleton Id */
  78876. id, scene) {
  78877. this.name = name;
  78878. this.id = id;
  78879. /**
  78880. * Gets the list of child bones
  78881. */
  78882. this.bones = new Array();
  78883. /**
  78884. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  78885. */
  78886. this.needInitialSkinMatrix = false;
  78887. this._isDirty = true;
  78888. this._meshesWithPoseMatrix = new Array();
  78889. this._identity = BABYLON.Matrix.Identity();
  78890. this._ranges = {};
  78891. this._lastAbsoluteTransformsUpdateId = -1;
  78892. /**
  78893. * Specifies if the skeleton should be serialized
  78894. */
  78895. this.doNotSerialize = false;
  78896. this._animationPropertiesOverride = null;
  78897. // Events
  78898. /**
  78899. * An observable triggered before computing the skeleton's matrices
  78900. */
  78901. this.onBeforeComputeObservable = new BABYLON.Observable();
  78902. this.bones = [];
  78903. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78904. scene.skeletons.push(this);
  78905. //make sure it will recalculate the matrix next time prepare is called.
  78906. this._isDirty = true;
  78907. }
  78908. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  78909. /**
  78910. * Gets or sets the animation properties override
  78911. */
  78912. get: function () {
  78913. if (!this._animationPropertiesOverride) {
  78914. return this._scene.animationPropertiesOverride;
  78915. }
  78916. return this._animationPropertiesOverride;
  78917. },
  78918. set: function (value) {
  78919. this._animationPropertiesOverride = value;
  78920. },
  78921. enumerable: true,
  78922. configurable: true
  78923. });
  78924. // Members
  78925. /**
  78926. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  78927. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  78928. * @returns a Float32Array containing matrices data
  78929. */
  78930. Skeleton.prototype.getTransformMatrices = function (mesh) {
  78931. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  78932. return mesh._bonesTransformMatrices;
  78933. }
  78934. if (!this._transformMatrices) {
  78935. this.prepare();
  78936. }
  78937. return this._transformMatrices;
  78938. };
  78939. /**
  78940. * Gets the current hosting scene
  78941. * @returns a scene object
  78942. */
  78943. Skeleton.prototype.getScene = function () {
  78944. return this._scene;
  78945. };
  78946. // Methods
  78947. /**
  78948. * Gets a string representing the current skeleton data
  78949. * @param fullDetails defines a boolean indicating if we want a verbose version
  78950. * @returns a string representing the current skeleton data
  78951. */
  78952. Skeleton.prototype.toString = function (fullDetails) {
  78953. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  78954. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  78955. if (fullDetails) {
  78956. ret += ", Ranges: {";
  78957. var first = true;
  78958. for (var name_1 in this._ranges) {
  78959. if (first) {
  78960. ret += ", ";
  78961. first = false;
  78962. }
  78963. ret += name_1;
  78964. }
  78965. ret += "}";
  78966. }
  78967. return ret;
  78968. };
  78969. /**
  78970. * Get bone's index searching by name
  78971. * @param name defines bone's name to search for
  78972. * @return the indice of the bone. Returns -1 if not found
  78973. */
  78974. Skeleton.prototype.getBoneIndexByName = function (name) {
  78975. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  78976. if (this.bones[boneIndex].name === name) {
  78977. return boneIndex;
  78978. }
  78979. }
  78980. return -1;
  78981. };
  78982. /**
  78983. * Creater a new animation range
  78984. * @param name defines the name of the range
  78985. * @param from defines the start key
  78986. * @param to defines the end key
  78987. */
  78988. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  78989. // check name not already in use
  78990. if (!this._ranges[name]) {
  78991. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  78992. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  78993. if (this.bones[i].animations[0]) {
  78994. this.bones[i].animations[0].createRange(name, from, to);
  78995. }
  78996. }
  78997. }
  78998. };
  78999. /**
  79000. * Delete a specific animation range
  79001. * @param name defines the name of the range
  79002. * @param deleteFrames defines if frames must be removed as well
  79003. */
  79004. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79005. if (deleteFrames === void 0) { deleteFrames = true; }
  79006. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79007. if (this.bones[i].animations[0]) {
  79008. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79009. }
  79010. }
  79011. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79012. };
  79013. /**
  79014. * Gets a specific animation range
  79015. * @param name defines the name of the range to look for
  79016. * @returns the requested animation range or null if not found
  79017. */
  79018. Skeleton.prototype.getAnimationRange = function (name) {
  79019. return this._ranges[name];
  79020. };
  79021. /**
  79022. * Gets the list of all animation ranges defined on this skeleton
  79023. * @returns an array
  79024. */
  79025. Skeleton.prototype.getAnimationRanges = function () {
  79026. var animationRanges = [];
  79027. var name;
  79028. var i = 0;
  79029. for (name in this._ranges) {
  79030. animationRanges[i] = this._ranges[name];
  79031. i++;
  79032. }
  79033. return animationRanges;
  79034. };
  79035. /**
  79036. * Copy animation range from a source skeleton.
  79037. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79038. * @param source defines the source skeleton
  79039. * @param name defines the name of the range to copy
  79040. * @param rescaleAsRequired defines if rescaling must be applied if required
  79041. * @returns true if operation was successful
  79042. */
  79043. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79044. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79045. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79046. return false;
  79047. }
  79048. var ret = true;
  79049. var frameOffset = this._getHighestAnimationFrame() + 1;
  79050. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79051. var boneDict = {};
  79052. var sourceBones = source.bones;
  79053. var nBones;
  79054. var i;
  79055. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79056. boneDict[sourceBones[i].name] = sourceBones[i];
  79057. }
  79058. if (this.bones.length !== sourceBones.length) {
  79059. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79060. ret = false;
  79061. }
  79062. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79063. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79064. var boneName = this.bones[i].name;
  79065. var sourceBone = boneDict[boneName];
  79066. if (sourceBone) {
  79067. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79068. }
  79069. else {
  79070. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79071. ret = false;
  79072. }
  79073. }
  79074. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79075. var range = source.getAnimationRange(name);
  79076. if (range) {
  79077. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79078. }
  79079. return ret;
  79080. };
  79081. /**
  79082. * Forces the skeleton to go to rest pose
  79083. */
  79084. Skeleton.prototype.returnToRest = function () {
  79085. for (var index = 0; index < this.bones.length; index++) {
  79086. this.bones[index].returnToRest();
  79087. }
  79088. };
  79089. Skeleton.prototype._getHighestAnimationFrame = function () {
  79090. var ret = 0;
  79091. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79092. if (this.bones[i].animations[0]) {
  79093. var highest = this.bones[i].animations[0].getHighestFrame();
  79094. if (ret < highest) {
  79095. ret = highest;
  79096. }
  79097. }
  79098. }
  79099. return ret;
  79100. };
  79101. /**
  79102. * Begin a specific animation range
  79103. * @param name defines the name of the range to start
  79104. * @param loop defines if looping must be turned on (false by default)
  79105. * @param speedRatio defines the speed ratio to apply (1 by default)
  79106. * @param onAnimationEnd defines a callback which will be called when animation will end
  79107. * @returns a new animatable
  79108. */
  79109. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79110. var range = this.getAnimationRange(name);
  79111. if (!range) {
  79112. return null;
  79113. }
  79114. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79115. };
  79116. /** @hidden */
  79117. Skeleton.prototype._markAsDirty = function () {
  79118. this._isDirty = true;
  79119. };
  79120. /** @hidden */
  79121. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79122. this._meshesWithPoseMatrix.push(mesh);
  79123. };
  79124. /** @hidden */
  79125. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79126. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79127. if (index > -1) {
  79128. this._meshesWithPoseMatrix.splice(index, 1);
  79129. }
  79130. };
  79131. /** @hidden */
  79132. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79133. this.onBeforeComputeObservable.notifyObservers(this);
  79134. for (var index = 0; index < this.bones.length; index++) {
  79135. var bone = this.bones[index];
  79136. var parentBone = bone.getParent();
  79137. if (parentBone) {
  79138. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79139. }
  79140. else {
  79141. if (initialSkinMatrix) {
  79142. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79143. }
  79144. else {
  79145. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79146. }
  79147. }
  79148. if (bone._index !== -1) {
  79149. var mappedIndex = bone._index === null ? index : bone._index;
  79150. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79151. }
  79152. }
  79153. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79154. };
  79155. /**
  79156. * Build all resources required to render a skeleton
  79157. */
  79158. Skeleton.prototype.prepare = function () {
  79159. if (!this._isDirty) {
  79160. return;
  79161. }
  79162. if (this.needInitialSkinMatrix) {
  79163. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79164. var mesh = this._meshesWithPoseMatrix[index];
  79165. var poseMatrix = mesh.getPoseMatrix();
  79166. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79167. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79168. }
  79169. if (this._synchronizedWithMesh !== mesh) {
  79170. this._synchronizedWithMesh = mesh;
  79171. // Prepare bones
  79172. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79173. var bone = this.bones[boneIndex];
  79174. if (!bone.getParent()) {
  79175. var matrix = bone.getBaseMatrix();
  79176. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79177. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79178. }
  79179. }
  79180. }
  79181. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79182. }
  79183. }
  79184. else {
  79185. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79186. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79187. }
  79188. this._computeTransformMatrices(this._transformMatrices, null);
  79189. }
  79190. this._isDirty = false;
  79191. this._scene._activeBones.addCount(this.bones.length, false);
  79192. };
  79193. /**
  79194. * Gets the list of animatables currently running for this skeleton
  79195. * @returns an array of animatables
  79196. */
  79197. Skeleton.prototype.getAnimatables = function () {
  79198. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79199. this._animatables = [];
  79200. for (var index = 0; index < this.bones.length; index++) {
  79201. this._animatables.push(this.bones[index]);
  79202. }
  79203. }
  79204. return this._animatables;
  79205. };
  79206. /**
  79207. * Clone the current skeleton
  79208. * @param name defines the name of the new skeleton
  79209. * @param id defines the id of the enw skeleton
  79210. * @returns the new skeleton
  79211. */
  79212. Skeleton.prototype.clone = function (name, id) {
  79213. var result = new Skeleton(name, id || name, this._scene);
  79214. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79215. for (var index = 0; index < this.bones.length; index++) {
  79216. var source = this.bones[index];
  79217. var parentBone = null;
  79218. var parent_1 = source.getParent();
  79219. if (parent_1) {
  79220. var parentIndex = this.bones.indexOf(parent_1);
  79221. parentBone = result.bones[parentIndex];
  79222. }
  79223. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  79224. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  79225. }
  79226. if (this._ranges) {
  79227. result._ranges = {};
  79228. for (var rangeName in this._ranges) {
  79229. var range = this._ranges[rangeName];
  79230. if (range) {
  79231. result._ranges[rangeName] = range.clone();
  79232. }
  79233. }
  79234. }
  79235. this._isDirty = true;
  79236. return result;
  79237. };
  79238. /**
  79239. * Enable animation blending for this skeleton
  79240. * @param blendingSpeed defines the blending speed to apply
  79241. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  79242. */
  79243. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  79244. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  79245. this.bones.forEach(function (bone) {
  79246. bone.animations.forEach(function (animation) {
  79247. animation.enableBlending = true;
  79248. animation.blendingSpeed = blendingSpeed;
  79249. });
  79250. });
  79251. };
  79252. /**
  79253. * Releases all resources associated with the current skeleton
  79254. */
  79255. Skeleton.prototype.dispose = function () {
  79256. this._meshesWithPoseMatrix = [];
  79257. // Animations
  79258. this.getScene().stopAnimation(this);
  79259. // Remove from scene
  79260. this.getScene().removeSkeleton(this);
  79261. };
  79262. /**
  79263. * Serialize the skeleton in a JSON object
  79264. * @returns a JSON object
  79265. */
  79266. Skeleton.prototype.serialize = function () {
  79267. var serializationObject = {};
  79268. serializationObject.name = this.name;
  79269. serializationObject.id = this.id;
  79270. if (this.dimensionsAtRest) {
  79271. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  79272. }
  79273. serializationObject.bones = [];
  79274. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79275. for (var index = 0; index < this.bones.length; index++) {
  79276. var bone = this.bones[index];
  79277. var parent_2 = bone.getParent();
  79278. var serializedBone = {
  79279. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  79280. name: bone.name,
  79281. matrix: bone.getBaseMatrix().toArray(),
  79282. rest: bone.getRestPose().toArray()
  79283. };
  79284. serializationObject.bones.push(serializedBone);
  79285. if (bone.length) {
  79286. serializedBone.length = bone.length;
  79287. }
  79288. if (bone.animations && bone.animations.length > 0) {
  79289. serializedBone.animation = bone.animations[0].serialize();
  79290. }
  79291. serializationObject.ranges = [];
  79292. for (var name in this._ranges) {
  79293. var source = this._ranges[name];
  79294. if (!source) {
  79295. continue;
  79296. }
  79297. var range = {};
  79298. range.name = name;
  79299. range.from = source.from;
  79300. range.to = source.to;
  79301. serializationObject.ranges.push(range);
  79302. }
  79303. }
  79304. return serializationObject;
  79305. };
  79306. /**
  79307. * Creates a new skeleton from serialized data
  79308. * @param parsedSkeleton defines the serialized data
  79309. * @param scene defines the hosting scene
  79310. * @returns a new skeleton
  79311. */
  79312. Skeleton.Parse = function (parsedSkeleton, scene) {
  79313. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  79314. if (parsedSkeleton.dimensionsAtRest) {
  79315. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  79316. }
  79317. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  79318. var index;
  79319. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  79320. var parsedBone = parsedSkeleton.bones[index];
  79321. var parentBone = null;
  79322. if (parsedBone.parentBoneIndex > -1) {
  79323. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  79324. }
  79325. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  79326. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  79327. if (parsedBone.length) {
  79328. bone.length = parsedBone.length;
  79329. }
  79330. if (parsedBone.animation) {
  79331. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  79332. }
  79333. }
  79334. // placed after bones, so createAnimationRange can cascade down
  79335. if (parsedSkeleton.ranges) {
  79336. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  79337. var data = parsedSkeleton.ranges[index];
  79338. skeleton.createAnimationRange(data.name, data.from, data.to);
  79339. }
  79340. }
  79341. return skeleton;
  79342. };
  79343. /**
  79344. * Compute all node absolute transforms
  79345. * @param forceUpdate defines if computation must be done even if cache is up to date
  79346. */
  79347. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  79348. if (forceUpdate === void 0) { forceUpdate = false; }
  79349. var renderId = this._scene.getRenderId();
  79350. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  79351. this.bones[0].computeAbsoluteTransforms();
  79352. this._lastAbsoluteTransformsUpdateId = renderId;
  79353. }
  79354. };
  79355. /**
  79356. * Gets the root pose matrix
  79357. * @returns a matrix
  79358. */
  79359. Skeleton.prototype.getPoseMatrix = function () {
  79360. var poseMatrix = null;
  79361. if (this._meshesWithPoseMatrix.length > 0) {
  79362. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  79363. }
  79364. return poseMatrix;
  79365. };
  79366. /**
  79367. * Sorts bones per internal index
  79368. */
  79369. Skeleton.prototype.sortBones = function () {
  79370. var bones = new Array();
  79371. var visited = new Array(this.bones.length);
  79372. for (var index = 0; index < this.bones.length; index++) {
  79373. this._sortBones(index, bones, visited);
  79374. }
  79375. this.bones = bones;
  79376. };
  79377. Skeleton.prototype._sortBones = function (index, bones, visited) {
  79378. if (visited[index]) {
  79379. return;
  79380. }
  79381. visited[index] = true;
  79382. var bone = this.bones[index];
  79383. if (bone._index === undefined) {
  79384. bone._index = index;
  79385. }
  79386. var parentBone = bone.getParent();
  79387. if (parentBone) {
  79388. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  79389. }
  79390. bones.push(bone);
  79391. };
  79392. return Skeleton;
  79393. }());
  79394. BABYLON.Skeleton = Skeleton;
  79395. })(BABYLON || (BABYLON = {}));
  79396. //# sourceMappingURL=babylon.skeleton.js.map
  79397. var BABYLON;
  79398. (function (BABYLON) {
  79399. var SphericalPolynomial = /** @class */ (function () {
  79400. function SphericalPolynomial() {
  79401. this.x = BABYLON.Vector3.Zero();
  79402. this.y = BABYLON.Vector3.Zero();
  79403. this.z = BABYLON.Vector3.Zero();
  79404. this.xx = BABYLON.Vector3.Zero();
  79405. this.yy = BABYLON.Vector3.Zero();
  79406. this.zz = BABYLON.Vector3.Zero();
  79407. this.xy = BABYLON.Vector3.Zero();
  79408. this.yz = BABYLON.Vector3.Zero();
  79409. this.zx = BABYLON.Vector3.Zero();
  79410. }
  79411. SphericalPolynomial.prototype.addAmbient = function (color) {
  79412. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79413. this.xx = this.xx.add(colorVector);
  79414. this.yy = this.yy.add(colorVector);
  79415. this.zz = this.zz.add(colorVector);
  79416. };
  79417. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  79418. var result = new SphericalPolynomial();
  79419. result.x = harmonics.L11.scale(1.02333);
  79420. result.y = harmonics.L1_1.scale(1.02333);
  79421. result.z = harmonics.L10.scale(1.02333);
  79422. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  79423. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  79424. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  79425. result.yz = harmonics.L2_1.scale(0.858086);
  79426. result.zx = harmonics.L21.scale(0.858086);
  79427. result.xy = harmonics.L2_2.scale(0.858086);
  79428. result.scale(1.0 / Math.PI);
  79429. return result;
  79430. };
  79431. SphericalPolynomial.prototype.scale = function (scale) {
  79432. this.x = this.x.scale(scale);
  79433. this.y = this.y.scale(scale);
  79434. this.z = this.z.scale(scale);
  79435. this.xx = this.xx.scale(scale);
  79436. this.yy = this.yy.scale(scale);
  79437. this.zz = this.zz.scale(scale);
  79438. this.yz = this.yz.scale(scale);
  79439. this.zx = this.zx.scale(scale);
  79440. this.xy = this.xy.scale(scale);
  79441. };
  79442. return SphericalPolynomial;
  79443. }());
  79444. BABYLON.SphericalPolynomial = SphericalPolynomial;
  79445. var SphericalHarmonics = /** @class */ (function () {
  79446. function SphericalHarmonics() {
  79447. this.L00 = BABYLON.Vector3.Zero();
  79448. this.L1_1 = BABYLON.Vector3.Zero();
  79449. this.L10 = BABYLON.Vector3.Zero();
  79450. this.L11 = BABYLON.Vector3.Zero();
  79451. this.L2_2 = BABYLON.Vector3.Zero();
  79452. this.L2_1 = BABYLON.Vector3.Zero();
  79453. this.L20 = BABYLON.Vector3.Zero();
  79454. this.L21 = BABYLON.Vector3.Zero();
  79455. this.L22 = BABYLON.Vector3.Zero();
  79456. }
  79457. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  79458. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79459. var c = colorVector.scale(deltaSolidAngle);
  79460. this.L00 = this.L00.add(c.scale(0.282095));
  79461. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  79462. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  79463. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  79464. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  79465. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  79466. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  79467. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  79468. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  79469. };
  79470. SphericalHarmonics.prototype.scale = function (scale) {
  79471. this.L00 = this.L00.scale(scale);
  79472. this.L1_1 = this.L1_1.scale(scale);
  79473. this.L10 = this.L10.scale(scale);
  79474. this.L11 = this.L11.scale(scale);
  79475. this.L2_2 = this.L2_2.scale(scale);
  79476. this.L2_1 = this.L2_1.scale(scale);
  79477. this.L20 = this.L20.scale(scale);
  79478. this.L21 = this.L21.scale(scale);
  79479. this.L22 = this.L22.scale(scale);
  79480. };
  79481. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  79482. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  79483. //
  79484. // E_lm = A_l * L_lm
  79485. //
  79486. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  79487. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  79488. // the scaling factors are given in equation 9.
  79489. // Constant (Band 0)
  79490. this.L00 = this.L00.scale(3.141593);
  79491. // Linear (Band 1)
  79492. this.L1_1 = this.L1_1.scale(2.094395);
  79493. this.L10 = this.L10.scale(2.094395);
  79494. this.L11 = this.L11.scale(2.094395);
  79495. // Quadratic (Band 2)
  79496. this.L2_2 = this.L2_2.scale(0.785398);
  79497. this.L2_1 = this.L2_1.scale(0.785398);
  79498. this.L20 = this.L20.scale(0.785398);
  79499. this.L21 = this.L21.scale(0.785398);
  79500. this.L22 = this.L22.scale(0.785398);
  79501. };
  79502. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  79503. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  79504. // L = (1/pi) * E * rho
  79505. //
  79506. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  79507. this.scale(1.0 / Math.PI);
  79508. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  79509. // (The pixel shader must apply albedo after texture fetches, etc).
  79510. };
  79511. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  79512. var result = new SphericalHarmonics();
  79513. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  79514. result.L1_1 = polynomial.y.scale(0.977204);
  79515. result.L10 = polynomial.z.scale(0.977204);
  79516. result.L11 = polynomial.x.scale(0.977204);
  79517. result.L2_2 = polynomial.xy.scale(1.16538);
  79518. result.L2_1 = polynomial.yz.scale(1.16538);
  79519. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  79520. result.L21 = polynomial.zx.scale(1.16538);
  79521. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  79522. result.scale(Math.PI);
  79523. return result;
  79524. };
  79525. return SphericalHarmonics;
  79526. }());
  79527. BABYLON.SphericalHarmonics = SphericalHarmonics;
  79528. })(BABYLON || (BABYLON = {}));
  79529. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  79530. var BABYLON;
  79531. (function (BABYLON) {
  79532. var FileFaceOrientation = /** @class */ (function () {
  79533. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  79534. this.name = name;
  79535. this.worldAxisForNormal = worldAxisForNormal;
  79536. this.worldAxisForFileX = worldAxisForFileX;
  79537. this.worldAxisForFileY = worldAxisForFileY;
  79538. }
  79539. return FileFaceOrientation;
  79540. }());
  79541. ;
  79542. /**
  79543. * Helper class dealing with the extraction of spherical polynomial dataArray
  79544. * from a cube map.
  79545. */
  79546. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  79547. function CubeMapToSphericalPolynomialTools() {
  79548. }
  79549. /**
  79550. * Converts a texture to the according Spherical Polynomial data.
  79551. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79552. *
  79553. * @param texture The texture to extract the information from.
  79554. * @return The Spherical Polynomial data.
  79555. */
  79556. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  79557. if (!texture.isCube) {
  79558. // Only supports cube Textures currently.
  79559. return null;
  79560. }
  79561. var size = texture.getSize().width;
  79562. var right = texture.readPixels(0);
  79563. var left = texture.readPixels(1);
  79564. var up;
  79565. var down;
  79566. if (texture.isRenderTarget) {
  79567. up = texture.readPixels(3);
  79568. down = texture.readPixels(2);
  79569. }
  79570. else {
  79571. up = texture.readPixels(2);
  79572. down = texture.readPixels(3);
  79573. }
  79574. var front = texture.readPixels(4);
  79575. var back = texture.readPixels(5);
  79576. var gammaSpace = texture.gammaSpace;
  79577. // Always read as RGBA.
  79578. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  79579. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79580. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79581. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79582. }
  79583. var cubeInfo = {
  79584. size: size,
  79585. right: right,
  79586. left: left,
  79587. up: up,
  79588. down: down,
  79589. front: front,
  79590. back: back,
  79591. format: format,
  79592. type: type,
  79593. gammaSpace: gammaSpace,
  79594. };
  79595. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  79596. };
  79597. /**
  79598. * Converts a cubemap to the according Spherical Polynomial data.
  79599. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79600. *
  79601. * @param cubeInfo The Cube map to extract the information from.
  79602. * @return The Spherical Polynomial data.
  79603. */
  79604. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  79605. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  79606. var totalSolidAngle = 0.0;
  79607. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  79608. var du = 2.0 / cubeInfo.size;
  79609. var dv = du;
  79610. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  79611. var minUV = du * 0.5 - 1.0;
  79612. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79613. var fileFace = this.FileFaces[faceIndex];
  79614. var dataArray = cubeInfo[fileFace.name];
  79615. var v = minUV;
  79616. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  79617. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  79618. // Because SP is still linear, so summation is fine in that basis.
  79619. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  79620. for (var y = 0; y < cubeInfo.size; y++) {
  79621. var u = minUV;
  79622. for (var x = 0; x < cubeInfo.size; x++) {
  79623. // World direction (not normalised)
  79624. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  79625. worldDirection.normalize();
  79626. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  79627. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  79628. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  79629. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  79630. // Handle Integer types.
  79631. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79632. r /= 255;
  79633. g /= 255;
  79634. b /= 255;
  79635. }
  79636. // Handle Gamma space textures.
  79637. if (cubeInfo.gammaSpace) {
  79638. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  79639. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  79640. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  79641. }
  79642. var color = new BABYLON.Color3(r, g, b);
  79643. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  79644. totalSolidAngle += deltaSolidAngle;
  79645. u += du;
  79646. }
  79647. v += dv;
  79648. }
  79649. }
  79650. // Solid angle for entire sphere is 4*pi
  79651. var sphereSolidAngle = 4.0 * Math.PI;
  79652. // Adjust the solid angle to allow for how many faces we processed.
  79653. var facesProcessed = 6.0;
  79654. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  79655. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  79656. // This is needed because the numerical integration over the cube uses a
  79657. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  79658. // and also to compensate for accumulative error due to float precision in the summation.
  79659. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  79660. sphericalHarmonics.scale(correctionFactor);
  79661. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  79662. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  79663. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  79664. };
  79665. CubeMapToSphericalPolynomialTools.FileFaces = [
  79666. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  79667. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  79668. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  79669. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  79670. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  79671. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  79672. ];
  79673. return CubeMapToSphericalPolynomialTools;
  79674. }());
  79675. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  79676. })(BABYLON || (BABYLON = {}));
  79677. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  79678. var BABYLON;
  79679. (function (BABYLON) {
  79680. /**
  79681. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  79682. */
  79683. var PanoramaToCubeMapTools = /** @class */ (function () {
  79684. function PanoramaToCubeMapTools() {
  79685. }
  79686. /**
  79687. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  79688. *
  79689. * @param float32Array The source data.
  79690. * @param inputWidth The width of the input panorama.
  79691. * @param inputhHeight The height of the input panorama.
  79692. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  79693. * @return The cubemap data
  79694. */
  79695. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  79696. if (!float32Array) {
  79697. throw "ConvertPanoramaToCubemap: input cannot be null";
  79698. }
  79699. if (float32Array.length != inputWidth * inputHeight * 3) {
  79700. throw "ConvertPanoramaToCubemap: input size is wrong";
  79701. }
  79702. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  79703. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  79704. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  79705. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  79706. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  79707. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  79708. return {
  79709. front: textureFront,
  79710. back: textureBack,
  79711. left: textureLeft,
  79712. right: textureRight,
  79713. up: textureUp,
  79714. down: textureDown,
  79715. size: size,
  79716. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  79717. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  79718. gammaSpace: false,
  79719. };
  79720. };
  79721. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  79722. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  79723. var textureArray = new Float32Array(buffer);
  79724. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  79725. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  79726. var dy = 1 / texSize;
  79727. var fy = 0;
  79728. for (var y = 0; y < texSize; y++) {
  79729. var xv1 = faceData[0];
  79730. var xv2 = faceData[2];
  79731. for (var x = 0; x < texSize; x++) {
  79732. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  79733. v.normalize();
  79734. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  79735. // 3 channels per pixels
  79736. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  79737. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  79738. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  79739. xv1 = xv1.add(rotDX1);
  79740. xv2 = xv2.add(rotDX2);
  79741. }
  79742. fy += dy;
  79743. }
  79744. return textureArray;
  79745. };
  79746. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  79747. var theta = Math.atan2(vDir.z, vDir.x);
  79748. var phi = Math.acos(vDir.y);
  79749. while (theta < -Math.PI)
  79750. theta += 2 * Math.PI;
  79751. while (theta > Math.PI)
  79752. theta -= 2 * Math.PI;
  79753. var dx = theta / Math.PI;
  79754. var dy = phi / Math.PI;
  79755. // recenter.
  79756. dx = dx * 0.5 + 0.5;
  79757. var px = Math.round(dx * inputWidth);
  79758. if (px < 0)
  79759. px = 0;
  79760. else if (px >= inputWidth)
  79761. px = inputWidth - 1;
  79762. var py = Math.round(dy * inputHeight);
  79763. if (py < 0)
  79764. py = 0;
  79765. else if (py >= inputHeight)
  79766. py = inputHeight - 1;
  79767. var inputY = (inputHeight - py - 1);
  79768. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  79769. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  79770. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  79771. return {
  79772. r: r,
  79773. g: g,
  79774. b: b
  79775. };
  79776. };
  79777. PanoramaToCubeMapTools.FACE_FRONT = [
  79778. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79779. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79780. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79781. new BABYLON.Vector3(1.0, 1.0, -1.0)
  79782. ];
  79783. PanoramaToCubeMapTools.FACE_BACK = [
  79784. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79785. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79786. new BABYLON.Vector3(1.0, 1.0, 1.0),
  79787. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  79788. ];
  79789. PanoramaToCubeMapTools.FACE_RIGHT = [
  79790. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79791. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79792. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79793. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79794. ];
  79795. PanoramaToCubeMapTools.FACE_LEFT = [
  79796. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79797. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79798. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79799. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  79800. ];
  79801. PanoramaToCubeMapTools.FACE_DOWN = [
  79802. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79803. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79804. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79805. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79806. ];
  79807. PanoramaToCubeMapTools.FACE_UP = [
  79808. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79809. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79810. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79811. new BABYLON.Vector3(1.0, -1.0, -1.0)
  79812. ];
  79813. return PanoramaToCubeMapTools;
  79814. }());
  79815. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  79816. })(BABYLON || (BABYLON = {}));
  79817. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  79818. var BABYLON;
  79819. (function (BABYLON) {
  79820. ;
  79821. /**
  79822. * This groups tools to convert HDR texture to native colors array.
  79823. */
  79824. var HDRTools = /** @class */ (function () {
  79825. function HDRTools() {
  79826. }
  79827. HDRTools.Ldexp = function (mantissa, exponent) {
  79828. if (exponent > 1023) {
  79829. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  79830. }
  79831. if (exponent < -1074) {
  79832. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  79833. }
  79834. return mantissa * Math.pow(2, exponent);
  79835. };
  79836. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  79837. if (exponent > 0) { /*nonzero pixel*/
  79838. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  79839. float32array[index + 0] = red * exponent;
  79840. float32array[index + 1] = green * exponent;
  79841. float32array[index + 2] = blue * exponent;
  79842. }
  79843. else {
  79844. float32array[index + 0] = 0;
  79845. float32array[index + 1] = 0;
  79846. float32array[index + 2] = 0;
  79847. }
  79848. };
  79849. HDRTools.readStringLine = function (uint8array, startIndex) {
  79850. var line = "";
  79851. var character = "";
  79852. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  79853. character = String.fromCharCode(uint8array[i]);
  79854. if (character == "\n") {
  79855. break;
  79856. }
  79857. line += character;
  79858. }
  79859. return line;
  79860. };
  79861. /**
  79862. * Reads header information from an RGBE texture stored in a native array.
  79863. * More information on this format are available here:
  79864. * https://en.wikipedia.org/wiki/RGBE_image_format
  79865. *
  79866. * @param uint8array The binary file stored in native array.
  79867. * @return The header information.
  79868. */
  79869. HDRTools.RGBE_ReadHeader = function (uint8array) {
  79870. var height = 0;
  79871. var width = 0;
  79872. var line = this.readStringLine(uint8array, 0);
  79873. if (line[0] != '#' || line[1] != '?') {
  79874. throw "Bad HDR Format.";
  79875. }
  79876. var endOfHeader = false;
  79877. var findFormat = false;
  79878. var lineIndex = 0;
  79879. do {
  79880. lineIndex += (line.length + 1);
  79881. line = this.readStringLine(uint8array, lineIndex);
  79882. if (line == "FORMAT=32-bit_rle_rgbe") {
  79883. findFormat = true;
  79884. }
  79885. else if (line.length == 0) {
  79886. endOfHeader = true;
  79887. }
  79888. } while (!endOfHeader);
  79889. if (!findFormat) {
  79890. throw "HDR Bad header format, unsupported FORMAT";
  79891. }
  79892. lineIndex += (line.length + 1);
  79893. line = this.readStringLine(uint8array, lineIndex);
  79894. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  79895. var match = sizeRegexp.exec(line);
  79896. // TODO. Support +Y and -X if needed.
  79897. if (!match || match.length < 3) {
  79898. throw "HDR Bad header format, no size";
  79899. }
  79900. width = parseInt(match[2]);
  79901. height = parseInt(match[1]);
  79902. if (width < 8 || width > 0x7fff) {
  79903. throw "HDR Bad header format, unsupported size";
  79904. }
  79905. lineIndex += (line.length + 1);
  79906. return {
  79907. height: height,
  79908. width: width,
  79909. dataPosition: lineIndex
  79910. };
  79911. };
  79912. /**
  79913. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  79914. * This RGBE texture needs to store the information as a panorama.
  79915. *
  79916. * More information on this format are available here:
  79917. * https://en.wikipedia.org/wiki/RGBE_image_format
  79918. *
  79919. * @param buffer The binary file stored in an array buffer.
  79920. * @param size The expected size of the extracted cubemap.
  79921. * @return The Cube Map information.
  79922. */
  79923. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  79924. var uint8array = new Uint8Array(buffer);
  79925. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  79926. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  79927. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  79928. return cubeMapData;
  79929. };
  79930. /**
  79931. * Returns the pixels data extracted from an RGBE texture.
  79932. * This pixels will be stored left to right up to down in the R G B order in one array.
  79933. *
  79934. * More information on this format are available here:
  79935. * https://en.wikipedia.org/wiki/RGBE_image_format
  79936. *
  79937. * @param uint8array The binary file stored in an array buffer.
  79938. * @param hdrInfo The header information of the file.
  79939. * @return The pixels data in RGB right to left up to down order.
  79940. */
  79941. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  79942. // Keep for multi format supports.
  79943. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  79944. };
  79945. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  79946. var num_scanlines = hdrInfo.height;
  79947. var scanline_width = hdrInfo.width;
  79948. var a, b, c, d, count;
  79949. var dataIndex = hdrInfo.dataPosition;
  79950. var index = 0, endIndex = 0, i = 0;
  79951. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  79952. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  79953. // 3 channels of 4 bytes per pixel in float.
  79954. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  79955. var resultArray = new Float32Array(resultBuffer);
  79956. // read in each successive scanline
  79957. while (num_scanlines > 0) {
  79958. a = uint8array[dataIndex++];
  79959. b = uint8array[dataIndex++];
  79960. c = uint8array[dataIndex++];
  79961. d = uint8array[dataIndex++];
  79962. if (a != 2 || b != 2 || (c & 0x80)) {
  79963. // this file is not run length encoded
  79964. throw "HDR Bad header format, not RLE";
  79965. }
  79966. if (((c << 8) | d) != scanline_width) {
  79967. throw "HDR Bad header format, wrong scan line width";
  79968. }
  79969. index = 0;
  79970. // read each of the four channels for the scanline into the buffer
  79971. for (i = 0; i < 4; i++) {
  79972. endIndex = (i + 1) * scanline_width;
  79973. while (index < endIndex) {
  79974. a = uint8array[dataIndex++];
  79975. b = uint8array[dataIndex++];
  79976. if (a > 128) {
  79977. // a run of the same value
  79978. count = a - 128;
  79979. if ((count == 0) || (count > endIndex - index)) {
  79980. throw "HDR Bad Format, bad scanline data (run)";
  79981. }
  79982. while (count-- > 0) {
  79983. scanLineArray[index++] = b;
  79984. }
  79985. }
  79986. else {
  79987. // a non-run
  79988. count = a;
  79989. if ((count == 0) || (count > endIndex - index)) {
  79990. throw "HDR Bad Format, bad scanline data (non-run)";
  79991. }
  79992. scanLineArray[index++] = b;
  79993. if (--count > 0) {
  79994. for (var j = 0; j < count; j++) {
  79995. scanLineArray[index++] = uint8array[dataIndex++];
  79996. }
  79997. }
  79998. }
  79999. }
  80000. }
  80001. // now convert data from buffer into floats
  80002. for (i = 0; i < scanline_width; i++) {
  80003. a = scanLineArray[i];
  80004. b = scanLineArray[i + scanline_width];
  80005. c = scanLineArray[i + 2 * scanline_width];
  80006. d = scanLineArray[i + 3 * scanline_width];
  80007. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80008. }
  80009. num_scanlines--;
  80010. }
  80011. return resultArray;
  80012. };
  80013. return HDRTools;
  80014. }());
  80015. BABYLON.HDRTools = HDRTools;
  80016. })(BABYLON || (BABYLON = {}));
  80017. //# sourceMappingURL=babylon.hdr.js.map
  80018. var BABYLON;
  80019. (function (BABYLON) {
  80020. /**
  80021. * This represents a texture coming from an HDR input.
  80022. *
  80023. * The only supported format is currently panorama picture stored in RGBE format.
  80024. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80025. */
  80026. var HDRCubeTexture = /** @class */ (function (_super) {
  80027. __extends(HDRCubeTexture, _super);
  80028. /**
  80029. * Instantiates an HDRTexture from the following parameters.
  80030. *
  80031. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80032. * @param scene The scene the texture will be used in
  80033. * @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.
  80034. * @param noMipmap Forces to not generate the mipmap if true
  80035. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80036. * @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)
  80037. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  80038. */
  80039. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  80040. if (noMipmap === void 0) { noMipmap = false; }
  80041. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80042. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  80043. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  80044. if (onLoad === void 0) { onLoad = null; }
  80045. if (onError === void 0) { onError = null; }
  80046. var _this = _super.call(this, scene) || this;
  80047. _this._useInGammaSpace = false;
  80048. _this._generateHarmonics = true;
  80049. _this._isBABYLONPreprocessed = false;
  80050. _this._onLoad = null;
  80051. _this._onError = null;
  80052. /**
  80053. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80054. */
  80055. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80056. /**
  80057. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  80058. * This is usefull at run time to apply the good shader.
  80059. */
  80060. _this.isPMREM = false;
  80061. _this._isBlocking = true;
  80062. _this._rotationY = 0;
  80063. /**
  80064. * Gets or sets the center of the bounding box associated with the cube texture
  80065. * It must define where the camera used to render the texture was set
  80066. */
  80067. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80068. if (!url) {
  80069. return _this;
  80070. }
  80071. _this.name = url;
  80072. _this.url = url;
  80073. _this.hasAlpha = false;
  80074. _this.isCube = true;
  80075. _this._textureMatrix = BABYLON.Matrix.Identity();
  80076. _this._onLoad = onLoad;
  80077. _this._onError = onError;
  80078. _this.gammaSpace = false;
  80079. var caps = scene.getEngine().getCaps();
  80080. if (size) {
  80081. _this._isBABYLONPreprocessed = false;
  80082. _this._noMipmap = noMipmap;
  80083. _this._size = size;
  80084. _this._useInGammaSpace = useInGammaSpace;
  80085. _this._usePMREMGenerator = usePMREMGenerator &&
  80086. caps.textureLOD &&
  80087. caps.textureFloat &&
  80088. !_this._useInGammaSpace;
  80089. }
  80090. else {
  80091. _this._isBABYLONPreprocessed = true;
  80092. _this._noMipmap = false;
  80093. _this._useInGammaSpace = false;
  80094. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  80095. !_this._useInGammaSpace;
  80096. }
  80097. _this.isPMREM = _this._usePMREMGenerator;
  80098. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80099. if (!_this._texture) {
  80100. if (!scene.useDelayedTextureLoading) {
  80101. _this.loadTexture();
  80102. }
  80103. else {
  80104. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80105. }
  80106. }
  80107. return _this;
  80108. }
  80109. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80110. /**
  80111. * Gets wether or not the texture is blocking during loading.
  80112. */
  80113. get: function () {
  80114. return this._isBlocking;
  80115. },
  80116. /**
  80117. * Sets wether or not the texture is blocking during loading.
  80118. */
  80119. set: function (value) {
  80120. this._isBlocking = value;
  80121. },
  80122. enumerable: true,
  80123. configurable: true
  80124. });
  80125. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80126. /**
  80127. * Gets texture matrix rotation angle around Y axis radians.
  80128. */
  80129. get: function () {
  80130. return this._rotationY;
  80131. },
  80132. /**
  80133. * Sets texture matrix rotation angle around Y axis in radians.
  80134. */
  80135. set: function (value) {
  80136. this._rotationY = value;
  80137. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80138. },
  80139. enumerable: true,
  80140. configurable: true
  80141. });
  80142. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80143. get: function () {
  80144. return this._boundingBoxSize;
  80145. },
  80146. /**
  80147. * Gets or sets the size of the bounding box associated with the cube texture
  80148. * When defined, the cubemap will switch to local mode
  80149. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80150. * @example https://www.babylonjs-playground.com/#RNASML
  80151. */
  80152. set: function (value) {
  80153. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80154. return;
  80155. }
  80156. this._boundingBoxSize = value;
  80157. var scene = this.getScene();
  80158. if (scene) {
  80159. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80160. }
  80161. },
  80162. enumerable: true,
  80163. configurable: true
  80164. });
  80165. /**
  80166. * Occurs when the file is a preprocessed .babylon.hdr file.
  80167. */
  80168. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  80169. var _this = this;
  80170. var mipLevels = 0;
  80171. var floatArrayView = null;
  80172. var scene = this.getScene();
  80173. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  80174. var mips = new Array();
  80175. if (!floatArrayView) {
  80176. return mips;
  80177. }
  80178. var startIndex = 30;
  80179. for (var level = 0; level < mipLevels; level++) {
  80180. mips.push([]);
  80181. // Fill each pixel of the mip level.
  80182. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  80183. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80184. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  80185. mips[level].push(faceData);
  80186. startIndex += faceSize;
  80187. }
  80188. }
  80189. return mips;
  80190. } : null;
  80191. var callback = function (buffer) {
  80192. var scene = _this.getScene();
  80193. if (!scene) {
  80194. return null;
  80195. }
  80196. // Create Native Array Views
  80197. var intArrayView = new Int32Array(buffer);
  80198. floatArrayView = new Float32Array(buffer);
  80199. // Fill header.
  80200. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  80201. _this._size = intArrayView[1]; // CubeMap max mip face size.
  80202. // Update Texture Information.
  80203. if (!_this._texture) {
  80204. return null;
  80205. }
  80206. _this._texture.updateSize(_this._size, _this._size);
  80207. // Fill polynomial information.
  80208. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  80209. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  80210. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  80211. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  80212. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  80213. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  80214. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  80215. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  80216. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  80217. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  80218. _this.sphericalPolynomial = sphericalPolynomial;
  80219. // Fill pixel data.
  80220. mipLevels = intArrayView[29]; // Number of mip levels.
  80221. var startIndex = 30;
  80222. var data = [];
  80223. var faceSize = Math.pow(_this._size, 2) * 3;
  80224. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80225. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  80226. startIndex += faceSize;
  80227. }
  80228. var results = [];
  80229. var byteArray = null;
  80230. // Push each faces.
  80231. for (var k = 0; k < 6; k++) {
  80232. var dataFace = null;
  80233. // To be deprecated.
  80234. if (version === 1) {
  80235. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  80236. dataFace = data[j];
  80237. }
  80238. // If special cases.
  80239. if (!mipmapGenerator && dataFace) {
  80240. if (!scene.getEngine().getCaps().textureFloat) {
  80241. // 3 channels of 1 bytes per pixel in bytes.
  80242. var byteBuffer = new ArrayBuffer(faceSize);
  80243. byteArray = new Uint8Array(byteBuffer);
  80244. }
  80245. for (var i = 0; i < _this._size * _this._size; i++) {
  80246. // Put in gamma space if requested.
  80247. if (_this._useInGammaSpace) {
  80248. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80249. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80250. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80251. }
  80252. // Convert to int texture for fallback.
  80253. if (byteArray) {
  80254. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80255. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80256. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80257. // May use luminance instead if the result is not accurate.
  80258. var max = Math.max(Math.max(r, g), b);
  80259. if (max > 255) {
  80260. var scale = 255 / max;
  80261. r *= scale;
  80262. g *= scale;
  80263. b *= scale;
  80264. }
  80265. byteArray[(i * 3) + 0] = r;
  80266. byteArray[(i * 3) + 1] = g;
  80267. byteArray[(i * 3) + 2] = b;
  80268. }
  80269. }
  80270. }
  80271. // Fill the array accordingly.
  80272. if (byteArray) {
  80273. results.push(byteArray);
  80274. }
  80275. else {
  80276. results.push(dataFace);
  80277. }
  80278. }
  80279. return results;
  80280. };
  80281. if (scene) {
  80282. 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);
  80283. }
  80284. };
  80285. /**
  80286. * Occurs when the file is raw .hdr file.
  80287. */
  80288. HDRCubeTexture.prototype.loadHDRTexture = function () {
  80289. var _this = this;
  80290. var callback = function (buffer) {
  80291. var scene = _this.getScene();
  80292. if (!scene) {
  80293. return null;
  80294. }
  80295. // Extract the raw linear data.
  80296. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80297. // Generate harmonics if needed.
  80298. if (_this._generateHarmonics) {
  80299. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80300. _this.sphericalPolynomial = sphericalPolynomial;
  80301. }
  80302. var results = [];
  80303. var byteArray = null;
  80304. // Push each faces.
  80305. for (var j = 0; j < 6; j++) {
  80306. // Create uintarray fallback.
  80307. if (!scene.getEngine().getCaps().textureFloat) {
  80308. // 3 channels of 1 bytes per pixel in bytes.
  80309. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80310. byteArray = new Uint8Array(byteBuffer);
  80311. }
  80312. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80313. // If special cases.
  80314. if (_this._useInGammaSpace || byteArray) {
  80315. for (var i = 0; i < _this._size * _this._size; i++) {
  80316. // Put in gamma space if requested.
  80317. if (_this._useInGammaSpace) {
  80318. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80319. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80320. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80321. }
  80322. // Convert to int texture for fallback.
  80323. if (byteArray) {
  80324. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80325. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80326. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80327. // May use luminance instead if the result is not accurate.
  80328. var max = Math.max(Math.max(r, g), b);
  80329. if (max > 255) {
  80330. var scale = 255 / max;
  80331. r *= scale;
  80332. g *= scale;
  80333. b *= scale;
  80334. }
  80335. byteArray[(i * 3) + 0] = r;
  80336. byteArray[(i * 3) + 1] = g;
  80337. byteArray[(i * 3) + 2] = b;
  80338. }
  80339. }
  80340. }
  80341. if (byteArray) {
  80342. results.push(byteArray);
  80343. }
  80344. else {
  80345. results.push(dataFace);
  80346. }
  80347. }
  80348. return results;
  80349. };
  80350. var mipmapGenerator = null;
  80351. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  80352. // if (!this._noMipmap &&
  80353. // this._usePMREMGenerator) {
  80354. // mipmapGenerator = (data: ArrayBufferView[]) => {
  80355. // // Custom setup of the generator matching with the PBR shader values.
  80356. // var generator = new BABYLON.PMREMGenerator(data,
  80357. // this._size,
  80358. // this._size,
  80359. // 0,
  80360. // 3,
  80361. // this.getScene().getEngine().getCaps().textureFloat,
  80362. // 2048,
  80363. // 0.25,
  80364. // false,
  80365. // true);
  80366. // return generator.filterCubeMap();
  80367. // };
  80368. // }
  80369. var scene = this.getScene();
  80370. if (scene) {
  80371. 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);
  80372. }
  80373. };
  80374. /**
  80375. * Starts the loading process of the texture.
  80376. */
  80377. HDRCubeTexture.prototype.loadTexture = function () {
  80378. if (this._isBABYLONPreprocessed) {
  80379. this.loadBabylonTexture();
  80380. }
  80381. else {
  80382. this.loadHDRTexture();
  80383. }
  80384. };
  80385. HDRCubeTexture.prototype.clone = function () {
  80386. var scene = this.getScene();
  80387. if (!scene) {
  80388. return this;
  80389. }
  80390. var size = (this._isBABYLONPreprocessed ? null : this._size);
  80391. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  80392. // Base texture
  80393. newTexture.level = this.level;
  80394. newTexture.wrapU = this.wrapU;
  80395. newTexture.wrapV = this.wrapV;
  80396. newTexture.coordinatesIndex = this.coordinatesIndex;
  80397. newTexture.coordinatesMode = this.coordinatesMode;
  80398. return newTexture;
  80399. };
  80400. // Methods
  80401. HDRCubeTexture.prototype.delayLoad = function () {
  80402. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80403. return;
  80404. }
  80405. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80406. this._texture = this._getFromCache(this.url, this._noMipmap);
  80407. if (!this._texture) {
  80408. this.loadTexture();
  80409. }
  80410. };
  80411. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  80412. return this._textureMatrix;
  80413. };
  80414. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  80415. this._textureMatrix = value;
  80416. };
  80417. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80418. var texture = null;
  80419. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80420. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  80421. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  80422. texture.name = parsedTexture.name;
  80423. texture.hasAlpha = parsedTexture.hasAlpha;
  80424. texture.level = parsedTexture.level;
  80425. texture.coordinatesMode = parsedTexture.coordinatesMode;
  80426. texture.isBlocking = parsedTexture.isBlocking;
  80427. }
  80428. if (texture) {
  80429. if (parsedTexture.boundingBoxPosition) {
  80430. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  80431. }
  80432. if (parsedTexture.boundingBoxSize) {
  80433. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  80434. }
  80435. if (parsedTexture.rotationY) {
  80436. texture.rotationY = parsedTexture.rotationY;
  80437. }
  80438. }
  80439. return texture;
  80440. };
  80441. HDRCubeTexture.prototype.serialize = function () {
  80442. if (!this.name) {
  80443. return null;
  80444. }
  80445. var serializationObject = {};
  80446. serializationObject.name = this.name;
  80447. serializationObject.hasAlpha = this.hasAlpha;
  80448. serializationObject.isCube = true;
  80449. serializationObject.level = this.level;
  80450. serializationObject.size = this._size;
  80451. serializationObject.coordinatesMode = this.coordinatesMode;
  80452. serializationObject.useInGammaSpace = this._useInGammaSpace;
  80453. serializationObject.generateHarmonics = this._generateHarmonics;
  80454. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  80455. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  80456. serializationObject.customType = "BABYLON.HDRCubeTexture";
  80457. serializationObject.noMipmap = this._noMipmap;
  80458. serializationObject.isBlocking = this._isBlocking;
  80459. serializationObject.rotationY = this._rotationY;
  80460. return serializationObject;
  80461. };
  80462. /**
  80463. * Saves as a file the data contained in the texture in a binary format.
  80464. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  80465. * as the spherical used in the lighting.
  80466. * @param url The HDR file url.
  80467. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  80468. * @param onError Method called if any error happens during download.
  80469. * @return The packed binary data.
  80470. */
  80471. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  80472. if (onError === void 0) { onError = null; }
  80473. var callback = function (buffer) {
  80474. var data = new Blob([buffer], { type: 'application/octet-stream' });
  80475. // Returns a URL you can use as a href.
  80476. var objUrl = window.URL.createObjectURL(data);
  80477. // Simulates a link to it and click to dowload.
  80478. var a = document.createElement("a");
  80479. document.body.appendChild(a);
  80480. a.style.display = "none";
  80481. a.href = objUrl;
  80482. a.download = "envmap.babylon.hdr";
  80483. a.click();
  80484. };
  80485. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  80486. };
  80487. /**
  80488. * Serializes the data contained in the texture in a binary format.
  80489. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  80490. * as the spherical used in the lighting.
  80491. * @param url The HDR file url.
  80492. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  80493. * @param onError Method called if any error happens during download.
  80494. * @return The packed binary data.
  80495. */
  80496. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  80497. if (onError === void 0) { onError = null; }
  80498. // Needs the url tho create the texture.
  80499. if (!url) {
  80500. return;
  80501. }
  80502. // Check Power of two size.
  80503. if (!BABYLON.Tools.IsExponentOfTwo(size)) { // Need to check engine.needPOTTextures
  80504. return;
  80505. }
  80506. // Coming Back in 3.x.
  80507. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  80508. };
  80509. HDRCubeTexture._facesMapping = [
  80510. "right",
  80511. "left",
  80512. "up",
  80513. "down",
  80514. "front",
  80515. "back"
  80516. ];
  80517. return HDRCubeTexture;
  80518. }(BABYLON.BaseTexture));
  80519. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80520. })(BABYLON || (BABYLON = {}));
  80521. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80522. var BABYLON;
  80523. (function (BABYLON) {
  80524. var IndexedVector2 = /** @class */ (function (_super) {
  80525. __extends(IndexedVector2, _super);
  80526. function IndexedVector2(original, index) {
  80527. var _this = _super.call(this, original.x, original.y) || this;
  80528. _this.index = index;
  80529. return _this;
  80530. }
  80531. return IndexedVector2;
  80532. }(BABYLON.Vector2));
  80533. var PolygonPoints = /** @class */ (function () {
  80534. function PolygonPoints() {
  80535. this.elements = new Array();
  80536. }
  80537. PolygonPoints.prototype.add = function (originalPoints) {
  80538. var _this = this;
  80539. var result = new Array();
  80540. originalPoints.forEach(function (point) {
  80541. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80542. var newPoint = new IndexedVector2(point, _this.elements.length);
  80543. result.push(newPoint);
  80544. _this.elements.push(newPoint);
  80545. }
  80546. });
  80547. return result;
  80548. };
  80549. PolygonPoints.prototype.computeBounds = function () {
  80550. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80551. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80552. this.elements.forEach(function (point) {
  80553. // x
  80554. if (point.x < lmin.x) {
  80555. lmin.x = point.x;
  80556. }
  80557. else if (point.x > lmax.x) {
  80558. lmax.x = point.x;
  80559. }
  80560. // y
  80561. if (point.y < lmin.y) {
  80562. lmin.y = point.y;
  80563. }
  80564. else if (point.y > lmax.y) {
  80565. lmax.y = point.y;
  80566. }
  80567. });
  80568. return {
  80569. min: lmin,
  80570. max: lmax,
  80571. width: lmax.x - lmin.x,
  80572. height: lmax.y - lmin.y
  80573. };
  80574. };
  80575. return PolygonPoints;
  80576. }());
  80577. var Polygon = /** @class */ (function () {
  80578. function Polygon() {
  80579. }
  80580. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  80581. return [
  80582. new BABYLON.Vector2(xmin, ymin),
  80583. new BABYLON.Vector2(xmax, ymin),
  80584. new BABYLON.Vector2(xmax, ymax),
  80585. new BABYLON.Vector2(xmin, ymax)
  80586. ];
  80587. };
  80588. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  80589. if (cx === void 0) { cx = 0; }
  80590. if (cy === void 0) { cy = 0; }
  80591. if (numberOfSides === void 0) { numberOfSides = 32; }
  80592. var result = new Array();
  80593. var angle = 0;
  80594. var increment = (Math.PI * 2) / numberOfSides;
  80595. for (var i = 0; i < numberOfSides; i++) {
  80596. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  80597. angle -= increment;
  80598. }
  80599. return result;
  80600. };
  80601. Polygon.Parse = function (input) {
  80602. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  80603. var i, result = [];
  80604. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  80605. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  80606. }
  80607. return result;
  80608. };
  80609. Polygon.StartingAt = function (x, y) {
  80610. return BABYLON.Path2.StartingAt(x, y);
  80611. };
  80612. return Polygon;
  80613. }());
  80614. BABYLON.Polygon = Polygon;
  80615. var PolygonMeshBuilder = /** @class */ (function () {
  80616. function PolygonMeshBuilder(name, contours, scene) {
  80617. this._points = new PolygonPoints();
  80618. this._outlinepoints = new PolygonPoints();
  80619. this._holes = new Array();
  80620. this._epoints = new Array();
  80621. this._eholes = new Array();
  80622. this._name = name;
  80623. this._scene = scene;
  80624. var points;
  80625. if (contours instanceof BABYLON.Path2) {
  80626. points = contours.getPoints();
  80627. }
  80628. else {
  80629. points = contours;
  80630. }
  80631. this._addToepoint(points);
  80632. this._points.add(points);
  80633. this._outlinepoints.add(points);
  80634. if (typeof earcut === 'undefined') {
  80635. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  80636. }
  80637. }
  80638. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80639. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80640. var p = points_1[_i];
  80641. this._epoints.push(p.x, p.y);
  80642. }
  80643. };
  80644. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80645. this._points.add(hole);
  80646. var holepoints = new PolygonPoints();
  80647. holepoints.add(hole);
  80648. this._holes.push(holepoints);
  80649. this._eholes.push(this._epoints.length / 2);
  80650. this._addToepoint(hole);
  80651. return this;
  80652. };
  80653. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80654. var _this = this;
  80655. if (updatable === void 0) { updatable = false; }
  80656. if (depth === void 0) { depth = 0; }
  80657. var result = new BABYLON.Mesh(this._name, this._scene);
  80658. var normals = new Array();
  80659. var positions = new Array();
  80660. var uvs = new Array();
  80661. var bounds = this._points.computeBounds();
  80662. this._points.elements.forEach(function (p) {
  80663. normals.push(0, 1.0, 0);
  80664. positions.push(p.x, 0, p.y);
  80665. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80666. });
  80667. var indices = new Array();
  80668. var res = earcut(this._epoints, this._eholes, 2);
  80669. for (var i = 0; i < res.length; i++) {
  80670. indices.push(res[i]);
  80671. }
  80672. if (depth > 0) {
  80673. var positionscount = (positions.length / 3); //get the current pointcount
  80674. this._points.elements.forEach(function (p) {
  80675. normals.push(0, -1.0, 0);
  80676. positions.push(p.x, -depth, p.y);
  80677. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80678. });
  80679. var totalCount = indices.length;
  80680. for (var i = 0; i < totalCount; i += 3) {
  80681. var i0 = indices[i + 0];
  80682. var i1 = indices[i + 1];
  80683. var i2 = indices[i + 2];
  80684. indices.push(i2 + positionscount);
  80685. indices.push(i1 + positionscount);
  80686. indices.push(i0 + positionscount);
  80687. }
  80688. //Add the sides
  80689. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80690. this._holes.forEach(function (hole) {
  80691. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80692. });
  80693. }
  80694. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80695. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80696. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80697. result.setIndices(indices);
  80698. return result;
  80699. };
  80700. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80701. var StartIndex = positions.length / 3;
  80702. var ulength = 0;
  80703. for (var i = 0; i < points.elements.length; i++) {
  80704. var p = points.elements[i];
  80705. var p1;
  80706. if ((i + 1) > points.elements.length - 1) {
  80707. p1 = points.elements[0];
  80708. }
  80709. else {
  80710. p1 = points.elements[i + 1];
  80711. }
  80712. positions.push(p.x, 0, p.y);
  80713. positions.push(p.x, -depth, p.y);
  80714. positions.push(p1.x, 0, p1.y);
  80715. positions.push(p1.x, -depth, p1.y);
  80716. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80717. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80718. var v3 = v2.subtract(v1);
  80719. var v4 = new BABYLON.Vector3(0, 1, 0);
  80720. var vn = BABYLON.Vector3.Cross(v3, v4);
  80721. vn = vn.normalize();
  80722. uvs.push(ulength / bounds.width, 0);
  80723. uvs.push(ulength / bounds.width, 1);
  80724. ulength += v3.length();
  80725. uvs.push((ulength / bounds.width), 0);
  80726. uvs.push((ulength / bounds.width), 1);
  80727. if (!flip) {
  80728. normals.push(-vn.x, -vn.y, -vn.z);
  80729. normals.push(-vn.x, -vn.y, -vn.z);
  80730. normals.push(-vn.x, -vn.y, -vn.z);
  80731. normals.push(-vn.x, -vn.y, -vn.z);
  80732. indices.push(StartIndex);
  80733. indices.push(StartIndex + 1);
  80734. indices.push(StartIndex + 2);
  80735. indices.push(StartIndex + 1);
  80736. indices.push(StartIndex + 3);
  80737. indices.push(StartIndex + 2);
  80738. }
  80739. else {
  80740. normals.push(vn.x, vn.y, vn.z);
  80741. normals.push(vn.x, vn.y, vn.z);
  80742. normals.push(vn.x, vn.y, vn.z);
  80743. normals.push(vn.x, vn.y, vn.z);
  80744. indices.push(StartIndex);
  80745. indices.push(StartIndex + 2);
  80746. indices.push(StartIndex + 1);
  80747. indices.push(StartIndex + 1);
  80748. indices.push(StartIndex + 2);
  80749. indices.push(StartIndex + 3);
  80750. }
  80751. StartIndex += 4;
  80752. }
  80753. ;
  80754. };
  80755. return PolygonMeshBuilder;
  80756. }());
  80757. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  80758. })(BABYLON || (BABYLON = {}));
  80759. //# sourceMappingURL=babylon.polygonMesh.js.map
  80760. var BABYLON;
  80761. (function (BABYLON) {
  80762. // Unique ID when we import meshes from Babylon to CSG
  80763. var currentCSGMeshId = 0;
  80764. // # class Vertex
  80765. // Represents a vertex of a polygon. Use your own vertex class instead of this
  80766. // one to provide additional features like texture coordinates and vertex
  80767. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  80768. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  80769. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  80770. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  80771. // is not used anywhere else.
  80772. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  80773. var Vertex = /** @class */ (function () {
  80774. function Vertex(pos, normal, uv) {
  80775. this.pos = pos;
  80776. this.normal = normal;
  80777. this.uv = uv;
  80778. }
  80779. Vertex.prototype.clone = function () {
  80780. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  80781. };
  80782. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  80783. // orientation of a polygon is flipped.
  80784. Vertex.prototype.flip = function () {
  80785. this.normal = this.normal.scale(-1);
  80786. };
  80787. // Create a new vertex between this vertex and `other` by linearly
  80788. // interpolating all properties using a parameter of `t`. Subclasses should
  80789. // override this to interpolate additional properties.
  80790. Vertex.prototype.interpolate = function (other, t) {
  80791. 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));
  80792. };
  80793. return Vertex;
  80794. }());
  80795. // # class Plane
  80796. // Represents a plane in 3D space.
  80797. var Plane = /** @class */ (function () {
  80798. function Plane(normal, w) {
  80799. this.normal = normal;
  80800. this.w = w;
  80801. }
  80802. Plane.FromPoints = function (a, b, c) {
  80803. var v0 = c.subtract(a);
  80804. var v1 = b.subtract(a);
  80805. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  80806. return null;
  80807. }
  80808. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  80809. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  80810. };
  80811. Plane.prototype.clone = function () {
  80812. return new Plane(this.normal.clone(), this.w);
  80813. };
  80814. Plane.prototype.flip = function () {
  80815. this.normal.scaleInPlace(-1);
  80816. this.w = -this.w;
  80817. };
  80818. // Split `polygon` by this plane if needed, then put the polygon or polygon
  80819. // fragments in the appropriate lists. Coplanar polygons go into either
  80820. // `coplanarFront` or `coplanarBack` depending on their orientation with
  80821. // respect to this plane. Polygons in front or in back of this plane go into
  80822. // either `front` or `back`.
  80823. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  80824. var COPLANAR = 0;
  80825. var FRONT = 1;
  80826. var BACK = 2;
  80827. var SPANNING = 3;
  80828. // Classify each point as well as the entire polygon into one of the above
  80829. // four classes.
  80830. var polygonType = 0;
  80831. var types = [];
  80832. var i;
  80833. var t;
  80834. for (i = 0; i < polygon.vertices.length; i++) {
  80835. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  80836. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  80837. polygonType |= type;
  80838. types.push(type);
  80839. }
  80840. // Put the polygon in the correct list, splitting it when necessary.
  80841. switch (polygonType) {
  80842. case COPLANAR:
  80843. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  80844. break;
  80845. case FRONT:
  80846. front.push(polygon);
  80847. break;
  80848. case BACK:
  80849. back.push(polygon);
  80850. break;
  80851. case SPANNING:
  80852. var f = [], b = [];
  80853. for (i = 0; i < polygon.vertices.length; i++) {
  80854. var j = (i + 1) % polygon.vertices.length;
  80855. var ti = types[i], tj = types[j];
  80856. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  80857. if (ti !== BACK)
  80858. f.push(vi);
  80859. if (ti !== FRONT)
  80860. b.push(ti !== BACK ? vi.clone() : vi);
  80861. if ((ti | tj) === SPANNING) {
  80862. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  80863. var v = vi.interpolate(vj, t);
  80864. f.push(v);
  80865. b.push(v.clone());
  80866. }
  80867. }
  80868. var poly;
  80869. if (f.length >= 3) {
  80870. poly = new Polygon(f, polygon.shared);
  80871. if (poly.plane)
  80872. front.push(poly);
  80873. }
  80874. if (b.length >= 3) {
  80875. poly = new Polygon(b, polygon.shared);
  80876. if (poly.plane)
  80877. back.push(poly);
  80878. }
  80879. break;
  80880. }
  80881. };
  80882. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  80883. // point is on the plane.
  80884. Plane.EPSILON = 1e-5;
  80885. return Plane;
  80886. }());
  80887. // # class Polygon
  80888. // Represents a convex polygon. The vertices used to initialize a polygon must
  80889. // be coplanar and form a convex loop.
  80890. //
  80891. // Each convex polygon has a `shared` property, which is shared between all
  80892. // polygons that are clones of each other or were split from the same polygon.
  80893. // This can be used to define per-polygon properties (such as surface color).
  80894. var Polygon = /** @class */ (function () {
  80895. function Polygon(vertices, shared) {
  80896. this.vertices = vertices;
  80897. this.shared = shared;
  80898. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  80899. }
  80900. Polygon.prototype.clone = function () {
  80901. var vertices = this.vertices.map(function (v) { return v.clone(); });
  80902. return new Polygon(vertices, this.shared);
  80903. };
  80904. Polygon.prototype.flip = function () {
  80905. this.vertices.reverse().map(function (v) { v.flip(); });
  80906. this.plane.flip();
  80907. };
  80908. return Polygon;
  80909. }());
  80910. // # class Node
  80911. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  80912. // by picking a polygon to split along. That polygon (and all other coplanar
  80913. // polygons) are added directly to that node and the other polygons are added to
  80914. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  80915. // no distinction between internal and leaf nodes.
  80916. var Node = /** @class */ (function () {
  80917. function Node(polygons) {
  80918. this.plane = null;
  80919. this.front = null;
  80920. this.back = null;
  80921. this.polygons = new Array();
  80922. if (polygons) {
  80923. this.build(polygons);
  80924. }
  80925. }
  80926. Node.prototype.clone = function () {
  80927. var node = new Node();
  80928. node.plane = this.plane && this.plane.clone();
  80929. node.front = this.front && this.front.clone();
  80930. node.back = this.back && this.back.clone();
  80931. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  80932. return node;
  80933. };
  80934. // Convert solid space to empty space and empty space to solid space.
  80935. Node.prototype.invert = function () {
  80936. for (var i = 0; i < this.polygons.length; i++) {
  80937. this.polygons[i].flip();
  80938. }
  80939. if (this.plane) {
  80940. this.plane.flip();
  80941. }
  80942. if (this.front) {
  80943. this.front.invert();
  80944. }
  80945. if (this.back) {
  80946. this.back.invert();
  80947. }
  80948. var temp = this.front;
  80949. this.front = this.back;
  80950. this.back = temp;
  80951. };
  80952. // Recursively remove all polygons in `polygons` that are inside this BSP
  80953. // tree.
  80954. Node.prototype.clipPolygons = function (polygons) {
  80955. if (!this.plane)
  80956. return polygons.slice();
  80957. var front = new Array(), back = new Array();
  80958. for (var i = 0; i < polygons.length; i++) {
  80959. this.plane.splitPolygon(polygons[i], front, back, front, back);
  80960. }
  80961. if (this.front) {
  80962. front = this.front.clipPolygons(front);
  80963. }
  80964. if (this.back) {
  80965. back = this.back.clipPolygons(back);
  80966. }
  80967. else {
  80968. back = [];
  80969. }
  80970. return front.concat(back);
  80971. };
  80972. // Remove all polygons in this BSP tree that are inside the other BSP tree
  80973. // `bsp`.
  80974. Node.prototype.clipTo = function (bsp) {
  80975. this.polygons = bsp.clipPolygons(this.polygons);
  80976. if (this.front)
  80977. this.front.clipTo(bsp);
  80978. if (this.back)
  80979. this.back.clipTo(bsp);
  80980. };
  80981. // Return a list of all polygons in this BSP tree.
  80982. Node.prototype.allPolygons = function () {
  80983. var polygons = this.polygons.slice();
  80984. if (this.front)
  80985. polygons = polygons.concat(this.front.allPolygons());
  80986. if (this.back)
  80987. polygons = polygons.concat(this.back.allPolygons());
  80988. return polygons;
  80989. };
  80990. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  80991. // new polygons are filtered down to the bottom of the tree and become new
  80992. // nodes there. Each set of polygons is partitioned using the first polygon
  80993. // (no heuristic is used to pick a good split).
  80994. Node.prototype.build = function (polygons) {
  80995. if (!polygons.length)
  80996. return;
  80997. if (!this.plane)
  80998. this.plane = polygons[0].plane.clone();
  80999. var front = new Array(), back = new Array();
  81000. for (var i = 0; i < polygons.length; i++) {
  81001. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  81002. }
  81003. if (front.length) {
  81004. if (!this.front)
  81005. this.front = new Node();
  81006. this.front.build(front);
  81007. }
  81008. if (back.length) {
  81009. if (!this.back)
  81010. this.back = new Node();
  81011. this.back.build(back);
  81012. }
  81013. };
  81014. return Node;
  81015. }());
  81016. var CSG = /** @class */ (function () {
  81017. function CSG() {
  81018. this.polygons = new Array();
  81019. }
  81020. // Convert BABYLON.Mesh to BABYLON.CSG
  81021. CSG.FromMesh = function (mesh) {
  81022. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  81023. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  81024. if (mesh instanceof BABYLON.Mesh) {
  81025. mesh.computeWorldMatrix(true);
  81026. matrix = mesh.getWorldMatrix();
  81027. meshPosition = mesh.position.clone();
  81028. meshRotation = mesh.rotation.clone();
  81029. if (mesh.rotationQuaternion) {
  81030. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  81031. }
  81032. meshScaling = mesh.scaling.clone();
  81033. }
  81034. else {
  81035. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  81036. }
  81037. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81038. var subMeshes = mesh.subMeshes;
  81039. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  81040. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  81041. vertices = [];
  81042. for (var j = 0; j < 3; j++) {
  81043. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  81044. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  81045. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  81046. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  81047. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  81048. vertex = new Vertex(position, normal, uv);
  81049. vertices.push(vertex);
  81050. }
  81051. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  81052. // To handle the case of degenerated triangle
  81053. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  81054. if (polygon.plane)
  81055. polygons.push(polygon);
  81056. }
  81057. }
  81058. var csg = CSG.FromPolygons(polygons);
  81059. csg.matrix = matrix;
  81060. csg.position = meshPosition;
  81061. csg.rotation = meshRotation;
  81062. csg.scaling = meshScaling;
  81063. csg.rotationQuaternion = meshRotationQuaternion;
  81064. currentCSGMeshId++;
  81065. return csg;
  81066. };
  81067. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  81068. CSG.FromPolygons = function (polygons) {
  81069. var csg = new CSG();
  81070. csg.polygons = polygons;
  81071. return csg;
  81072. };
  81073. CSG.prototype.clone = function () {
  81074. var csg = new CSG();
  81075. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  81076. csg.copyTransformAttributes(this);
  81077. return csg;
  81078. };
  81079. CSG.prototype.union = function (csg) {
  81080. var a = new Node(this.clone().polygons);
  81081. var b = new Node(csg.clone().polygons);
  81082. a.clipTo(b);
  81083. b.clipTo(a);
  81084. b.invert();
  81085. b.clipTo(a);
  81086. b.invert();
  81087. a.build(b.allPolygons());
  81088. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81089. };
  81090. CSG.prototype.unionInPlace = function (csg) {
  81091. var a = new Node(this.polygons);
  81092. var b = new Node(csg.polygons);
  81093. a.clipTo(b);
  81094. b.clipTo(a);
  81095. b.invert();
  81096. b.clipTo(a);
  81097. b.invert();
  81098. a.build(b.allPolygons());
  81099. this.polygons = a.allPolygons();
  81100. };
  81101. CSG.prototype.subtract = function (csg) {
  81102. var a = new Node(this.clone().polygons);
  81103. var b = new Node(csg.clone().polygons);
  81104. a.invert();
  81105. a.clipTo(b);
  81106. b.clipTo(a);
  81107. b.invert();
  81108. b.clipTo(a);
  81109. b.invert();
  81110. a.build(b.allPolygons());
  81111. a.invert();
  81112. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81113. };
  81114. CSG.prototype.subtractInPlace = function (csg) {
  81115. var a = new Node(this.polygons);
  81116. var b = new Node(csg.polygons);
  81117. a.invert();
  81118. a.clipTo(b);
  81119. b.clipTo(a);
  81120. b.invert();
  81121. b.clipTo(a);
  81122. b.invert();
  81123. a.build(b.allPolygons());
  81124. a.invert();
  81125. this.polygons = a.allPolygons();
  81126. };
  81127. CSG.prototype.intersect = function (csg) {
  81128. var a = new Node(this.clone().polygons);
  81129. var b = new Node(csg.clone().polygons);
  81130. a.invert();
  81131. b.clipTo(a);
  81132. b.invert();
  81133. a.clipTo(b);
  81134. b.clipTo(a);
  81135. a.build(b.allPolygons());
  81136. a.invert();
  81137. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81138. };
  81139. CSG.prototype.intersectInPlace = function (csg) {
  81140. var a = new Node(this.polygons);
  81141. var b = new Node(csg.polygons);
  81142. a.invert();
  81143. b.clipTo(a);
  81144. b.invert();
  81145. a.clipTo(b);
  81146. b.clipTo(a);
  81147. a.build(b.allPolygons());
  81148. a.invert();
  81149. this.polygons = a.allPolygons();
  81150. };
  81151. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81152. // not modified.
  81153. CSG.prototype.inverse = function () {
  81154. var csg = this.clone();
  81155. csg.inverseInPlace();
  81156. return csg;
  81157. };
  81158. CSG.prototype.inverseInPlace = function () {
  81159. this.polygons.map(function (p) { p.flip(); });
  81160. };
  81161. // This is used to keep meshes transformations so they can be restored
  81162. // when we build back a Babylon Mesh
  81163. // NB : All CSG operations are performed in world coordinates
  81164. CSG.prototype.copyTransformAttributes = function (csg) {
  81165. this.matrix = csg.matrix;
  81166. this.position = csg.position;
  81167. this.rotation = csg.rotation;
  81168. this.scaling = csg.scaling;
  81169. this.rotationQuaternion = csg.rotationQuaternion;
  81170. return this;
  81171. };
  81172. // Build Raw mesh from CSG
  81173. // Coordinates here are in world space
  81174. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81175. var matrix = this.matrix.clone();
  81176. matrix.invert();
  81177. 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;
  81178. if (keepSubMeshes) {
  81179. // Sort Polygons, since subMeshes are indices range
  81180. polygons.sort(function (a, b) {
  81181. if (a.shared.meshId === b.shared.meshId) {
  81182. return a.shared.subMeshId - b.shared.subMeshId;
  81183. }
  81184. else {
  81185. return a.shared.meshId - b.shared.meshId;
  81186. }
  81187. });
  81188. }
  81189. for (var i = 0, il = polygons.length; i < il; i++) {
  81190. polygon = polygons[i];
  81191. // Building SubMeshes
  81192. if (!subMesh_dict[polygon.shared.meshId]) {
  81193. subMesh_dict[polygon.shared.meshId] = {};
  81194. }
  81195. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81196. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81197. indexStart: +Infinity,
  81198. indexEnd: -Infinity,
  81199. materialIndex: polygon.shared.materialIndex
  81200. };
  81201. }
  81202. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81203. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81204. polygonIndices[0] = 0;
  81205. polygonIndices[1] = j - 1;
  81206. polygonIndices[2] = j;
  81207. for (var k = 0; k < 3; k++) {
  81208. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81209. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81210. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81211. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81212. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81213. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81214. // Check if 2 points can be merged
  81215. if (!(typeof vertex_idx !== 'undefined' &&
  81216. normals[vertex_idx * 3] === localNormal.x &&
  81217. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81218. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81219. uvs[vertex_idx * 2] === uv.x &&
  81220. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81221. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81222. uvs.push(uv.x, uv.y);
  81223. normals.push(normal.x, normal.y, normal.z);
  81224. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81225. }
  81226. indices.push(vertex_idx);
  81227. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81228. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81229. currentIndex++;
  81230. }
  81231. }
  81232. }
  81233. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81234. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81235. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81236. mesh.setIndices(indices, null);
  81237. if (keepSubMeshes) {
  81238. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81239. var materialIndexOffset = 0, materialMaxIndex;
  81240. mesh.subMeshes = new Array();
  81241. for (var m in subMesh_dict) {
  81242. materialMaxIndex = -1;
  81243. for (var sm in subMesh_dict[m]) {
  81244. subMesh_obj = subMesh_dict[m][sm];
  81245. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81246. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81247. }
  81248. materialIndexOffset += ++materialMaxIndex;
  81249. }
  81250. }
  81251. return mesh;
  81252. };
  81253. // Build Mesh from CSG taking material and transforms into account
  81254. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81255. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81256. mesh.material = material;
  81257. mesh.position.copyFrom(this.position);
  81258. mesh.rotation.copyFrom(this.rotation);
  81259. if (this.rotationQuaternion) {
  81260. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81261. }
  81262. mesh.scaling.copyFrom(this.scaling);
  81263. mesh.computeWorldMatrix(true);
  81264. return mesh;
  81265. };
  81266. return CSG;
  81267. }());
  81268. BABYLON.CSG = CSG;
  81269. })(BABYLON || (BABYLON = {}));
  81270. //# sourceMappingURL=babylon.csg.js.map
  81271. var BABYLON;
  81272. (function (BABYLON) {
  81273. var LensFlare = /** @class */ (function () {
  81274. function LensFlare(size, position, color, imgUrl, system) {
  81275. this.size = size;
  81276. this.position = position;
  81277. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81278. this.color = color || new BABYLON.Color3(1, 1, 1);
  81279. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81280. this._system = system;
  81281. system.lensFlares.push(this);
  81282. }
  81283. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81284. return new LensFlare(size, position, color, imgUrl, system);
  81285. };
  81286. LensFlare.prototype.dispose = function () {
  81287. if (this.texture) {
  81288. this.texture.dispose();
  81289. }
  81290. // Remove from scene
  81291. var index = this._system.lensFlares.indexOf(this);
  81292. this._system.lensFlares.splice(index, 1);
  81293. };
  81294. ;
  81295. return LensFlare;
  81296. }());
  81297. BABYLON.LensFlare = LensFlare;
  81298. })(BABYLON || (BABYLON = {}));
  81299. //# sourceMappingURL=babylon.lensFlare.js.map
  81300. var BABYLON;
  81301. (function (BABYLON) {
  81302. var LensFlareSystem = /** @class */ (function () {
  81303. function LensFlareSystem(name, emitter, scene) {
  81304. this.name = name;
  81305. this.lensFlares = new Array();
  81306. this.borderLimit = 300;
  81307. this.viewportBorder = 0;
  81308. this.layerMask = 0x0FFFFFFF;
  81309. this._vertexBuffers = {};
  81310. this._isEnabled = true;
  81311. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81312. this._emitter = emitter;
  81313. this.id = name;
  81314. scene.lensFlareSystems.push(this);
  81315. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81316. var engine = scene.getEngine();
  81317. // VBO
  81318. var vertices = [];
  81319. vertices.push(1, 1);
  81320. vertices.push(-1, 1);
  81321. vertices.push(-1, -1);
  81322. vertices.push(1, -1);
  81323. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81324. // Indices
  81325. var indices = [];
  81326. indices.push(0);
  81327. indices.push(1);
  81328. indices.push(2);
  81329. indices.push(0);
  81330. indices.push(2);
  81331. indices.push(3);
  81332. this._indexBuffer = engine.createIndexBuffer(indices);
  81333. // Effects
  81334. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81335. }
  81336. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81337. get: function () {
  81338. return this._isEnabled;
  81339. },
  81340. set: function (value) {
  81341. this._isEnabled = value;
  81342. },
  81343. enumerable: true,
  81344. configurable: true
  81345. });
  81346. LensFlareSystem.prototype.getScene = function () {
  81347. return this._scene;
  81348. };
  81349. LensFlareSystem.prototype.getEmitter = function () {
  81350. return this._emitter;
  81351. };
  81352. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81353. this._emitter = newEmitter;
  81354. };
  81355. LensFlareSystem.prototype.getEmitterPosition = function () {
  81356. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81357. };
  81358. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81359. var position = this.getEmitterPosition();
  81360. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81361. this._positionX = position.x;
  81362. this._positionY = position.y;
  81363. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81364. if (this.viewportBorder > 0) {
  81365. globalViewport.x -= this.viewportBorder;
  81366. globalViewport.y -= this.viewportBorder;
  81367. globalViewport.width += this.viewportBorder * 2;
  81368. globalViewport.height += this.viewportBorder * 2;
  81369. position.x += this.viewportBorder;
  81370. position.y += this.viewportBorder;
  81371. this._positionX += this.viewportBorder;
  81372. this._positionY += this.viewportBorder;
  81373. }
  81374. if (position.z > 0) {
  81375. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81376. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81377. return true;
  81378. }
  81379. return true;
  81380. }
  81381. return false;
  81382. };
  81383. LensFlareSystem.prototype._isVisible = function () {
  81384. if (!this._isEnabled || !this._scene.activeCamera) {
  81385. return false;
  81386. }
  81387. var emitterPosition = this.getEmitterPosition();
  81388. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81389. var distance = direction.length();
  81390. direction.normalize();
  81391. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81392. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81393. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81394. };
  81395. LensFlareSystem.prototype.render = function () {
  81396. if (!this._effect.isReady() || !this._scene.activeCamera)
  81397. return false;
  81398. var engine = this._scene.getEngine();
  81399. var viewport = this._scene.activeCamera.viewport;
  81400. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81401. // Position
  81402. if (!this.computeEffectivePosition(globalViewport)) {
  81403. return false;
  81404. }
  81405. // Visibility
  81406. if (!this._isVisible()) {
  81407. return false;
  81408. }
  81409. // Intensity
  81410. var awayX;
  81411. var awayY;
  81412. if (this._positionX < this.borderLimit + globalViewport.x) {
  81413. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81414. }
  81415. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81416. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81417. }
  81418. else {
  81419. awayX = 0;
  81420. }
  81421. if (this._positionY < this.borderLimit + globalViewport.y) {
  81422. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81423. }
  81424. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81425. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81426. }
  81427. else {
  81428. awayY = 0;
  81429. }
  81430. var away = (awayX > awayY) ? awayX : awayY;
  81431. away -= this.viewportBorder;
  81432. if (away > this.borderLimit) {
  81433. away = this.borderLimit;
  81434. }
  81435. var intensity = 1.0 - (away / this.borderLimit);
  81436. if (intensity < 0) {
  81437. return false;
  81438. }
  81439. if (intensity > 1.0) {
  81440. intensity = 1.0;
  81441. }
  81442. if (this.viewportBorder > 0) {
  81443. globalViewport.x += this.viewportBorder;
  81444. globalViewport.y += this.viewportBorder;
  81445. globalViewport.width -= this.viewportBorder * 2;
  81446. globalViewport.height -= this.viewportBorder * 2;
  81447. this._positionX -= this.viewportBorder;
  81448. this._positionY -= this.viewportBorder;
  81449. }
  81450. // Position
  81451. var centerX = globalViewport.x + globalViewport.width / 2;
  81452. var centerY = globalViewport.y + globalViewport.height / 2;
  81453. var distX = centerX - this._positionX;
  81454. var distY = centerY - this._positionY;
  81455. // Effects
  81456. engine.enableEffect(this._effect);
  81457. engine.setState(false);
  81458. engine.setDepthBuffer(false);
  81459. // VBOs
  81460. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81461. // Flares
  81462. for (var index = 0; index < this.lensFlares.length; index++) {
  81463. var flare = this.lensFlares[index];
  81464. engine.setAlphaMode(flare.alphaMode);
  81465. var x = centerX - (distX * flare.position);
  81466. var y = centerY - (distY * flare.position);
  81467. var cw = flare.size;
  81468. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  81469. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  81470. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  81471. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  81472. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  81473. // Texture
  81474. this._effect.setTexture("textureSampler", flare.texture);
  81475. // Color
  81476. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  81477. // Draw order
  81478. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81479. }
  81480. engine.setDepthBuffer(true);
  81481. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81482. return true;
  81483. };
  81484. LensFlareSystem.prototype.dispose = function () {
  81485. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81486. if (vertexBuffer) {
  81487. vertexBuffer.dispose();
  81488. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81489. }
  81490. if (this._indexBuffer) {
  81491. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81492. this._indexBuffer = null;
  81493. }
  81494. while (this.lensFlares.length) {
  81495. this.lensFlares[0].dispose();
  81496. }
  81497. // Remove from scene
  81498. var index = this._scene.lensFlareSystems.indexOf(this);
  81499. this._scene.lensFlareSystems.splice(index, 1);
  81500. };
  81501. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  81502. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  81503. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  81504. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  81505. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  81506. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  81507. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  81508. var parsedFlare = parsedLensFlareSystem.flares[index];
  81509. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  81510. }
  81511. return lensFlareSystem;
  81512. };
  81513. LensFlareSystem.prototype.serialize = function () {
  81514. var serializationObject = {};
  81515. serializationObject.id = this.id;
  81516. serializationObject.name = this.name;
  81517. serializationObject.emitterId = this.getEmitter().id;
  81518. serializationObject.borderLimit = this.borderLimit;
  81519. serializationObject.flares = [];
  81520. for (var index = 0; index < this.lensFlares.length; index++) {
  81521. var flare = this.lensFlares[index];
  81522. serializationObject.flares.push({
  81523. size: flare.size,
  81524. position: flare.position,
  81525. color: flare.color.asArray(),
  81526. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81527. });
  81528. }
  81529. return serializationObject;
  81530. };
  81531. return LensFlareSystem;
  81532. }());
  81533. BABYLON.LensFlareSystem = LensFlareSystem;
  81534. })(BABYLON || (BABYLON = {}));
  81535. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81536. var BABYLON;
  81537. (function (BABYLON) {
  81538. /**
  81539. * This is a holder class for the physics joint created by the physics plugin.
  81540. * It holds a set of functions to control the underlying joint.
  81541. */
  81542. var PhysicsJoint = /** @class */ (function () {
  81543. function PhysicsJoint(type, jointData) {
  81544. this.type = type;
  81545. this.jointData = jointData;
  81546. jointData.nativeParams = jointData.nativeParams || {};
  81547. }
  81548. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81549. get: function () {
  81550. return this._physicsJoint;
  81551. },
  81552. set: function (newJoint) {
  81553. if (this._physicsJoint) {
  81554. //remove from the wolrd
  81555. }
  81556. this._physicsJoint = newJoint;
  81557. },
  81558. enumerable: true,
  81559. configurable: true
  81560. });
  81561. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  81562. set: function (physicsPlugin) {
  81563. this._physicsPlugin = physicsPlugin;
  81564. },
  81565. enumerable: true,
  81566. configurable: true
  81567. });
  81568. /**
  81569. * Execute a function that is physics-plugin specific.
  81570. * @param {Function} func the function that will be executed.
  81571. * It accepts two parameters: the physics world and the physics joint.
  81572. */
  81573. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  81574. func(this._physicsPlugin.world, this._physicsJoint);
  81575. };
  81576. //TODO check if the native joints are the same
  81577. //Joint Types
  81578. PhysicsJoint.DistanceJoint = 0;
  81579. PhysicsJoint.HingeJoint = 1;
  81580. PhysicsJoint.BallAndSocketJoint = 2;
  81581. PhysicsJoint.WheelJoint = 3;
  81582. PhysicsJoint.SliderJoint = 4;
  81583. //OIMO
  81584. PhysicsJoint.PrismaticJoint = 5;
  81585. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  81586. PhysicsJoint.UniversalJoint = 6;
  81587. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  81588. //Cannon
  81589. //Similar to a Ball-Joint. Different in params
  81590. PhysicsJoint.PointToPointJoint = 8;
  81591. //Cannon only at the moment
  81592. PhysicsJoint.SpringJoint = 9;
  81593. PhysicsJoint.LockJoint = 10;
  81594. return PhysicsJoint;
  81595. }());
  81596. BABYLON.PhysicsJoint = PhysicsJoint;
  81597. /**
  81598. * A class representing a physics distance joint.
  81599. */
  81600. var DistanceJoint = /** @class */ (function (_super) {
  81601. __extends(DistanceJoint, _super);
  81602. function DistanceJoint(jointData) {
  81603. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  81604. }
  81605. /**
  81606. * Update the predefined distance.
  81607. */
  81608. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  81609. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  81610. };
  81611. return DistanceJoint;
  81612. }(PhysicsJoint));
  81613. BABYLON.DistanceJoint = DistanceJoint;
  81614. var MotorEnabledJoint = /** @class */ (function (_super) {
  81615. __extends(MotorEnabledJoint, _super);
  81616. function MotorEnabledJoint(type, jointData) {
  81617. return _super.call(this, type, jointData) || this;
  81618. }
  81619. /**
  81620. * Set the motor values.
  81621. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81622. * @param {number} force the force to apply
  81623. * @param {number} maxForce max force for this motor.
  81624. */
  81625. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  81626. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81627. };
  81628. /**
  81629. * Set the motor's limits.
  81630. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81631. */
  81632. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81633. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81634. };
  81635. return MotorEnabledJoint;
  81636. }(PhysicsJoint));
  81637. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81638. /**
  81639. * This class represents a single hinge physics joint
  81640. */
  81641. var HingeJoint = /** @class */ (function (_super) {
  81642. __extends(HingeJoint, _super);
  81643. function HingeJoint(jointData) {
  81644. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81645. }
  81646. /**
  81647. * Set the motor values.
  81648. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81649. * @param {number} force the force to apply
  81650. * @param {number} maxForce max force for this motor.
  81651. */
  81652. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81653. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81654. };
  81655. /**
  81656. * Set the motor's limits.
  81657. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81658. */
  81659. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81660. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81661. };
  81662. return HingeJoint;
  81663. }(MotorEnabledJoint));
  81664. BABYLON.HingeJoint = HingeJoint;
  81665. /**
  81666. * This class represents a dual hinge physics joint (same as wheel joint)
  81667. */
  81668. var Hinge2Joint = /** @class */ (function (_super) {
  81669. __extends(Hinge2Joint, _super);
  81670. function Hinge2Joint(jointData) {
  81671. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81672. }
  81673. /**
  81674. * Set the motor values.
  81675. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81676. * @param {number} force the force to apply
  81677. * @param {number} maxForce max force for this motor.
  81678. * @param {motorIndex} the motor's index, 0 or 1.
  81679. */
  81680. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81681. if (motorIndex === void 0) { motorIndex = 0; }
  81682. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81683. };
  81684. /**
  81685. * Set the motor limits.
  81686. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81687. * @param {number} upperLimit the upper limit
  81688. * @param {number} lowerLimit lower limit
  81689. * @param {motorIndex} the motor's index, 0 or 1.
  81690. */
  81691. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81692. if (motorIndex === void 0) { motorIndex = 0; }
  81693. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81694. };
  81695. return Hinge2Joint;
  81696. }(MotorEnabledJoint));
  81697. BABYLON.Hinge2Joint = Hinge2Joint;
  81698. })(BABYLON || (BABYLON = {}));
  81699. //# sourceMappingURL=babylon.physicsJoint.js.map
  81700. var BABYLON;
  81701. (function (BABYLON) {
  81702. var PhysicsImpostor = /** @class */ (function () {
  81703. function PhysicsImpostor(object, type, _options, _scene) {
  81704. if (_options === void 0) { _options = { mass: 0 }; }
  81705. var _this = this;
  81706. this.object = object;
  81707. this.type = type;
  81708. this._options = _options;
  81709. this._scene = _scene;
  81710. this._bodyUpdateRequired = false;
  81711. this._onBeforePhysicsStepCallbacks = new Array();
  81712. this._onAfterPhysicsStepCallbacks = new Array();
  81713. this._onPhysicsCollideCallbacks = [];
  81714. this._deltaPosition = BABYLON.Vector3.Zero();
  81715. this._isDisposed = false;
  81716. //temp variables for parent rotation calculations
  81717. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81718. this._tmpQuat = new BABYLON.Quaternion();
  81719. this._tmpQuat2 = new BABYLON.Quaternion();
  81720. /**
  81721. * this function is executed by the physics engine.
  81722. */
  81723. this.beforeStep = function () {
  81724. if (!_this._physicsEngine) {
  81725. return;
  81726. }
  81727. _this.object.translate(_this._deltaPosition, -1);
  81728. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81729. _this.object.computeWorldMatrix(false);
  81730. if (_this.object.parent && _this.object.rotationQuaternion) {
  81731. _this.getParentsRotation();
  81732. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81733. }
  81734. else {
  81735. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81736. }
  81737. if (!_this._options.disableBidirectionalTransformation) {
  81738. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81739. }
  81740. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81741. func(_this);
  81742. });
  81743. };
  81744. /**
  81745. * this function is executed by the physics engine.
  81746. */
  81747. this.afterStep = function () {
  81748. if (!_this._physicsEngine) {
  81749. return;
  81750. }
  81751. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81752. func(_this);
  81753. });
  81754. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81755. // object has now its world rotation. needs to be converted to local.
  81756. if (_this.object.parent && _this.object.rotationQuaternion) {
  81757. _this.getParentsRotation();
  81758. _this._tmpQuat.conjugateInPlace();
  81759. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  81760. }
  81761. // take the position set and make it the absolute position of this object.
  81762. _this.object.setAbsolutePosition(_this.object.position);
  81763. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  81764. _this.object.translate(_this._deltaPosition, 1);
  81765. };
  81766. /**
  81767. * Legacy collision detection event support
  81768. */
  81769. this.onCollideEvent = null;
  81770. //event and body object due to cannon's event-based architecture.
  81771. this.onCollide = function (e) {
  81772. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  81773. return;
  81774. }
  81775. if (!_this._physicsEngine) {
  81776. return;
  81777. }
  81778. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  81779. if (otherImpostor) {
  81780. // Legacy collision detection event support
  81781. if (_this.onCollideEvent) {
  81782. _this.onCollideEvent(_this, otherImpostor);
  81783. }
  81784. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  81785. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  81786. }).forEach(function (obj) {
  81787. obj.callback(_this, otherImpostor);
  81788. });
  81789. }
  81790. };
  81791. //sanity check!
  81792. if (!this.object) {
  81793. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  81794. return;
  81795. }
  81796. //legacy support for old syntax.
  81797. if (!this._scene && object.getScene) {
  81798. this._scene = object.getScene();
  81799. }
  81800. if (!this._scene) {
  81801. return;
  81802. }
  81803. this._physicsEngine = this._scene.getPhysicsEngine();
  81804. if (!this._physicsEngine) {
  81805. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  81806. }
  81807. else {
  81808. //set the object's quaternion, if not set
  81809. if (!this.object.rotationQuaternion) {
  81810. if (this.object.rotation) {
  81811. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  81812. }
  81813. else {
  81814. this.object.rotationQuaternion = new BABYLON.Quaternion();
  81815. }
  81816. }
  81817. //default options params
  81818. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  81819. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  81820. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  81821. this._joints = [];
  81822. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  81823. if (!this.object.parent || this._options.ignoreParent) {
  81824. this._init();
  81825. }
  81826. else if (this.object.parent.physicsImpostor) {
  81827. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  81828. }
  81829. }
  81830. }
  81831. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  81832. get: function () {
  81833. return this._isDisposed;
  81834. },
  81835. enumerable: true,
  81836. configurable: true
  81837. });
  81838. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  81839. get: function () {
  81840. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  81841. },
  81842. set: function (value) {
  81843. this.setMass(value);
  81844. },
  81845. enumerable: true,
  81846. configurable: true
  81847. });
  81848. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  81849. get: function () {
  81850. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  81851. },
  81852. set: function (value) {
  81853. if (!this._physicsEngine) {
  81854. return;
  81855. }
  81856. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  81857. },
  81858. enumerable: true,
  81859. configurable: true
  81860. });
  81861. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  81862. get: function () {
  81863. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  81864. },
  81865. set: function (value) {
  81866. if (!this._physicsEngine) {
  81867. return;
  81868. }
  81869. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  81870. },
  81871. enumerable: true,
  81872. configurable: true
  81873. });
  81874. /**
  81875. * This function will completly initialize this impostor.
  81876. * It will create a new body - but only if this mesh has no parent.
  81877. * If it has, this impostor will not be used other than to define the impostor
  81878. * of the child mesh.
  81879. */
  81880. PhysicsImpostor.prototype._init = function () {
  81881. if (!this._physicsEngine) {
  81882. return;
  81883. }
  81884. this._physicsEngine.removeImpostor(this);
  81885. this.physicsBody = null;
  81886. this._parent = this._parent || this._getPhysicsParent();
  81887. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  81888. this._physicsEngine.addImpostor(this);
  81889. }
  81890. };
  81891. PhysicsImpostor.prototype._getPhysicsParent = function () {
  81892. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  81893. var parentMesh = this.object.parent;
  81894. return parentMesh.physicsImpostor;
  81895. }
  81896. return null;
  81897. };
  81898. /**
  81899. * Should a new body be generated.
  81900. */
  81901. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  81902. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  81903. };
  81904. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  81905. this.forceUpdate();
  81906. };
  81907. /**
  81908. * Force a regeneration of this or the parent's impostor's body.
  81909. * Use under cautious - This will remove all joints already implemented.
  81910. */
  81911. PhysicsImpostor.prototype.forceUpdate = function () {
  81912. this._init();
  81913. if (this.parent && !this._options.ignoreParent) {
  81914. this.parent.forceUpdate();
  81915. }
  81916. };
  81917. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  81918. /*public get mesh(): AbstractMesh {
  81919. return this._mesh;
  81920. }*/
  81921. /**
  81922. * Gets the body that holds this impostor. Either its own, or its parent.
  81923. */
  81924. get: function () {
  81925. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  81926. },
  81927. /**
  81928. * Set the physics body. Used mainly by the physics engine/plugin
  81929. */
  81930. set: function (physicsBody) {
  81931. if (this._physicsBody && this._physicsEngine) {
  81932. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  81933. }
  81934. this._physicsBody = physicsBody;
  81935. this.resetUpdateFlags();
  81936. },
  81937. enumerable: true,
  81938. configurable: true
  81939. });
  81940. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  81941. get: function () {
  81942. return !this._options.ignoreParent && this._parent ? this._parent : null;
  81943. },
  81944. set: function (value) {
  81945. this._parent = value;
  81946. },
  81947. enumerable: true,
  81948. configurable: true
  81949. });
  81950. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  81951. this._bodyUpdateRequired = false;
  81952. };
  81953. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  81954. if (this.object.getBoundingInfo) {
  81955. var q = this.object.rotationQuaternion;
  81956. //reset rotation
  81957. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  81958. //calculate the world matrix with no rotation
  81959. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81960. var boundingInfo = this.object.getBoundingInfo();
  81961. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  81962. //bring back the rotation
  81963. this.object.rotationQuaternion = q;
  81964. //calculate the world matrix with the new rotation
  81965. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81966. return size;
  81967. }
  81968. else {
  81969. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  81970. }
  81971. };
  81972. PhysicsImpostor.prototype.getObjectCenter = function () {
  81973. if (this.object.getBoundingInfo) {
  81974. var boundingInfo = this.object.getBoundingInfo();
  81975. return boundingInfo.boundingBox.centerWorld;
  81976. }
  81977. else {
  81978. return this.object.position;
  81979. }
  81980. };
  81981. /**
  81982. * Get a specific parametes from the options parameter.
  81983. */
  81984. PhysicsImpostor.prototype.getParam = function (paramName) {
  81985. return this._options[paramName];
  81986. };
  81987. /**
  81988. * Sets a specific parameter in the options given to the physics plugin
  81989. */
  81990. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  81991. this._options[paramName] = value;
  81992. this._bodyUpdateRequired = true;
  81993. };
  81994. /**
  81995. * Specifically change the body's mass option. Won't recreate the physics body object
  81996. */
  81997. PhysicsImpostor.prototype.setMass = function (mass) {
  81998. if (this.getParam("mass") !== mass) {
  81999. this.setParam("mass", mass);
  82000. }
  82001. if (this._physicsEngine) {
  82002. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  82003. }
  82004. };
  82005. PhysicsImpostor.prototype.getLinearVelocity = function () {
  82006. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  82007. };
  82008. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  82009. if (this._physicsEngine) {
  82010. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  82011. }
  82012. };
  82013. PhysicsImpostor.prototype.getAngularVelocity = function () {
  82014. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  82015. };
  82016. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  82017. if (this._physicsEngine) {
  82018. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  82019. }
  82020. };
  82021. /**
  82022. * Execute a function with the physics plugin native code.
  82023. * Provide a function the will have two variables - the world object and the physics body object.
  82024. */
  82025. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  82026. if (this._physicsEngine) {
  82027. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  82028. }
  82029. };
  82030. /**
  82031. * Register a function that will be executed before the physics world is stepping forward.
  82032. */
  82033. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  82034. this._onBeforePhysicsStepCallbacks.push(func);
  82035. };
  82036. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  82037. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  82038. if (index > -1) {
  82039. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  82040. }
  82041. else {
  82042. BABYLON.Tools.Warn("Function to remove was not found");
  82043. }
  82044. };
  82045. /**
  82046. * Register a function that will be executed after the physics step
  82047. */
  82048. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  82049. this._onAfterPhysicsStepCallbacks.push(func);
  82050. };
  82051. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  82052. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  82053. if (index > -1) {
  82054. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  82055. }
  82056. else {
  82057. BABYLON.Tools.Warn("Function to remove was not found");
  82058. }
  82059. };
  82060. /**
  82061. * register a function that will be executed when this impostor collides against a different body.
  82062. */
  82063. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  82064. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82065. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  82066. };
  82067. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  82068. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82069. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  82070. if (index > -1) {
  82071. this._onPhysicsCollideCallbacks.splice(index, 1);
  82072. }
  82073. else {
  82074. BABYLON.Tools.Warn("Function to remove was not found");
  82075. }
  82076. };
  82077. PhysicsImpostor.prototype.getParentsRotation = function () {
  82078. var parent = this.object.parent;
  82079. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82080. while (parent) {
  82081. if (parent.rotationQuaternion) {
  82082. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82083. }
  82084. else {
  82085. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82086. }
  82087. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82088. parent = parent.parent;
  82089. }
  82090. return this._tmpQuat;
  82091. };
  82092. /**
  82093. * Apply a force
  82094. */
  82095. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82096. if (this._physicsEngine) {
  82097. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82098. }
  82099. return this;
  82100. };
  82101. /**
  82102. * Apply an impulse
  82103. */
  82104. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82105. if (this._physicsEngine) {
  82106. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82107. }
  82108. return this;
  82109. };
  82110. /**
  82111. * A help function to create a joint.
  82112. */
  82113. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82114. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82115. this.addJoint(otherImpostor, joint);
  82116. return this;
  82117. };
  82118. /**
  82119. * Add a joint to this impostor with a different impostor.
  82120. */
  82121. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82122. this._joints.push({
  82123. otherImpostor: otherImpostor,
  82124. joint: joint
  82125. });
  82126. if (this._physicsEngine) {
  82127. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82128. }
  82129. return this;
  82130. };
  82131. /**
  82132. * Will keep this body still, in a sleep mode.
  82133. */
  82134. PhysicsImpostor.prototype.sleep = function () {
  82135. if (this._physicsEngine) {
  82136. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82137. }
  82138. return this;
  82139. };
  82140. /**
  82141. * Wake the body up.
  82142. */
  82143. PhysicsImpostor.prototype.wakeUp = function () {
  82144. if (this._physicsEngine) {
  82145. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82146. }
  82147. return this;
  82148. };
  82149. PhysicsImpostor.prototype.clone = function (newObject) {
  82150. if (!newObject)
  82151. return null;
  82152. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82153. };
  82154. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82155. var _this = this;
  82156. //no dispose if no physics engine is available.
  82157. if (!this._physicsEngine) {
  82158. return;
  82159. }
  82160. this._joints.forEach(function (j) {
  82161. if (_this._physicsEngine) {
  82162. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82163. }
  82164. });
  82165. //dispose the physics body
  82166. this._physicsEngine.removeImpostor(this);
  82167. if (this.parent) {
  82168. this.parent.forceUpdate();
  82169. }
  82170. else {
  82171. /*this._object.getChildMeshes().forEach(function(mesh) {
  82172. if (mesh.physicsImpostor) {
  82173. if (disposeChildren) {
  82174. mesh.physicsImpostor.dispose();
  82175. mesh.physicsImpostor = null;
  82176. }
  82177. }
  82178. })*/
  82179. }
  82180. this._isDisposed = true;
  82181. };
  82182. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82183. this._deltaPosition.copyFrom(position);
  82184. };
  82185. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82186. if (!this._deltaRotation) {
  82187. this._deltaRotation = new BABYLON.Quaternion();
  82188. }
  82189. this._deltaRotation.copyFrom(rotation);
  82190. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82191. };
  82192. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82193. if (this._physicsEngine) {
  82194. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82195. }
  82196. return this;
  82197. };
  82198. PhysicsImpostor.prototype.getRadius = function () {
  82199. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82200. };
  82201. /**
  82202. * Sync a bone with this impostor
  82203. * @param bone The bone to sync to the impostor.
  82204. * @param boneMesh The mesh that the bone is influencing.
  82205. * @param jointPivot The pivot of the joint / bone in local space.
  82206. * @param distToJoint Optional distance from the impostor to the joint.
  82207. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82208. */
  82209. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82210. var tempVec = PhysicsImpostor._tmpVecs[0];
  82211. var mesh = this.object;
  82212. if (mesh.rotationQuaternion) {
  82213. if (adjustRotation) {
  82214. var tempQuat = PhysicsImpostor._tmpQuat;
  82215. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82216. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82217. }
  82218. else {
  82219. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82220. }
  82221. }
  82222. tempVec.x = 0;
  82223. tempVec.y = 0;
  82224. tempVec.z = 0;
  82225. if (jointPivot) {
  82226. tempVec.x = jointPivot.x;
  82227. tempVec.y = jointPivot.y;
  82228. tempVec.z = jointPivot.z;
  82229. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82230. if (distToJoint === undefined || distToJoint === null) {
  82231. distToJoint = jointPivot.length();
  82232. }
  82233. tempVec.x *= distToJoint;
  82234. tempVec.y *= distToJoint;
  82235. tempVec.z *= distToJoint;
  82236. }
  82237. if (bone.getParent()) {
  82238. tempVec.addInPlace(mesh.getAbsolutePosition());
  82239. bone.setAbsolutePosition(tempVec, boneMesh);
  82240. }
  82241. else {
  82242. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82243. boneMesh.position.x -= tempVec.x;
  82244. boneMesh.position.y -= tempVec.y;
  82245. boneMesh.position.z -= tempVec.z;
  82246. }
  82247. };
  82248. /**
  82249. * Sync impostor to a bone
  82250. * @param bone The bone that the impostor will be synced to.
  82251. * @param boneMesh The mesh that the bone is influencing.
  82252. * @param jointPivot The pivot of the joint / bone in local space.
  82253. * @param distToJoint Optional distance from the impostor to the joint.
  82254. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82255. * @param boneAxis Optional vector3 axis the bone is aligned with
  82256. */
  82257. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82258. var mesh = this.object;
  82259. if (mesh.rotationQuaternion) {
  82260. if (adjustRotation) {
  82261. var tempQuat = PhysicsImpostor._tmpQuat;
  82262. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82263. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82264. }
  82265. else {
  82266. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82267. }
  82268. }
  82269. var pos = PhysicsImpostor._tmpVecs[0];
  82270. var boneDir = PhysicsImpostor._tmpVecs[1];
  82271. if (!boneAxis) {
  82272. boneAxis = PhysicsImpostor._tmpVecs[2];
  82273. boneAxis.x = 0;
  82274. boneAxis.y = 1;
  82275. boneAxis.z = 0;
  82276. }
  82277. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82278. bone.getAbsolutePositionToRef(boneMesh, pos);
  82279. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82280. distToJoint = jointPivot.length();
  82281. }
  82282. if (distToJoint !== undefined && distToJoint !== null) {
  82283. pos.x += boneDir.x * distToJoint;
  82284. pos.y += boneDir.y * distToJoint;
  82285. pos.z += boneDir.z * distToJoint;
  82286. }
  82287. mesh.setAbsolutePosition(pos);
  82288. };
  82289. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82290. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82291. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82292. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82293. //Impostor types
  82294. PhysicsImpostor.NoImpostor = 0;
  82295. PhysicsImpostor.SphereImpostor = 1;
  82296. PhysicsImpostor.BoxImpostor = 2;
  82297. PhysicsImpostor.PlaneImpostor = 3;
  82298. PhysicsImpostor.MeshImpostor = 4;
  82299. PhysicsImpostor.CylinderImpostor = 7;
  82300. PhysicsImpostor.ParticleImpostor = 8;
  82301. PhysicsImpostor.HeightmapImpostor = 9;
  82302. return PhysicsImpostor;
  82303. }());
  82304. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82305. })(BABYLON || (BABYLON = {}));
  82306. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82307. var BABYLON;
  82308. (function (BABYLON) {
  82309. var PhysicsEngine = /** @class */ (function () {
  82310. function PhysicsEngine(gravity, _physicsPlugin) {
  82311. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82312. this._physicsPlugin = _physicsPlugin;
  82313. //new methods and parameters
  82314. this._impostors = [];
  82315. this._joints = [];
  82316. if (!this._physicsPlugin.isSupported()) {
  82317. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82318. + "Please make sure it is included.");
  82319. }
  82320. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82321. this.setGravity(gravity);
  82322. this.setTimeStep();
  82323. }
  82324. PhysicsEngine.prototype.setGravity = function (gravity) {
  82325. this.gravity = gravity;
  82326. this._physicsPlugin.setGravity(this.gravity);
  82327. };
  82328. /**
  82329. * Set the time step of the physics engine.
  82330. * default is 1/60.
  82331. * To slow it down, enter 1/600 for example.
  82332. * To speed it up, 1/30
  82333. * @param {number} newTimeStep the new timestep to apply to this world.
  82334. */
  82335. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82336. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82337. this._physicsPlugin.setTimeStep(newTimeStep);
  82338. };
  82339. /**
  82340. * Get the time step of the physics engine.
  82341. */
  82342. PhysicsEngine.prototype.getTimeStep = function () {
  82343. return this._physicsPlugin.getTimeStep();
  82344. };
  82345. PhysicsEngine.prototype.dispose = function () {
  82346. this._impostors.forEach(function (impostor) {
  82347. impostor.dispose();
  82348. });
  82349. this._physicsPlugin.dispose();
  82350. };
  82351. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82352. return this._physicsPlugin.name;
  82353. };
  82354. /**
  82355. * Adding a new impostor for the impostor tracking.
  82356. * This will be done by the impostor itself.
  82357. * @param {PhysicsImpostor} impostor the impostor to add
  82358. */
  82359. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82360. impostor.uniqueId = this._impostors.push(impostor);
  82361. //if no parent, generate the body
  82362. if (!impostor.parent) {
  82363. this._physicsPlugin.generatePhysicsBody(impostor);
  82364. }
  82365. };
  82366. /**
  82367. * Remove an impostor from the engine.
  82368. * This impostor and its mesh will not longer be updated by the physics engine.
  82369. * @param {PhysicsImpostor} impostor the impostor to remove
  82370. */
  82371. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82372. var index = this._impostors.indexOf(impostor);
  82373. if (index > -1) {
  82374. var removed = this._impostors.splice(index, 1);
  82375. //Is it needed?
  82376. if (removed.length) {
  82377. //this will also remove it from the world.
  82378. removed[0].physicsBody = null;
  82379. }
  82380. }
  82381. };
  82382. /**
  82383. * Add a joint to the physics engine
  82384. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82385. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82386. * @param {PhysicsJoint} the joint that will connect both impostors.
  82387. */
  82388. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82389. var impostorJoint = {
  82390. mainImpostor: mainImpostor,
  82391. connectedImpostor: connectedImpostor,
  82392. joint: joint
  82393. };
  82394. joint.physicsPlugin = this._physicsPlugin;
  82395. this._joints.push(impostorJoint);
  82396. this._physicsPlugin.generateJoint(impostorJoint);
  82397. };
  82398. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82399. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82400. return (impostorJoint.connectedImpostor === connectedImpostor
  82401. && impostorJoint.joint === joint
  82402. && impostorJoint.mainImpostor === mainImpostor);
  82403. });
  82404. if (matchingJoints.length) {
  82405. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82406. //TODO remove it from the list as well
  82407. }
  82408. };
  82409. /**
  82410. * Called by the scene. no need to call it.
  82411. */
  82412. PhysicsEngine.prototype._step = function (delta) {
  82413. var _this = this;
  82414. //check if any mesh has no body / requires an update
  82415. this._impostors.forEach(function (impostor) {
  82416. if (impostor.isBodyInitRequired()) {
  82417. _this._physicsPlugin.generatePhysicsBody(impostor);
  82418. }
  82419. });
  82420. if (delta > 0.1) {
  82421. delta = 0.1;
  82422. }
  82423. else if (delta <= 0) {
  82424. delta = 1.0 / 60.0;
  82425. }
  82426. this._physicsPlugin.executeStep(delta, this._impostors);
  82427. };
  82428. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  82429. return this._physicsPlugin;
  82430. };
  82431. PhysicsEngine.prototype.getImpostors = function () {
  82432. return this._impostors;
  82433. };
  82434. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  82435. for (var i = 0; i < this._impostors.length; ++i) {
  82436. if (this._impostors[i].object === object) {
  82437. return this._impostors[i];
  82438. }
  82439. }
  82440. return null;
  82441. };
  82442. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  82443. for (var i = 0; i < this._impostors.length; ++i) {
  82444. if (this._impostors[i].physicsBody === body) {
  82445. return this._impostors[i];
  82446. }
  82447. }
  82448. return null;
  82449. };
  82450. // Statics
  82451. PhysicsEngine.Epsilon = 0.001;
  82452. return PhysicsEngine;
  82453. }());
  82454. BABYLON.PhysicsEngine = PhysicsEngine;
  82455. })(BABYLON || (BABYLON = {}));
  82456. //# sourceMappingURL=babylon.physicsEngine.js.map
  82457. var BABYLON;
  82458. (function (BABYLON) {
  82459. var PhysicsHelper = /** @class */ (function () {
  82460. function PhysicsHelper(scene) {
  82461. this._scene = scene;
  82462. this._physicsEngine = this._scene.getPhysicsEngine();
  82463. if (!this._physicsEngine) {
  82464. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  82465. }
  82466. }
  82467. /**
  82468. * @param {Vector3} origin the origin of the explosion
  82469. * @param {number} radius the explosion radius
  82470. * @param {number} strength the explosion strength
  82471. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82472. */
  82473. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  82474. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82475. if (!this._physicsEngine) {
  82476. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  82477. return null;
  82478. }
  82479. var impostors = this._physicsEngine.getImpostors();
  82480. if (impostors.length === 0) {
  82481. return null;
  82482. }
  82483. var event = new PhysicsRadialExplosionEvent(this._scene);
  82484. impostors.forEach(function (impostor) {
  82485. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82486. if (!impostorForceAndContactPoint) {
  82487. return;
  82488. }
  82489. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82490. });
  82491. event.dispose(false);
  82492. return event;
  82493. };
  82494. /**
  82495. * @param {Vector3} origin the origin of the explosion
  82496. * @param {number} radius the explosion radius
  82497. * @param {number} strength the explosion strength
  82498. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82499. */
  82500. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  82501. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82502. if (!this._physicsEngine) {
  82503. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82504. return null;
  82505. }
  82506. var impostors = this._physicsEngine.getImpostors();
  82507. if (impostors.length === 0) {
  82508. return null;
  82509. }
  82510. var event = new PhysicsRadialExplosionEvent(this._scene);
  82511. impostors.forEach(function (impostor) {
  82512. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82513. if (!impostorForceAndContactPoint) {
  82514. return;
  82515. }
  82516. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82517. });
  82518. event.dispose(false);
  82519. return event;
  82520. };
  82521. /**
  82522. * @param {Vector3} origin the origin of the explosion
  82523. * @param {number} radius the explosion radius
  82524. * @param {number} strength the explosion strength
  82525. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82526. */
  82527. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82528. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82529. if (!this._physicsEngine) {
  82530. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82531. return null;
  82532. }
  82533. var impostors = this._physicsEngine.getImpostors();
  82534. if (impostors.length === 0) {
  82535. return null;
  82536. }
  82537. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82538. event.dispose(false);
  82539. return event;
  82540. };
  82541. /**
  82542. * @param {Vector3} origin the origin of the updraft
  82543. * @param {number} radius the radius of the updraft
  82544. * @param {number} strength the strength of the updraft
  82545. * @param {number} height the height of the updraft
  82546. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  82547. */
  82548. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  82549. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  82550. if (!this._physicsEngine) {
  82551. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82552. return null;
  82553. }
  82554. if (this._physicsEngine.getImpostors().length === 0) {
  82555. return null;
  82556. }
  82557. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  82558. event.dispose(false);
  82559. return event;
  82560. };
  82561. /**
  82562. * @param {Vector3} origin the of the vortex
  82563. * @param {number} radius the radius of the vortex
  82564. * @param {number} strength the strength of the vortex
  82565. * @param {number} height the height of the vortex
  82566. */
  82567. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  82568. if (!this._physicsEngine) {
  82569. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82570. return null;
  82571. }
  82572. if (this._physicsEngine.getImpostors().length === 0) {
  82573. return null;
  82574. }
  82575. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  82576. event.dispose(false);
  82577. return event;
  82578. };
  82579. return PhysicsHelper;
  82580. }());
  82581. BABYLON.PhysicsHelper = PhysicsHelper;
  82582. /***** Radial explosion *****/
  82583. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  82584. function PhysicsRadialExplosionEvent(scene) {
  82585. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  82586. this._rays = [];
  82587. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  82588. this._scene = scene;
  82589. }
  82590. /**
  82591. * Returns the data related to the radial explosion event (sphere & rays).
  82592. * @returns {PhysicsRadialExplosionEventData}
  82593. */
  82594. PhysicsRadialExplosionEvent.prototype.getData = function () {
  82595. this._dataFetched = true;
  82596. return {
  82597. sphere: this._sphere,
  82598. rays: this._rays,
  82599. };
  82600. };
  82601. /**
  82602. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  82603. * @param impostor
  82604. * @param {Vector3} origin the origin of the explosion
  82605. * @param {number} radius the explosion radius
  82606. * @param {number} strength the explosion strength
  82607. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  82608. * @returns {Nullable<PhysicsForceAndContactPoint>}
  82609. */
  82610. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  82611. if (impostor.mass === 0) {
  82612. return null;
  82613. }
  82614. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  82615. return null;
  82616. }
  82617. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82618. return null;
  82619. }
  82620. var impostorObjectCenter = impostor.getObjectCenter();
  82621. var direction = impostorObjectCenter.subtract(origin);
  82622. var ray = new BABYLON.Ray(origin, direction, radius);
  82623. this._rays.push(ray);
  82624. var hit = ray.intersectsMesh(impostor.object);
  82625. var contactPoint = hit.pickedPoint;
  82626. if (!contactPoint) {
  82627. return null;
  82628. }
  82629. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  82630. if (distanceFromOrigin > radius) {
  82631. return null;
  82632. }
  82633. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  82634. ? strength
  82635. : strength * (1 - (distanceFromOrigin / radius));
  82636. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82637. return { force: force, contactPoint: contactPoint };
  82638. };
  82639. /**
  82640. * Disposes the sphere.
  82641. * @param {bolean} force
  82642. */
  82643. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82644. var _this = this;
  82645. if (force === void 0) { force = true; }
  82646. if (force) {
  82647. this._sphere.dispose();
  82648. }
  82649. else {
  82650. setTimeout(function () {
  82651. if (!_this._dataFetched) {
  82652. _this._sphere.dispose();
  82653. }
  82654. }, 0);
  82655. }
  82656. };
  82657. /*** Helpers ***/
  82658. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82659. if (!this._sphere) {
  82660. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82661. this._sphere.isVisible = false;
  82662. }
  82663. };
  82664. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82665. var impostorObject = impostor.object;
  82666. this._prepareSphere();
  82667. this._sphere.position = origin;
  82668. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82669. this._sphere._updateBoundingInfo();
  82670. this._sphere.computeWorldMatrix(true);
  82671. return this._sphere.intersectsMesh(impostorObject, true);
  82672. };
  82673. return PhysicsRadialExplosionEvent;
  82674. }());
  82675. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82676. /***** Gravitational Field *****/
  82677. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82678. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82679. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82680. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82681. this._physicsHelper = physicsHelper;
  82682. this._scene = scene;
  82683. this._origin = origin;
  82684. this._radius = radius;
  82685. this._strength = strength;
  82686. this._falloff = falloff;
  82687. this._tickCallback = this._tick.bind(this);
  82688. }
  82689. /**
  82690. * Returns the data related to the gravitational field event (sphere).
  82691. * @returns {PhysicsGravitationalFieldEventData}
  82692. */
  82693. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82694. this._dataFetched = true;
  82695. return {
  82696. sphere: this._sphere,
  82697. };
  82698. };
  82699. /**
  82700. * Enables the gravitational field.
  82701. */
  82702. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82703. this._tickCallback.call(this);
  82704. this._scene.registerBeforeRender(this._tickCallback);
  82705. };
  82706. /**
  82707. * Disables the gravitational field.
  82708. */
  82709. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82710. this._scene.unregisterBeforeRender(this._tickCallback);
  82711. };
  82712. /**
  82713. * Disposes the sphere.
  82714. * @param {bolean} force
  82715. */
  82716. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82717. var _this = this;
  82718. if (force === void 0) { force = true; }
  82719. if (force) {
  82720. this._sphere.dispose();
  82721. }
  82722. else {
  82723. setTimeout(function () {
  82724. if (!_this._dataFetched) {
  82725. _this._sphere.dispose();
  82726. }
  82727. }, 0);
  82728. }
  82729. };
  82730. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82731. // Since the params won't change, we fetch the event only once
  82732. if (this._sphere) {
  82733. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82734. }
  82735. else {
  82736. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82737. if (radialExplosionEvent) {
  82738. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82739. }
  82740. }
  82741. };
  82742. return PhysicsGravitationalFieldEvent;
  82743. }());
  82744. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  82745. /***** Updraft *****/
  82746. var PhysicsUpdraftEvent = /** @class */ (function () {
  82747. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  82748. this._scene = _scene;
  82749. this._origin = _origin;
  82750. this._radius = _radius;
  82751. this._strength = _strength;
  82752. this._height = _height;
  82753. this._updraftMode = _updraftMode;
  82754. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82755. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  82756. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82757. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82758. this._physicsEngine = this._scene.getPhysicsEngine();
  82759. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82760. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82761. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82762. this._originDirection = this._origin.subtract(this._originTop).normalize();
  82763. }
  82764. this._tickCallback = this._tick.bind(this);
  82765. }
  82766. /**
  82767. * Returns the data related to the updraft event (cylinder).
  82768. * @returns {PhysicsUpdraftEventData}
  82769. */
  82770. PhysicsUpdraftEvent.prototype.getData = function () {
  82771. this._dataFetched = true;
  82772. return {
  82773. cylinder: this._cylinder,
  82774. };
  82775. };
  82776. /**
  82777. * Enables the updraft.
  82778. */
  82779. PhysicsUpdraftEvent.prototype.enable = function () {
  82780. this._tickCallback.call(this);
  82781. this._scene.registerBeforeRender(this._tickCallback);
  82782. };
  82783. /**
  82784. * Disables the cortex.
  82785. */
  82786. PhysicsUpdraftEvent.prototype.disable = function () {
  82787. this._scene.unregisterBeforeRender(this._tickCallback);
  82788. };
  82789. /**
  82790. * Disposes the sphere.
  82791. * @param {bolean} force
  82792. */
  82793. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  82794. var _this = this;
  82795. if (force === void 0) { force = true; }
  82796. if (force) {
  82797. this._cylinder.dispose();
  82798. }
  82799. else {
  82800. setTimeout(function () {
  82801. if (!_this._dataFetched) {
  82802. _this._cylinder.dispose();
  82803. }
  82804. }, 0);
  82805. }
  82806. };
  82807. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82808. if (impostor.mass === 0) {
  82809. return null;
  82810. }
  82811. if (!this._intersectsWithCylinder(impostor)) {
  82812. return null;
  82813. }
  82814. var impostorObjectCenter = impostor.getObjectCenter();
  82815. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82816. var direction = this._originDirection;
  82817. }
  82818. else {
  82819. var direction = impostorObjectCenter.subtract(this._originTop);
  82820. }
  82821. var multiplier = this._strength * -1;
  82822. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82823. return { force: force, contactPoint: impostorObjectCenter };
  82824. };
  82825. PhysicsUpdraftEvent.prototype._tick = function () {
  82826. var _this = this;
  82827. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82828. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82829. if (!impostorForceAndContactPoint) {
  82830. return;
  82831. }
  82832. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82833. });
  82834. };
  82835. /*** Helpers ***/
  82836. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  82837. if (!this._cylinder) {
  82838. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  82839. height: this._height,
  82840. diameter: this._radius * 2,
  82841. }, this._scene);
  82842. this._cylinder.isVisible = false;
  82843. }
  82844. };
  82845. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  82846. var impostorObject = impostor.object;
  82847. this._prepareCylinder();
  82848. this._cylinder.position = this._cylinderPosition;
  82849. return this._cylinder.intersectsMesh(impostorObject, true);
  82850. };
  82851. return PhysicsUpdraftEvent;
  82852. }());
  82853. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  82854. /***** Vortex *****/
  82855. var PhysicsVortexEvent = /** @class */ (function () {
  82856. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  82857. this._scene = _scene;
  82858. this._origin = _origin;
  82859. this._radius = _radius;
  82860. this._strength = _strength;
  82861. this._height = _height;
  82862. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82863. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  82864. this._updraftMultiplier = 0.02;
  82865. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82866. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82867. this._physicsEngine = this._scene.getPhysicsEngine();
  82868. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82869. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82870. this._tickCallback = this._tick.bind(this);
  82871. }
  82872. /**
  82873. * Returns the data related to the vortex event (cylinder).
  82874. * @returns {PhysicsVortexEventData}
  82875. */
  82876. PhysicsVortexEvent.prototype.getData = function () {
  82877. this._dataFetched = true;
  82878. return {
  82879. cylinder: this._cylinder,
  82880. };
  82881. };
  82882. /**
  82883. * Enables the vortex.
  82884. */
  82885. PhysicsVortexEvent.prototype.enable = function () {
  82886. this._tickCallback.call(this);
  82887. this._scene.registerBeforeRender(this._tickCallback);
  82888. };
  82889. /**
  82890. * Disables the cortex.
  82891. */
  82892. PhysicsVortexEvent.prototype.disable = function () {
  82893. this._scene.unregisterBeforeRender(this._tickCallback);
  82894. };
  82895. /**
  82896. * Disposes the sphere.
  82897. * @param {bolean} force
  82898. */
  82899. PhysicsVortexEvent.prototype.dispose = function (force) {
  82900. var _this = this;
  82901. if (force === void 0) { force = true; }
  82902. if (force) {
  82903. this._cylinder.dispose();
  82904. }
  82905. else {
  82906. setTimeout(function () {
  82907. if (!_this._dataFetched) {
  82908. _this._cylinder.dispose();
  82909. }
  82910. }, 0);
  82911. }
  82912. };
  82913. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82914. if (impostor.mass === 0) {
  82915. return null;
  82916. }
  82917. if (!this._intersectsWithCylinder(impostor)) {
  82918. return null;
  82919. }
  82920. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82921. return null;
  82922. }
  82923. var impostorObjectCenter = impostor.getObjectCenter();
  82924. 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)
  82925. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  82926. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  82927. var hit = ray.intersectsMesh(impostor.object);
  82928. var contactPoint = hit.pickedPoint;
  82929. if (!contactPoint) {
  82930. return null;
  82931. }
  82932. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  82933. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  82934. var directionToOrigin = contactPoint.normalize();
  82935. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82936. directionToOrigin = directionToOrigin.negate();
  82937. }
  82938. // TODO: find a more physically based solution
  82939. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82940. var forceX = directionToOrigin.x * this._strength / 8;
  82941. var forceY = directionToOrigin.y * this._updraftMultiplier;
  82942. var forceZ = directionToOrigin.z * this._strength / 8;
  82943. }
  82944. else {
  82945. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  82946. var forceY = this._originTop.y * this._updraftMultiplier;
  82947. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  82948. }
  82949. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  82950. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  82951. return { force: force, contactPoint: impostorObjectCenter };
  82952. };
  82953. PhysicsVortexEvent.prototype._tick = function () {
  82954. var _this = this;
  82955. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82956. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82957. if (!impostorForceAndContactPoint) {
  82958. return;
  82959. }
  82960. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82961. });
  82962. };
  82963. /*** Helpers ***/
  82964. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  82965. if (!this._cylinder) {
  82966. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  82967. height: this._height,
  82968. diameter: this._radius * 2,
  82969. }, this._scene);
  82970. this._cylinder.isVisible = false;
  82971. }
  82972. };
  82973. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  82974. var impostorObject = impostor.object;
  82975. this._prepareCylinder();
  82976. this._cylinder.position = this._cylinderPosition;
  82977. return this._cylinder.intersectsMesh(impostorObject, true);
  82978. };
  82979. return PhysicsVortexEvent;
  82980. }());
  82981. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  82982. /***** Enums *****/
  82983. /**
  82984. * The strenght of the force in correspondence to the distance of the affected object
  82985. */
  82986. var PhysicsRadialImpulseFalloff;
  82987. (function (PhysicsRadialImpulseFalloff) {
  82988. /** Defines that impulse is constant in strength across it's whole radius */
  82989. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  82990. /** DEfines that impulse gets weaker if it's further from the origin */
  82991. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  82992. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  82993. /**
  82994. * The strenght of the force in correspondence to the distance of the affected object
  82995. */
  82996. var PhysicsUpdraftMode;
  82997. (function (PhysicsUpdraftMode) {
  82998. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  82999. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  83000. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  83001. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  83002. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  83003. })(BABYLON || (BABYLON = {}));
  83004. //# sourceMappingURL=babylon.physicsHelper.js.map
  83005. var BABYLON;
  83006. (function (BABYLON) {
  83007. var CannonJSPlugin = /** @class */ (function () {
  83008. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  83009. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  83010. if (iterations === void 0) { iterations = 10; }
  83011. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  83012. this.name = "CannonJSPlugin";
  83013. this._physicsMaterials = new Array();
  83014. this._fixedTimeStep = 1 / 60;
  83015. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  83016. this.BJSCANNON = CANNON;
  83017. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  83018. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  83019. this._tmpPosition = BABYLON.Vector3.Zero();
  83020. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  83021. this._tmpUnityRotation = new BABYLON.Quaternion();
  83022. if (!this.isSupported()) {
  83023. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  83024. return;
  83025. }
  83026. this._extendNamespace();
  83027. this.world = new this.BJSCANNON.World();
  83028. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  83029. this.world.solver.iterations = iterations;
  83030. }
  83031. CannonJSPlugin.prototype.setGravity = function (gravity) {
  83032. this.world.gravity.copy(gravity);
  83033. };
  83034. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  83035. this._fixedTimeStep = timeStep;
  83036. };
  83037. CannonJSPlugin.prototype.getTimeStep = function () {
  83038. return this._fixedTimeStep;
  83039. };
  83040. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  83041. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  83042. };
  83043. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83044. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83045. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83046. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  83047. };
  83048. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83049. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83050. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83051. impostor.physicsBody.applyForce(impulse, worldPoint);
  83052. };
  83053. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83054. //parent-child relationship. Does this impostor has a parent impostor?
  83055. if (impostor.parent) {
  83056. if (impostor.physicsBody) {
  83057. this.removePhysicsBody(impostor);
  83058. //TODO is that needed?
  83059. impostor.forceUpdate();
  83060. }
  83061. return;
  83062. }
  83063. //should a new body be created for this impostor?
  83064. if (impostor.isBodyInitRequired()) {
  83065. var shape = this._createShape(impostor);
  83066. //unregister events, if body is being changed
  83067. var oldBody = impostor.physicsBody;
  83068. if (oldBody) {
  83069. this.removePhysicsBody(impostor);
  83070. }
  83071. //create the body and material
  83072. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  83073. var bodyCreationObject = {
  83074. mass: impostor.getParam("mass"),
  83075. material: material
  83076. };
  83077. // A simple extend, in case native options were used.
  83078. var nativeOptions = impostor.getParam("nativeOptions");
  83079. for (var key in nativeOptions) {
  83080. if (nativeOptions.hasOwnProperty(key)) {
  83081. bodyCreationObject[key] = nativeOptions[key];
  83082. }
  83083. }
  83084. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83085. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83086. this.world.addEventListener("preStep", impostor.beforeStep);
  83087. this.world.addEventListener("postStep", impostor.afterStep);
  83088. impostor.physicsBody.addShape(shape);
  83089. this.world.add(impostor.physicsBody);
  83090. //try to keep the body moving in the right direction by taking old properties.
  83091. //Should be tested!
  83092. if (oldBody) {
  83093. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83094. impostor.physicsBody[param].copy(oldBody[param]);
  83095. });
  83096. }
  83097. this._processChildMeshes(impostor);
  83098. }
  83099. //now update the body's transformation
  83100. this._updatePhysicsBodyTransformation(impostor);
  83101. };
  83102. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83103. var _this = this;
  83104. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83105. var currentRotation = mainImpostor.object.rotationQuaternion;
  83106. if (meshChildren.length) {
  83107. var processMesh = function (localPosition, mesh) {
  83108. if (!currentRotation || !mesh.rotationQuaternion) {
  83109. return;
  83110. }
  83111. var childImpostor = mesh.getPhysicsImpostor();
  83112. if (childImpostor) {
  83113. var parent = childImpostor.parent;
  83114. if (parent !== mainImpostor) {
  83115. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83116. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83117. if (childImpostor.physicsBody) {
  83118. _this.removePhysicsBody(childImpostor);
  83119. childImpostor.physicsBody = null;
  83120. }
  83121. childImpostor.parent = mainImpostor;
  83122. childImpostor.resetUpdateFlags();
  83123. 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));
  83124. //Add the mass of the children.
  83125. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83126. }
  83127. }
  83128. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83129. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83130. };
  83131. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83132. }
  83133. };
  83134. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83135. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83136. this.world.removeEventListener("preStep", impostor.beforeStep);
  83137. this.world.removeEventListener("postStep", impostor.afterStep);
  83138. this.world.remove(impostor.physicsBody);
  83139. };
  83140. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83141. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83142. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83143. if (!mainBody || !connectedBody) {
  83144. return;
  83145. }
  83146. var constraint;
  83147. var jointData = impostorJoint.joint.jointData;
  83148. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83149. var constraintData = {
  83150. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83151. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83152. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83153. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83154. maxForce: jointData.nativeParams.maxForce,
  83155. collideConnected: !!jointData.collision
  83156. };
  83157. switch (impostorJoint.joint.type) {
  83158. case BABYLON.PhysicsJoint.HingeJoint:
  83159. case BABYLON.PhysicsJoint.Hinge2Joint:
  83160. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83161. break;
  83162. case BABYLON.PhysicsJoint.DistanceJoint:
  83163. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83164. break;
  83165. case BABYLON.PhysicsJoint.SpringJoint:
  83166. var springData = jointData;
  83167. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83168. restLength: springData.length,
  83169. stiffness: springData.stiffness,
  83170. damping: springData.damping,
  83171. localAnchorA: constraintData.pivotA,
  83172. localAnchorB: constraintData.pivotB
  83173. });
  83174. break;
  83175. case BABYLON.PhysicsJoint.LockJoint:
  83176. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83177. break;
  83178. case BABYLON.PhysicsJoint.PointToPointJoint:
  83179. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83180. default:
  83181. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83182. break;
  83183. }
  83184. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83185. constraint.collideConnected = !!jointData.collision;
  83186. impostorJoint.joint.physicsJoint = constraint;
  83187. //don't add spring as constraint, as it is not one.
  83188. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83189. this.world.addConstraint(constraint);
  83190. }
  83191. else {
  83192. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83193. constraint.applyForce();
  83194. });
  83195. }
  83196. };
  83197. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83198. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83199. };
  83200. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83201. var index;
  83202. var mat;
  83203. for (index = 0; index < this._physicsMaterials.length; index++) {
  83204. mat = this._physicsMaterials[index];
  83205. if (mat.friction === friction && mat.restitution === restitution) {
  83206. return mat;
  83207. }
  83208. }
  83209. var currentMat = new this.BJSCANNON.Material(name);
  83210. currentMat.friction = friction;
  83211. currentMat.restitution = restitution;
  83212. this._physicsMaterials.push(currentMat);
  83213. return currentMat;
  83214. };
  83215. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83216. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83217. };
  83218. CannonJSPlugin.prototype._createShape = function (impostor) {
  83219. var object = impostor.object;
  83220. var returnValue;
  83221. var extendSize = impostor.getObjectExtendSize();
  83222. switch (impostor.type) {
  83223. case BABYLON.PhysicsImpostor.SphereImpostor:
  83224. var radiusX = extendSize.x;
  83225. var radiusY = extendSize.y;
  83226. var radiusZ = extendSize.z;
  83227. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83228. break;
  83229. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83230. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83231. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83232. break;
  83233. case BABYLON.PhysicsImpostor.BoxImpostor:
  83234. var box = extendSize.scale(0.5);
  83235. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83236. break;
  83237. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83238. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83239. returnValue = new this.BJSCANNON.Plane();
  83240. break;
  83241. case BABYLON.PhysicsImpostor.MeshImpostor:
  83242. // should transform the vertex data to world coordinates!!
  83243. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83244. var rawFaces = object.getIndices ? object.getIndices() : [];
  83245. if (!rawVerts)
  83246. return;
  83247. // get only scale! so the object could transform correctly.
  83248. var oldPosition = object.position.clone();
  83249. var oldRotation = object.rotation && object.rotation.clone();
  83250. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83251. object.position.copyFromFloats(0, 0, 0);
  83252. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83253. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83254. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83255. var transform = object.computeWorldMatrix(true);
  83256. // convert rawVerts to object space
  83257. var temp = new Array();
  83258. var index;
  83259. for (index = 0; index < rawVerts.length; index += 3) {
  83260. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83261. }
  83262. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83263. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83264. //now set back the transformation!
  83265. object.position.copyFrom(oldPosition);
  83266. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83267. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83268. break;
  83269. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83270. var oldPosition2 = object.position.clone();
  83271. var oldRotation2 = object.rotation && object.rotation.clone();
  83272. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83273. object.position.copyFromFloats(0, 0, 0);
  83274. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83275. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83276. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83277. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83278. returnValue = this._createHeightmap(object);
  83279. object.position.copyFrom(oldPosition2);
  83280. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83281. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83282. object.computeWorldMatrix(true);
  83283. break;
  83284. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83285. returnValue = new this.BJSCANNON.Particle();
  83286. break;
  83287. }
  83288. return returnValue;
  83289. };
  83290. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83291. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83292. var transform = object.computeWorldMatrix(true);
  83293. // convert rawVerts to object space
  83294. var temp = new Array();
  83295. var index;
  83296. for (index = 0; index < pos.length; index += 3) {
  83297. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83298. }
  83299. pos = temp;
  83300. var matrix = new Array();
  83301. //For now pointDepth will not be used and will be automatically calculated.
  83302. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83303. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83304. var boundingInfo = object.getBoundingInfo();
  83305. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83306. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83307. var elementSize = dim * 2 / arraySize;
  83308. for (var i = 0; i < pos.length; i = i + 3) {
  83309. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83310. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83311. var y = -pos[i + 2] + minY;
  83312. if (!matrix[x]) {
  83313. matrix[x] = [];
  83314. }
  83315. if (!matrix[x][z]) {
  83316. matrix[x][z] = y;
  83317. }
  83318. matrix[x][z] = Math.max(y, matrix[x][z]);
  83319. }
  83320. for (var x = 0; x <= arraySize; ++x) {
  83321. if (!matrix[x]) {
  83322. var loc = 1;
  83323. while (!matrix[(x + loc) % arraySize]) {
  83324. loc++;
  83325. }
  83326. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83327. //console.log("missing x", x);
  83328. }
  83329. for (var z = 0; z <= arraySize; ++z) {
  83330. if (!matrix[x][z]) {
  83331. var loc = 1;
  83332. var newValue;
  83333. while (newValue === undefined) {
  83334. newValue = matrix[x][(z + loc++) % arraySize];
  83335. }
  83336. matrix[x][z] = newValue;
  83337. }
  83338. }
  83339. }
  83340. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83341. elementSize: elementSize
  83342. });
  83343. //For future reference, needed for body transformation
  83344. shape.minY = minY;
  83345. return shape;
  83346. };
  83347. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83348. var object = impostor.object;
  83349. //make sure it is updated...
  83350. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83351. // The delta between the mesh position and the mesh bounding box center
  83352. var bInfo = object.getBoundingInfo();
  83353. if (!bInfo)
  83354. return;
  83355. var center = impostor.getObjectCenter();
  83356. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83357. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83358. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83359. this._tmpPosition.copyFrom(center);
  83360. var quaternion = object.rotationQuaternion;
  83361. if (!quaternion) {
  83362. return;
  83363. }
  83364. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83365. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83366. //-90 DEG in X, precalculated
  83367. quaternion = quaternion.multiply(this._minus90X);
  83368. //Invert! (Precalculated, 90 deg in X)
  83369. //No need to clone. this will never change.
  83370. impostor.setDeltaRotation(this._plus90X);
  83371. }
  83372. //If it is a heightfield, if should be centered.
  83373. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83374. var mesh = object;
  83375. var boundingInfo = mesh.getBoundingInfo();
  83376. //calculate the correct body position:
  83377. var rotationQuaternion = mesh.rotationQuaternion;
  83378. mesh.rotationQuaternion = this._tmpUnityRotation;
  83379. mesh.computeWorldMatrix(true);
  83380. //get original center with no rotation
  83381. var c = center.clone();
  83382. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83383. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83384. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83385. mesh.setPreTransformMatrix(p);
  83386. mesh.computeWorldMatrix(true);
  83387. //calculate the translation
  83388. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83389. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83390. //add it inverted to the delta
  83391. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83392. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83393. //rotation is back
  83394. mesh.rotationQuaternion = rotationQuaternion;
  83395. mesh.setPreTransformMatrix(oldPivot);
  83396. mesh.computeWorldMatrix(true);
  83397. }
  83398. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83399. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83400. //this._tmpPosition.copyFrom(object.position);
  83401. }
  83402. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83403. //Now update the impostor object
  83404. impostor.physicsBody.position.copy(this._tmpPosition);
  83405. impostor.physicsBody.quaternion.copy(quaternion);
  83406. };
  83407. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83408. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83409. if (impostor.object.rotationQuaternion) {
  83410. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83411. }
  83412. };
  83413. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83414. impostor.physicsBody.position.copy(newPosition);
  83415. impostor.physicsBody.quaternion.copy(newRotation);
  83416. };
  83417. CannonJSPlugin.prototype.isSupported = function () {
  83418. return this.BJSCANNON !== undefined;
  83419. };
  83420. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83421. impostor.physicsBody.velocity.copy(velocity);
  83422. };
  83423. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83424. impostor.physicsBody.angularVelocity.copy(velocity);
  83425. };
  83426. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83427. var v = impostor.physicsBody.velocity;
  83428. if (!v) {
  83429. return null;
  83430. }
  83431. return new BABYLON.Vector3(v.x, v.y, v.z);
  83432. };
  83433. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83434. var v = impostor.physicsBody.angularVelocity;
  83435. if (!v) {
  83436. return null;
  83437. }
  83438. return new BABYLON.Vector3(v.x, v.y, v.z);
  83439. };
  83440. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83441. impostor.physicsBody.mass = mass;
  83442. impostor.physicsBody.updateMassProperties();
  83443. };
  83444. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  83445. return impostor.physicsBody.mass;
  83446. };
  83447. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  83448. return impostor.physicsBody.material.friction;
  83449. };
  83450. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83451. impostor.physicsBody.material.friction = friction;
  83452. };
  83453. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83454. return impostor.physicsBody.material.restitution;
  83455. };
  83456. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83457. impostor.physicsBody.material.restitution = restitution;
  83458. };
  83459. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  83460. impostor.physicsBody.sleep();
  83461. };
  83462. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  83463. impostor.physicsBody.wakeUp();
  83464. };
  83465. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83466. joint.physicsJoint.distance = maxDistance;
  83467. };
  83468. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83469. // if (!motorIndex) {
  83470. // joint.physicsJoint.enableMotor();
  83471. // }
  83472. // }
  83473. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83474. // if (!motorIndex) {
  83475. // joint.physicsJoint.disableMotor();
  83476. // }
  83477. // }
  83478. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83479. if (!motorIndex) {
  83480. joint.physicsJoint.enableMotor();
  83481. joint.physicsJoint.setMotorSpeed(speed);
  83482. if (maxForce) {
  83483. this.setLimit(joint, maxForce);
  83484. }
  83485. }
  83486. };
  83487. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  83488. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  83489. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  83490. };
  83491. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83492. var body = impostor.physicsBody;
  83493. mesh.position.x = body.position.x;
  83494. mesh.position.y = body.position.y;
  83495. mesh.position.z = body.position.z;
  83496. if (mesh.rotationQuaternion) {
  83497. mesh.rotationQuaternion.x = body.quaternion.x;
  83498. mesh.rotationQuaternion.y = body.quaternion.y;
  83499. mesh.rotationQuaternion.z = body.quaternion.z;
  83500. mesh.rotationQuaternion.w = body.quaternion.w;
  83501. }
  83502. };
  83503. CannonJSPlugin.prototype.getRadius = function (impostor) {
  83504. var shape = impostor.physicsBody.shapes[0];
  83505. return shape.boundingSphereRadius;
  83506. };
  83507. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83508. var shape = impostor.physicsBody.shapes[0];
  83509. result.x = shape.halfExtents.x * 2;
  83510. result.y = shape.halfExtents.y * 2;
  83511. result.z = shape.halfExtents.z * 2;
  83512. };
  83513. CannonJSPlugin.prototype.dispose = function () {
  83514. };
  83515. CannonJSPlugin.prototype._extendNamespace = function () {
  83516. //this will force cannon to execute at least one step when using interpolation
  83517. var step_tmp1 = new this.BJSCANNON.Vec3();
  83518. var Engine = this.BJSCANNON;
  83519. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83520. maxSubSteps = maxSubSteps || 10;
  83521. timeSinceLastCalled = timeSinceLastCalled || 0;
  83522. if (timeSinceLastCalled === 0) {
  83523. this.internalStep(dt);
  83524. this.time += dt;
  83525. }
  83526. else {
  83527. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83528. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83529. var t0 = performance.now();
  83530. for (var i = 0; i !== internalSteps; i++) {
  83531. this.internalStep(dt);
  83532. if (performance.now() - t0 > dt * 1000) {
  83533. break;
  83534. }
  83535. }
  83536. this.time += timeSinceLastCalled;
  83537. var h = this.time % dt;
  83538. var h_div_dt = h / dt;
  83539. var interpvelo = step_tmp1;
  83540. var bodies = this.bodies;
  83541. for (var j = 0; j !== bodies.length; j++) {
  83542. var b = bodies[j];
  83543. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  83544. b.position.vsub(b.previousPosition, interpvelo);
  83545. interpvelo.scale(h_div_dt, interpvelo);
  83546. b.position.vadd(interpvelo, b.interpolatedPosition);
  83547. }
  83548. else {
  83549. b.interpolatedPosition.copy(b.position);
  83550. b.interpolatedQuaternion.copy(b.quaternion);
  83551. }
  83552. }
  83553. }
  83554. };
  83555. };
  83556. return CannonJSPlugin;
  83557. }());
  83558. BABYLON.CannonJSPlugin = CannonJSPlugin;
  83559. })(BABYLON || (BABYLON = {}));
  83560. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  83561. var BABYLON;
  83562. (function (BABYLON) {
  83563. var OimoJSPlugin = /** @class */ (function () {
  83564. function OimoJSPlugin(iterations) {
  83565. this.name = "OimoJSPlugin";
  83566. this._tmpImpostorsArray = [];
  83567. this._tmpPositionVector = BABYLON.Vector3.Zero();
  83568. this.BJSOIMO = OIMO;
  83569. this.world = new this.BJSOIMO.World({
  83570. iterations: iterations
  83571. });
  83572. this.world.clear();
  83573. }
  83574. OimoJSPlugin.prototype.setGravity = function (gravity) {
  83575. this.world.gravity.copy(gravity);
  83576. };
  83577. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  83578. this.world.timeStep = timeStep;
  83579. };
  83580. OimoJSPlugin.prototype.getTimeStep = function () {
  83581. return this.world.timeStep;
  83582. };
  83583. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  83584. var _this = this;
  83585. impostors.forEach(function (impostor) {
  83586. impostor.beforeStep();
  83587. });
  83588. this.world.step();
  83589. impostors.forEach(function (impostor) {
  83590. impostor.afterStep();
  83591. //update the ordered impostors array
  83592. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  83593. });
  83594. //check for collisions
  83595. var contact = this.world.contacts;
  83596. while (contact !== null) {
  83597. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  83598. contact = contact.next;
  83599. continue;
  83600. }
  83601. //is this body colliding with any other? get the impostor
  83602. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  83603. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  83604. if (!mainImpostor || !collidingImpostor) {
  83605. contact = contact.next;
  83606. continue;
  83607. }
  83608. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  83609. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  83610. contact = contact.next;
  83611. }
  83612. };
  83613. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83614. var mass = impostor.physicsBody.mass;
  83615. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  83616. };
  83617. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83618. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  83619. this.applyImpulse(impostor, force, contactPoint);
  83620. };
  83621. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83622. var _this = this;
  83623. //parent-child relationship. Does this impostor has a parent impostor?
  83624. if (impostor.parent) {
  83625. if (impostor.physicsBody) {
  83626. this.removePhysicsBody(impostor);
  83627. //TODO is that needed?
  83628. impostor.forceUpdate();
  83629. }
  83630. return;
  83631. }
  83632. if (impostor.isBodyInitRequired()) {
  83633. var bodyConfig = {
  83634. name: impostor.uniqueId,
  83635. //Oimo must have mass, also for static objects.
  83636. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  83637. size: [],
  83638. type: [],
  83639. pos: [],
  83640. posShape: [],
  83641. rot: [],
  83642. rotShape: [],
  83643. move: impostor.getParam("mass") !== 0,
  83644. density: impostor.getParam("mass"),
  83645. friction: impostor.getParam("friction"),
  83646. restitution: impostor.getParam("restitution"),
  83647. //Supporting older versions of Oimo
  83648. world: this.world
  83649. };
  83650. var impostors = [impostor];
  83651. var addToArray = function (parent) {
  83652. if (!parent.getChildMeshes)
  83653. return;
  83654. parent.getChildMeshes().forEach(function (m) {
  83655. if (m.physicsImpostor) {
  83656. impostors.push(m.physicsImpostor);
  83657. //m.physicsImpostor._init();
  83658. }
  83659. });
  83660. };
  83661. addToArray(impostor.object);
  83662. var checkWithEpsilon_1 = function (value) {
  83663. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83664. };
  83665. impostors.forEach(function (i) {
  83666. if (!i.object.rotationQuaternion) {
  83667. return;
  83668. }
  83669. //get the correct bounding box
  83670. var oldQuaternion = i.object.rotationQuaternion;
  83671. var rot = oldQuaternion.toEulerAngles();
  83672. var extendSize = i.getObjectExtendSize();
  83673. var radToDeg = 57.295779513082320876;
  83674. if (i === impostor) {
  83675. var center = impostor.getObjectCenter();
  83676. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83677. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83678. //Can also use Array.prototype.push.apply
  83679. bodyConfig.pos.push(center.x);
  83680. bodyConfig.pos.push(center.y);
  83681. bodyConfig.pos.push(center.z);
  83682. bodyConfig.posShape.push(0, 0, 0);
  83683. //tmp solution
  83684. bodyConfig.rot.push(rot.x * radToDeg);
  83685. bodyConfig.rot.push(rot.y * radToDeg);
  83686. bodyConfig.rot.push(rot.z * radToDeg);
  83687. bodyConfig.rotShape.push(0, 0, 0);
  83688. }
  83689. else {
  83690. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83691. bodyConfig.posShape.push(localPosition.x);
  83692. bodyConfig.posShape.push(localPosition.y);
  83693. bodyConfig.posShape.push(localPosition.z);
  83694. bodyConfig.pos.push(0, 0, 0);
  83695. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83696. bodyConfig.rot.push(0);
  83697. bodyConfig.rot.push(0);
  83698. bodyConfig.rot.push(0);
  83699. bodyConfig.rotShape.push(rot.x * radToDeg);
  83700. bodyConfig.rotShape.push(rot.y * radToDeg);
  83701. bodyConfig.rotShape.push(rot.z * radToDeg);
  83702. }
  83703. // register mesh
  83704. switch (i.type) {
  83705. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83706. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83707. case BABYLON.PhysicsImpostor.SphereImpostor:
  83708. var radiusX = extendSize.x;
  83709. var radiusY = extendSize.y;
  83710. var radiusZ = extendSize.z;
  83711. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83712. bodyConfig.type.push('sphere');
  83713. //due to the way oimo works with compounds, add 3 times
  83714. bodyConfig.size.push(size);
  83715. bodyConfig.size.push(size);
  83716. bodyConfig.size.push(size);
  83717. break;
  83718. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83719. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83720. var sizeY = checkWithEpsilon_1(extendSize.y);
  83721. bodyConfig.type.push('cylinder');
  83722. bodyConfig.size.push(sizeX);
  83723. bodyConfig.size.push(sizeY);
  83724. //due to the way oimo works with compounds, add one more value.
  83725. bodyConfig.size.push(sizeY);
  83726. break;
  83727. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83728. case BABYLON.PhysicsImpostor.BoxImpostor:
  83729. default:
  83730. var sizeX = checkWithEpsilon_1(extendSize.x);
  83731. var sizeY = checkWithEpsilon_1(extendSize.y);
  83732. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83733. bodyConfig.type.push('box');
  83734. //if (i === impostor) {
  83735. bodyConfig.size.push(sizeX);
  83736. bodyConfig.size.push(sizeY);
  83737. bodyConfig.size.push(sizeZ);
  83738. //} else {
  83739. // bodyConfig.size.push(0,0,0);
  83740. //}
  83741. break;
  83742. }
  83743. //actually not needed, but hey...
  83744. i.object.rotationQuaternion = oldQuaternion;
  83745. });
  83746. impostor.physicsBody = this.world.add(bodyConfig);
  83747. }
  83748. else {
  83749. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  83750. }
  83751. impostor.setDeltaPosition(this._tmpPositionVector);
  83752. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  83753. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  83754. };
  83755. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83756. //impostor.physicsBody.dispose();
  83757. //Same as : (older oimo versions)
  83758. this.world.removeRigidBody(impostor.physicsBody);
  83759. };
  83760. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83761. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83762. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83763. if (!mainBody || !connectedBody) {
  83764. return;
  83765. }
  83766. var jointData = impostorJoint.joint.jointData;
  83767. var options = jointData.nativeParams || {};
  83768. var type;
  83769. var nativeJointData = {
  83770. body1: mainBody,
  83771. body2: connectedBody,
  83772. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  83773. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  83774. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  83775. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  83776. min: options.min,
  83777. max: options.max,
  83778. collision: options.collision || jointData.collision,
  83779. spring: options.spring,
  83780. //supporting older version of Oimo
  83781. world: this.world
  83782. };
  83783. switch (impostorJoint.joint.type) {
  83784. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83785. type = "jointBall";
  83786. break;
  83787. case BABYLON.PhysicsJoint.SpringJoint:
  83788. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  83789. var springData = jointData;
  83790. nativeJointData.min = springData.length || nativeJointData.min;
  83791. //Max should also be set, just make sure it is at least min
  83792. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  83793. case BABYLON.PhysicsJoint.DistanceJoint:
  83794. type = "jointDistance";
  83795. nativeJointData.max = jointData.maxDistance;
  83796. break;
  83797. case BABYLON.PhysicsJoint.PrismaticJoint:
  83798. type = "jointPrisme";
  83799. break;
  83800. case BABYLON.PhysicsJoint.SliderJoint:
  83801. type = "jointSlide";
  83802. break;
  83803. case BABYLON.PhysicsJoint.WheelJoint:
  83804. type = "jointWheel";
  83805. break;
  83806. case BABYLON.PhysicsJoint.HingeJoint:
  83807. default:
  83808. type = "jointHinge";
  83809. break;
  83810. }
  83811. nativeJointData.type = type;
  83812. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  83813. };
  83814. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83815. //Bug in Oimo prevents us from disposing a joint in the playground
  83816. //joint.joint.physicsJoint.dispose();
  83817. //So we will bruteforce it!
  83818. try {
  83819. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  83820. }
  83821. catch (e) {
  83822. BABYLON.Tools.Warn(e);
  83823. }
  83824. };
  83825. OimoJSPlugin.prototype.isSupported = function () {
  83826. return this.BJSOIMO !== undefined;
  83827. };
  83828. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83829. if (!impostor.physicsBody.sleeping) {
  83830. //TODO check that
  83831. /*if (impostor.physicsBody.shapes.next) {
  83832. var parentShape = this._getLastShape(impostor.physicsBody);
  83833. impostor.object.position.copyFrom(parentShape.position);
  83834. console.log(parentShape.position);
  83835. } else {*/
  83836. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  83837. //}
  83838. if (impostor.object.rotationQuaternion) {
  83839. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  83840. }
  83841. }
  83842. };
  83843. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83844. var body = impostor.physicsBody;
  83845. body.position.copy(newPosition);
  83846. body.orientation.copy(newRotation);
  83847. body.syncShapes();
  83848. body.awake();
  83849. };
  83850. /*private _getLastShape(body: any): any {
  83851. var lastShape = body.shapes;
  83852. while (lastShape.next) {
  83853. lastShape = lastShape.next;
  83854. }
  83855. return lastShape;
  83856. }*/
  83857. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83858. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  83859. };
  83860. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83861. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  83862. };
  83863. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83864. var v = impostor.physicsBody.linearVelocity;
  83865. if (!v) {
  83866. return null;
  83867. }
  83868. return new BABYLON.Vector3(v.x, v.y, v.z);
  83869. };
  83870. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83871. var v = impostor.physicsBody.angularVelocity;
  83872. if (!v) {
  83873. return null;
  83874. }
  83875. return new BABYLON.Vector3(v.x, v.y, v.z);
  83876. };
  83877. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83878. var staticBody = mass === 0;
  83879. //this will actually set the body's density and not its mass.
  83880. //But this is how oimo treats the mass variable.
  83881. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  83882. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  83883. };
  83884. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  83885. return impostor.physicsBody.shapes.density;
  83886. };
  83887. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  83888. return impostor.physicsBody.shapes.friction;
  83889. };
  83890. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83891. impostor.physicsBody.shapes.friction = friction;
  83892. };
  83893. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83894. return impostor.physicsBody.shapes.restitution;
  83895. };
  83896. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83897. impostor.physicsBody.shapes.restitution = restitution;
  83898. };
  83899. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  83900. impostor.physicsBody.sleep();
  83901. };
  83902. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  83903. impostor.physicsBody.awake();
  83904. };
  83905. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83906. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  83907. if (minDistance !== void 0) {
  83908. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  83909. }
  83910. };
  83911. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83912. //TODO separate rotational and transational motors.
  83913. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83914. if (motor) {
  83915. motor.setMotor(speed, maxForce);
  83916. }
  83917. };
  83918. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  83919. //TODO separate rotational and transational motors.
  83920. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83921. if (motor) {
  83922. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  83923. }
  83924. };
  83925. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83926. var body = impostor.physicsBody;
  83927. mesh.position.x = body.position.x;
  83928. mesh.position.y = body.position.y;
  83929. mesh.position.z = body.position.z;
  83930. if (mesh.rotationQuaternion) {
  83931. mesh.rotationQuaternion.x = body.orientation.x;
  83932. mesh.rotationQuaternion.y = body.orientation.y;
  83933. mesh.rotationQuaternion.z = body.orientation.z;
  83934. mesh.rotationQuaternion.w = body.orientation.s;
  83935. }
  83936. };
  83937. OimoJSPlugin.prototype.getRadius = function (impostor) {
  83938. return impostor.physicsBody.shapes.radius;
  83939. };
  83940. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83941. var shape = impostor.physicsBody.shapes;
  83942. result.x = shape.halfWidth * 2;
  83943. result.y = shape.halfHeight * 2;
  83944. result.z = shape.halfDepth * 2;
  83945. };
  83946. OimoJSPlugin.prototype.dispose = function () {
  83947. this.world.clear();
  83948. };
  83949. return OimoJSPlugin;
  83950. }());
  83951. BABYLON.OimoJSPlugin = OimoJSPlugin;
  83952. })(BABYLON || (BABYLON = {}));
  83953. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  83954. var BABYLON;
  83955. (function (BABYLON) {
  83956. /*
  83957. * Based on jsTGALoader - Javascript loader for TGA file
  83958. * By Vincent Thibault
  83959. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  83960. */
  83961. var TGATools = /** @class */ (function () {
  83962. function TGATools() {
  83963. }
  83964. TGATools.GetTGAHeader = function (data) {
  83965. var offset = 0;
  83966. var header = {
  83967. id_length: data[offset++],
  83968. colormap_type: data[offset++],
  83969. image_type: data[offset++],
  83970. colormap_index: data[offset++] | data[offset++] << 8,
  83971. colormap_length: data[offset++] | data[offset++] << 8,
  83972. colormap_size: data[offset++],
  83973. origin: [
  83974. data[offset++] | data[offset++] << 8,
  83975. data[offset++] | data[offset++] << 8
  83976. ],
  83977. width: data[offset++] | data[offset++] << 8,
  83978. height: data[offset++] | data[offset++] << 8,
  83979. pixel_size: data[offset++],
  83980. flags: data[offset++]
  83981. };
  83982. return header;
  83983. };
  83984. TGATools.UploadContent = function (gl, data) {
  83985. // Not enough data to contain header ?
  83986. if (data.length < 19) {
  83987. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  83988. return;
  83989. }
  83990. // Read Header
  83991. var offset = 18;
  83992. var header = TGATools.GetTGAHeader(data);
  83993. // Assume it's a valid Targa file.
  83994. if (header.id_length + offset > data.length) {
  83995. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  83996. return;
  83997. }
  83998. // Skip not needed data
  83999. offset += header.id_length;
  84000. var use_rle = false;
  84001. var use_pal = false;
  84002. var use_grey = false;
  84003. // Get some informations.
  84004. switch (header.image_type) {
  84005. case TGATools._TYPE_RLE_INDEXED:
  84006. use_rle = true;
  84007. case TGATools._TYPE_INDEXED:
  84008. use_pal = true;
  84009. break;
  84010. case TGATools._TYPE_RLE_RGB:
  84011. use_rle = true;
  84012. case TGATools._TYPE_RGB:
  84013. // use_rgb = true;
  84014. break;
  84015. case TGATools._TYPE_RLE_GREY:
  84016. use_rle = true;
  84017. case TGATools._TYPE_GREY:
  84018. use_grey = true;
  84019. break;
  84020. }
  84021. var pixel_data;
  84022. // var numAlphaBits = header.flags & 0xf;
  84023. var pixel_size = header.pixel_size >> 3;
  84024. var pixel_total = header.width * header.height * pixel_size;
  84025. // Read palettes
  84026. var palettes;
  84027. if (use_pal) {
  84028. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  84029. }
  84030. // Read LRE
  84031. if (use_rle) {
  84032. pixel_data = new Uint8Array(pixel_total);
  84033. var c, count, i;
  84034. var localOffset = 0;
  84035. var pixels = new Uint8Array(pixel_size);
  84036. while (offset < pixel_total && localOffset < pixel_total) {
  84037. c = data[offset++];
  84038. count = (c & 0x7f) + 1;
  84039. // RLE pixels
  84040. if (c & 0x80) {
  84041. // Bind pixel tmp array
  84042. for (i = 0; i < pixel_size; ++i) {
  84043. pixels[i] = data[offset++];
  84044. }
  84045. // Copy pixel array
  84046. for (i = 0; i < count; ++i) {
  84047. pixel_data.set(pixels, localOffset + i * pixel_size);
  84048. }
  84049. localOffset += pixel_size * count;
  84050. }
  84051. // Raw pixels
  84052. else {
  84053. count *= pixel_size;
  84054. for (i = 0; i < count; ++i) {
  84055. pixel_data[localOffset + i] = data[offset++];
  84056. }
  84057. localOffset += count;
  84058. }
  84059. }
  84060. }
  84061. // RAW Pixels
  84062. else {
  84063. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  84064. }
  84065. // Load to texture
  84066. var x_start, y_start, x_step, y_step, y_end, x_end;
  84067. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  84068. default:
  84069. case TGATools._ORIGIN_UL:
  84070. x_start = 0;
  84071. x_step = 1;
  84072. x_end = header.width;
  84073. y_start = 0;
  84074. y_step = 1;
  84075. y_end = header.height;
  84076. break;
  84077. case TGATools._ORIGIN_BL:
  84078. x_start = 0;
  84079. x_step = 1;
  84080. x_end = header.width;
  84081. y_start = header.height - 1;
  84082. y_step = -1;
  84083. y_end = -1;
  84084. break;
  84085. case TGATools._ORIGIN_UR:
  84086. x_start = header.width - 1;
  84087. x_step = -1;
  84088. x_end = -1;
  84089. y_start = 0;
  84090. y_step = 1;
  84091. y_end = header.height;
  84092. break;
  84093. case TGATools._ORIGIN_BR:
  84094. x_start = header.width - 1;
  84095. x_step = -1;
  84096. x_end = -1;
  84097. y_start = header.height - 1;
  84098. y_step = -1;
  84099. y_end = -1;
  84100. break;
  84101. }
  84102. // Load the specify method
  84103. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84104. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84105. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84106. };
  84107. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84108. var image = pixel_data, colormap = palettes;
  84109. var width = header.width, height = header.height;
  84110. var color, i = 0, x, y;
  84111. var imageData = new Uint8Array(width * height * 4);
  84112. for (y = y_start; y !== y_end; y += y_step) {
  84113. for (x = x_start; x !== x_end; x += x_step, i++) {
  84114. color = image[i];
  84115. imageData[(x + width * y) * 4 + 3] = 255;
  84116. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84117. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84118. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84119. }
  84120. }
  84121. return imageData;
  84122. };
  84123. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84124. var image = pixel_data;
  84125. var width = header.width, height = header.height;
  84126. var color, i = 0, x, y;
  84127. var imageData = new Uint8Array(width * height * 4);
  84128. for (y = y_start; y !== y_end; y += y_step) {
  84129. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84130. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84131. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84132. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84133. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84134. imageData[(x + width * y) * 4 + 0] = r;
  84135. imageData[(x + width * y) * 4 + 1] = g;
  84136. imageData[(x + width * y) * 4 + 2] = b;
  84137. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84138. }
  84139. }
  84140. return imageData;
  84141. };
  84142. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84143. var image = pixel_data;
  84144. var width = header.width, height = header.height;
  84145. var i = 0, x, y;
  84146. var imageData = new Uint8Array(width * height * 4);
  84147. for (y = y_start; y !== y_end; y += y_step) {
  84148. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84149. imageData[(x + width * y) * 4 + 3] = 255;
  84150. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84151. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84152. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84153. }
  84154. }
  84155. return imageData;
  84156. };
  84157. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84158. var image = pixel_data;
  84159. var width = header.width, height = header.height;
  84160. var i = 0, x, y;
  84161. var imageData = new Uint8Array(width * height * 4);
  84162. for (y = y_start; y !== y_end; y += y_step) {
  84163. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84164. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84165. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84166. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84167. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84168. }
  84169. }
  84170. return imageData;
  84171. };
  84172. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84173. var image = pixel_data;
  84174. var width = header.width, height = header.height;
  84175. var color, i = 0, x, y;
  84176. var imageData = new Uint8Array(width * height * 4);
  84177. for (y = y_start; y !== y_end; y += y_step) {
  84178. for (x = x_start; x !== x_end; x += x_step, i++) {
  84179. color = image[i];
  84180. imageData[(x + width * y) * 4 + 0] = color;
  84181. imageData[(x + width * y) * 4 + 1] = color;
  84182. imageData[(x + width * y) * 4 + 2] = color;
  84183. imageData[(x + width * y) * 4 + 3] = 255;
  84184. }
  84185. }
  84186. return imageData;
  84187. };
  84188. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84189. var image = pixel_data;
  84190. var width = header.width, height = header.height;
  84191. var i = 0, x, y;
  84192. var imageData = new Uint8Array(width * height * 4);
  84193. for (y = y_start; y !== y_end; y += y_step) {
  84194. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84195. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84196. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84197. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84198. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84199. }
  84200. }
  84201. return imageData;
  84202. };
  84203. //private static _TYPE_NO_DATA = 0;
  84204. TGATools._TYPE_INDEXED = 1;
  84205. TGATools._TYPE_RGB = 2;
  84206. TGATools._TYPE_GREY = 3;
  84207. TGATools._TYPE_RLE_INDEXED = 9;
  84208. TGATools._TYPE_RLE_RGB = 10;
  84209. TGATools._TYPE_RLE_GREY = 11;
  84210. TGATools._ORIGIN_MASK = 0x30;
  84211. TGATools._ORIGIN_SHIFT = 0x04;
  84212. TGATools._ORIGIN_BL = 0x00;
  84213. TGATools._ORIGIN_BR = 0x01;
  84214. TGATools._ORIGIN_UL = 0x02;
  84215. TGATools._ORIGIN_UR = 0x03;
  84216. return TGATools;
  84217. }());
  84218. BABYLON.TGATools = TGATools;
  84219. })(BABYLON || (BABYLON = {}));
  84220. //# sourceMappingURL=babylon.tga.js.map
  84221. var BABYLON;
  84222. (function (BABYLON) {
  84223. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84224. // All values and structures referenced from:
  84225. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84226. var DDS_MAGIC = 0x20534444;
  84227. var
  84228. //DDSD_CAPS = 0x1,
  84229. //DDSD_HEIGHT = 0x2,
  84230. //DDSD_WIDTH = 0x4,
  84231. //DDSD_PITCH = 0x8,
  84232. //DDSD_PIXELFORMAT = 0x1000,
  84233. DDSD_MIPMAPCOUNT = 0x20000;
  84234. //DDSD_LINEARSIZE = 0x80000,
  84235. //DDSD_DEPTH = 0x800000;
  84236. // var DDSCAPS_COMPLEX = 0x8,
  84237. // DDSCAPS_MIPMAP = 0x400000,
  84238. // DDSCAPS_TEXTURE = 0x1000;
  84239. var DDSCAPS2_CUBEMAP = 0x200;
  84240. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84241. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84242. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84243. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84244. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84245. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84246. // DDSCAPS2_VOLUME = 0x200000;
  84247. var
  84248. //DDPF_ALPHAPIXELS = 0x1,
  84249. //DDPF_ALPHA = 0x2,
  84250. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84251. //DDPF_YUV = 0x200,
  84252. DDPF_LUMINANCE = 0x20000;
  84253. function FourCCToInt32(value) {
  84254. return value.charCodeAt(0) +
  84255. (value.charCodeAt(1) << 8) +
  84256. (value.charCodeAt(2) << 16) +
  84257. (value.charCodeAt(3) << 24);
  84258. }
  84259. function Int32ToFourCC(value) {
  84260. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84261. }
  84262. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84263. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84264. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84265. var FOURCC_DX10 = FourCCToInt32("DX10");
  84266. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84267. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84268. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84269. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84270. var headerLengthInt = 31; // The header length in 32 bit ints
  84271. // Offsets into the header array
  84272. var off_magic = 0;
  84273. var off_size = 1;
  84274. var off_flags = 2;
  84275. var off_height = 3;
  84276. var off_width = 4;
  84277. var off_mipmapCount = 7;
  84278. var off_pfFlags = 20;
  84279. var off_pfFourCC = 21;
  84280. var off_RGBbpp = 22;
  84281. var off_RMask = 23;
  84282. var off_GMask = 24;
  84283. var off_BMask = 25;
  84284. var off_AMask = 26;
  84285. // var off_caps1 = 27;
  84286. var off_caps2 = 28;
  84287. // var off_caps3 = 29;
  84288. // var off_caps4 = 30;
  84289. var off_dxgiFormat = 32;
  84290. ;
  84291. var DDSTools = /** @class */ (function () {
  84292. function DDSTools() {
  84293. }
  84294. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84295. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84296. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84297. var mipmapCount = 1;
  84298. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84299. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84300. }
  84301. var fourCC = header[off_pfFourCC];
  84302. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84303. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84304. switch (fourCC) {
  84305. case FOURCC_D3DFMT_R16G16B16A16F:
  84306. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84307. break;
  84308. case FOURCC_D3DFMT_R32G32B32A32F:
  84309. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84310. break;
  84311. case FOURCC_DX10:
  84312. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84313. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84314. break;
  84315. }
  84316. }
  84317. return {
  84318. width: header[off_width],
  84319. height: header[off_height],
  84320. mipmapCount: mipmapCount,
  84321. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84322. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84323. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84324. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84325. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84326. dxgiFormat: dxgiFormat,
  84327. textureType: textureType
  84328. };
  84329. };
  84330. DDSTools._ToHalfFloat = function (value) {
  84331. if (!DDSTools._FloatView) {
  84332. DDSTools._FloatView = new Float32Array(1);
  84333. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84334. }
  84335. DDSTools._FloatView[0] = value;
  84336. var x = DDSTools._Int32View[0];
  84337. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84338. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84339. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84340. /* If zero, or denormal, or exponent underflows too much for a denormal
  84341. * half, return signed zero. */
  84342. if (e < 103) {
  84343. return bits;
  84344. }
  84345. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84346. if (e > 142) {
  84347. bits |= 0x7c00;
  84348. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84349. * not Inf, so make sure we set one mantissa bit too. */
  84350. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84351. return bits;
  84352. }
  84353. /* If exponent underflows but not too much, return a denormal */
  84354. if (e < 113) {
  84355. m |= 0x0800;
  84356. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84357. * to 1, which is OK. */
  84358. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84359. return bits;
  84360. }
  84361. bits |= ((e - 112) << 10) | (m >> 1);
  84362. bits += m & 1;
  84363. return bits;
  84364. };
  84365. DDSTools._FromHalfFloat = function (value) {
  84366. var s = (value & 0x8000) >> 15;
  84367. var e = (value & 0x7C00) >> 10;
  84368. var f = value & 0x03FF;
  84369. if (e === 0) {
  84370. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84371. }
  84372. else if (e == 0x1F) {
  84373. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84374. }
  84375. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84376. };
  84377. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84378. var destArray = new Float32Array(dataLength);
  84379. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84380. var index = 0;
  84381. for (var y = 0; y < height; y++) {
  84382. for (var x = 0; x < width; x++) {
  84383. var srcPos = (x + y * width) * 4;
  84384. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84385. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84386. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84387. if (DDSTools.StoreLODInAlphaChannel) {
  84388. destArray[index + 3] = lod;
  84389. }
  84390. else {
  84391. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84392. }
  84393. index += 4;
  84394. }
  84395. }
  84396. return destArray;
  84397. };
  84398. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84399. if (DDSTools.StoreLODInAlphaChannel) {
  84400. var destArray = new Uint16Array(dataLength);
  84401. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84402. var index = 0;
  84403. for (var y = 0; y < height; y++) {
  84404. for (var x = 0; x < width; x++) {
  84405. var srcPos = (x + y * width) * 4;
  84406. destArray[index] = srcData[srcPos];
  84407. destArray[index + 1] = srcData[srcPos + 1];
  84408. destArray[index + 2] = srcData[srcPos + 2];
  84409. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84410. index += 4;
  84411. }
  84412. }
  84413. return destArray;
  84414. }
  84415. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84416. };
  84417. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84418. if (DDSTools.StoreLODInAlphaChannel) {
  84419. var destArray = new Float32Array(dataLength);
  84420. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84421. var index = 0;
  84422. for (var y = 0; y < height; y++) {
  84423. for (var x = 0; x < width; x++) {
  84424. var srcPos = (x + y * width) * 4;
  84425. destArray[index] = srcData[srcPos];
  84426. destArray[index + 1] = srcData[srcPos + 1];
  84427. destArray[index + 2] = srcData[srcPos + 2];
  84428. destArray[index + 3] = lod;
  84429. index += 4;
  84430. }
  84431. }
  84432. return destArray;
  84433. }
  84434. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  84435. };
  84436. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84437. var destArray = new Uint8Array(dataLength);
  84438. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84439. var index = 0;
  84440. for (var y = 0; y < height; y++) {
  84441. for (var x = 0; x < width; x++) {
  84442. var srcPos = (x + y * width) * 4;
  84443. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  84444. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  84445. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  84446. if (DDSTools.StoreLODInAlphaChannel) {
  84447. destArray[index + 3] = lod;
  84448. }
  84449. else {
  84450. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  84451. }
  84452. index += 4;
  84453. }
  84454. }
  84455. return destArray;
  84456. };
  84457. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84458. var destArray = new Uint8Array(dataLength);
  84459. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84460. var index = 0;
  84461. for (var y = 0; y < height; y++) {
  84462. for (var x = 0; x < width; x++) {
  84463. var srcPos = (x + y * width) * 4;
  84464. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  84465. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  84466. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  84467. if (DDSTools.StoreLODInAlphaChannel) {
  84468. destArray[index + 3] = lod;
  84469. }
  84470. else {
  84471. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  84472. }
  84473. index += 4;
  84474. }
  84475. }
  84476. return destArray;
  84477. };
  84478. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  84479. var byteArray = new Uint8Array(dataLength);
  84480. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84481. var index = 0;
  84482. for (var y = 0; y < height; y++) {
  84483. for (var x = 0; x < width; x++) {
  84484. var srcPos = (x + y * width) * 4;
  84485. byteArray[index] = srcData[srcPos + rOffset];
  84486. byteArray[index + 1] = srcData[srcPos + gOffset];
  84487. byteArray[index + 2] = srcData[srcPos + bOffset];
  84488. byteArray[index + 3] = srcData[srcPos + aOffset];
  84489. index += 4;
  84490. }
  84491. }
  84492. return byteArray;
  84493. };
  84494. DDSTools._ExtractLongWordOrder = function (value) {
  84495. if (value === 0 || value === 255 || value === -16777216) {
  84496. return 0;
  84497. }
  84498. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  84499. };
  84500. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  84501. var byteArray = new Uint8Array(dataLength);
  84502. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84503. var index = 0;
  84504. for (var y = 0; y < height; y++) {
  84505. for (var x = 0; x < width; x++) {
  84506. var srcPos = (x + y * width) * 3;
  84507. byteArray[index] = srcData[srcPos + rOffset];
  84508. byteArray[index + 1] = srcData[srcPos + gOffset];
  84509. byteArray[index + 2] = srcData[srcPos + bOffset];
  84510. index += 3;
  84511. }
  84512. }
  84513. return byteArray;
  84514. };
  84515. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  84516. var byteArray = new Uint8Array(dataLength);
  84517. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84518. var index = 0;
  84519. for (var y = 0; y < height; y++) {
  84520. for (var x = 0; x < width; x++) {
  84521. var srcPos = (x + y * width);
  84522. byteArray[index] = srcData[srcPos];
  84523. index++;
  84524. }
  84525. }
  84526. return byteArray;
  84527. };
  84528. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84529. if (lodIndex === void 0) { lodIndex = -1; }
  84530. var sphericalPolynomialFaces = null;
  84531. if (info.sphericalPolynomial) {
  84532. sphericalPolynomialFaces = new Array();
  84533. }
  84534. var ext = engine.getCaps().s3tc;
  84535. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84536. var fourCC, width, height, dataLength = 0, dataOffset;
  84537. var byteArray, mipmapCount, mip;
  84538. var internalFormat = 0;
  84539. var format = 0;
  84540. var blockBytes = 1;
  84541. if (header[off_magic] !== DDS_MAGIC) {
  84542. BABYLON.Tools.Error("Invalid magic number in DDS header");
  84543. return;
  84544. }
  84545. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  84546. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  84547. return;
  84548. }
  84549. if (info.isCompressed && !ext) {
  84550. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  84551. return;
  84552. }
  84553. var bpp = header[off_RGBbpp];
  84554. dataOffset = header[off_size] + 4;
  84555. var computeFormats = false;
  84556. if (info.isFourCC) {
  84557. fourCC = header[off_pfFourCC];
  84558. switch (fourCC) {
  84559. case FOURCC_DXT1:
  84560. blockBytes = 8;
  84561. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  84562. break;
  84563. case FOURCC_DXT3:
  84564. blockBytes = 16;
  84565. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  84566. break;
  84567. case FOURCC_DXT5:
  84568. blockBytes = 16;
  84569. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  84570. break;
  84571. case FOURCC_D3DFMT_R16G16B16A16F:
  84572. computeFormats = true;
  84573. break;
  84574. case FOURCC_D3DFMT_R32G32B32A32F:
  84575. computeFormats = true;
  84576. break;
  84577. case FOURCC_DX10:
  84578. // There is an additionnal header so dataOffset need to be changed
  84579. dataOffset += 5 * 4; // 5 uints
  84580. var supported = false;
  84581. switch (info.dxgiFormat) {
  84582. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  84583. computeFormats = true;
  84584. supported = true;
  84585. break;
  84586. case DXGI_FORMAT_B8G8R8X8_UNORM:
  84587. info.isRGB = true;
  84588. info.isFourCC = false;
  84589. bpp = 32;
  84590. supported = true;
  84591. break;
  84592. }
  84593. if (supported) {
  84594. break;
  84595. }
  84596. default:
  84597. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  84598. return;
  84599. }
  84600. }
  84601. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  84602. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  84603. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  84604. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  84605. if (computeFormats) {
  84606. format = engine._getWebGLTextureType(info.textureType);
  84607. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84608. }
  84609. mipmapCount = 1;
  84610. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  84611. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84612. }
  84613. for (var face = 0; face < faces; face++) {
  84614. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  84615. width = header[off_width];
  84616. height = header[off_height];
  84617. for (mip = 0; mip < mipmapCount; ++mip) {
  84618. if (lodIndex === -1 || lodIndex === mip) {
  84619. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  84620. var i = (lodIndex === -1) ? mip : 0;
  84621. if (!info.isCompressed && info.isFourCC) {
  84622. dataLength = width * height * 4;
  84623. var floatArray = null;
  84624. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  84625. if (bpp === 128) {
  84626. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84627. if (sphericalPolynomialFaces && i == 0) {
  84628. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84629. }
  84630. }
  84631. else if (bpp === 64) {
  84632. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84633. if (sphericalPolynomialFaces && i == 0) {
  84634. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84635. }
  84636. }
  84637. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84638. format = engine._getWebGLTextureType(info.textureType);
  84639. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84640. }
  84641. else {
  84642. if (bpp === 128) {
  84643. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84644. if (sphericalPolynomialFaces && i == 0) {
  84645. sphericalPolynomialFaces.push(floatArray);
  84646. }
  84647. }
  84648. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  84649. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84650. if (sphericalPolynomialFaces && i == 0) {
  84651. sphericalPolynomialFaces.push(floatArray);
  84652. }
  84653. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84654. format = engine._getWebGLTextureType(info.textureType);
  84655. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84656. }
  84657. else { // 64
  84658. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84659. if (sphericalPolynomialFaces && i == 0) {
  84660. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84661. }
  84662. }
  84663. }
  84664. if (floatArray) {
  84665. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84666. }
  84667. }
  84668. else if (info.isRGB) {
  84669. if (bpp === 24) {
  84670. dataLength = width * height * 3;
  84671. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84672. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84673. }
  84674. else { // 32
  84675. dataLength = width * height * 4;
  84676. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84677. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84678. }
  84679. }
  84680. else if (info.isLuminance) {
  84681. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84682. var unpaddedRowSize = width;
  84683. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84684. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84685. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84686. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84687. }
  84688. else {
  84689. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84690. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84691. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84692. }
  84693. }
  84694. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84695. width *= 0.5;
  84696. height *= 0.5;
  84697. width = Math.max(1.0, width);
  84698. height = Math.max(1.0, height);
  84699. }
  84700. if (currentFace !== undefined) {
  84701. // Loading a single face
  84702. break;
  84703. }
  84704. }
  84705. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  84706. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  84707. size: header[off_width],
  84708. right: sphericalPolynomialFaces[0],
  84709. left: sphericalPolynomialFaces[1],
  84710. up: sphericalPolynomialFaces[2],
  84711. down: sphericalPolynomialFaces[3],
  84712. front: sphericalPolynomialFaces[4],
  84713. back: sphericalPolynomialFaces[5],
  84714. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  84715. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84716. gammaSpace: false,
  84717. });
  84718. }
  84719. else {
  84720. info.sphericalPolynomial = undefined;
  84721. }
  84722. };
  84723. DDSTools.StoreLODInAlphaChannel = false;
  84724. return DDSTools;
  84725. }());
  84726. BABYLON.DDSTools = DDSTools;
  84727. })(BABYLON || (BABYLON = {}));
  84728. //# sourceMappingURL=babylon.dds.js.map
  84729. var BABYLON;
  84730. (function (BABYLON) {
  84731. /**
  84732. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84733. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84734. */
  84735. var KhronosTextureContainer = /** @class */ (function () {
  84736. /**
  84737. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84738. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84739. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84740. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84741. */
  84742. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  84743. this.arrayBuffer = arrayBuffer;
  84744. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  84745. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  84746. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  84747. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  84748. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  84749. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  84750. BABYLON.Tools.Error("texture missing KTX identifier");
  84751. return;
  84752. }
  84753. // load the reset of the header in native 32 bit int
  84754. var header = new Int32Array(this.arrayBuffer, 12, 13);
  84755. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  84756. var oppositeEndianess = header[0] === 0x01020304;
  84757. // read all the header elements in order they exist in the file, without modification (sans endainness)
  84758. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  84759. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  84760. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  84761. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  84762. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  84763. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  84764. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  84765. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  84766. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  84767. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  84768. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  84769. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  84770. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  84771. if (this.glType !== 0) {
  84772. BABYLON.Tools.Error("only compressed formats currently supported");
  84773. return;
  84774. }
  84775. else {
  84776. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  84777. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  84778. }
  84779. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  84780. BABYLON.Tools.Error("only 2D textures currently supported");
  84781. return;
  84782. }
  84783. if (this.numberOfArrayElements !== 0) {
  84784. BABYLON.Tools.Error("texture arrays not currently supported");
  84785. return;
  84786. }
  84787. if (this.numberOfFaces !== facesExpected) {
  84788. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  84789. return;
  84790. }
  84791. // we now have a completely validated file, so could use existence of loadType as success
  84792. // would need to make this more elaborate & adjust checks above to support more than one load type
  84793. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  84794. }
  84795. // not as fast hardware based, but will probably never need to use
  84796. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  84797. return ((val & 0xFF) << 24)
  84798. | ((val & 0xFF00) << 8)
  84799. | ((val >> 8) & 0xFF00)
  84800. | ((val >> 24) & 0xFF);
  84801. };
  84802. /**
  84803. * It is assumed that the texture has already been created & is currently bound
  84804. */
  84805. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  84806. switch (this.loadType) {
  84807. case KhronosTextureContainer.COMPRESSED_2D:
  84808. this._upload2DCompressedLevels(gl, loadMipmaps);
  84809. break;
  84810. case KhronosTextureContainer.TEX_2D:
  84811. case KhronosTextureContainer.COMPRESSED_3D:
  84812. case KhronosTextureContainer.TEX_3D:
  84813. }
  84814. };
  84815. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  84816. // initialize width & height for level 1
  84817. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  84818. var width = this.pixelWidth;
  84819. var height = this.pixelHeight;
  84820. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  84821. for (var level = 0; level < mipmapCount; level++) {
  84822. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  84823. for (var face = 0; face < this.numberOfFaces; face++) {
  84824. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  84825. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  84826. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  84827. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  84828. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  84829. }
  84830. width = Math.max(1.0, width * 0.5);
  84831. height = Math.max(1.0, height * 0.5);
  84832. }
  84833. };
  84834. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  84835. // load types
  84836. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  84837. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  84838. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  84839. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  84840. return KhronosTextureContainer;
  84841. }());
  84842. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  84843. })(BABYLON || (BABYLON = {}));
  84844. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  84845. var BABYLON;
  84846. (function (BABYLON) {
  84847. var Debug;
  84848. (function (Debug) {
  84849. /**
  84850. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  84851. */
  84852. var SkeletonViewer = /** @class */ (function () {
  84853. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  84854. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  84855. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  84856. this.skeleton = skeleton;
  84857. this.mesh = mesh;
  84858. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  84859. this.renderingGroupId = renderingGroupId;
  84860. this.color = BABYLON.Color3.White();
  84861. this._debugLines = new Array();
  84862. this._isEnabled = false;
  84863. this._scene = scene;
  84864. this.update();
  84865. this._renderFunction = this.update.bind(this);
  84866. }
  84867. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  84868. get: function () {
  84869. return this._isEnabled;
  84870. },
  84871. set: function (value) {
  84872. if (this._isEnabled === value) {
  84873. return;
  84874. }
  84875. this._isEnabled = value;
  84876. if (value) {
  84877. this._scene.registerBeforeRender(this._renderFunction);
  84878. }
  84879. else {
  84880. this._scene.unregisterBeforeRender(this._renderFunction);
  84881. }
  84882. },
  84883. enumerable: true,
  84884. configurable: true
  84885. });
  84886. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  84887. if (x === void 0) { x = 0; }
  84888. if (y === void 0) { y = 0; }
  84889. if (z === void 0) { z = 0; }
  84890. var tmat = BABYLON.Tmp.Matrix[0];
  84891. var parentBone = bone.getParent();
  84892. tmat.copyFrom(bone.getLocalMatrix());
  84893. if (x !== 0 || y !== 0 || z !== 0) {
  84894. var tmat2 = BABYLON.Tmp.Matrix[1];
  84895. BABYLON.Matrix.IdentityToRef(tmat2);
  84896. tmat2.m[12] = x;
  84897. tmat2.m[13] = y;
  84898. tmat2.m[14] = z;
  84899. tmat2.multiplyToRef(tmat, tmat);
  84900. }
  84901. if (parentBone) {
  84902. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  84903. }
  84904. tmat.multiplyToRef(meshMat, tmat);
  84905. position.x = tmat.m[12];
  84906. position.y = tmat.m[13];
  84907. position.z = tmat.m[14];
  84908. };
  84909. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  84910. var len = bones.length;
  84911. var meshPos = this.mesh.position;
  84912. for (var i = 0; i < len; i++) {
  84913. var bone = bones[i];
  84914. var points = this._debugLines[i];
  84915. if (!points) {
  84916. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84917. this._debugLines[i] = points;
  84918. }
  84919. this._getBonePosition(points[0], bone, meshMat);
  84920. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  84921. points[0].subtractInPlace(meshPos);
  84922. points[1].subtractInPlace(meshPos);
  84923. }
  84924. };
  84925. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  84926. var len = bones.length;
  84927. var boneNum = 0;
  84928. var meshPos = this.mesh.position;
  84929. for (var i = len - 1; i >= 0; i--) {
  84930. var childBone = bones[i];
  84931. var parentBone = childBone.getParent();
  84932. if (!parentBone) {
  84933. continue;
  84934. }
  84935. var points = this._debugLines[boneNum];
  84936. if (!points) {
  84937. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84938. this._debugLines[boneNum] = points;
  84939. }
  84940. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  84941. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  84942. points[0].subtractInPlace(meshPos);
  84943. points[1].subtractInPlace(meshPos);
  84944. boneNum++;
  84945. }
  84946. };
  84947. SkeletonViewer.prototype.update = function () {
  84948. if (this.autoUpdateBonesMatrices) {
  84949. this.skeleton.computeAbsoluteTransforms();
  84950. }
  84951. if (this.skeleton.bones[0].length === undefined) {
  84952. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84953. }
  84954. else {
  84955. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84956. }
  84957. if (!this._debugMesh) {
  84958. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  84959. this._debugMesh.renderingGroupId = this.renderingGroupId;
  84960. }
  84961. else {
  84962. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  84963. }
  84964. this._debugMesh.position.copyFrom(this.mesh.position);
  84965. this._debugMesh.color = this.color;
  84966. };
  84967. SkeletonViewer.prototype.dispose = function () {
  84968. if (this._debugMesh) {
  84969. this.isEnabled = false;
  84970. this._debugMesh.dispose();
  84971. this._debugMesh = null;
  84972. }
  84973. };
  84974. return SkeletonViewer;
  84975. }());
  84976. Debug.SkeletonViewer = SkeletonViewer;
  84977. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84978. })(BABYLON || (BABYLON = {}));
  84979. //# sourceMappingURL=babylon.skeletonViewer.js.map
  84980. /**
  84981. * Module Debug contains the (visual) components to debug a scene correctly
  84982. */
  84983. var BABYLON;
  84984. (function (BABYLON) {
  84985. var Debug;
  84986. (function (Debug) {
  84987. /**
  84988. * The Axes viewer will show 3 axes in a specific point in space
  84989. */
  84990. var AxesViewer = /** @class */ (function () {
  84991. function AxesViewer(scene, scaleLines) {
  84992. if (scaleLines === void 0) { scaleLines = 1; }
  84993. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84994. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84995. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84996. this.scaleLines = 1;
  84997. this.scaleLines = scaleLines;
  84998. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  84999. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  85000. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  85001. this._xmesh.renderingGroupId = 2;
  85002. this._ymesh.renderingGroupId = 2;
  85003. this._zmesh.renderingGroupId = 2;
  85004. this._xmesh.material.checkReadyOnlyOnce = true;
  85005. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  85006. this._ymesh.material.checkReadyOnlyOnce = true;
  85007. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  85008. this._zmesh.material.checkReadyOnlyOnce = true;
  85009. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  85010. this.scene = scene;
  85011. }
  85012. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  85013. var scaleLines = this.scaleLines;
  85014. if (this._xmesh) {
  85015. this._xmesh.position.copyFrom(position);
  85016. }
  85017. if (this._ymesh) {
  85018. this._ymesh.position.copyFrom(position);
  85019. }
  85020. if (this._zmesh) {
  85021. this._zmesh.position.copyFrom(position);
  85022. }
  85023. var point2 = this._xline[1];
  85024. point2.x = xaxis.x * scaleLines;
  85025. point2.y = xaxis.y * scaleLines;
  85026. point2.z = xaxis.z * scaleLines;
  85027. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  85028. point2 = this._yline[1];
  85029. point2.x = yaxis.x * scaleLines;
  85030. point2.y = yaxis.y * scaleLines;
  85031. point2.z = yaxis.z * scaleLines;
  85032. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  85033. point2 = this._zline[1];
  85034. point2.x = zaxis.x * scaleLines;
  85035. point2.y = zaxis.y * scaleLines;
  85036. point2.z = zaxis.z * scaleLines;
  85037. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  85038. };
  85039. AxesViewer.prototype.dispose = function () {
  85040. if (this._xmesh) {
  85041. this._xmesh.dispose();
  85042. }
  85043. if (this._ymesh) {
  85044. this._ymesh.dispose();
  85045. }
  85046. if (this._zmesh) {
  85047. this._zmesh.dispose();
  85048. }
  85049. this._xmesh = null;
  85050. this._ymesh = null;
  85051. this._zmesh = null;
  85052. this.scene = null;
  85053. };
  85054. return AxesViewer;
  85055. }());
  85056. Debug.AxesViewer = AxesViewer;
  85057. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85058. })(BABYLON || (BABYLON = {}));
  85059. //# sourceMappingURL=babylon.axesViewer.js.map
  85060. var BABYLON;
  85061. (function (BABYLON) {
  85062. var Debug;
  85063. (function (Debug) {
  85064. /**
  85065. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  85066. */
  85067. var BoneAxesViewer = /** @class */ (function (_super) {
  85068. __extends(BoneAxesViewer, _super);
  85069. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  85070. if (scaleLines === void 0) { scaleLines = 1; }
  85071. var _this = _super.call(this, scene, scaleLines) || this;
  85072. _this.pos = BABYLON.Vector3.Zero();
  85073. _this.xaxis = BABYLON.Vector3.Zero();
  85074. _this.yaxis = BABYLON.Vector3.Zero();
  85075. _this.zaxis = BABYLON.Vector3.Zero();
  85076. _this.mesh = mesh;
  85077. _this.bone = bone;
  85078. return _this;
  85079. }
  85080. BoneAxesViewer.prototype.update = function () {
  85081. if (!this.mesh || !this.bone) {
  85082. return;
  85083. }
  85084. var bone = this.bone;
  85085. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85086. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85087. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85088. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85089. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85090. };
  85091. BoneAxesViewer.prototype.dispose = function () {
  85092. if (this.mesh) {
  85093. this.mesh = null;
  85094. this.bone = null;
  85095. _super.prototype.dispose.call(this);
  85096. }
  85097. };
  85098. return BoneAxesViewer;
  85099. }(Debug.AxesViewer));
  85100. Debug.BoneAxesViewer = BoneAxesViewer;
  85101. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85102. })(BABYLON || (BABYLON = {}));
  85103. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85104. var BABYLON;
  85105. (function (BABYLON) {
  85106. var RayHelper = /** @class */ (function () {
  85107. function RayHelper(ray) {
  85108. this.ray = ray;
  85109. }
  85110. RayHelper.CreateAndShow = function (ray, scene, color) {
  85111. var helper = new RayHelper(ray);
  85112. helper.show(scene, color);
  85113. return helper;
  85114. };
  85115. RayHelper.prototype.show = function (scene, color) {
  85116. if (!this._renderFunction && this.ray) {
  85117. var ray = this.ray;
  85118. this._renderFunction = this._render.bind(this);
  85119. this._scene = scene;
  85120. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85121. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85122. if (this._renderFunction) {
  85123. this._scene.registerBeforeRender(this._renderFunction);
  85124. }
  85125. }
  85126. if (color && this._renderLine) {
  85127. this._renderLine.color.copyFrom(color);
  85128. }
  85129. };
  85130. RayHelper.prototype.hide = function () {
  85131. if (this._renderFunction && this._scene) {
  85132. this._scene.unregisterBeforeRender(this._renderFunction);
  85133. this._scene = null;
  85134. this._renderFunction = null;
  85135. if (this._renderLine) {
  85136. this._renderLine.dispose();
  85137. this._renderLine = null;
  85138. }
  85139. this._renderPoints = [];
  85140. }
  85141. };
  85142. RayHelper.prototype._render = function () {
  85143. var ray = this.ray;
  85144. if (!ray) {
  85145. return;
  85146. }
  85147. var point = this._renderPoints[1];
  85148. var len = Math.min(ray.length, 1000000);
  85149. point.copyFrom(ray.direction);
  85150. point.scaleInPlace(len);
  85151. point.addInPlace(ray.origin);
  85152. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85153. };
  85154. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85155. this._attachedToMesh = mesh;
  85156. var ray = this.ray;
  85157. if (!ray) {
  85158. return;
  85159. }
  85160. if (!ray.direction) {
  85161. ray.direction = BABYLON.Vector3.Zero();
  85162. }
  85163. if (!ray.origin) {
  85164. ray.origin = BABYLON.Vector3.Zero();
  85165. }
  85166. if (length) {
  85167. ray.length = length;
  85168. }
  85169. if (!meshSpaceOrigin) {
  85170. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85171. }
  85172. if (!meshSpaceDirection) {
  85173. // -1 so that this will work with Mesh.lookAt
  85174. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85175. }
  85176. if (!this._meshSpaceDirection) {
  85177. this._meshSpaceDirection = meshSpaceDirection.clone();
  85178. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85179. }
  85180. else {
  85181. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85182. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85183. }
  85184. if (!this._updateToMeshFunction) {
  85185. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85186. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85187. }
  85188. this._updateToMesh();
  85189. };
  85190. RayHelper.prototype.detachFromMesh = function () {
  85191. if (this._attachedToMesh) {
  85192. if (this._updateToMeshFunction) {
  85193. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85194. }
  85195. this._attachedToMesh = null;
  85196. this._updateToMeshFunction = null;
  85197. }
  85198. };
  85199. RayHelper.prototype._updateToMesh = function () {
  85200. var ray = this.ray;
  85201. if (!this._attachedToMesh || !ray) {
  85202. return;
  85203. }
  85204. if (this._attachedToMesh._isDisposed) {
  85205. this.detachFromMesh();
  85206. return;
  85207. }
  85208. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85209. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85210. };
  85211. RayHelper.prototype.dispose = function () {
  85212. this.hide();
  85213. this.detachFromMesh();
  85214. this.ray = null;
  85215. };
  85216. return RayHelper;
  85217. }());
  85218. BABYLON.RayHelper = RayHelper;
  85219. })(BABYLON || (BABYLON = {}));
  85220. //# sourceMappingURL=babylon.rayHelper.js.map
  85221. var BABYLON;
  85222. (function (BABYLON) {
  85223. // load the inspector using require, if not present in the global namespace.
  85224. var DebugLayer = /** @class */ (function () {
  85225. function DebugLayer(scene) {
  85226. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85227. this._scene = scene;
  85228. // load inspector using require, if it doesn't exist on the global namespace.
  85229. }
  85230. /** Creates the inspector window. */
  85231. DebugLayer.prototype._createInspector = function (config) {
  85232. if (config === void 0) { config = {}; }
  85233. var popup = config.popup || false;
  85234. var initialTab = config.initialTab || 0;
  85235. var parentElement = config.parentElement || null;
  85236. if (!this._inspector) {
  85237. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85238. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85239. } // else nothing to do,; instance is already existing
  85240. };
  85241. DebugLayer.prototype.isVisible = function () {
  85242. if (!this._inspector) {
  85243. return false;
  85244. }
  85245. return true;
  85246. };
  85247. DebugLayer.prototype.hide = function () {
  85248. if (this._inspector) {
  85249. try {
  85250. this._inspector.dispose();
  85251. }
  85252. catch (e) {
  85253. // If the inspector has been removed directly from the inspector tool
  85254. }
  85255. this._inspector = null;
  85256. }
  85257. };
  85258. DebugLayer.prototype.show = function (config) {
  85259. if (config === void 0) { config = {}; }
  85260. if (typeof this.BJSINSPECTOR == 'undefined') {
  85261. // Load inspector and add it to the DOM
  85262. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85263. }
  85264. else {
  85265. // Otherwise creates the inspector
  85266. this._createInspector(config);
  85267. }
  85268. };
  85269. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85270. return DebugLayer;
  85271. }());
  85272. BABYLON.DebugLayer = DebugLayer;
  85273. })(BABYLON || (BABYLON = {}));
  85274. //# sourceMappingURL=babylon.debugLayer.js.map
  85275. var BABYLON;
  85276. (function (BABYLON) {
  85277. var Debug;
  85278. (function (Debug) {
  85279. /**
  85280. * Used to show the physics impostor around the specific mesh.
  85281. */
  85282. var PhysicsViewer = /** @class */ (function () {
  85283. function PhysicsViewer(scene) {
  85284. this._impostors = [];
  85285. this._meshes = [];
  85286. this._numMeshes = 0;
  85287. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85288. var physicEngine = this._scene.getPhysicsEngine();
  85289. if (physicEngine) {
  85290. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85291. }
  85292. }
  85293. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85294. var plugin = this._physicsEnginePlugin;
  85295. for (var i = 0; i < this._numMeshes; i++) {
  85296. var impostor = this._impostors[i];
  85297. if (!impostor) {
  85298. continue;
  85299. }
  85300. if (impostor.isDisposed) {
  85301. this.hideImpostor(this._impostors[i--]);
  85302. }
  85303. else {
  85304. var mesh = this._meshes[i];
  85305. if (mesh && plugin) {
  85306. plugin.syncMeshWithImpostor(mesh, impostor);
  85307. }
  85308. }
  85309. }
  85310. };
  85311. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85312. if (!this._scene) {
  85313. return;
  85314. }
  85315. for (var i = 0; i < this._numMeshes; i++) {
  85316. if (this._impostors[i] == impostor) {
  85317. return;
  85318. }
  85319. }
  85320. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85321. if (debugMesh) {
  85322. this._impostors[this._numMeshes] = impostor;
  85323. this._meshes[this._numMeshes] = debugMesh;
  85324. if (this._numMeshes === 0) {
  85325. this._renderFunction = this._updateDebugMeshes.bind(this);
  85326. this._scene.registerBeforeRender(this._renderFunction);
  85327. }
  85328. this._numMeshes++;
  85329. }
  85330. };
  85331. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85332. if (!impostor || !this._scene) {
  85333. return;
  85334. }
  85335. var removed = false;
  85336. for (var i = 0; i < this._numMeshes; i++) {
  85337. if (this._impostors[i] == impostor) {
  85338. var mesh = this._meshes[i];
  85339. if (!mesh) {
  85340. continue;
  85341. }
  85342. this._scene.removeMesh(mesh);
  85343. mesh.dispose();
  85344. this._numMeshes--;
  85345. if (this._numMeshes > 0) {
  85346. this._meshes[i] = this._meshes[this._numMeshes];
  85347. this._impostors[i] = this._impostors[this._numMeshes];
  85348. this._meshes[this._numMeshes] = null;
  85349. this._impostors[this._numMeshes] = null;
  85350. }
  85351. else {
  85352. this._meshes[0] = null;
  85353. this._impostors[0] = null;
  85354. }
  85355. removed = true;
  85356. break;
  85357. }
  85358. }
  85359. if (removed && this._numMeshes === 0) {
  85360. this._scene.unregisterBeforeRender(this._renderFunction);
  85361. }
  85362. };
  85363. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85364. if (!this._debugMaterial) {
  85365. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85366. this._debugMaterial.wireframe = true;
  85367. }
  85368. return this._debugMaterial;
  85369. };
  85370. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85371. if (!this._debugBoxMesh) {
  85372. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85373. this._debugBoxMesh.renderingGroupId = 1;
  85374. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85375. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85376. scene.removeMesh(this._debugBoxMesh);
  85377. }
  85378. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85379. };
  85380. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  85381. if (!this._debugSphereMesh) {
  85382. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  85383. this._debugSphereMesh.renderingGroupId = 1;
  85384. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85385. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  85386. scene.removeMesh(this._debugSphereMesh);
  85387. }
  85388. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  85389. };
  85390. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  85391. var mesh = null;
  85392. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  85393. mesh = this._getDebugBoxMesh(scene);
  85394. impostor.getBoxSizeToRef(mesh.scaling);
  85395. }
  85396. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  85397. mesh = this._getDebugSphereMesh(scene);
  85398. var radius = impostor.getRadius();
  85399. mesh.scaling.x = radius * 2;
  85400. mesh.scaling.y = radius * 2;
  85401. mesh.scaling.z = radius * 2;
  85402. }
  85403. return mesh;
  85404. };
  85405. PhysicsViewer.prototype.dispose = function () {
  85406. for (var i = 0; i < this._numMeshes; i++) {
  85407. this.hideImpostor(this._impostors[i]);
  85408. }
  85409. if (this._debugBoxMesh) {
  85410. this._debugBoxMesh.dispose();
  85411. }
  85412. if (this._debugSphereMesh) {
  85413. this._debugSphereMesh.dispose();
  85414. }
  85415. if (this._debugMaterial) {
  85416. this._debugMaterial.dispose();
  85417. }
  85418. this._impostors.length = 0;
  85419. this._scene = null;
  85420. this._physicsEnginePlugin = null;
  85421. };
  85422. return PhysicsViewer;
  85423. }());
  85424. Debug.PhysicsViewer = PhysicsViewer;
  85425. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85426. })(BABYLON || (BABYLON = {}));
  85427. //# sourceMappingURL=babylon.physicsViewer.js.map
  85428. var BABYLON;
  85429. (function (BABYLON) {
  85430. var BoundingBoxRenderer = /** @class */ (function () {
  85431. function BoundingBoxRenderer(scene) {
  85432. this.frontColor = new BABYLON.Color3(1, 1, 1);
  85433. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  85434. this.showBackLines = true;
  85435. this.renderList = new BABYLON.SmartArray(32);
  85436. this._vertexBuffers = {};
  85437. this._scene = scene;
  85438. }
  85439. BoundingBoxRenderer.prototype._prepareRessources = function () {
  85440. if (this._colorShader) {
  85441. return;
  85442. }
  85443. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  85444. attributes: [BABYLON.VertexBuffer.PositionKind],
  85445. uniforms: ["world", "viewProjection", "color"]
  85446. });
  85447. var engine = this._scene.getEngine();
  85448. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  85449. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  85450. this._createIndexBuffer();
  85451. };
  85452. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  85453. var engine = this._scene.getEngine();
  85454. 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]);
  85455. };
  85456. BoundingBoxRenderer.prototype._rebuild = function () {
  85457. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85458. if (vb) {
  85459. vb._rebuild();
  85460. }
  85461. this._createIndexBuffer();
  85462. };
  85463. BoundingBoxRenderer.prototype.reset = function () {
  85464. this.renderList.reset();
  85465. };
  85466. BoundingBoxRenderer.prototype.render = function () {
  85467. if (this.renderList.length === 0) {
  85468. return;
  85469. }
  85470. this._prepareRessources();
  85471. if (!this._colorShader.isReady()) {
  85472. return;
  85473. }
  85474. var engine = this._scene.getEngine();
  85475. engine.setDepthWrite(false);
  85476. this._colorShader._preBind();
  85477. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  85478. var boundingBox = this.renderList.data[boundingBoxIndex];
  85479. var min = boundingBox.minimum;
  85480. var max = boundingBox.maximum;
  85481. var diff = max.subtract(min);
  85482. var median = min.add(diff.scale(0.5));
  85483. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85484. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85485. .multiply(boundingBox.getWorldMatrix());
  85486. // VBOs
  85487. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85488. if (this.showBackLines) {
  85489. // Back
  85490. engine.setDepthFunctionToGreaterOrEqual();
  85491. this._scene.resetCachedMaterial();
  85492. this._colorShader.setColor4("color", this.backColor.toColor4());
  85493. this._colorShader.bind(worldMatrix);
  85494. // Draw order
  85495. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85496. }
  85497. // Front
  85498. engine.setDepthFunctionToLess();
  85499. this._scene.resetCachedMaterial();
  85500. this._colorShader.setColor4("color", this.frontColor.toColor4());
  85501. this._colorShader.bind(worldMatrix);
  85502. // Draw order
  85503. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85504. }
  85505. this._colorShader.unbind();
  85506. engine.setDepthFunctionToLessOrEqual();
  85507. engine.setDepthWrite(true);
  85508. };
  85509. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  85510. this._prepareRessources();
  85511. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  85512. return;
  85513. }
  85514. var engine = this._scene.getEngine();
  85515. engine.setDepthWrite(false);
  85516. engine.setColorWrite(false);
  85517. this._colorShader._preBind();
  85518. var boundingBox = mesh._boundingInfo.boundingBox;
  85519. var min = boundingBox.minimum;
  85520. var max = boundingBox.maximum;
  85521. var diff = max.subtract(min);
  85522. var median = min.add(diff.scale(0.5));
  85523. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85524. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85525. .multiply(boundingBox.getWorldMatrix());
  85526. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85527. engine.setDepthFunctionToLess();
  85528. this._scene.resetCachedMaterial();
  85529. this._colorShader.bind(worldMatrix);
  85530. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85531. this._colorShader.unbind();
  85532. engine.setDepthFunctionToLessOrEqual();
  85533. engine.setDepthWrite(true);
  85534. engine.setColorWrite(true);
  85535. };
  85536. BoundingBoxRenderer.prototype.dispose = function () {
  85537. if (!this._colorShader) {
  85538. return;
  85539. }
  85540. this.renderList.dispose();
  85541. this._colorShader.dispose();
  85542. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85543. if (buffer) {
  85544. buffer.dispose();
  85545. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85546. }
  85547. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85548. };
  85549. return BoundingBoxRenderer;
  85550. }());
  85551. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  85552. })(BABYLON || (BABYLON = {}));
  85553. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  85554. var BABYLON;
  85555. (function (BABYLON) {
  85556. /**
  85557. * Defines a target to use with MorphTargetManager
  85558. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85559. */
  85560. var MorphTarget = /** @class */ (function () {
  85561. /**
  85562. * Creates a new MorphTarget
  85563. * @param name defines the name of the target
  85564. * @param influence defines the influence to use
  85565. */
  85566. function MorphTarget(
  85567. /** defines the name of the target */
  85568. name, influence) {
  85569. if (influence === void 0) { influence = 0; }
  85570. this.name = name;
  85571. /**
  85572. * Gets or sets the list of animations
  85573. */
  85574. this.animations = new Array();
  85575. this._positions = null;
  85576. this._normals = null;
  85577. this._tangents = null;
  85578. /**
  85579. * Observable raised when the influence changes
  85580. */
  85581. this.onInfluenceChanged = new BABYLON.Observable();
  85582. this.influence = influence;
  85583. }
  85584. Object.defineProperty(MorphTarget.prototype, "influence", {
  85585. /**
  85586. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  85587. */
  85588. get: function () {
  85589. return this._influence;
  85590. },
  85591. set: function (influence) {
  85592. if (this._influence === influence) {
  85593. return;
  85594. }
  85595. var previous = this._influence;
  85596. this._influence = influence;
  85597. if (this.onInfluenceChanged.hasObservers) {
  85598. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  85599. }
  85600. },
  85601. enumerable: true,
  85602. configurable: true
  85603. });
  85604. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  85605. /**
  85606. * Gets a boolean defining if the target contains position data
  85607. */
  85608. get: function () {
  85609. return !!this._positions;
  85610. },
  85611. enumerable: true,
  85612. configurable: true
  85613. });
  85614. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  85615. /**
  85616. * Gets a boolean defining if the target contains normal data
  85617. */
  85618. get: function () {
  85619. return !!this._normals;
  85620. },
  85621. enumerable: true,
  85622. configurable: true
  85623. });
  85624. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  85625. /**
  85626. * Gets a boolean defining if the target contains tangent data
  85627. */
  85628. get: function () {
  85629. return !!this._tangents;
  85630. },
  85631. enumerable: true,
  85632. configurable: true
  85633. });
  85634. /**
  85635. * Affects position data to this target
  85636. * @param data defines the position data to use
  85637. */
  85638. MorphTarget.prototype.setPositions = function (data) {
  85639. this._positions = data;
  85640. };
  85641. /**
  85642. * Gets the position data stored in this target
  85643. * @returns a FloatArray containing the position data (or null if not present)
  85644. */
  85645. MorphTarget.prototype.getPositions = function () {
  85646. return this._positions;
  85647. };
  85648. /**
  85649. * Affects normal data to this target
  85650. * @param data defines the normal data to use
  85651. */
  85652. MorphTarget.prototype.setNormals = function (data) {
  85653. this._normals = data;
  85654. };
  85655. /**
  85656. * Gets the normal data stored in this target
  85657. * @returns a FloatArray containing the normal data (or null if not present)
  85658. */
  85659. MorphTarget.prototype.getNormals = function () {
  85660. return this._normals;
  85661. };
  85662. /**
  85663. * Affects tangent data to this target
  85664. * @param data defines the tangent data to use
  85665. */
  85666. MorphTarget.prototype.setTangents = function (data) {
  85667. this._tangents = data;
  85668. };
  85669. /**
  85670. * Gets the tangent data stored in this target
  85671. * @returns a FloatArray containing the tangent data (or null if not present)
  85672. */
  85673. MorphTarget.prototype.getTangents = function () {
  85674. return this._tangents;
  85675. };
  85676. /**
  85677. * Serializes the current target into a Serialization object
  85678. * @returns the serialized object
  85679. */
  85680. MorphTarget.prototype.serialize = function () {
  85681. var serializationObject = {};
  85682. serializationObject.name = this.name;
  85683. serializationObject.influence = this.influence;
  85684. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85685. if (this.hasNormals) {
  85686. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85687. }
  85688. if (this.hasTangents) {
  85689. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85690. }
  85691. // Animations
  85692. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85693. return serializationObject;
  85694. };
  85695. // Statics
  85696. /**
  85697. * Creates a new target from serialized data
  85698. * @param serializationObject defines the serialized data to use
  85699. * @returns a new MorphTarget
  85700. */
  85701. MorphTarget.Parse = function (serializationObject) {
  85702. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85703. result.setPositions(serializationObject.positions);
  85704. if (serializationObject.normals) {
  85705. result.setNormals(serializationObject.normals);
  85706. }
  85707. if (serializationObject.tangents) {
  85708. result.setTangents(serializationObject.tangents);
  85709. }
  85710. // Animations
  85711. if (serializationObject.animations) {
  85712. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85713. var parsedAnimation = serializationObject.animations[animationIndex];
  85714. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85715. }
  85716. }
  85717. return result;
  85718. };
  85719. /**
  85720. * Creates a MorphTarget from mesh data
  85721. * @param mesh defines the source mesh
  85722. * @param name defines the name to use for the new target
  85723. * @param influence defines the influence to attach to the target
  85724. * @returns a new MorphTarget
  85725. */
  85726. MorphTarget.FromMesh = function (mesh, name, influence) {
  85727. if (!name) {
  85728. name = mesh.name;
  85729. }
  85730. var result = new MorphTarget(name, influence);
  85731. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85732. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85733. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  85734. }
  85735. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  85736. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  85737. }
  85738. return result;
  85739. };
  85740. return MorphTarget;
  85741. }());
  85742. BABYLON.MorphTarget = MorphTarget;
  85743. })(BABYLON || (BABYLON = {}));
  85744. //# sourceMappingURL=babylon.morphTarget.js.map
  85745. var BABYLON;
  85746. (function (BABYLON) {
  85747. /**
  85748. * This class is used to deform meshes using morphing between different targets
  85749. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85750. */
  85751. var MorphTargetManager = /** @class */ (function () {
  85752. /**
  85753. * Creates a new MorphTargetManager
  85754. * @param scene defines the current scene
  85755. */
  85756. function MorphTargetManager(scene) {
  85757. if (scene === void 0) { scene = null; }
  85758. this._targets = new Array();
  85759. this._targetObservable = new Array();
  85760. this._activeTargets = new BABYLON.SmartArray(16);
  85761. this._supportsNormals = false;
  85762. this._supportsTangents = false;
  85763. this._vertexCount = 0;
  85764. this._uniqueId = 0;
  85765. this._tempInfluences = new Array();
  85766. if (!scene) {
  85767. scene = BABYLON.Engine.LastCreatedScene;
  85768. }
  85769. this._scene = scene;
  85770. if (this._scene) {
  85771. this._scene.morphTargetManagers.push(this);
  85772. this._uniqueId = this._scene.getUniqueId();
  85773. }
  85774. }
  85775. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  85776. /**
  85777. * Gets the unique ID of this manager
  85778. */
  85779. get: function () {
  85780. return this._uniqueId;
  85781. },
  85782. enumerable: true,
  85783. configurable: true
  85784. });
  85785. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  85786. /**
  85787. * Gets the number of vertices handled by this manager
  85788. */
  85789. get: function () {
  85790. return this._vertexCount;
  85791. },
  85792. enumerable: true,
  85793. configurable: true
  85794. });
  85795. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  85796. /**
  85797. * Gets a boolean indicating if this manager supports morphing of normals
  85798. */
  85799. get: function () {
  85800. return this._supportsNormals;
  85801. },
  85802. enumerable: true,
  85803. configurable: true
  85804. });
  85805. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  85806. /**
  85807. * Gets a boolean indicating if this manager supports morphing of tangents
  85808. */
  85809. get: function () {
  85810. return this._supportsTangents;
  85811. },
  85812. enumerable: true,
  85813. configurable: true
  85814. });
  85815. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  85816. /**
  85817. * Gets the number of targets stored in this manager
  85818. */
  85819. get: function () {
  85820. return this._targets.length;
  85821. },
  85822. enumerable: true,
  85823. configurable: true
  85824. });
  85825. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  85826. /**
  85827. * Gets the number of influencers (ie. the number of targets with influences > 0)
  85828. */
  85829. get: function () {
  85830. return this._activeTargets.length;
  85831. },
  85832. enumerable: true,
  85833. configurable: true
  85834. });
  85835. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  85836. /**
  85837. * Gets the list of influences (one per target)
  85838. */
  85839. get: function () {
  85840. return this._influences;
  85841. },
  85842. enumerable: true,
  85843. configurable: true
  85844. });
  85845. /**
  85846. * Gets the active target at specified index. An active target is a target with an influence > 0
  85847. * @param index defines the index to check
  85848. * @returns the requested target
  85849. */
  85850. MorphTargetManager.prototype.getActiveTarget = function (index) {
  85851. return this._activeTargets.data[index];
  85852. };
  85853. /**
  85854. * Gets the target at specified index
  85855. * @param index defines the index to check
  85856. * @returns the requested target
  85857. */
  85858. MorphTargetManager.prototype.getTarget = function (index) {
  85859. return this._targets[index];
  85860. };
  85861. /**
  85862. * Add a new target to this manager
  85863. * @param target defines the target to add
  85864. */
  85865. MorphTargetManager.prototype.addTarget = function (target) {
  85866. var _this = this;
  85867. this._targets.push(target);
  85868. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  85869. _this._syncActiveTargets(needUpdate);
  85870. }));
  85871. this._syncActiveTargets(true);
  85872. };
  85873. /**
  85874. * Removes a target from the manager
  85875. * @param target defines the target to remove
  85876. */
  85877. MorphTargetManager.prototype.removeTarget = function (target) {
  85878. var index = this._targets.indexOf(target);
  85879. if (index >= 0) {
  85880. this._targets.splice(index, 1);
  85881. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  85882. this._syncActiveTargets(true);
  85883. }
  85884. };
  85885. /**
  85886. * Serializes the current manager into a Serialization object
  85887. * @returns the serialized object
  85888. */
  85889. MorphTargetManager.prototype.serialize = function () {
  85890. var serializationObject = {};
  85891. serializationObject.id = this.uniqueId;
  85892. serializationObject.targets = [];
  85893. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85894. var target = _a[_i];
  85895. serializationObject.targets.push(target.serialize());
  85896. }
  85897. return serializationObject;
  85898. };
  85899. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  85900. var influenceCount = 0;
  85901. this._activeTargets.reset();
  85902. this._supportsNormals = true;
  85903. this._supportsTangents = true;
  85904. this._vertexCount = 0;
  85905. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85906. var target = _a[_i];
  85907. this._activeTargets.push(target);
  85908. this._tempInfluences[influenceCount++] = target.influence;
  85909. var positions = target.getPositions();
  85910. if (positions) {
  85911. this._supportsNormals = this._supportsNormals && target.hasNormals;
  85912. this._supportsTangents = this._supportsTangents && target.hasTangents;
  85913. var vertexCount = positions.length / 3;
  85914. if (this._vertexCount === 0) {
  85915. this._vertexCount = vertexCount;
  85916. }
  85917. else if (this._vertexCount !== vertexCount) {
  85918. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  85919. return;
  85920. }
  85921. }
  85922. }
  85923. if (!this._influences || this._influences.length !== influenceCount) {
  85924. this._influences = new Float32Array(influenceCount);
  85925. }
  85926. for (var index = 0; index < influenceCount; index++) {
  85927. this._influences[index] = this._tempInfluences[index];
  85928. }
  85929. if (needUpdate) {
  85930. this.synchronize();
  85931. }
  85932. };
  85933. /**
  85934. * Syncrhonize the targets with all the meshes using this morph target manager
  85935. */
  85936. MorphTargetManager.prototype.synchronize = function () {
  85937. if (!this._scene) {
  85938. return;
  85939. }
  85940. // Flag meshes as dirty to resync with the active targets
  85941. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  85942. var mesh = _a[_i];
  85943. if (mesh.morphTargetManager === this) {
  85944. mesh._syncGeometryWithMorphTargetManager();
  85945. }
  85946. }
  85947. };
  85948. // Statics
  85949. /**
  85950. * Creates a new MorphTargetManager from serialized data
  85951. * @param serializationObject defines the serialized data
  85952. * @param scene defines the hosting scene
  85953. * @returns the new MorphTargetManager
  85954. */
  85955. MorphTargetManager.Parse = function (serializationObject, scene) {
  85956. var result = new MorphTargetManager(scene);
  85957. result._uniqueId = serializationObject.id;
  85958. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  85959. var targetData = _a[_i];
  85960. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  85961. }
  85962. return result;
  85963. };
  85964. return MorphTargetManager;
  85965. }());
  85966. BABYLON.MorphTargetManager = MorphTargetManager;
  85967. })(BABYLON || (BABYLON = {}));
  85968. //# sourceMappingURL=babylon.morphTargetManager.js.map
  85969. var BABYLON;
  85970. (function (BABYLON) {
  85971. var Octree = /** @class */ (function () {
  85972. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  85973. if (maxDepth === void 0) { maxDepth = 2; }
  85974. this.maxDepth = maxDepth;
  85975. this.dynamicContent = new Array();
  85976. this._maxBlockCapacity = maxBlockCapacity || 64;
  85977. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  85978. this._creationFunc = creationFunc;
  85979. }
  85980. // Methods
  85981. Octree.prototype.update = function (worldMin, worldMax, entries) {
  85982. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  85983. };
  85984. Octree.prototype.addMesh = function (entry) {
  85985. for (var index = 0; index < this.blocks.length; index++) {
  85986. var block = this.blocks[index];
  85987. block.addEntry(entry);
  85988. }
  85989. };
  85990. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  85991. this._selectionContent.reset();
  85992. for (var index = 0; index < this.blocks.length; index++) {
  85993. var block = this.blocks[index];
  85994. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  85995. }
  85996. if (allowDuplicate) {
  85997. this._selectionContent.concat(this.dynamicContent);
  85998. }
  85999. else {
  86000. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86001. }
  86002. return this._selectionContent;
  86003. };
  86004. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  86005. this._selectionContent.reset();
  86006. for (var index = 0; index < this.blocks.length; index++) {
  86007. var block = this.blocks[index];
  86008. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  86009. }
  86010. if (allowDuplicate) {
  86011. this._selectionContent.concat(this.dynamicContent);
  86012. }
  86013. else {
  86014. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86015. }
  86016. return this._selectionContent;
  86017. };
  86018. Octree.prototype.intersectsRay = function (ray) {
  86019. this._selectionContent.reset();
  86020. for (var index = 0; index < this.blocks.length; index++) {
  86021. var block = this.blocks[index];
  86022. block.intersectsRay(ray, this._selectionContent);
  86023. }
  86024. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86025. return this._selectionContent;
  86026. };
  86027. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  86028. target.blocks = new Array();
  86029. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  86030. // Segmenting space
  86031. for (var x = 0; x < 2; x++) {
  86032. for (var y = 0; y < 2; y++) {
  86033. for (var z = 0; z < 2; z++) {
  86034. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  86035. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  86036. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  86037. block.addEntries(entries);
  86038. target.blocks.push(block);
  86039. }
  86040. }
  86041. }
  86042. };
  86043. Octree.CreationFuncForMeshes = function (entry, block) {
  86044. var boundingInfo = entry.getBoundingInfo();
  86045. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86046. block.entries.push(entry);
  86047. }
  86048. };
  86049. Octree.CreationFuncForSubMeshes = function (entry, block) {
  86050. var boundingInfo = entry.getBoundingInfo();
  86051. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86052. block.entries.push(entry);
  86053. }
  86054. };
  86055. return Octree;
  86056. }());
  86057. BABYLON.Octree = Octree;
  86058. })(BABYLON || (BABYLON = {}));
  86059. //# sourceMappingURL=babylon.octree.js.map
  86060. var BABYLON;
  86061. (function (BABYLON) {
  86062. var OctreeBlock = /** @class */ (function () {
  86063. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  86064. this.entries = new Array();
  86065. this._boundingVectors = new Array();
  86066. this._capacity = capacity;
  86067. this._depth = depth;
  86068. this._maxDepth = maxDepth;
  86069. this._creationFunc = creationFunc;
  86070. this._minPoint = minPoint;
  86071. this._maxPoint = maxPoint;
  86072. this._boundingVectors.push(minPoint.clone());
  86073. this._boundingVectors.push(maxPoint.clone());
  86074. this._boundingVectors.push(minPoint.clone());
  86075. this._boundingVectors[2].x = maxPoint.x;
  86076. this._boundingVectors.push(minPoint.clone());
  86077. this._boundingVectors[3].y = maxPoint.y;
  86078. this._boundingVectors.push(minPoint.clone());
  86079. this._boundingVectors[4].z = maxPoint.z;
  86080. this._boundingVectors.push(maxPoint.clone());
  86081. this._boundingVectors[5].z = minPoint.z;
  86082. this._boundingVectors.push(maxPoint.clone());
  86083. this._boundingVectors[6].x = minPoint.x;
  86084. this._boundingVectors.push(maxPoint.clone());
  86085. this._boundingVectors[7].y = minPoint.y;
  86086. }
  86087. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  86088. // Property
  86089. get: function () {
  86090. return this._capacity;
  86091. },
  86092. enumerable: true,
  86093. configurable: true
  86094. });
  86095. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  86096. get: function () {
  86097. return this._minPoint;
  86098. },
  86099. enumerable: true,
  86100. configurable: true
  86101. });
  86102. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  86103. get: function () {
  86104. return this._maxPoint;
  86105. },
  86106. enumerable: true,
  86107. configurable: true
  86108. });
  86109. // Methods
  86110. OctreeBlock.prototype.addEntry = function (entry) {
  86111. if (this.blocks) {
  86112. for (var index = 0; index < this.blocks.length; index++) {
  86113. var block = this.blocks[index];
  86114. block.addEntry(entry);
  86115. }
  86116. return;
  86117. }
  86118. this._creationFunc(entry, this);
  86119. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  86120. this.createInnerBlocks();
  86121. }
  86122. };
  86123. OctreeBlock.prototype.addEntries = function (entries) {
  86124. for (var index = 0; index < entries.length; index++) {
  86125. var mesh = entries[index];
  86126. this.addEntry(mesh);
  86127. }
  86128. };
  86129. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  86130. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  86131. if (this.blocks) {
  86132. for (var index = 0; index < this.blocks.length; index++) {
  86133. var block = this.blocks[index];
  86134. block.select(frustumPlanes, selection, allowDuplicate);
  86135. }
  86136. return;
  86137. }
  86138. if (allowDuplicate) {
  86139. selection.concat(this.entries);
  86140. }
  86141. else {
  86142. selection.concatWithNoDuplicate(this.entries);
  86143. }
  86144. }
  86145. };
  86146. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  86147. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  86148. if (this.blocks) {
  86149. for (var index = 0; index < this.blocks.length; index++) {
  86150. var block = this.blocks[index];
  86151. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  86152. }
  86153. return;
  86154. }
  86155. if (allowDuplicate) {
  86156. selection.concat(this.entries);
  86157. }
  86158. else {
  86159. selection.concatWithNoDuplicate(this.entries);
  86160. }
  86161. }
  86162. };
  86163. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  86164. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  86165. if (this.blocks) {
  86166. for (var index = 0; index < this.blocks.length; index++) {
  86167. var block = this.blocks[index];
  86168. block.intersectsRay(ray, selection);
  86169. }
  86170. return;
  86171. }
  86172. selection.concatWithNoDuplicate(this.entries);
  86173. }
  86174. };
  86175. OctreeBlock.prototype.createInnerBlocks = function () {
  86176. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  86177. };
  86178. return OctreeBlock;
  86179. }());
  86180. BABYLON.OctreeBlock = OctreeBlock;
  86181. })(BABYLON || (BABYLON = {}));
  86182. //# sourceMappingURL=babylon.octreeBlock.js.map
  86183. var BABYLON;
  86184. (function (BABYLON) {
  86185. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86186. __extends(VRDistortionCorrectionPostProcess, _super);
  86187. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86188. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86189. 'LensCenter',
  86190. 'Scale',
  86191. 'ScaleIn',
  86192. 'HmdWarpParam'
  86193. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86194. _this._isRightEye = isRightEye;
  86195. _this._distortionFactors = vrMetrics.distortionK;
  86196. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86197. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86198. _this.adaptScaleToCurrentViewport = true;
  86199. _this.onSizeChangedObservable.add(function () {
  86200. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86201. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86202. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86203. });
  86204. _this.onApplyObservable.add(function (effect) {
  86205. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86206. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86207. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86208. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86209. });
  86210. return _this;
  86211. }
  86212. return VRDistortionCorrectionPostProcess;
  86213. }(BABYLON.PostProcess));
  86214. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  86215. })(BABYLON || (BABYLON = {}));
  86216. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  86217. var BABYLON;
  86218. (function (BABYLON) {
  86219. /**
  86220. * Postprocess used to generate anaglyphic rendering
  86221. */
  86222. var AnaglyphPostProcess = /** @class */ (function (_super) {
  86223. __extends(AnaglyphPostProcess, _super);
  86224. /**
  86225. * Creates a new AnaglyphPostProcess
  86226. * @param name defines postprocess name
  86227. * @param options defines creation options or target ratio scale
  86228. * @param rigCameras defines cameras using this postprocess
  86229. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  86230. * @param engine defines hosting engine
  86231. * @param reusable defines if the postprocess will be reused multiple times per frame
  86232. */
  86233. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  86234. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  86235. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86236. _this.onApplyObservable.add(function (effect) {
  86237. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  86238. });
  86239. return _this;
  86240. }
  86241. return AnaglyphPostProcess;
  86242. }(BABYLON.PostProcess));
  86243. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  86244. })(BABYLON || (BABYLON = {}));
  86245. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  86246. var BABYLON;
  86247. (function (BABYLON) {
  86248. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  86249. __extends(StereoscopicInterlacePostProcess, _super);
  86250. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  86251. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  86252. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86253. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86254. _this.onSizeChangedObservable.add(function () {
  86255. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86256. });
  86257. _this.onApplyObservable.add(function (effect) {
  86258. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  86259. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  86260. });
  86261. return _this;
  86262. }
  86263. return StereoscopicInterlacePostProcess;
  86264. }(BABYLON.PostProcess));
  86265. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  86266. })(BABYLON || (BABYLON = {}));
  86267. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  86268. var BABYLON;
  86269. (function (BABYLON) {
  86270. /**
  86271. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  86272. * Screen rotation is taken into account.
  86273. */
  86274. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  86275. function FreeCameraDeviceOrientationInput() {
  86276. var _this = this;
  86277. this._screenOrientationAngle = 0;
  86278. this._screenQuaternion = new BABYLON.Quaternion();
  86279. this._alpha = 0;
  86280. this._beta = 0;
  86281. this._gamma = 0;
  86282. this._orientationChanged = function () {
  86283. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  86284. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  86285. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  86286. };
  86287. this._deviceOrientation = function (evt) {
  86288. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  86289. _this._beta = evt.beta !== null ? evt.beta : 0;
  86290. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  86291. };
  86292. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  86293. this._orientationChanged();
  86294. }
  86295. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  86296. get: function () {
  86297. return this._camera;
  86298. },
  86299. set: function (camera) {
  86300. this._camera = camera;
  86301. if (this._camera != null && !this._camera.rotationQuaternion) {
  86302. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  86303. }
  86304. },
  86305. enumerable: true,
  86306. configurable: true
  86307. });
  86308. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86309. window.addEventListener("orientationchange", this._orientationChanged);
  86310. window.addEventListener("deviceorientation", this._deviceOrientation);
  86311. //In certain cases, the attach control is called AFTER orientation was changed,
  86312. //So this is needed.
  86313. this._orientationChanged();
  86314. };
  86315. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  86316. window.removeEventListener("orientationchange", this._orientationChanged);
  86317. window.removeEventListener("deviceorientation", this._deviceOrientation);
  86318. };
  86319. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  86320. //if no device orientation provided, don't update the rotation.
  86321. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  86322. if (!this._alpha)
  86323. return;
  86324. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  86325. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  86326. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  86327. //Mirror on XY Plane
  86328. this._camera.rotationQuaternion.z *= -1;
  86329. this._camera.rotationQuaternion.w *= -1;
  86330. };
  86331. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  86332. return "FreeCameraDeviceOrientationInput";
  86333. };
  86334. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  86335. return "deviceOrientation";
  86336. };
  86337. return FreeCameraDeviceOrientationInput;
  86338. }());
  86339. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  86340. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  86341. })(BABYLON || (BABYLON = {}));
  86342. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  86343. var BABYLON;
  86344. (function (BABYLON) {
  86345. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  86346. function ArcRotateCameraVRDeviceOrientationInput() {
  86347. this.alphaCorrection = 1;
  86348. this.betaCorrection = 1;
  86349. this.gammaCorrection = 1;
  86350. this._alpha = 0;
  86351. this._gamma = 0;
  86352. this._dirty = false;
  86353. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  86354. }
  86355. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86356. this.camera.attachControl(element, noPreventDefault);
  86357. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  86358. };
  86359. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  86360. if (evt.alpha !== null) {
  86361. this._alpha = +evt.alpha | 0;
  86362. }
  86363. if (evt.gamma !== null) {
  86364. this._gamma = +evt.gamma | 0;
  86365. }
  86366. this._dirty = true;
  86367. };
  86368. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  86369. if (this._dirty) {
  86370. this._dirty = false;
  86371. if (this._gamma < 0) {
  86372. this._gamma = 180 + this._gamma;
  86373. }
  86374. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  86375. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  86376. }
  86377. };
  86378. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  86379. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  86380. };
  86381. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  86382. return "ArcRotateCameraVRDeviceOrientationInput";
  86383. };
  86384. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  86385. return "VRDeviceOrientation";
  86386. };
  86387. return ArcRotateCameraVRDeviceOrientationInput;
  86388. }());
  86389. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  86390. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  86391. })(BABYLON || (BABYLON = {}));
  86392. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  86393. var BABYLON;
  86394. (function (BABYLON) {
  86395. var VRCameraMetrics = /** @class */ (function () {
  86396. function VRCameraMetrics() {
  86397. this.compensateDistortion = true;
  86398. }
  86399. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  86400. get: function () {
  86401. return this.hResolution / (2 * this.vResolution);
  86402. },
  86403. enumerable: true,
  86404. configurable: true
  86405. });
  86406. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  86407. get: function () {
  86408. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  86409. },
  86410. enumerable: true,
  86411. configurable: true
  86412. });
  86413. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  86414. get: function () {
  86415. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86416. var h = (4 * meters) / this.hScreenSize;
  86417. return BABYLON.Matrix.Translation(h, 0, 0);
  86418. },
  86419. enumerable: true,
  86420. configurable: true
  86421. });
  86422. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  86423. get: function () {
  86424. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86425. var h = (4 * meters) / this.hScreenSize;
  86426. return BABYLON.Matrix.Translation(-h, 0, 0);
  86427. },
  86428. enumerable: true,
  86429. configurable: true
  86430. });
  86431. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  86432. get: function () {
  86433. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  86434. },
  86435. enumerable: true,
  86436. configurable: true
  86437. });
  86438. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  86439. get: function () {
  86440. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  86441. },
  86442. enumerable: true,
  86443. configurable: true
  86444. });
  86445. VRCameraMetrics.GetDefault = function () {
  86446. var result = new VRCameraMetrics();
  86447. result.hResolution = 1280;
  86448. result.vResolution = 800;
  86449. result.hScreenSize = 0.149759993;
  86450. result.vScreenSize = 0.0935999975;
  86451. result.vScreenCenter = 0.0467999987;
  86452. result.eyeToScreenDistance = 0.0410000011;
  86453. result.lensSeparationDistance = 0.0635000020;
  86454. result.interpupillaryDistance = 0.0640000030;
  86455. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  86456. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  86457. result.postProcessScaleFactor = 1.714605507808412;
  86458. result.lensCenterOffset = 0.151976421;
  86459. return result;
  86460. };
  86461. return VRCameraMetrics;
  86462. }());
  86463. BABYLON.VRCameraMetrics = VRCameraMetrics;
  86464. })(BABYLON || (BABYLON = {}));
  86465. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  86466. var BABYLON;
  86467. (function (BABYLON) {
  86468. /**
  86469. * This represents a WebVR camera.
  86470. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  86471. * @example http://doc.babylonjs.com/how_to/webvr_camera
  86472. */
  86473. var WebVRFreeCamera = /** @class */ (function (_super) {
  86474. __extends(WebVRFreeCamera, _super);
  86475. /**
  86476. * Instantiates a WebVRFreeCamera.
  86477. * @param name The name of the WebVRFreeCamera
  86478. * @param position The starting anchor position for the camera
  86479. * @param scene The scene the camera belongs to
  86480. * @param webVROptions a set of customizable options for the webVRCamera
  86481. */
  86482. function WebVRFreeCamera(name, position, scene, webVROptions) {
  86483. if (webVROptions === void 0) { webVROptions = {}; }
  86484. var _this = _super.call(this, name, position, scene) || this;
  86485. _this.webVROptions = webVROptions;
  86486. /**
  86487. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  86488. */
  86489. _this._vrDevice = null;
  86490. /**
  86491. * The rawPose of the vrDevice.
  86492. */
  86493. _this.rawPose = null;
  86494. _this._specsVersion = "1.1";
  86495. _this._attached = false;
  86496. _this._descendants = [];
  86497. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  86498. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  86499. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  86500. _this._standingMatrix = null;
  86501. /**
  86502. * Represents device position in babylon space.
  86503. */
  86504. _this.devicePosition = BABYLON.Vector3.Zero();
  86505. /**
  86506. * Represents device rotation in babylon space.
  86507. */
  86508. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  86509. /**
  86510. * The scale of the device to be used when translating from device space to babylon space.
  86511. */
  86512. _this.deviceScaleFactor = 1;
  86513. _this._deviceToWorld = BABYLON.Matrix.Identity();
  86514. _this._worldToDevice = BABYLON.Matrix.Identity();
  86515. /**
  86516. * References to the webVR controllers for the vrDevice.
  86517. */
  86518. _this.controllers = [];
  86519. /**
  86520. * Emits an event when a controller is attached.
  86521. */
  86522. _this.onControllersAttachedObservable = new BABYLON.Observable();
  86523. /**
  86524. * Emits an event when a controller's mesh has been loaded;
  86525. */
  86526. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86527. /**
  86528. * If the rig cameras be used as parent instead of this camera.
  86529. */
  86530. _this.rigParenting = true;
  86531. _this._defaultHeight = undefined;
  86532. _this._workingVector = BABYLON.Vector3.Zero();
  86533. _this._oneVector = BABYLON.Vector3.One();
  86534. _this._workingMatrix = BABYLON.Matrix.Identity();
  86535. _this._cache.position = BABYLON.Vector3.Zero();
  86536. if (webVROptions.defaultHeight) {
  86537. _this._defaultHeight = webVROptions.defaultHeight;
  86538. _this.position.y = _this._defaultHeight;
  86539. }
  86540. _this.minZ = 0.1;
  86541. //legacy support - the compensation boolean was removed.
  86542. if (arguments.length === 5) {
  86543. _this.webVROptions = arguments[4];
  86544. }
  86545. // default webVR options
  86546. if (_this.webVROptions.trackPosition == undefined) {
  86547. _this.webVROptions.trackPosition = true;
  86548. }
  86549. if (_this.webVROptions.controllerMeshes == undefined) {
  86550. _this.webVROptions.controllerMeshes = true;
  86551. }
  86552. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  86553. _this.webVROptions.defaultLightingOnControllers = true;
  86554. }
  86555. _this.rotationQuaternion = new BABYLON.Quaternion();
  86556. if (_this.webVROptions && _this.webVROptions.positionScale) {
  86557. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  86558. }
  86559. //enable VR
  86560. var engine = _this.getEngine();
  86561. _this._onVREnabled = function (success) { if (success) {
  86562. _this.initControllers();
  86563. } };
  86564. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  86565. engine.initWebVR().add(function (event) {
  86566. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  86567. return;
  86568. }
  86569. _this._vrDevice = event.vrDisplay;
  86570. //reset the rig parameters.
  86571. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  86572. if (_this._attached) {
  86573. _this.getEngine().enableVR();
  86574. }
  86575. });
  86576. if (typeof (VRFrameData) !== "undefined")
  86577. _this._frameData = new VRFrameData();
  86578. /**
  86579. * The idea behind the following lines:
  86580. * objects that have the camera as parent should actually have the rig cameras as a parent.
  86581. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  86582. * the second will not show it correctly.
  86583. *
  86584. * To solve this - each object that has the camera as parent will be added to a protected array.
  86585. * When the rig camera renders, it will take this array and set all of those to be its children.
  86586. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  86587. * Amazing!
  86588. */
  86589. scene.onBeforeCameraRenderObservable.add(function (camera) {
  86590. if (camera.parent === _this && _this.rigParenting) {
  86591. _this._descendants = _this.getDescendants(true, function (n) {
  86592. // don't take the cameras or the controllers!
  86593. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  86594. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  86595. return !isController && !isRigCamera;
  86596. });
  86597. _this._descendants.forEach(function (node) {
  86598. node.parent = camera;
  86599. });
  86600. }
  86601. });
  86602. scene.onAfterCameraRenderObservable.add(function (camera) {
  86603. if (camera.parent === _this && _this.rigParenting) {
  86604. _this._descendants.forEach(function (node) {
  86605. node.parent = _this;
  86606. });
  86607. }
  86608. });
  86609. return _this;
  86610. }
  86611. /**
  86612. * Gets the device distance from the ground in meters.
  86613. * @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.
  86614. */
  86615. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  86616. if (this._standingMatrix) {
  86617. // Add standing matrix offset to get real offset from ground in room
  86618. this._standingMatrix.getTranslationToRef(this._workingVector);
  86619. return this._deviceRoomPosition.y + this._workingVector.y;
  86620. }
  86621. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  86622. return this._defaultHeight || 0;
  86623. };
  86624. /**
  86625. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86626. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  86627. */
  86628. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  86629. var _this = this;
  86630. if (callback === void 0) { callback = function (bool) { }; }
  86631. // Use standing matrix if available
  86632. this.getEngine().initWebVRAsync().then(function (result) {
  86633. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  86634. callback(false);
  86635. }
  86636. else {
  86637. _this._standingMatrix = new BABYLON.Matrix();
  86638. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  86639. if (!_this.getScene().useRightHandedSystem) {
  86640. [2, 6, 8, 9, 14].forEach(function (num) {
  86641. if (_this._standingMatrix) {
  86642. _this._standingMatrix.m[num] *= -1;
  86643. }
  86644. });
  86645. }
  86646. callback(true);
  86647. }
  86648. });
  86649. };
  86650. /**
  86651. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86652. * @returns A promise with a boolean set to if the standing matrix is supported.
  86653. */
  86654. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  86655. var _this = this;
  86656. return new Promise(function (res, rej) {
  86657. _this.useStandingMatrix(function (supported) {
  86658. res(supported);
  86659. });
  86660. });
  86661. };
  86662. /**
  86663. * Disposes the camera
  86664. */
  86665. WebVRFreeCamera.prototype.dispose = function () {
  86666. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  86667. _super.prototype.dispose.call(this);
  86668. };
  86669. /**
  86670. * Gets a vrController by name.
  86671. * @param name The name of the controller to retreive
  86672. * @returns the controller matching the name specified or null if not found
  86673. */
  86674. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  86675. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  86676. var gp = _a[_i];
  86677. if (gp.hand === name) {
  86678. return gp;
  86679. }
  86680. }
  86681. return null;
  86682. };
  86683. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  86684. /**
  86685. * The controller corrisponding to the users left hand.
  86686. */
  86687. get: function () {
  86688. if (!this._leftController) {
  86689. this._leftController = this.getControllerByName("left");
  86690. }
  86691. return this._leftController;
  86692. },
  86693. enumerable: true,
  86694. configurable: true
  86695. });
  86696. ;
  86697. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86698. /**
  86699. * The controller corrisponding to the users right hand.
  86700. */
  86701. get: function () {
  86702. if (!this._rightController) {
  86703. this._rightController = this.getControllerByName("right");
  86704. }
  86705. return this._rightController;
  86706. },
  86707. enumerable: true,
  86708. configurable: true
  86709. });
  86710. ;
  86711. /**
  86712. * Casts a ray forward from the vrCamera's gaze.
  86713. * @param length Length of the ray (default: 100)
  86714. * @returns the ray corrisponding to the gaze
  86715. */
  86716. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86717. if (length === void 0) { length = 100; }
  86718. if (this.leftCamera) {
  86719. // Use left eye to avoid computation to compute center on every call
  86720. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86721. }
  86722. else {
  86723. return _super.prototype.getForwardRay.call(this, length);
  86724. }
  86725. };
  86726. /**
  86727. * Updates the camera based on device's frame data
  86728. */
  86729. WebVRFreeCamera.prototype._checkInputs = function () {
  86730. if (this._vrDevice && this._vrDevice.isPresenting) {
  86731. this._vrDevice.getFrameData(this._frameData);
  86732. this.updateFromDevice(this._frameData.pose);
  86733. }
  86734. _super.prototype._checkInputs.call(this);
  86735. };
  86736. /**
  86737. * Updates the poseControlled values based on the input device pose.
  86738. * @param poseData Pose coming from the device
  86739. */
  86740. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  86741. if (poseData && poseData.orientation) {
  86742. this.rawPose = poseData;
  86743. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  86744. if (this.getScene().useRightHandedSystem) {
  86745. this._deviceRoomRotationQuaternion.z *= -1;
  86746. this._deviceRoomRotationQuaternion.w *= -1;
  86747. }
  86748. if (this.webVROptions.trackPosition && this.rawPose.position) {
  86749. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  86750. if (this.getScene().useRightHandedSystem) {
  86751. this._deviceRoomPosition.z *= -1;
  86752. }
  86753. }
  86754. }
  86755. };
  86756. /**
  86757. * WebVR's attach control will start broadcasting frames to the device.
  86758. * Note that in certain browsers (chrome for example) this function must be called
  86759. * within a user-interaction callback. Example:
  86760. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  86761. *
  86762. * @param element html element to attach the vrDevice to
  86763. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  86764. */
  86765. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  86766. _super.prototype.attachControl.call(this, element, noPreventDefault);
  86767. this._attached = true;
  86768. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  86769. if (this._vrDevice) {
  86770. this.getEngine().enableVR();
  86771. }
  86772. };
  86773. /**
  86774. * Detaches the camera from the html element and disables VR
  86775. *
  86776. * @param element html element to detach from
  86777. */
  86778. WebVRFreeCamera.prototype.detachControl = function (element) {
  86779. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  86780. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  86781. _super.prototype.detachControl.call(this, element);
  86782. this._attached = false;
  86783. this.getEngine().disableVR();
  86784. };
  86785. /**
  86786. * @returns the name of this class
  86787. */
  86788. WebVRFreeCamera.prototype.getClassName = function () {
  86789. return "WebVRFreeCamera";
  86790. };
  86791. /**
  86792. * Calls resetPose on the vrDisplay
  86793. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  86794. */
  86795. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  86796. //uses the vrDisplay's "resetPose()".
  86797. //pitch and roll won't be affected.
  86798. this._vrDevice.resetPose();
  86799. };
  86800. /**
  86801. * Updates the rig cameras (left and right eye)
  86802. */
  86803. WebVRFreeCamera.prototype._updateRigCameras = function () {
  86804. var camLeft = this._rigCameras[0];
  86805. var camRight = this._rigCameras[1];
  86806. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86807. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86808. camLeft.position.copyFrom(this._deviceRoomPosition);
  86809. camRight.position.copyFrom(this._deviceRoomPosition);
  86810. };
  86811. /**
  86812. * Updates the cached values of the camera
  86813. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  86814. */
  86815. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  86816. var _this = this;
  86817. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  86818. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  86819. if (!this.updateCacheCalled) {
  86820. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  86821. this.updateCacheCalled = true;
  86822. this.update();
  86823. }
  86824. // Set working vector to the device position in room space rotated by the new rotation
  86825. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  86826. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  86827. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  86828. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  86829. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  86830. // Add translation from anchor position
  86831. this._deviceToWorld.getTranslationToRef(this._workingVector);
  86832. this._workingVector.addInPlace(this.position);
  86833. this._workingVector.subtractInPlace(this._cache.position);
  86834. this._deviceToWorld.setTranslation(this._workingVector);
  86835. // Set an inverted matrix to be used when updating the camera
  86836. this._deviceToWorld.invertToRef(this._worldToDevice);
  86837. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  86838. this.controllers.forEach(function (controller) {
  86839. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  86840. controller.update();
  86841. });
  86842. }
  86843. if (!ignoreParentClass) {
  86844. _super.prototype._updateCache.call(this);
  86845. }
  86846. this.updateCacheCalled = false;
  86847. };
  86848. /**
  86849. * Updates the current device position and rotation in the babylon world
  86850. */
  86851. WebVRFreeCamera.prototype.update = function () {
  86852. // Get current device position in babylon world
  86853. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  86854. // Get current device rotation in babylon world
  86855. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  86856. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  86857. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  86858. _super.prototype.update.call(this);
  86859. };
  86860. /**
  86861. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  86862. * @returns an identity matrix
  86863. */
  86864. WebVRFreeCamera.prototype._getViewMatrix = function () {
  86865. return BABYLON.Matrix.Identity();
  86866. };
  86867. /**
  86868. * This function is called by the two RIG cameras.
  86869. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  86870. */
  86871. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  86872. var _this = this;
  86873. // Update the parent camera prior to using a child camera to avoid desynchronization
  86874. var parentCamera = this._cameraRigParams["parentCamera"];
  86875. parentCamera._updateCache();
  86876. //WebVR 1.1
  86877. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  86878. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  86879. if (!this.getScene().useRightHandedSystem) {
  86880. [2, 6, 8, 9, 14].forEach(function (num) {
  86881. _this._webvrViewMatrix.m[num] *= -1;
  86882. });
  86883. }
  86884. // update the camera rotation matrix
  86885. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  86886. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  86887. // Computing target and final matrix
  86888. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  86889. // should the view matrix be updated with scale and position offset?
  86890. if (parentCamera.deviceScaleFactor !== 1) {
  86891. this._webvrViewMatrix.invert();
  86892. // scale the position, if set
  86893. if (parentCamera.deviceScaleFactor) {
  86894. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  86895. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  86896. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  86897. }
  86898. this._webvrViewMatrix.invert();
  86899. }
  86900. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  86901. return this._webvrViewMatrix;
  86902. };
  86903. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  86904. var _this = this;
  86905. var parentCamera = this.parent;
  86906. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  86907. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  86908. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  86909. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  86910. //babylon compatible matrix
  86911. if (!this.getScene().useRightHandedSystem) {
  86912. [8, 9, 10, 11].forEach(function (num) {
  86913. _this._projectionMatrix.m[num] *= -1;
  86914. });
  86915. }
  86916. return this._projectionMatrix;
  86917. };
  86918. /**
  86919. * Initializes the controllers and their meshes
  86920. */
  86921. WebVRFreeCamera.prototype.initControllers = function () {
  86922. var _this = this;
  86923. this.controllers = [];
  86924. var manager = this.getScene().gamepadManager;
  86925. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  86926. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86927. var webVrController = gamepad;
  86928. if (webVrController.defaultModel) {
  86929. webVrController.defaultModel.setEnabled(false);
  86930. }
  86931. if (webVrController.hand === "right") {
  86932. _this._rightController = null;
  86933. }
  86934. if (webVrController.hand === "left") {
  86935. _this._leftController = null;
  86936. }
  86937. var controllerIndex = _this.controllers.indexOf(webVrController);
  86938. if (controllerIndex !== -1) {
  86939. _this.controllers.splice(controllerIndex, 1);
  86940. }
  86941. }
  86942. });
  86943. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  86944. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86945. var webVrController_1 = gamepad;
  86946. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  86947. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  86948. if (_this.webVROptions.controllerMeshes) {
  86949. if (webVrController_1.defaultModel) {
  86950. webVrController_1.defaultModel.setEnabled(true);
  86951. }
  86952. else {
  86953. // Load the meshes
  86954. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  86955. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  86956. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  86957. if (_this.webVROptions.defaultLightingOnControllers) {
  86958. if (!_this._lightOnControllers) {
  86959. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  86960. }
  86961. var activateLightOnSubMeshes_1 = function (mesh, light) {
  86962. var children = mesh.getChildren();
  86963. if (children.length !== 0) {
  86964. children.forEach(function (mesh) {
  86965. light.includedOnlyMeshes.push(mesh);
  86966. activateLightOnSubMeshes_1(mesh, light);
  86967. });
  86968. }
  86969. };
  86970. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  86971. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  86972. }
  86973. });
  86974. }
  86975. }
  86976. webVrController_1.attachToPoseControlledCamera(_this);
  86977. // since this is async - sanity check. Is the controller already stored?
  86978. if (_this.controllers.indexOf(webVrController_1) === -1) {
  86979. //add to the controllers array
  86980. _this.controllers.push(webVrController_1);
  86981. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  86982. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  86983. // So we're overriding setting left & right manually to be sure
  86984. var firstViveWandDetected = false;
  86985. for (var i = 0; i < _this.controllers.length; i++) {
  86986. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  86987. if (!firstViveWandDetected) {
  86988. firstViveWandDetected = true;
  86989. _this.controllers[i].hand = "left";
  86990. }
  86991. else {
  86992. _this.controllers[i].hand = "right";
  86993. }
  86994. }
  86995. }
  86996. //did we find enough controllers? Great! let the developer know.
  86997. if (_this.controllers.length >= 2) {
  86998. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  86999. }
  87000. }
  87001. }
  87002. });
  87003. };
  87004. return WebVRFreeCamera;
  87005. }(BABYLON.FreeCamera));
  87006. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  87007. })(BABYLON || (BABYLON = {}));
  87008. //# sourceMappingURL=babylon.webVRCamera.js.map
  87009. var BABYLON;
  87010. (function (BABYLON) {
  87011. // We're mainly based on the logic defined into the FreeCamera code
  87012. /**
  87013. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  87014. * being tilted forward or back and left or right.
  87015. */
  87016. var DeviceOrientationCamera = /** @class */ (function (_super) {
  87017. __extends(DeviceOrientationCamera, _super);
  87018. /**
  87019. * Creates a new device orientation camera
  87020. * @param name The name of the camera
  87021. * @param position The start position camera
  87022. * @param scene The scene the camera belongs to
  87023. */
  87024. function DeviceOrientationCamera(name, position, scene) {
  87025. var _this = _super.call(this, name, position, scene) || this;
  87026. _this._quaternionCache = new BABYLON.Quaternion();
  87027. _this.inputs.addDeviceOrientation();
  87028. return _this;
  87029. }
  87030. /**
  87031. * Gets the current instance class name ("DeviceOrientationCamera").
  87032. * This helps avoiding instanceof at run time.
  87033. * @returns the class name
  87034. */
  87035. DeviceOrientationCamera.prototype.getClassName = function () {
  87036. return "DeviceOrientationCamera";
  87037. };
  87038. /**
  87039. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  87040. */
  87041. DeviceOrientationCamera.prototype._checkInputs = function () {
  87042. _super.prototype._checkInputs.call(this);
  87043. this._quaternionCache.copyFrom(this.rotationQuaternion);
  87044. if (this._initialQuaternion) {
  87045. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87046. }
  87047. };
  87048. /**
  87049. * Reset the camera to its default orientation on the specified axis only.
  87050. * @param axis The axis to reset
  87051. */
  87052. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  87053. var _this = this;
  87054. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  87055. //can only work if this camera has a rotation quaternion already.
  87056. if (!this.rotationQuaternion)
  87057. return;
  87058. if (!this._initialQuaternion) {
  87059. this._initialQuaternion = new BABYLON.Quaternion();
  87060. }
  87061. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  87062. ['x', 'y', 'z'].forEach(function (axisName) {
  87063. if (!axis[axisName]) {
  87064. _this._initialQuaternion[axisName] = 0;
  87065. }
  87066. else {
  87067. _this._initialQuaternion[axisName] *= -1;
  87068. }
  87069. });
  87070. this._initialQuaternion.normalize();
  87071. //force rotation update
  87072. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87073. };
  87074. return DeviceOrientationCamera;
  87075. }(BABYLON.FreeCamera));
  87076. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  87077. })(BABYLON || (BABYLON = {}));
  87078. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  87079. var BABYLON;
  87080. (function (BABYLON) {
  87081. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  87082. __extends(VRDeviceOrientationFreeCamera, _super);
  87083. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87084. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87085. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87086. var _this = _super.call(this, name, position, scene) || this;
  87087. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87088. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87089. return _this;
  87090. }
  87091. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  87092. return "VRDeviceOrientationFreeCamera";
  87093. };
  87094. return VRDeviceOrientationFreeCamera;
  87095. }(BABYLON.DeviceOrientationCamera));
  87096. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  87097. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  87098. __extends(VRDeviceOrientationGamepadCamera, _super);
  87099. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87100. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87101. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87102. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  87103. _this.inputs.addGamepad();
  87104. return _this;
  87105. }
  87106. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  87107. return "VRDeviceOrientationGamepadCamera";
  87108. };
  87109. return VRDeviceOrientationGamepadCamera;
  87110. }(VRDeviceOrientationFreeCamera));
  87111. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  87112. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  87113. __extends(VRDeviceOrientationArcRotateCamera, _super);
  87114. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  87115. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87116. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87117. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87118. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87119. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87120. _this.inputs.addVRDeviceOrientation();
  87121. return _this;
  87122. }
  87123. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  87124. return "VRDeviceOrientationArcRotateCamera";
  87125. };
  87126. return VRDeviceOrientationArcRotateCamera;
  87127. }(BABYLON.ArcRotateCamera));
  87128. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  87129. })(BABYLON || (BABYLON = {}));
  87130. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  87131. var BABYLON;
  87132. (function (BABYLON) {
  87133. /**
  87134. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  87135. */
  87136. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  87137. __extends(AnaglyphFreeCamera, _super);
  87138. /**
  87139. * Creates a new AnaglyphFreeCamera
  87140. * @param name defines camera name
  87141. * @param position defines initial position
  87142. * @param interaxialDistance defines distance between each color axis
  87143. * @param scene defines the hosting scene
  87144. */
  87145. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  87146. var _this = _super.call(this, name, position, scene) || this;
  87147. _this.interaxialDistance = interaxialDistance;
  87148. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87149. return _this;
  87150. }
  87151. /**
  87152. * Gets camera class name
  87153. * @returns AnaglyphFreeCamera
  87154. */
  87155. AnaglyphFreeCamera.prototype.getClassName = function () {
  87156. return "AnaglyphFreeCamera";
  87157. };
  87158. return AnaglyphFreeCamera;
  87159. }(BABYLON.FreeCamera));
  87160. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  87161. /**
  87162. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  87163. */
  87164. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  87165. __extends(AnaglyphArcRotateCamera, _super);
  87166. /**
  87167. * Creates a new AnaglyphArcRotateCamera
  87168. * @param name defines camera name
  87169. * @param alpha defines alpha angle (in radians)
  87170. * @param beta defines beta angle (in radians)
  87171. * @param radius defines radius
  87172. * @param target defines camera target
  87173. * @param interaxialDistance defines distance between each color axis
  87174. * @param scene defines the hosting scene
  87175. */
  87176. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  87177. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87178. _this.interaxialDistance = interaxialDistance;
  87179. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87180. return _this;
  87181. }
  87182. /**
  87183. * Gets camera class name
  87184. * @returns AnaglyphArcRotateCamera
  87185. */
  87186. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87187. return "AnaglyphArcRotateCamera";
  87188. };
  87189. return AnaglyphArcRotateCamera;
  87190. }(BABYLON.ArcRotateCamera));
  87191. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87192. /**
  87193. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87194. */
  87195. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87196. __extends(AnaglyphGamepadCamera, _super);
  87197. /**
  87198. * Creates a new AnaglyphGamepadCamera
  87199. * @param name defines camera name
  87200. * @param position defines initial position
  87201. * @param interaxialDistance defines distance between each color axis
  87202. * @param scene defines the hosting scene
  87203. */
  87204. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  87205. var _this = _super.call(this, name, position, scene) || this;
  87206. _this.interaxialDistance = interaxialDistance;
  87207. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87208. return _this;
  87209. }
  87210. /**
  87211. * Gets camera class name
  87212. * @returns AnaglyphGamepadCamera
  87213. */
  87214. AnaglyphGamepadCamera.prototype.getClassName = function () {
  87215. return "AnaglyphGamepadCamera";
  87216. };
  87217. return AnaglyphGamepadCamera;
  87218. }(BABYLON.GamepadCamera));
  87219. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  87220. /**
  87221. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  87222. */
  87223. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  87224. __extends(AnaglyphUniversalCamera, _super);
  87225. /**
  87226. * Creates a new AnaglyphUniversalCamera
  87227. * @param name defines camera name
  87228. * @param position defines initial position
  87229. * @param interaxialDistance defines distance between each color axis
  87230. * @param scene defines the hosting scene
  87231. */
  87232. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  87233. var _this = _super.call(this, name, position, scene) || this;
  87234. _this.interaxialDistance = interaxialDistance;
  87235. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87236. return _this;
  87237. }
  87238. /**
  87239. * Gets camera class name
  87240. * @returns AnaglyphUniversalCamera
  87241. */
  87242. AnaglyphUniversalCamera.prototype.getClassName = function () {
  87243. return "AnaglyphUniversalCamera";
  87244. };
  87245. return AnaglyphUniversalCamera;
  87246. }(BABYLON.UniversalCamera));
  87247. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  87248. /**
  87249. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  87250. */
  87251. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  87252. __extends(StereoscopicFreeCamera, _super);
  87253. /**
  87254. * Creates a new StereoscopicFreeCamera
  87255. * @param name defines camera name
  87256. * @param position defines initial position
  87257. * @param interaxialDistance defines distance between each color axis
  87258. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87259. * @param scene defines the hosting scene
  87260. */
  87261. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87262. var _this = _super.call(this, name, position, scene) || this;
  87263. _this.interaxialDistance = interaxialDistance;
  87264. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87265. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87266. return _this;
  87267. }
  87268. /**
  87269. * Gets camera class name
  87270. * @returns StereoscopicFreeCamera
  87271. */
  87272. StereoscopicFreeCamera.prototype.getClassName = function () {
  87273. return "StereoscopicFreeCamera";
  87274. };
  87275. return StereoscopicFreeCamera;
  87276. }(BABYLON.FreeCamera));
  87277. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  87278. /**
  87279. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  87280. */
  87281. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  87282. __extends(StereoscopicArcRotateCamera, _super);
  87283. /**
  87284. * Creates a new StereoscopicArcRotateCamera
  87285. * @param name defines camera name
  87286. * @param alpha defines alpha angle (in radians)
  87287. * @param beta defines beta angle (in radians)
  87288. * @param radius defines radius
  87289. * @param target defines camera target
  87290. * @param interaxialDistance defines distance between each color axis
  87291. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87292. * @param scene defines the hosting scene
  87293. */
  87294. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  87295. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87296. _this.interaxialDistance = interaxialDistance;
  87297. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87298. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87299. return _this;
  87300. }
  87301. /**
  87302. * Gets camera class name
  87303. * @returns StereoscopicArcRotateCamera
  87304. */
  87305. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  87306. return "StereoscopicArcRotateCamera";
  87307. };
  87308. return StereoscopicArcRotateCamera;
  87309. }(BABYLON.ArcRotateCamera));
  87310. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  87311. /**
  87312. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  87313. */
  87314. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  87315. __extends(StereoscopicGamepadCamera, _super);
  87316. /**
  87317. * Creates a new StereoscopicGamepadCamera
  87318. * @param name defines camera name
  87319. * @param position defines initial position
  87320. * @param interaxialDistance defines distance between each color axis
  87321. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87322. * @param scene defines the hosting scene
  87323. */
  87324. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87325. var _this = _super.call(this, name, position, scene) || this;
  87326. _this.interaxialDistance = interaxialDistance;
  87327. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87328. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87329. return _this;
  87330. }
  87331. /**
  87332. * Gets camera class name
  87333. * @returns StereoscopicGamepadCamera
  87334. */
  87335. StereoscopicGamepadCamera.prototype.getClassName = function () {
  87336. return "StereoscopicGamepadCamera";
  87337. };
  87338. return StereoscopicGamepadCamera;
  87339. }(BABYLON.GamepadCamera));
  87340. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  87341. /**
  87342. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  87343. */
  87344. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  87345. __extends(StereoscopicUniversalCamera, _super);
  87346. /**
  87347. * Creates a new StereoscopicUniversalCamera
  87348. * @param name defines camera name
  87349. * @param position defines initial position
  87350. * @param interaxialDistance defines distance between each color axis
  87351. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87352. * @param scene defines the hosting scene
  87353. */
  87354. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87355. var _this = _super.call(this, name, position, scene) || this;
  87356. _this.interaxialDistance = interaxialDistance;
  87357. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87358. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87359. return _this;
  87360. }
  87361. /**
  87362. * Gets camera class name
  87363. * @returns StereoscopicUniversalCamera
  87364. */
  87365. StereoscopicUniversalCamera.prototype.getClassName = function () {
  87366. return "StereoscopicUniversalCamera";
  87367. };
  87368. return StereoscopicUniversalCamera;
  87369. }(BABYLON.UniversalCamera));
  87370. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  87371. })(BABYLON || (BABYLON = {}));
  87372. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  87373. var BABYLON;
  87374. (function (BABYLON) {
  87375. var VRExperienceHelperGazer = /** @class */ (function () {
  87376. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  87377. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  87378. this.scene = scene;
  87379. this._pointerDownOnMeshAsked = false;
  87380. this._isActionableMesh = false;
  87381. this._teleportationRequestInitiated = false;
  87382. this._teleportationBackRequestInitiated = false;
  87383. this._dpadPressed = true;
  87384. this._activePointer = false;
  87385. this._id = VRExperienceHelperGazer._idCounter++;
  87386. // Gaze tracker
  87387. if (!gazeTrackerToClone) {
  87388. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  87389. this._gazeTracker.bakeCurrentTransformIntoVertices();
  87390. this._gazeTracker.isPickable = false;
  87391. this._gazeTracker.isVisible = false;
  87392. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  87393. targetMat.specularColor = BABYLON.Color3.Black();
  87394. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87395. targetMat.backFaceCulling = false;
  87396. this._gazeTracker.material = targetMat;
  87397. }
  87398. else {
  87399. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  87400. }
  87401. }
  87402. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  87403. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  87404. };
  87405. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  87406. this._pointerDownOnMeshAsked = true;
  87407. if (this._currentMeshSelected && this._currentHit) {
  87408. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  87409. }
  87410. };
  87411. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  87412. if (this._currentMeshSelected && this._currentHit) {
  87413. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  87414. }
  87415. this._pointerDownOnMeshAsked = false;
  87416. };
  87417. VRExperienceHelperGazer.prototype._activatePointer = function () {
  87418. this._activePointer = true;
  87419. };
  87420. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  87421. this._activePointer = false;
  87422. };
  87423. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  87424. };
  87425. VRExperienceHelperGazer.prototype.dispose = function () {
  87426. this._interactionsEnabled = false;
  87427. this._teleportationEnabled = false;
  87428. };
  87429. VRExperienceHelperGazer._idCounter = 0;
  87430. return VRExperienceHelperGazer;
  87431. }());
  87432. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  87433. __extends(VRExperienceHelperControllerGazer, _super);
  87434. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  87435. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  87436. _this.webVRController = webVRController;
  87437. // Laser pointer
  87438. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  87439. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  87440. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87441. laserPointerMaterial.alpha = 0.6;
  87442. _this._laserPointer.material = laserPointerMaterial;
  87443. _this._laserPointer.rotation.x = Math.PI / 2;
  87444. _this._laserPointer.position.z = -0.5;
  87445. _this._laserPointer.isVisible = false;
  87446. if (!webVRController.mesh) {
  87447. // Create an empty mesh that is used prior to loading the high quality model
  87448. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  87449. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  87450. preloadPointerPose.rotation.x = -0.7;
  87451. preloadMesh.addChild(preloadPointerPose);
  87452. webVRController.attachToMesh(preloadMesh);
  87453. }
  87454. _this._setLaserPointerParent(webVRController.mesh);
  87455. return _this;
  87456. }
  87457. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  87458. return this.webVRController.getForwardRay(length);
  87459. };
  87460. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  87461. _super.prototype._activatePointer.call(this);
  87462. this._laserPointer.isVisible = true;
  87463. };
  87464. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  87465. _super.prototype._deactivatePointer.call(this);
  87466. this._laserPointer.isVisible = false;
  87467. };
  87468. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  87469. this._laserPointer.material.emissiveColor = color;
  87470. };
  87471. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  87472. var makeNotPick = function (root) {
  87473. root.name += " laserPointer";
  87474. root.getChildMeshes().forEach(function (c) {
  87475. makeNotPick(c);
  87476. });
  87477. };
  87478. makeNotPick(mesh);
  87479. var childMeshes = mesh.getChildMeshes();
  87480. this.webVRController._pointingPoseNode = null;
  87481. for (var i = 0; i < childMeshes.length; i++) {
  87482. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  87483. mesh = childMeshes[i];
  87484. this.webVRController._pointingPoseNode = mesh;
  87485. break;
  87486. }
  87487. }
  87488. this._laserPointer.parent = mesh;
  87489. };
  87490. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  87491. this._laserPointer.scaling.y = distance;
  87492. this._laserPointer.position.z = -distance / 2;
  87493. };
  87494. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  87495. _super.prototype.dispose.call(this);
  87496. this._laserPointer.dispose();
  87497. };
  87498. return VRExperienceHelperControllerGazer;
  87499. }(VRExperienceHelperGazer));
  87500. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  87501. __extends(VRExperienceHelperCameraGazer, _super);
  87502. function VRExperienceHelperCameraGazer(getCamera, scene) {
  87503. var _this = _super.call(this, scene) || this;
  87504. _this.getCamera = getCamera;
  87505. return _this;
  87506. }
  87507. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  87508. var camera = this.getCamera();
  87509. if (camera) {
  87510. return camera.getForwardRay(length);
  87511. }
  87512. else {
  87513. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  87514. }
  87515. };
  87516. return VRExperienceHelperCameraGazer;
  87517. }(VRExperienceHelperGazer));
  87518. /**
  87519. * Helps to quickly add VR support to an existing scene.
  87520. * See http://doc.babylonjs.com/how_to/webvr_helper
  87521. */
  87522. var VRExperienceHelper = /** @class */ (function () {
  87523. /**
  87524. * Instantiates a VRExperienceHelper.
  87525. * Helps to quickly add VR support to an existing scene.
  87526. * @param scene The scene the VRExperienceHelper belongs to.
  87527. * @param webVROptions Options to modify the vr experience helper's behavior.
  87528. */
  87529. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  87530. if (webVROptions === void 0) { webVROptions = {}; }
  87531. var _this = this;
  87532. this.webVROptions = webVROptions;
  87533. // Can the system support WebVR, even if a headset isn't plugged in?
  87534. this._webVRsupported = false;
  87535. // If WebVR is supported, is a headset plugged in and are we ready to present?
  87536. this._webVRready = false;
  87537. // Are we waiting for the requestPresent callback to complete?
  87538. this._webVRrequesting = false;
  87539. // Are we presenting to the headset right now?
  87540. this._webVRpresenting = false;
  87541. // Are we presenting in the fullscreen fallback?
  87542. this._fullscreenVRpresenting = false;
  87543. /**
  87544. * Observable raised when entering VR.
  87545. */
  87546. this.onEnteringVRObservable = new BABYLON.Observable();
  87547. /**
  87548. * Observable raised when exiting VR.
  87549. */
  87550. this.onExitingVRObservable = new BABYLON.Observable();
  87551. /**
  87552. * Observable raised when controller mesh is loaded.
  87553. */
  87554. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87555. this._useCustomVRButton = false;
  87556. this._teleportationRequested = false;
  87557. this._teleportActive = false;
  87558. this._floorMeshesCollection = [];
  87559. this._rotationAllowed = true;
  87560. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  87561. this._rotationRightAsked = false;
  87562. this._rotationLeftAsked = false;
  87563. this._isDefaultTeleportationTarget = true;
  87564. this._teleportationFillColor = "#444444";
  87565. this._teleportationBorderColor = "#FFFFFF";
  87566. this._rotationAngle = 0;
  87567. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  87568. this._padSensibilityUp = 0.65;
  87569. this._padSensibilityDown = 0.35;
  87570. this.leftController = null;
  87571. this.rightController = null;
  87572. /**
  87573. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  87574. */
  87575. this.onNewMeshSelected = new BABYLON.Observable();
  87576. /**
  87577. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  87578. */
  87579. this.onNewMeshPicked = new BABYLON.Observable();
  87580. /**
  87581. * Observable raised before camera teleportation
  87582. */
  87583. this.onBeforeCameraTeleport = new BABYLON.Observable();
  87584. /**
  87585. * Observable raised after camera teleportation
  87586. */
  87587. this.onAfterCameraTeleport = new BABYLON.Observable();
  87588. /**
  87589. * Observable raised when current selected mesh gets unselected
  87590. */
  87591. this.onSelectedMeshUnselected = new BABYLON.Observable();
  87592. /**
  87593. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  87594. */
  87595. this.teleportationEnabled = true;
  87596. this._teleportationInitialized = false;
  87597. this._interactionsEnabled = false;
  87598. this._interactionsRequested = false;
  87599. this._displayGaze = true;
  87600. this._displayLaserPointer = true;
  87601. this._onResize = function () {
  87602. _this.moveButtonToBottomRight();
  87603. if (_this._fullscreenVRpresenting && _this._webVRready) {
  87604. _this.exitVR();
  87605. }
  87606. };
  87607. this._onFullscreenChange = function () {
  87608. if (document.fullscreen !== undefined) {
  87609. _this._fullscreenVRpresenting = document.fullscreen;
  87610. }
  87611. else if (document.mozFullScreen !== undefined) {
  87612. _this._fullscreenVRpresenting = document.mozFullScreen;
  87613. }
  87614. else if (document.webkitIsFullScreen !== undefined) {
  87615. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  87616. }
  87617. else if (document.msIsFullScreen !== undefined) {
  87618. _this._fullscreenVRpresenting = document.msIsFullScreen;
  87619. }
  87620. if (!_this._fullscreenVRpresenting && _this._canvas) {
  87621. _this.exitVR();
  87622. if (!_this._useCustomVRButton) {
  87623. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  87624. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  87625. }
  87626. }
  87627. };
  87628. this.beforeRender = function () {
  87629. if (_this.leftController && _this.leftController._activePointer) {
  87630. _this._castRayAndSelectObject(_this.leftController);
  87631. }
  87632. if (_this.rightController && _this.rightController._activePointer) {
  87633. _this._castRayAndSelectObject(_this.rightController);
  87634. }
  87635. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  87636. _this._castRayAndSelectObject(_this._cameraGazer);
  87637. }
  87638. else {
  87639. _this._cameraGazer._gazeTracker.isVisible = false;
  87640. }
  87641. };
  87642. this._onNewGamepadConnected = function (gamepad) {
  87643. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  87644. if (gamepad.leftStick) {
  87645. gamepad.onleftstickchanged(function (stickValues) {
  87646. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  87647. // Listening to classic/xbox gamepad only if no VR controller is active
  87648. if ((!_this.leftController && !_this.rightController) ||
  87649. ((_this.leftController && !_this.leftController._activePointer) &&
  87650. (_this.rightController && !_this.rightController._activePointer))) {
  87651. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  87652. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  87653. }
  87654. }
  87655. });
  87656. }
  87657. if (gamepad.rightStick) {
  87658. gamepad.onrightstickchanged(function (stickValues) {
  87659. if (_this._teleportationInitialized) {
  87660. _this._checkRotate(stickValues, _this._cameraGazer);
  87661. }
  87662. });
  87663. }
  87664. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  87665. gamepad.onbuttondown(function (buttonPressed) {
  87666. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87667. _this._cameraGazer._selectionPointerDown();
  87668. }
  87669. });
  87670. gamepad.onbuttonup(function (buttonPressed) {
  87671. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87672. _this._cameraGazer._selectionPointerUp();
  87673. }
  87674. });
  87675. }
  87676. }
  87677. else {
  87678. var webVRController = gamepad;
  87679. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  87680. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  87681. _this.rightController = controller;
  87682. }
  87683. else {
  87684. _this.leftController = controller;
  87685. }
  87686. _this._tryEnableInteractionOnController(controller);
  87687. }
  87688. };
  87689. // 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
  87690. this._tryEnableInteractionOnController = function (controller) {
  87691. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  87692. _this._enableInteractionOnController(controller);
  87693. }
  87694. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  87695. _this._enableTeleportationOnController(controller);
  87696. }
  87697. };
  87698. this._onNewGamepadDisconnected = function (gamepad) {
  87699. if (gamepad instanceof BABYLON.WebVRController) {
  87700. if (gamepad.hand === "left" && _this.leftController != null) {
  87701. _this.leftController.dispose();
  87702. _this.leftController = null;
  87703. }
  87704. if (gamepad.hand === "right" && _this.rightController != null) {
  87705. _this.rightController.dispose();
  87706. _this.rightController = null;
  87707. }
  87708. }
  87709. };
  87710. this._workingVector = BABYLON.Vector3.Zero();
  87711. this._workingQuaternion = BABYLON.Quaternion.Identity();
  87712. this._workingMatrix = BABYLON.Matrix.Identity();
  87713. this._scene = scene;
  87714. this._canvas = scene.getEngine().getRenderingCanvas();
  87715. // Parse options
  87716. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  87717. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  87718. }
  87719. if (webVROptions.createDeviceOrientationCamera === undefined) {
  87720. webVROptions.createDeviceOrientationCamera = true;
  87721. }
  87722. if (webVROptions.defaultHeight === undefined) {
  87723. webVROptions.defaultHeight = 1.7;
  87724. }
  87725. if (webVROptions.useCustomVRButton) {
  87726. this._useCustomVRButton = true;
  87727. if (webVROptions.customVRButton) {
  87728. this._btnVR = webVROptions.customVRButton;
  87729. }
  87730. }
  87731. if (webVROptions.rayLength) {
  87732. this._rayLength = webVROptions.rayLength;
  87733. }
  87734. this._defaultHeight = webVROptions.defaultHeight;
  87735. if (webVROptions.positionScale) {
  87736. this._rayLength *= webVROptions.positionScale;
  87737. this._defaultHeight *= webVROptions.positionScale;
  87738. }
  87739. // Set position
  87740. if (this._scene.activeCamera) {
  87741. this._position = this._scene.activeCamera.position.clone();
  87742. }
  87743. else {
  87744. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  87745. }
  87746. // Set non-vr camera
  87747. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  87748. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  87749. // Copy data from existing camera
  87750. if (this._scene.activeCamera) {
  87751. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87752. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  87753. // Set rotation from previous camera
  87754. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  87755. var targetCamera = this._scene.activeCamera;
  87756. if (targetCamera.rotationQuaternion) {
  87757. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  87758. }
  87759. else {
  87760. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  87761. }
  87762. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  87763. }
  87764. }
  87765. this._scene.activeCamera = this._deviceOrientationCamera;
  87766. if (this._canvas) {
  87767. this._scene.activeCamera.attachControl(this._canvas);
  87768. }
  87769. }
  87770. else {
  87771. this._existingCamera = this._scene.activeCamera;
  87772. }
  87773. // Create VR cameras
  87774. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87775. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  87776. }
  87777. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  87778. this._webVRCamera.useStandingMatrix();
  87779. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  87780. // Create default button
  87781. if (!this._useCustomVRButton) {
  87782. this._btnVR = document.createElement("BUTTON");
  87783. this._btnVR.className = "babylonVRicon";
  87784. this._btnVR.id = "babylonVRiconbtn";
  87785. this._btnVR.title = "Click to switch to VR";
  87786. 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) }";
  87787. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  87788. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  87789. // css += ".babylonVRicon.vrdisplaysupported { }";
  87790. // css += ".babylonVRicon.vrdisplayready { }";
  87791. // css += ".babylonVRicon.vrdisplayrequesting { }";
  87792. var style = document.createElement('style');
  87793. style.appendChild(document.createTextNode(css));
  87794. document.getElementsByTagName('head')[0].appendChild(style);
  87795. this.moveButtonToBottomRight();
  87796. }
  87797. // VR button click event
  87798. if (this._btnVR) {
  87799. this._btnVR.addEventListener("click", function () {
  87800. if (!_this.isInVRMode) {
  87801. _this.enterVR();
  87802. }
  87803. else {
  87804. _this.exitVR();
  87805. }
  87806. });
  87807. }
  87808. // Window events
  87809. window.addEventListener("resize", this._onResize);
  87810. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  87811. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  87812. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  87813. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  87814. // Display vr button when headset is connected
  87815. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87816. this.displayVRButton();
  87817. }
  87818. else {
  87819. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  87820. if (e.vrDisplay) {
  87821. _this.displayVRButton();
  87822. }
  87823. });
  87824. }
  87825. // Exiting VR mode using 'ESC' key on desktop
  87826. this._onKeyDown = function (event) {
  87827. if (event.keyCode === 27 && _this.isInVRMode) {
  87828. _this.exitVR();
  87829. }
  87830. };
  87831. document.addEventListener("keydown", this._onKeyDown);
  87832. // Exiting VR mode double tapping the touch screen
  87833. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  87834. if (_this.isInVRMode) {
  87835. _this.exitVR();
  87836. if (_this._fullscreenVRpresenting) {
  87837. _this._scene.getEngine().switchFullscreen(true);
  87838. }
  87839. }
  87840. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  87841. // Listen for WebVR display changes
  87842. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  87843. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  87844. this._onVRRequestPresentStart = function () {
  87845. _this._webVRrequesting = true;
  87846. _this.updateButtonVisibility();
  87847. };
  87848. this._onVRRequestPresentComplete = function (success) {
  87849. _this._webVRrequesting = false;
  87850. _this.updateButtonVisibility();
  87851. };
  87852. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  87853. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  87854. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  87855. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87856. scene.onDisposeObservable.add(function () {
  87857. _this.dispose();
  87858. });
  87859. // Gamepad connection events
  87860. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  87861. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  87862. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  87863. this.updateButtonVisibility();
  87864. //create easing functions
  87865. this._circleEase = new BABYLON.CircleEase();
  87866. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87867. }
  87868. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  87869. /** Return this.onEnteringVRObservable
  87870. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  87871. */
  87872. get: function () {
  87873. return this.onEnteringVRObservable;
  87874. },
  87875. enumerable: true,
  87876. configurable: true
  87877. });
  87878. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  87879. /** Return this.onExitingVRObservable
  87880. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  87881. */
  87882. get: function () {
  87883. return this.onExitingVRObservable;
  87884. },
  87885. enumerable: true,
  87886. configurable: true
  87887. });
  87888. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  87889. /** Return this.onControllerMeshLoadedObservable
  87890. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  87891. */
  87892. get: function () {
  87893. return this.onControllerMeshLoadedObservable;
  87894. },
  87895. enumerable: true,
  87896. configurable: true
  87897. });
  87898. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  87899. /**
  87900. * The mesh used to display where the user is going to teleport.
  87901. */
  87902. get: function () {
  87903. return this._teleportationTarget;
  87904. },
  87905. /**
  87906. * Sets the mesh to be used to display where the user is going to teleport.
  87907. */
  87908. set: function (value) {
  87909. if (value) {
  87910. value.name = "teleportationTarget";
  87911. this._isDefaultTeleportationTarget = false;
  87912. this._teleportationTarget = value;
  87913. }
  87914. },
  87915. enumerable: true,
  87916. configurable: true
  87917. });
  87918. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  87919. /**
  87920. * The mesh used to display where the user is selecting,
  87921. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  87922. * See http://doc.babylonjs.com/resources/baking_transformations
  87923. */
  87924. get: function () {
  87925. return this._cameraGazer._gazeTracker;
  87926. },
  87927. set: function (value) {
  87928. if (value) {
  87929. this._cameraGazer._gazeTracker = value;
  87930. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  87931. this._cameraGazer._gazeTracker.isPickable = false;
  87932. this._cameraGazer._gazeTracker.isVisible = false;
  87933. this._cameraGazer._gazeTracker.name = "gazeTracker";
  87934. if (this.leftController) {
  87935. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87936. }
  87937. if (this.rightController) {
  87938. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87939. }
  87940. }
  87941. },
  87942. enumerable: true,
  87943. configurable: true
  87944. });
  87945. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  87946. /**
  87947. * If the ray of the gaze should be displayed.
  87948. */
  87949. get: function () {
  87950. return this._displayGaze;
  87951. },
  87952. /**
  87953. * Sets if the ray of the gaze should be displayed.
  87954. */
  87955. set: function (value) {
  87956. this._displayGaze = value;
  87957. if (!value) {
  87958. this._cameraGazer._gazeTracker.isVisible = false;
  87959. if (this.leftController) {
  87960. this.leftController._gazeTracker.isVisible = false;
  87961. }
  87962. if (this.rightController) {
  87963. this.rightController._gazeTracker.isVisible = false;
  87964. }
  87965. }
  87966. },
  87967. enumerable: true,
  87968. configurable: true
  87969. });
  87970. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  87971. /**
  87972. * If the ray of the LaserPointer should be displayed.
  87973. */
  87974. get: function () {
  87975. return this._displayLaserPointer;
  87976. },
  87977. /**
  87978. * Sets if the ray of the LaserPointer should be displayed.
  87979. */
  87980. set: function (value) {
  87981. this._displayLaserPointer = value;
  87982. if (!value) {
  87983. if (this.rightController) {
  87984. this.rightController._deactivatePointer();
  87985. this.rightController._gazeTracker.isVisible = false;
  87986. }
  87987. if (this.leftController) {
  87988. this.leftController._deactivatePointer();
  87989. this.leftController._gazeTracker.isVisible = false;
  87990. }
  87991. }
  87992. else {
  87993. if (this.rightController) {
  87994. this.rightController._activatePointer();
  87995. }
  87996. else if (this.leftController) {
  87997. this.leftController._activatePointer();
  87998. }
  87999. }
  88000. },
  88001. enumerable: true,
  88002. configurable: true
  88003. });
  88004. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  88005. /**
  88006. * The deviceOrientationCamera used as the camera when not in VR.
  88007. */
  88008. get: function () {
  88009. return this._deviceOrientationCamera;
  88010. },
  88011. enumerable: true,
  88012. configurable: true
  88013. });
  88014. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  88015. /**
  88016. * Based on the current WebVR support, returns the current VR camera used.
  88017. */
  88018. get: function () {
  88019. if (this._webVRready) {
  88020. return this._webVRCamera;
  88021. }
  88022. else {
  88023. return this._scene.activeCamera;
  88024. }
  88025. },
  88026. enumerable: true,
  88027. configurable: true
  88028. });
  88029. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  88030. /**
  88031. * The webVRCamera which is used when in VR.
  88032. */
  88033. get: function () {
  88034. return this._webVRCamera;
  88035. },
  88036. enumerable: true,
  88037. configurable: true
  88038. });
  88039. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  88040. /**
  88041. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  88042. */
  88043. get: function () {
  88044. return this._vrDeviceOrientationCamera;
  88045. },
  88046. enumerable: true,
  88047. configurable: true
  88048. });
  88049. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  88050. get: function () {
  88051. var result = this._cameraGazer._teleportationRequestInitiated
  88052. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  88053. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  88054. return result;
  88055. },
  88056. enumerable: true,
  88057. configurable: true
  88058. });
  88059. // Raised when one of the controller has loaded successfully its associated default mesh
  88060. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  88061. if (this.leftController && this.leftController.webVRController == webVRController) {
  88062. if (webVRController.mesh) {
  88063. this.leftController._setLaserPointerParent(webVRController.mesh);
  88064. }
  88065. }
  88066. if (this.rightController && this.rightController.webVRController == webVRController) {
  88067. if (webVRController.mesh) {
  88068. this.rightController._setLaserPointerParent(webVRController.mesh);
  88069. }
  88070. }
  88071. try {
  88072. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  88073. }
  88074. catch (err) {
  88075. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  88076. }
  88077. };
  88078. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  88079. /**
  88080. * Gets a value indicating if we are currently in VR mode.
  88081. */
  88082. get: function () {
  88083. return this._webVRpresenting || this._fullscreenVRpresenting;
  88084. },
  88085. enumerable: true,
  88086. configurable: true
  88087. });
  88088. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  88089. var vrDisplay = this._scene.getEngine().getVRDevice();
  88090. if (vrDisplay) {
  88091. var wasPresenting = this._webVRpresenting;
  88092. // A VR display is connected
  88093. this._webVRpresenting = vrDisplay.isPresenting;
  88094. if (wasPresenting && !this._webVRpresenting)
  88095. this.exitVR();
  88096. }
  88097. else {
  88098. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  88099. }
  88100. this.updateButtonVisibility();
  88101. };
  88102. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  88103. this._webVRsupported = eventArgs.vrSupported;
  88104. this._webVRready = !!eventArgs.vrDisplay;
  88105. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  88106. this.updateButtonVisibility();
  88107. };
  88108. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  88109. if (this._canvas && !this._useCustomVRButton) {
  88110. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  88111. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  88112. }
  88113. };
  88114. VRExperienceHelper.prototype.displayVRButton = function () {
  88115. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  88116. document.body.appendChild(this._btnVR);
  88117. this._btnVRDisplayed = true;
  88118. }
  88119. };
  88120. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  88121. if (!this._btnVR || this._useCustomVRButton) {
  88122. return;
  88123. }
  88124. this._btnVR.className = "babylonVRicon";
  88125. if (this.isInVRMode) {
  88126. this._btnVR.className += " vrdisplaypresenting";
  88127. }
  88128. else {
  88129. if (this._webVRready)
  88130. this._btnVR.className += " vrdisplayready";
  88131. if (this._webVRsupported)
  88132. this._btnVR.className += " vrdisplaysupported";
  88133. if (this._webVRrequesting)
  88134. this._btnVR.className += " vrdisplayrequesting";
  88135. }
  88136. };
  88137. /**
  88138. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  88139. * Otherwise, will use the fullscreen API.
  88140. */
  88141. VRExperienceHelper.prototype.enterVR = function () {
  88142. if (this.onEnteringVRObservable) {
  88143. try {
  88144. this.onEnteringVRObservable.notifyObservers(this);
  88145. }
  88146. catch (err) {
  88147. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  88148. }
  88149. }
  88150. if (this._scene.activeCamera) {
  88151. this._position = this._scene.activeCamera.position.clone();
  88152. // make sure that we return to the last active camera
  88153. this._existingCamera = this._scene.activeCamera;
  88154. }
  88155. if (this._webVRrequesting)
  88156. return;
  88157. // If WebVR is supported and a headset is connected
  88158. if (this._webVRready) {
  88159. if (!this._webVRpresenting) {
  88160. this._webVRCamera.position = this._position;
  88161. this._scene.activeCamera = this._webVRCamera;
  88162. }
  88163. }
  88164. else if (this._vrDeviceOrientationCamera) {
  88165. this._vrDeviceOrientationCamera.position = this._position;
  88166. if (this._scene.activeCamera) {
  88167. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88168. }
  88169. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  88170. this._scene.getEngine().switchFullscreen(true);
  88171. this.updateButtonVisibility();
  88172. }
  88173. if (this._scene.activeCamera && this._canvas) {
  88174. this._scene.activeCamera.attachControl(this._canvas);
  88175. }
  88176. if (this._interactionsEnabled) {
  88177. this._scene.registerBeforeRender(this.beforeRender);
  88178. }
  88179. };
  88180. /**
  88181. * Attempt to exit VR, or fullscreen.
  88182. */
  88183. VRExperienceHelper.prototype.exitVR = function () {
  88184. if (this.onExitingVRObservable) {
  88185. try {
  88186. this.onExitingVRObservable.notifyObservers(this);
  88187. }
  88188. catch (err) {
  88189. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  88190. }
  88191. }
  88192. if (this._webVRpresenting) {
  88193. this._scene.getEngine().disableVR();
  88194. }
  88195. if (this._scene.activeCamera) {
  88196. this._position = this._scene.activeCamera.position.clone();
  88197. }
  88198. if (this._deviceOrientationCamera) {
  88199. this._deviceOrientationCamera.position = this._position;
  88200. this._scene.activeCamera = this._deviceOrientationCamera;
  88201. if (this._canvas) {
  88202. this._scene.activeCamera.attachControl(this._canvas);
  88203. }
  88204. }
  88205. else if (this._existingCamera) {
  88206. this._existingCamera.position = this._position;
  88207. this._scene.activeCamera = this._existingCamera;
  88208. }
  88209. this.updateButtonVisibility();
  88210. if (this._interactionsEnabled) {
  88211. this._scene.unregisterBeforeRender(this.beforeRender);
  88212. }
  88213. // resize to update width and height when exiting vr exits fullscreen
  88214. this._scene.getEngine().resize();
  88215. };
  88216. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  88217. /**
  88218. * The position of the vr experience helper.
  88219. */
  88220. get: function () {
  88221. return this._position;
  88222. },
  88223. /**
  88224. * Sets the position of the vr experience helper.
  88225. */
  88226. set: function (value) {
  88227. this._position = value;
  88228. if (this._scene.activeCamera) {
  88229. this._scene.activeCamera.position = value;
  88230. }
  88231. },
  88232. enumerable: true,
  88233. configurable: true
  88234. });
  88235. /**
  88236. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  88237. */
  88238. VRExperienceHelper.prototype.enableInteractions = function () {
  88239. var _this = this;
  88240. if (!this._interactionsEnabled) {
  88241. this._interactionsRequested = true;
  88242. if (this.leftController) {
  88243. this._enableInteractionOnController(this.leftController);
  88244. }
  88245. if (this.rightController) {
  88246. this._enableInteractionOnController(this.rightController);
  88247. }
  88248. this.raySelectionPredicate = function (mesh) {
  88249. return mesh.isVisible;
  88250. };
  88251. this.meshSelectionPredicate = function (mesh) {
  88252. return true;
  88253. };
  88254. this._raySelectionPredicate = function (mesh) {
  88255. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  88256. && mesh.name.indexOf("teleportationTarget") === -1
  88257. && mesh.name.indexOf("torusTeleportation") === -1
  88258. && mesh.name.indexOf("laserPointer") === -1)) {
  88259. return _this.raySelectionPredicate(mesh);
  88260. }
  88261. return false;
  88262. };
  88263. this._interactionsEnabled = true;
  88264. }
  88265. };
  88266. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  88267. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  88268. if (this._floorMeshesCollection[i].id === mesh.id) {
  88269. return true;
  88270. }
  88271. }
  88272. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  88273. return true;
  88274. }
  88275. return false;
  88276. };
  88277. /**
  88278. * Adds a floor mesh to be used for teleportation.
  88279. * @param floorMesh the mesh to be used for teleportation.
  88280. */
  88281. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  88282. if (!this._floorMeshesCollection) {
  88283. return;
  88284. }
  88285. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  88286. return;
  88287. }
  88288. this._floorMeshesCollection.push(floorMesh);
  88289. };
  88290. /**
  88291. * Removes a floor mesh from being used for teleportation.
  88292. * @param floorMesh the mesh to be removed.
  88293. */
  88294. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  88295. if (!this._floorMeshesCollection) {
  88296. return;
  88297. }
  88298. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  88299. if (meshIndex !== -1) {
  88300. this._floorMeshesCollection.splice(meshIndex, 1);
  88301. }
  88302. };
  88303. /**
  88304. * Enables interactions and teleportation using the VR controllers and gaze.
  88305. * @param vrTeleportationOptions options to modify teleportation behavior.
  88306. */
  88307. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  88308. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  88309. if (!this._teleportationInitialized) {
  88310. this._teleportationRequested = true;
  88311. this.enableInteractions();
  88312. if (vrTeleportationOptions.floorMeshName) {
  88313. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  88314. }
  88315. if (vrTeleportationOptions.floorMeshes) {
  88316. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  88317. }
  88318. if (this.leftController != null) {
  88319. this._enableTeleportationOnController(this.leftController);
  88320. }
  88321. if (this.rightController != null) {
  88322. this._enableTeleportationOnController(this.rightController);
  88323. }
  88324. // Creates an image processing post process for the vignette not relying
  88325. // on the main scene configuration for image processing to reduce setup and spaces
  88326. // (gamma/linear) conflicts.
  88327. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  88328. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88329. imageProcessingConfiguration.vignetteEnabled = true;
  88330. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  88331. this._webVRCamera.detachPostProcess(this._postProcessMove);
  88332. this._teleportationInitialized = true;
  88333. if (this._isDefaultTeleportationTarget) {
  88334. this._createTeleportationCircles();
  88335. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  88336. }
  88337. }
  88338. };
  88339. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  88340. var _this = this;
  88341. var controllerMesh = controller.webVRController.mesh;
  88342. if (controllerMesh) {
  88343. controller._interactionsEnabled = true;
  88344. controller._activatePointer();
  88345. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  88346. // Enabling / disabling laserPointer
  88347. if (_this._displayLaserPointer && stateObject.value === 1) {
  88348. if (controller._activePointer) {
  88349. controller._deactivatePointer();
  88350. }
  88351. else {
  88352. controller._activatePointer();
  88353. }
  88354. if (_this.displayGaze) {
  88355. controller._gazeTracker.isVisible = controller._activePointer;
  88356. }
  88357. }
  88358. });
  88359. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  88360. if (!controller._pointerDownOnMeshAsked) {
  88361. if (stateObject.value > _this._padSensibilityUp) {
  88362. controller._selectionPointerDown();
  88363. }
  88364. }
  88365. else if (stateObject.value < _this._padSensibilityDown) {
  88366. controller._selectionPointerUp();
  88367. }
  88368. });
  88369. }
  88370. };
  88371. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  88372. // Dont teleport if another gaze already requested teleportation
  88373. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  88374. return;
  88375. }
  88376. if (!gazer._teleportationRequestInitiated) {
  88377. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  88378. gazer._activatePointer();
  88379. gazer._teleportationRequestInitiated = true;
  88380. }
  88381. }
  88382. else {
  88383. // Listening to the proper controller values changes to confirm teleportation
  88384. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  88385. if (this._teleportActive) {
  88386. this._teleportCamera(this._haloCenter);
  88387. }
  88388. gazer._teleportationRequestInitiated = false;
  88389. }
  88390. }
  88391. };
  88392. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  88393. // Only rotate when user is not currently selecting a teleportation location
  88394. if (gazer._teleportationRequestInitiated) {
  88395. return;
  88396. }
  88397. if (!this._rotationLeftAsked) {
  88398. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  88399. this._rotationLeftAsked = true;
  88400. if (this._rotationAllowed) {
  88401. this._rotateCamera(false);
  88402. }
  88403. }
  88404. }
  88405. else {
  88406. if (stateObject.x > -this._padSensibilityDown) {
  88407. this._rotationLeftAsked = false;
  88408. }
  88409. }
  88410. if (!this._rotationRightAsked) {
  88411. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  88412. this._rotationRightAsked = true;
  88413. if (this._rotationAllowed) {
  88414. this._rotateCamera(true);
  88415. }
  88416. }
  88417. }
  88418. else {
  88419. if (stateObject.x < this._padSensibilityDown) {
  88420. this._rotationRightAsked = false;
  88421. }
  88422. }
  88423. };
  88424. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  88425. // Only teleport backwards when user is not currently selecting a teleportation location
  88426. if (gazer._teleportationRequestInitiated) {
  88427. return;
  88428. }
  88429. // Teleport backwards
  88430. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  88431. if (!gazer._teleportationBackRequestInitiated) {
  88432. if (!this.currentVRCamera) {
  88433. return;
  88434. }
  88435. // Get rotation and position of the current camera
  88436. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  88437. var position = this.currentVRCamera.position;
  88438. // If the camera has device position, use that instead
  88439. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  88440. rotation = this.currentVRCamera.deviceRotationQuaternion;
  88441. position = this.currentVRCamera.devicePosition;
  88442. }
  88443. // Get matrix with only the y rotation of the device rotation
  88444. rotation.toEulerAnglesToRef(this._workingVector);
  88445. this._workingVector.z = 0;
  88446. this._workingVector.x = 0;
  88447. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  88448. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  88449. // Rotate backwards ray by device rotation to cast at the ground behind the user
  88450. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  88451. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  88452. var ray = new BABYLON.Ray(position, this._workingVector);
  88453. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88454. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  88455. this._teleportCamera(hit.pickedPoint);
  88456. }
  88457. gazer._teleportationBackRequestInitiated = true;
  88458. }
  88459. }
  88460. else {
  88461. gazer._teleportationBackRequestInitiated = false;
  88462. }
  88463. };
  88464. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  88465. var _this = this;
  88466. var controllerMesh = controller.webVRController.mesh;
  88467. if (controllerMesh) {
  88468. if (!controller._interactionsEnabled) {
  88469. this._enableInteractionOnController(controller);
  88470. }
  88471. controller._interactionsEnabled = true;
  88472. controller._teleportationEnabled = true;
  88473. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  88474. controller._dpadPressed = false;
  88475. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  88476. controller._dpadPressed = stateObject.pressed;
  88477. if (!controller._dpadPressed) {
  88478. _this._rotationLeftAsked = false;
  88479. _this._rotationRightAsked = false;
  88480. controller._teleportationBackRequestInitiated = false;
  88481. }
  88482. });
  88483. }
  88484. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  88485. if (_this.teleportationEnabled) {
  88486. _this._checkTeleportBackwards(stateObject, controller);
  88487. _this._checkTeleportWithRay(stateObject, controller);
  88488. }
  88489. _this._checkRotate(stateObject, controller);
  88490. });
  88491. }
  88492. };
  88493. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  88494. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  88495. this._teleportationTarget.isPickable = false;
  88496. var length = 512;
  88497. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  88498. dynamicTexture.hasAlpha = true;
  88499. var context = dynamicTexture.getContext();
  88500. var centerX = length / 2;
  88501. var centerY = length / 2;
  88502. var radius = 200;
  88503. context.beginPath();
  88504. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  88505. context.fillStyle = this._teleportationFillColor;
  88506. context.fill();
  88507. context.lineWidth = 10;
  88508. context.strokeStyle = this._teleportationBorderColor;
  88509. context.stroke();
  88510. context.closePath();
  88511. dynamicTexture.update();
  88512. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  88513. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  88514. this._teleportationTarget.material = teleportationCircleMaterial;
  88515. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  88516. torus.isPickable = false;
  88517. torus.parent = this._teleportationTarget;
  88518. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88519. var keys = [];
  88520. keys.push({
  88521. frame: 0,
  88522. value: 0
  88523. });
  88524. keys.push({
  88525. frame: 30,
  88526. value: 0.4
  88527. });
  88528. keys.push({
  88529. frame: 60,
  88530. value: 0
  88531. });
  88532. animationInnerCircle.setKeys(keys);
  88533. var easingFunction = new BABYLON.SineEase();
  88534. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88535. animationInnerCircle.setEasingFunction(easingFunction);
  88536. torus.animations = [];
  88537. torus.animations.push(animationInnerCircle);
  88538. this._scene.beginAnimation(torus, 0, 60, true);
  88539. this._hideTeleportationTarget();
  88540. };
  88541. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  88542. this._teleportActive = true;
  88543. if (this._teleportationInitialized) {
  88544. this._teleportationTarget.isVisible = true;
  88545. if (this._isDefaultTeleportationTarget) {
  88546. this._teleportationTarget.getChildren()[0].isVisible = true;
  88547. }
  88548. }
  88549. };
  88550. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  88551. this._teleportActive = false;
  88552. if (this._teleportationInitialized) {
  88553. this._teleportationTarget.isVisible = false;
  88554. if (this._isDefaultTeleportationTarget) {
  88555. this._teleportationTarget.getChildren()[0].isVisible = false;
  88556. }
  88557. }
  88558. };
  88559. VRExperienceHelper.prototype._rotateCamera = function (right) {
  88560. var _this = this;
  88561. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88562. return;
  88563. }
  88564. if (right) {
  88565. this._rotationAngle++;
  88566. }
  88567. else {
  88568. this._rotationAngle--;
  88569. }
  88570. this.currentVRCamera.animations = [];
  88571. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  88572. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88573. var animationRotationKeys = [];
  88574. animationRotationKeys.push({
  88575. frame: 0,
  88576. value: this.currentVRCamera.rotationQuaternion
  88577. });
  88578. animationRotationKeys.push({
  88579. frame: 6,
  88580. value: target
  88581. });
  88582. animationRotation.setKeys(animationRotationKeys);
  88583. animationRotation.setEasingFunction(this._circleEase);
  88584. this.currentVRCamera.animations.push(animationRotation);
  88585. this._postProcessMove.animations = [];
  88586. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88587. var vignetteWeightKeys = [];
  88588. vignetteWeightKeys.push({
  88589. frame: 0,
  88590. value: 0
  88591. });
  88592. vignetteWeightKeys.push({
  88593. frame: 3,
  88594. value: 4
  88595. });
  88596. vignetteWeightKeys.push({
  88597. frame: 6,
  88598. value: 0
  88599. });
  88600. animationPP.setKeys(vignetteWeightKeys);
  88601. animationPP.setEasingFunction(this._circleEase);
  88602. this._postProcessMove.animations.push(animationPP);
  88603. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88604. var vignetteStretchKeys = [];
  88605. vignetteStretchKeys.push({
  88606. frame: 0,
  88607. value: 0
  88608. });
  88609. vignetteStretchKeys.push({
  88610. frame: 3,
  88611. value: 10
  88612. });
  88613. vignetteStretchKeys.push({
  88614. frame: 6,
  88615. value: 0
  88616. });
  88617. animationPP2.setKeys(vignetteStretchKeys);
  88618. animationPP2.setEasingFunction(this._circleEase);
  88619. this._postProcessMove.animations.push(animationPP2);
  88620. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88621. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88622. this._postProcessMove.samples = 4;
  88623. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88624. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  88625. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88626. });
  88627. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  88628. };
  88629. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  88630. if (hit.pickedPoint) {
  88631. if (gazer._teleportationRequestInitiated) {
  88632. this._displayTeleportationTarget();
  88633. this._haloCenter.copyFrom(hit.pickedPoint);
  88634. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  88635. }
  88636. var pickNormal = hit.getNormal(true, false);
  88637. if (pickNormal) {
  88638. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88639. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88640. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  88641. }
  88642. this._teleportationTarget.position.y += 0.1;
  88643. }
  88644. };
  88645. VRExperienceHelper.prototype._teleportCamera = function (location) {
  88646. var _this = this;
  88647. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88648. return;
  88649. }
  88650. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  88651. // offset of the headset from the anchor.
  88652. if (this.webVRCamera.leftCamera) {
  88653. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  88654. this._workingVector.subtractInPlace(this.webVRCamera.position);
  88655. location.subtractToRef(this._workingVector, this._workingVector);
  88656. }
  88657. else {
  88658. this._workingVector.copyFrom(location);
  88659. }
  88660. // Add height to account for user's height offset
  88661. if (this.isInVRMode) {
  88662. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  88663. }
  88664. else {
  88665. this._workingVector.y += this._defaultHeight;
  88666. }
  88667. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  88668. // Create animation from the camera's position to the new location
  88669. this.currentVRCamera.animations = [];
  88670. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88671. var animationCameraTeleportationKeys = [{
  88672. frame: 0,
  88673. value: this.currentVRCamera.position
  88674. },
  88675. {
  88676. frame: 11,
  88677. value: this._workingVector
  88678. }
  88679. ];
  88680. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  88681. animationCameraTeleportation.setEasingFunction(this._circleEase);
  88682. this.currentVRCamera.animations.push(animationCameraTeleportation);
  88683. this._postProcessMove.animations = [];
  88684. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88685. var vignetteWeightKeys = [];
  88686. vignetteWeightKeys.push({
  88687. frame: 0,
  88688. value: 0
  88689. });
  88690. vignetteWeightKeys.push({
  88691. frame: 5,
  88692. value: 8
  88693. });
  88694. vignetteWeightKeys.push({
  88695. frame: 11,
  88696. value: 0
  88697. });
  88698. animationPP.setKeys(vignetteWeightKeys);
  88699. this._postProcessMove.animations.push(animationPP);
  88700. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88701. var vignetteStretchKeys = [];
  88702. vignetteStretchKeys.push({
  88703. frame: 0,
  88704. value: 0
  88705. });
  88706. vignetteStretchKeys.push({
  88707. frame: 5,
  88708. value: 10
  88709. });
  88710. vignetteStretchKeys.push({
  88711. frame: 11,
  88712. value: 0
  88713. });
  88714. animationPP2.setKeys(vignetteStretchKeys);
  88715. this._postProcessMove.animations.push(animationPP2);
  88716. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88717. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88718. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88719. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  88720. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88721. });
  88722. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  88723. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  88724. });
  88725. this._hideTeleportationTarget();
  88726. };
  88727. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  88728. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88729. return;
  88730. }
  88731. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  88732. // Moving the gazeTracker on the mesh face targetted
  88733. if (hit && hit.pickedPoint) {
  88734. if (this._displayGaze) {
  88735. var multiplier = 1;
  88736. gazer._gazeTracker.isVisible = true;
  88737. if (gazer._isActionableMesh) {
  88738. multiplier = 3;
  88739. }
  88740. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  88741. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  88742. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  88743. var pickNormal = hit.getNormal();
  88744. // To avoid z-fighting
  88745. var deltaFighting = 0.002;
  88746. if (pickNormal) {
  88747. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88748. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88749. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  88750. }
  88751. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  88752. if (gazer._gazeTracker.position.x < 0) {
  88753. gazer._gazeTracker.position.x += deltaFighting;
  88754. }
  88755. else {
  88756. gazer._gazeTracker.position.x -= deltaFighting;
  88757. }
  88758. if (gazer._gazeTracker.position.y < 0) {
  88759. gazer._gazeTracker.position.y += deltaFighting;
  88760. }
  88761. else {
  88762. gazer._gazeTracker.position.y -= deltaFighting;
  88763. }
  88764. if (gazer._gazeTracker.position.z < 0) {
  88765. gazer._gazeTracker.position.z += deltaFighting;
  88766. }
  88767. else {
  88768. gazer._gazeTracker.position.z -= deltaFighting;
  88769. }
  88770. }
  88771. // Changing the size of the laser pointer based on the distance from the targetted point
  88772. gazer._updatePointerDistance(hit.distance);
  88773. }
  88774. else {
  88775. gazer._gazeTracker.isVisible = false;
  88776. }
  88777. if (hit && hit.pickedMesh) {
  88778. gazer._currentHit = hit;
  88779. if (gazer._pointerDownOnMeshAsked) {
  88780. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  88781. }
  88782. // The object selected is the floor, we're in a teleportation scenario
  88783. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  88784. // Moving the teleportation area to this targetted point
  88785. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  88786. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  88787. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88788. }
  88789. gazer._currentMeshSelected = null;
  88790. if (gazer._teleportationRequestInitiated) {
  88791. this._moveTeleportationSelectorTo(hit, gazer);
  88792. }
  88793. return;
  88794. }
  88795. // If not, we're in a selection scenario
  88796. //this._teleportationAllowed = false;
  88797. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  88798. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  88799. this.onNewMeshPicked.notifyObservers(hit);
  88800. gazer._currentMeshSelected = hit.pickedMesh;
  88801. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  88802. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  88803. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  88804. gazer._isActionableMesh = true;
  88805. }
  88806. else {
  88807. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88808. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88809. gazer._isActionableMesh = false;
  88810. }
  88811. try {
  88812. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  88813. }
  88814. catch (err) {
  88815. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  88816. }
  88817. }
  88818. else {
  88819. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88820. gazer._currentMeshSelected = null;
  88821. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88822. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88823. }
  88824. }
  88825. }
  88826. else {
  88827. gazer._currentHit = null;
  88828. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88829. gazer._currentMeshSelected = null;
  88830. //this._teleportationAllowed = false;
  88831. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88832. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88833. }
  88834. };
  88835. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  88836. if (mesh) {
  88837. this.onSelectedMeshUnselected.notifyObservers(mesh);
  88838. }
  88839. };
  88840. /**
  88841. * Sets the color of the laser ray from the vr controllers.
  88842. * @param color new color for the ray.
  88843. */
  88844. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  88845. if (this.leftController) {
  88846. this.leftController._setLaserPointerColor(color);
  88847. }
  88848. if (this.rightController) {
  88849. this.rightController._setLaserPointerColor(color);
  88850. }
  88851. };
  88852. /**
  88853. * Sets the color of the ray from the vr headsets gaze.
  88854. * @param color new color for the ray.
  88855. */
  88856. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  88857. if (!this._cameraGazer._gazeTracker.material) {
  88858. return;
  88859. }
  88860. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  88861. if (this.leftController) {
  88862. this.leftController._gazeTracker.material.emissiveColor = color;
  88863. }
  88864. if (this.rightController) {
  88865. this.rightController._gazeTracker.material.emissiveColor = color;
  88866. }
  88867. };
  88868. /**
  88869. * Exits VR and disposes of the vr experience helper
  88870. */
  88871. VRExperienceHelper.prototype.dispose = function () {
  88872. if (this.isInVRMode) {
  88873. this.exitVR();
  88874. }
  88875. if (this._postProcessMove) {
  88876. this._postProcessMove.dispose();
  88877. }
  88878. if (this._webVRCamera) {
  88879. this._webVRCamera.dispose();
  88880. }
  88881. if (this._vrDeviceOrientationCamera) {
  88882. this._vrDeviceOrientationCamera.dispose();
  88883. }
  88884. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  88885. document.body.removeChild(this._btnVR);
  88886. }
  88887. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  88888. this._deviceOrientationCamera.dispose();
  88889. }
  88890. if (this._cameraGazer) {
  88891. this._cameraGazer.dispose();
  88892. }
  88893. if (this.leftController) {
  88894. this.leftController.dispose();
  88895. }
  88896. if (this.rightController) {
  88897. this.rightController.dispose();
  88898. }
  88899. if (this._teleportationTarget) {
  88900. this._teleportationTarget.dispose();
  88901. }
  88902. this._floorMeshesCollection = [];
  88903. document.removeEventListener("keydown", this._onKeyDown);
  88904. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88905. window.removeEventListener("resize", this._onResize);
  88906. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  88907. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  88908. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  88909. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  88910. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  88911. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  88912. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  88913. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88914. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  88915. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  88916. this._scene.unregisterBeforeRender(this.beforeRender);
  88917. };
  88918. /**
  88919. * Gets the name of the VRExperienceHelper class
  88920. * @returns "VRExperienceHelper"
  88921. */
  88922. VRExperienceHelper.prototype.getClassName = function () {
  88923. return "VRExperienceHelper";
  88924. };
  88925. return VRExperienceHelper;
  88926. }());
  88927. BABYLON.VRExperienceHelper = VRExperienceHelper;
  88928. })(BABYLON || (BABYLON = {}));
  88929. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  88930. // Mainly based on these 2 articles :
  88931. // 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
  88932. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  88933. var BABYLON;
  88934. (function (BABYLON) {
  88935. /**
  88936. * Defines the potential axis of a Joystick
  88937. */
  88938. var JoystickAxis;
  88939. (function (JoystickAxis) {
  88940. /** X axis */
  88941. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  88942. /** Y axis */
  88943. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  88944. /** Z axis */
  88945. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  88946. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  88947. /**
  88948. * Class used to define virtual joystick (used in touch mode)
  88949. */
  88950. var VirtualJoystick = /** @class */ (function () {
  88951. /**
  88952. * Creates a new virtual joystick
  88953. * @param leftJoystick defines that the joystick is for left hand (false by default)
  88954. */
  88955. function VirtualJoystick(leftJoystick) {
  88956. var _this = this;
  88957. if (leftJoystick) {
  88958. this._leftJoystick = true;
  88959. }
  88960. else {
  88961. this._leftJoystick = false;
  88962. }
  88963. VirtualJoystick._globalJoystickIndex++;
  88964. // By default left & right arrow keys are moving the X
  88965. // and up & down keys are moving the Y
  88966. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  88967. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  88968. this.reverseLeftRight = false;
  88969. this.reverseUpDown = false;
  88970. // collections of pointers
  88971. this._touches = new BABYLON.StringDictionary();
  88972. this.deltaPosition = BABYLON.Vector3.Zero();
  88973. this._joystickSensibility = 25;
  88974. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88975. this._onResize = function (evt) {
  88976. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88977. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88978. if (VirtualJoystick.vjCanvas) {
  88979. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  88980. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  88981. }
  88982. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  88983. };
  88984. // injecting a canvas element on top of the canvas 3D game
  88985. if (!VirtualJoystick.vjCanvas) {
  88986. window.addEventListener("resize", this._onResize, false);
  88987. VirtualJoystick.vjCanvas = document.createElement("canvas");
  88988. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88989. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88990. VirtualJoystick.vjCanvas.width = window.innerWidth;
  88991. VirtualJoystick.vjCanvas.height = window.innerHeight;
  88992. VirtualJoystick.vjCanvas.style.width = "100%";
  88993. VirtualJoystick.vjCanvas.style.height = "100%";
  88994. VirtualJoystick.vjCanvas.style.position = "absolute";
  88995. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  88996. VirtualJoystick.vjCanvas.style.top = "0px";
  88997. VirtualJoystick.vjCanvas.style.left = "0px";
  88998. VirtualJoystick.vjCanvas.style.zIndex = "5";
  88999. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  89000. // Support for jQuery PEP polyfill
  89001. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  89002. var context = VirtualJoystick.vjCanvas.getContext('2d');
  89003. if (!context) {
  89004. throw new Error("Unable to create canvas for virtual joystick");
  89005. }
  89006. VirtualJoystick.vjCanvasContext = context;
  89007. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  89008. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89009. document.body.appendChild(VirtualJoystick.vjCanvas);
  89010. }
  89011. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  89012. this.pressed = false;
  89013. // default joystick color
  89014. this._joystickColor = "cyan";
  89015. this._joystickPointerID = -1;
  89016. // current joystick position
  89017. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  89018. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  89019. // origin joystick position
  89020. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  89021. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  89022. this._onPointerDownHandlerRef = function (evt) {
  89023. _this._onPointerDown(evt);
  89024. };
  89025. this._onPointerMoveHandlerRef = function (evt) {
  89026. _this._onPointerMove(evt);
  89027. };
  89028. this._onPointerUpHandlerRef = function (evt) {
  89029. _this._onPointerUp(evt);
  89030. };
  89031. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  89032. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  89033. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  89034. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  89035. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  89036. evt.preventDefault(); // Disables system menu
  89037. }, false);
  89038. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89039. }
  89040. /**
  89041. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  89042. * @param newJoystickSensibility defines the new sensibility
  89043. */
  89044. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  89045. this._joystickSensibility = newJoystickSensibility;
  89046. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89047. };
  89048. VirtualJoystick.prototype._onPointerDown = function (e) {
  89049. var positionOnScreenCondition;
  89050. e.preventDefault();
  89051. if (this._leftJoystick === true) {
  89052. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  89053. }
  89054. else {
  89055. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  89056. }
  89057. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  89058. // First contact will be dedicated to the virtual joystick
  89059. this._joystickPointerID = e.pointerId;
  89060. this._joystickPointerStartPos.x = e.clientX;
  89061. this._joystickPointerStartPos.y = e.clientY;
  89062. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  89063. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  89064. this._deltaJoystickVector.x = 0;
  89065. this._deltaJoystickVector.y = 0;
  89066. this.pressed = true;
  89067. this._touches.add(e.pointerId.toString(), e);
  89068. }
  89069. else {
  89070. // You can only trigger the action buttons with a joystick declared
  89071. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  89072. this._action();
  89073. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  89074. }
  89075. }
  89076. };
  89077. VirtualJoystick.prototype._onPointerMove = function (e) {
  89078. // If the current pointer is the one associated to the joystick (first touch contact)
  89079. if (this._joystickPointerID == e.pointerId) {
  89080. this._joystickPointerPos.x = e.clientX;
  89081. this._joystickPointerPos.y = e.clientY;
  89082. this._deltaJoystickVector = this._joystickPointerPos.clone();
  89083. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  89084. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  89085. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  89086. switch (this._axisTargetedByLeftAndRight) {
  89087. case JoystickAxis.X:
  89088. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  89089. break;
  89090. case JoystickAxis.Y:
  89091. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  89092. break;
  89093. case JoystickAxis.Z:
  89094. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  89095. break;
  89096. }
  89097. var directionUpDown = this.reverseUpDown ? 1 : -1;
  89098. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  89099. switch (this._axisTargetedByUpAndDown) {
  89100. case JoystickAxis.X:
  89101. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  89102. break;
  89103. case JoystickAxis.Y:
  89104. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  89105. break;
  89106. case JoystickAxis.Z:
  89107. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  89108. break;
  89109. }
  89110. }
  89111. else {
  89112. var data = this._touches.get(e.pointerId.toString());
  89113. if (data) {
  89114. data.x = e.clientX;
  89115. data.y = e.clientY;
  89116. }
  89117. }
  89118. };
  89119. VirtualJoystick.prototype._onPointerUp = function (e) {
  89120. if (this._joystickPointerID == e.pointerId) {
  89121. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  89122. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  89123. this._joystickPointerID = -1;
  89124. this.pressed = false;
  89125. }
  89126. else {
  89127. var touch = this._touches.get(e.pointerId.toString());
  89128. if (touch) {
  89129. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89130. }
  89131. }
  89132. this._deltaJoystickVector.x = 0;
  89133. this._deltaJoystickVector.y = 0;
  89134. this._touches.remove(e.pointerId.toString());
  89135. };
  89136. /**
  89137. * Change the color of the virtual joystick
  89138. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  89139. */
  89140. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  89141. this._joystickColor = newColor;
  89142. };
  89143. /**
  89144. * Defines a callback to call when the joystick is touched
  89145. * @param action defines the callback
  89146. */
  89147. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  89148. this._action = action;
  89149. };
  89150. /**
  89151. * Defines which axis you'd like to control for left & right
  89152. * @param axis defines the axis to use
  89153. */
  89154. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  89155. switch (axis) {
  89156. case JoystickAxis.X:
  89157. case JoystickAxis.Y:
  89158. case JoystickAxis.Z:
  89159. this._axisTargetedByLeftAndRight = axis;
  89160. break;
  89161. default:
  89162. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89163. break;
  89164. }
  89165. };
  89166. /**
  89167. * Defines which axis you'd like to control for up & down
  89168. * @param axis defines the axis to use
  89169. */
  89170. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  89171. switch (axis) {
  89172. case JoystickAxis.X:
  89173. case JoystickAxis.Y:
  89174. case JoystickAxis.Z:
  89175. this._axisTargetedByUpAndDown = axis;
  89176. break;
  89177. default:
  89178. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89179. break;
  89180. }
  89181. };
  89182. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  89183. var _this = this;
  89184. if (this.pressed) {
  89185. this._touches.forEach(function (key, touch) {
  89186. if (touch.pointerId === _this._joystickPointerID) {
  89187. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  89188. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  89189. VirtualJoystick.vjCanvasContext.beginPath();
  89190. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89191. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89192. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  89193. VirtualJoystick.vjCanvasContext.stroke();
  89194. VirtualJoystick.vjCanvasContext.closePath();
  89195. VirtualJoystick.vjCanvasContext.beginPath();
  89196. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89197. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89198. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  89199. VirtualJoystick.vjCanvasContext.stroke();
  89200. VirtualJoystick.vjCanvasContext.closePath();
  89201. VirtualJoystick.vjCanvasContext.beginPath();
  89202. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89203. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  89204. VirtualJoystick.vjCanvasContext.stroke();
  89205. VirtualJoystick.vjCanvasContext.closePath();
  89206. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  89207. }
  89208. else {
  89209. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89210. VirtualJoystick.vjCanvasContext.beginPath();
  89211. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  89212. VirtualJoystick.vjCanvasContext.beginPath();
  89213. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  89214. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89215. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  89216. VirtualJoystick.vjCanvasContext.stroke();
  89217. VirtualJoystick.vjCanvasContext.closePath();
  89218. touch.prevX = touch.x;
  89219. touch.prevY = touch.y;
  89220. }
  89221. ;
  89222. });
  89223. }
  89224. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89225. };
  89226. /**
  89227. * Release internal HTML canvas
  89228. */
  89229. VirtualJoystick.prototype.releaseCanvas = function () {
  89230. if (VirtualJoystick.vjCanvas) {
  89231. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  89232. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  89233. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  89234. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  89235. window.removeEventListener("resize", this._onResize);
  89236. document.body.removeChild(VirtualJoystick.vjCanvas);
  89237. VirtualJoystick.vjCanvas = null;
  89238. }
  89239. };
  89240. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  89241. VirtualJoystick._globalJoystickIndex = 0;
  89242. return VirtualJoystick;
  89243. }());
  89244. BABYLON.VirtualJoystick = VirtualJoystick;
  89245. })(BABYLON || (BABYLON = {}));
  89246. //# sourceMappingURL=babylon.virtualJoystick.js.map
  89247. var BABYLON;
  89248. (function (BABYLON) {
  89249. // We're mainly based on the logic defined into the FreeCamera code
  89250. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  89251. __extends(VirtualJoysticksCamera, _super);
  89252. function VirtualJoysticksCamera(name, position, scene) {
  89253. var _this = _super.call(this, name, position, scene) || this;
  89254. _this.inputs.addVirtualJoystick();
  89255. return _this;
  89256. }
  89257. VirtualJoysticksCamera.prototype.getClassName = function () {
  89258. return "VirtualJoysticksCamera";
  89259. };
  89260. return VirtualJoysticksCamera;
  89261. }(BABYLON.FreeCamera));
  89262. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  89263. })(BABYLON || (BABYLON = {}));
  89264. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  89265. var BABYLON;
  89266. (function (BABYLON) {
  89267. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  89268. function FreeCameraVirtualJoystickInput() {
  89269. }
  89270. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  89271. return this._leftjoystick;
  89272. };
  89273. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  89274. return this._rightjoystick;
  89275. };
  89276. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  89277. if (this._leftjoystick) {
  89278. var camera = this.camera;
  89279. var speed = camera._computeLocalCameraSpeed() * 50;
  89280. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  89281. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  89282. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  89283. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  89284. if (!this._leftjoystick.pressed) {
  89285. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  89286. }
  89287. if (!this._rightjoystick.pressed) {
  89288. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  89289. }
  89290. }
  89291. };
  89292. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  89293. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  89294. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  89295. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  89296. this._leftjoystick.setJoystickSensibility(0.15);
  89297. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  89298. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  89299. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  89300. this._rightjoystick.reverseUpDown = true;
  89301. this._rightjoystick.setJoystickSensibility(0.05);
  89302. this._rightjoystick.setJoystickColor("yellow");
  89303. };
  89304. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  89305. this._leftjoystick.releaseCanvas();
  89306. this._rightjoystick.releaseCanvas();
  89307. };
  89308. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  89309. return "FreeCameraVirtualJoystickInput";
  89310. };
  89311. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  89312. return "virtualJoystick";
  89313. };
  89314. return FreeCameraVirtualJoystickInput;
  89315. }());
  89316. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  89317. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  89318. })(BABYLON || (BABYLON = {}));
  89319. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  89320. var BABYLON;
  89321. (function (BABYLON) {
  89322. var SimplificationSettings = /** @class */ (function () {
  89323. function SimplificationSettings(quality, distance, optimizeMesh) {
  89324. this.quality = quality;
  89325. this.distance = distance;
  89326. this.optimizeMesh = optimizeMesh;
  89327. }
  89328. return SimplificationSettings;
  89329. }());
  89330. BABYLON.SimplificationSettings = SimplificationSettings;
  89331. var SimplificationQueue = /** @class */ (function () {
  89332. function SimplificationQueue() {
  89333. this.running = false;
  89334. this._simplificationArray = [];
  89335. }
  89336. SimplificationQueue.prototype.addTask = function (task) {
  89337. this._simplificationArray.push(task);
  89338. };
  89339. SimplificationQueue.prototype.executeNext = function () {
  89340. var task = this._simplificationArray.pop();
  89341. if (task) {
  89342. this.running = true;
  89343. this.runSimplification(task);
  89344. }
  89345. else {
  89346. this.running = false;
  89347. }
  89348. };
  89349. SimplificationQueue.prototype.runSimplification = function (task) {
  89350. var _this = this;
  89351. if (task.parallelProcessing) {
  89352. //parallel simplifier
  89353. task.settings.forEach(function (setting) {
  89354. var simplifier = _this.getSimplifier(task);
  89355. simplifier.simplify(setting, function (newMesh) {
  89356. task.mesh.addLODLevel(setting.distance, newMesh);
  89357. newMesh.isVisible = true;
  89358. //check if it is the last
  89359. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  89360. //all done, run the success callback.
  89361. task.successCallback();
  89362. }
  89363. _this.executeNext();
  89364. });
  89365. });
  89366. }
  89367. else {
  89368. //single simplifier.
  89369. var simplifier = this.getSimplifier(task);
  89370. var runDecimation = function (setting, callback) {
  89371. simplifier.simplify(setting, function (newMesh) {
  89372. task.mesh.addLODLevel(setting.distance, newMesh);
  89373. newMesh.isVisible = true;
  89374. //run the next quality level
  89375. callback();
  89376. });
  89377. };
  89378. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  89379. runDecimation(task.settings[loop.index], function () {
  89380. loop.executeNext();
  89381. });
  89382. }, function () {
  89383. //execution ended, run the success callback.
  89384. if (task.successCallback) {
  89385. task.successCallback();
  89386. }
  89387. _this.executeNext();
  89388. });
  89389. }
  89390. };
  89391. SimplificationQueue.prototype.getSimplifier = function (task) {
  89392. switch (task.simplificationType) {
  89393. case SimplificationType.QUADRATIC:
  89394. default:
  89395. return new QuadraticErrorSimplification(task.mesh);
  89396. }
  89397. };
  89398. return SimplificationQueue;
  89399. }());
  89400. BABYLON.SimplificationQueue = SimplificationQueue;
  89401. /**
  89402. * The implemented types of simplification
  89403. * At the moment only Quadratic Error Decimation is implemented
  89404. */
  89405. var SimplificationType;
  89406. (function (SimplificationType) {
  89407. /** Quadratic error decimation */
  89408. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  89409. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  89410. var DecimationTriangle = /** @class */ (function () {
  89411. function DecimationTriangle(vertices) {
  89412. this.vertices = vertices;
  89413. this.error = new Array(4);
  89414. this.deleted = false;
  89415. this.isDirty = false;
  89416. this.deletePending = false;
  89417. this.borderFactor = 0;
  89418. }
  89419. return DecimationTriangle;
  89420. }());
  89421. BABYLON.DecimationTriangle = DecimationTriangle;
  89422. var DecimationVertex = /** @class */ (function () {
  89423. function DecimationVertex(position, id) {
  89424. this.position = position;
  89425. this.id = id;
  89426. this.isBorder = true;
  89427. this.q = new QuadraticMatrix();
  89428. this.triangleCount = 0;
  89429. this.triangleStart = 0;
  89430. this.originalOffsets = [];
  89431. }
  89432. DecimationVertex.prototype.updatePosition = function (newPosition) {
  89433. this.position.copyFrom(newPosition);
  89434. };
  89435. return DecimationVertex;
  89436. }());
  89437. BABYLON.DecimationVertex = DecimationVertex;
  89438. var QuadraticMatrix = /** @class */ (function () {
  89439. function QuadraticMatrix(data) {
  89440. this.data = new Array(10);
  89441. for (var i = 0; i < 10; ++i) {
  89442. if (data && data[i]) {
  89443. this.data[i] = data[i];
  89444. }
  89445. else {
  89446. this.data[i] = 0;
  89447. }
  89448. }
  89449. }
  89450. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  89451. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  89452. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  89453. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  89454. return det;
  89455. };
  89456. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  89457. for (var i = 0; i < 10; ++i) {
  89458. this.data[i] += matrix.data[i];
  89459. }
  89460. };
  89461. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  89462. for (var i = 0; i < 10; ++i) {
  89463. this.data[i] += data[i];
  89464. }
  89465. };
  89466. QuadraticMatrix.prototype.add = function (matrix) {
  89467. var m = new QuadraticMatrix();
  89468. for (var i = 0; i < 10; ++i) {
  89469. m.data[i] = this.data[i] + matrix.data[i];
  89470. }
  89471. return m;
  89472. };
  89473. QuadraticMatrix.FromData = function (a, b, c, d) {
  89474. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  89475. };
  89476. //returning an array to avoid garbage collection
  89477. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  89478. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  89479. };
  89480. return QuadraticMatrix;
  89481. }());
  89482. BABYLON.QuadraticMatrix = QuadraticMatrix;
  89483. var Reference = /** @class */ (function () {
  89484. function Reference(vertexId, triangleId) {
  89485. this.vertexId = vertexId;
  89486. this.triangleId = triangleId;
  89487. }
  89488. return Reference;
  89489. }());
  89490. BABYLON.Reference = Reference;
  89491. /**
  89492. * An implementation of the Quadratic Error simplification algorithm.
  89493. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  89494. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  89495. * @author RaananW
  89496. */
  89497. var QuadraticErrorSimplification = /** @class */ (function () {
  89498. function QuadraticErrorSimplification(_mesh) {
  89499. this._mesh = _mesh;
  89500. this.syncIterations = 5000;
  89501. this.aggressiveness = 7;
  89502. this.decimationIterations = 100;
  89503. this.boundingBoxEpsilon = BABYLON.Epsilon;
  89504. }
  89505. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  89506. var _this = this;
  89507. this.initDecimatedMesh();
  89508. //iterating through the submeshes array, one after the other.
  89509. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  89510. _this.initWithMesh(loop.index, function () {
  89511. _this.runDecimation(settings, loop.index, function () {
  89512. loop.executeNext();
  89513. });
  89514. }, settings.optimizeMesh);
  89515. }, function () {
  89516. setTimeout(function () {
  89517. successCallback(_this._reconstructedMesh);
  89518. }, 0);
  89519. });
  89520. };
  89521. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  89522. var _this = this;
  89523. var targetCount = ~~(this.triangles.length * settings.quality);
  89524. var deletedTriangles = 0;
  89525. var triangleCount = this.triangles.length;
  89526. var iterationFunction = function (iteration, callback) {
  89527. setTimeout(function () {
  89528. if (iteration % 5 === 0) {
  89529. _this.updateMesh(iteration === 0);
  89530. }
  89531. for (var i = 0; i < _this.triangles.length; ++i) {
  89532. _this.triangles[i].isDirty = false;
  89533. }
  89534. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  89535. var trianglesIterator = function (i) {
  89536. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  89537. var t = _this.triangles[tIdx];
  89538. if (!t)
  89539. return;
  89540. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  89541. return;
  89542. }
  89543. for (var j = 0; j < 3; ++j) {
  89544. if (t.error[j] < threshold) {
  89545. var deleted0 = [];
  89546. var deleted1 = [];
  89547. var v0 = t.vertices[j];
  89548. var v1 = t.vertices[(j + 1) % 3];
  89549. if (v0.isBorder || v1.isBorder)
  89550. continue;
  89551. var p = BABYLON.Vector3.Zero();
  89552. var n = BABYLON.Vector3.Zero();
  89553. var uv = BABYLON.Vector2.Zero();
  89554. var color = new BABYLON.Color4(0, 0, 0, 1);
  89555. _this.calculateError(v0, v1, p, n, uv, color);
  89556. var delTr = new Array();
  89557. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  89558. continue;
  89559. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  89560. continue;
  89561. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  89562. continue;
  89563. var uniqueArray = new Array();
  89564. delTr.forEach(function (deletedT) {
  89565. if (uniqueArray.indexOf(deletedT) === -1) {
  89566. deletedT.deletePending = true;
  89567. uniqueArray.push(deletedT);
  89568. }
  89569. });
  89570. if (uniqueArray.length % 2 !== 0) {
  89571. continue;
  89572. }
  89573. v0.q = v1.q.add(v0.q);
  89574. v0.updatePosition(p);
  89575. var tStart = _this.references.length;
  89576. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  89577. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  89578. var tCount = _this.references.length - tStart;
  89579. if (tCount <= v0.triangleCount) {
  89580. if (tCount) {
  89581. for (var c = 0; c < tCount; c++) {
  89582. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  89583. }
  89584. }
  89585. }
  89586. else {
  89587. v0.triangleStart = tStart;
  89588. }
  89589. v0.triangleCount = tCount;
  89590. break;
  89591. }
  89592. }
  89593. };
  89594. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  89595. }, 0);
  89596. };
  89597. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  89598. if (triangleCount - deletedTriangles <= targetCount)
  89599. loop.breakLoop();
  89600. else {
  89601. iterationFunction(loop.index, function () {
  89602. loop.executeNext();
  89603. });
  89604. }
  89605. }, function () {
  89606. setTimeout(function () {
  89607. //reconstruct this part of the mesh
  89608. _this.reconstructMesh(submeshIndex);
  89609. successCallback();
  89610. }, 0);
  89611. });
  89612. };
  89613. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  89614. var _this = this;
  89615. this.vertices = [];
  89616. this.triangles = [];
  89617. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  89618. var indices = this._mesh.getIndices();
  89619. var submesh = this._mesh.subMeshes[submeshIndex];
  89620. var findInVertices = function (positionToSearch) {
  89621. if (optimizeMesh) {
  89622. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  89623. if (_this.vertices[ii].position.equals(positionToSearch)) {
  89624. return _this.vertices[ii];
  89625. }
  89626. }
  89627. }
  89628. return null;
  89629. };
  89630. var vertexReferences = [];
  89631. var vertexInit = function (i) {
  89632. if (!positionData) {
  89633. return;
  89634. }
  89635. var offset = i + submesh.verticesStart;
  89636. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  89637. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  89638. vertex.originalOffsets.push(offset);
  89639. if (vertex.id === _this.vertices.length) {
  89640. _this.vertices.push(vertex);
  89641. }
  89642. vertexReferences.push(vertex.id);
  89643. };
  89644. //var totalVertices = mesh.getTotalVertices();
  89645. var totalVertices = submesh.verticesCount;
  89646. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  89647. var indicesInit = function (i) {
  89648. if (!indices) {
  89649. return;
  89650. }
  89651. var offset = (submesh.indexStart / 3) + i;
  89652. var pos = (offset * 3);
  89653. var i0 = indices[pos + 0];
  89654. var i1 = indices[pos + 1];
  89655. var i2 = indices[pos + 2];
  89656. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  89657. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  89658. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  89659. var triangle = new DecimationTriangle([v0, v1, v2]);
  89660. triangle.originalOffset = pos;
  89661. _this.triangles.push(triangle);
  89662. };
  89663. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  89664. _this.init(callback);
  89665. });
  89666. });
  89667. };
  89668. QuadraticErrorSimplification.prototype.init = function (callback) {
  89669. var _this = this;
  89670. var triangleInit1 = function (i) {
  89671. var t = _this.triangles[i];
  89672. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  89673. for (var j = 0; j < 3; j++) {
  89674. 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))));
  89675. }
  89676. };
  89677. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  89678. var triangleInit2 = function (i) {
  89679. var t = _this.triangles[i];
  89680. for (var j = 0; j < 3; ++j) {
  89681. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  89682. }
  89683. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89684. };
  89685. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  89686. callback();
  89687. });
  89688. });
  89689. };
  89690. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  89691. var newTriangles = [];
  89692. var i;
  89693. for (i = 0; i < this.vertices.length; ++i) {
  89694. this.vertices[i].triangleCount = 0;
  89695. }
  89696. var t;
  89697. var j;
  89698. for (i = 0; i < this.triangles.length; ++i) {
  89699. if (!this.triangles[i].deleted) {
  89700. t = this.triangles[i];
  89701. for (j = 0; j < 3; ++j) {
  89702. t.vertices[j].triangleCount = 1;
  89703. }
  89704. newTriangles.push(t);
  89705. }
  89706. }
  89707. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  89708. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  89709. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  89710. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  89711. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  89712. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89713. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  89714. var vertexCount = 0;
  89715. for (i = 0; i < this.vertices.length; ++i) {
  89716. var vertex = this.vertices[i];
  89717. vertex.id = vertexCount;
  89718. if (vertex.triangleCount) {
  89719. vertex.originalOffsets.forEach(function (originalOffset) {
  89720. if (!normalData) {
  89721. return;
  89722. }
  89723. newPositionData.push(vertex.position.x);
  89724. newPositionData.push(vertex.position.y);
  89725. newPositionData.push(vertex.position.z);
  89726. newNormalData.push(normalData[originalOffset * 3]);
  89727. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  89728. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  89729. if (uvs && uvs.length) {
  89730. newUVsData.push(uvs[(originalOffset * 2)]);
  89731. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  89732. }
  89733. else if (colorsData && colorsData.length) {
  89734. newColorsData.push(colorsData[(originalOffset * 4)]);
  89735. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  89736. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  89737. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  89738. }
  89739. ++vertexCount;
  89740. });
  89741. }
  89742. }
  89743. var startingIndex = this._reconstructedMesh.getTotalIndices();
  89744. var startingVertex = this._reconstructedMesh.getTotalVertices();
  89745. var submeshesArray = this._reconstructedMesh.subMeshes;
  89746. this._reconstructedMesh.subMeshes = [];
  89747. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  89748. var originalIndices = this._mesh.getIndices();
  89749. for (i = 0; i < newTriangles.length; ++i) {
  89750. t = newTriangles[i]; //now get the new referencing point for each vertex
  89751. [0, 1, 2].forEach(function (idx) {
  89752. var id = originalIndices[t.originalOffset + idx];
  89753. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  89754. if (offset < 0)
  89755. offset = 0;
  89756. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  89757. });
  89758. }
  89759. //overwriting the old vertex buffers and indices.
  89760. this._reconstructedMesh.setIndices(newIndicesArray);
  89761. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  89762. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  89763. if (newUVsData.length > 0)
  89764. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  89765. if (newColorsData.length > 0)
  89766. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  89767. //create submesh
  89768. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  89769. if (submeshIndex > 0) {
  89770. this._reconstructedMesh.subMeshes = [];
  89771. submeshesArray.forEach(function (submesh) {
  89772. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  89773. });
  89774. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  89775. }
  89776. };
  89777. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  89778. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  89779. this._reconstructedMesh.material = this._mesh.material;
  89780. this._reconstructedMesh.parent = this._mesh.parent;
  89781. this._reconstructedMesh.isVisible = false;
  89782. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  89783. };
  89784. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  89785. for (var i = 0; i < vertex1.triangleCount; ++i) {
  89786. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  89787. if (t.deleted)
  89788. continue;
  89789. var s = this.references[vertex1.triangleStart + i].vertexId;
  89790. var v1 = t.vertices[(s + 1) % 3];
  89791. var v2 = t.vertices[(s + 2) % 3];
  89792. if ((v1 === vertex2 || v2 === vertex2)) {
  89793. deletedArray[i] = true;
  89794. delTr.push(t);
  89795. continue;
  89796. }
  89797. var d1 = v1.position.subtract(point);
  89798. d1 = d1.normalize();
  89799. var d2 = v2.position.subtract(point);
  89800. d2 = d2.normalize();
  89801. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  89802. return true;
  89803. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  89804. deletedArray[i] = false;
  89805. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  89806. return true;
  89807. }
  89808. return false;
  89809. };
  89810. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  89811. var newDeleted = deletedTriangles;
  89812. for (var i = 0; i < vertex.triangleCount; ++i) {
  89813. var ref = this.references[vertex.triangleStart + i];
  89814. var t = this.triangles[ref.triangleId];
  89815. if (t.deleted)
  89816. continue;
  89817. if (deletedArray[i] && t.deletePending) {
  89818. t.deleted = true;
  89819. newDeleted++;
  89820. continue;
  89821. }
  89822. t.vertices[ref.vertexId] = origVertex;
  89823. t.isDirty = true;
  89824. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  89825. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  89826. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  89827. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89828. this.references.push(ref);
  89829. }
  89830. return newDeleted;
  89831. };
  89832. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  89833. for (var i = 0; i < this.vertices.length; ++i) {
  89834. var vCount = [];
  89835. var vId = [];
  89836. var v = this.vertices[i];
  89837. var j;
  89838. for (j = 0; j < v.triangleCount; ++j) {
  89839. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  89840. for (var ii = 0; ii < 3; ii++) {
  89841. var ofs = 0;
  89842. var vv = triangle.vertices[ii];
  89843. while (ofs < vCount.length) {
  89844. if (vId[ofs] === vv.id)
  89845. break;
  89846. ++ofs;
  89847. }
  89848. if (ofs === vCount.length) {
  89849. vCount.push(1);
  89850. vId.push(vv.id);
  89851. }
  89852. else {
  89853. vCount[ofs]++;
  89854. }
  89855. }
  89856. }
  89857. for (j = 0; j < vCount.length; ++j) {
  89858. if (vCount[j] === 1) {
  89859. this.vertices[vId[j]].isBorder = true;
  89860. }
  89861. else {
  89862. this.vertices[vId[j]].isBorder = false;
  89863. }
  89864. }
  89865. }
  89866. };
  89867. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  89868. if (identifyBorders === void 0) { identifyBorders = false; }
  89869. var i;
  89870. if (!identifyBorders) {
  89871. var newTrianglesVector = [];
  89872. for (i = 0; i < this.triangles.length; ++i) {
  89873. if (!this.triangles[i].deleted) {
  89874. newTrianglesVector.push(this.triangles[i]);
  89875. }
  89876. }
  89877. this.triangles = newTrianglesVector;
  89878. }
  89879. for (i = 0; i < this.vertices.length; ++i) {
  89880. this.vertices[i].triangleCount = 0;
  89881. this.vertices[i].triangleStart = 0;
  89882. }
  89883. var t;
  89884. var j;
  89885. var v;
  89886. for (i = 0; i < this.triangles.length; ++i) {
  89887. t = this.triangles[i];
  89888. for (j = 0; j < 3; ++j) {
  89889. v = t.vertices[j];
  89890. v.triangleCount++;
  89891. }
  89892. }
  89893. var tStart = 0;
  89894. for (i = 0; i < this.vertices.length; ++i) {
  89895. this.vertices[i].triangleStart = tStart;
  89896. tStart += this.vertices[i].triangleCount;
  89897. this.vertices[i].triangleCount = 0;
  89898. }
  89899. var newReferences = new Array(this.triangles.length * 3);
  89900. for (i = 0; i < this.triangles.length; ++i) {
  89901. t = this.triangles[i];
  89902. for (j = 0; j < 3; ++j) {
  89903. v = t.vertices[j];
  89904. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  89905. v.triangleCount++;
  89906. }
  89907. }
  89908. this.references = newReferences;
  89909. if (identifyBorders) {
  89910. this.identifyBorder();
  89911. }
  89912. };
  89913. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  89914. var x = point.x;
  89915. var y = point.y;
  89916. var z = point.z;
  89917. 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
  89918. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  89919. };
  89920. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  89921. var q = vertex1.q.add(vertex2.q);
  89922. var border = vertex1.isBorder && vertex2.isBorder;
  89923. var error = 0;
  89924. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  89925. if (qDet !== 0 && !border) {
  89926. if (!pointResult) {
  89927. pointResult = BABYLON.Vector3.Zero();
  89928. }
  89929. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  89930. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  89931. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  89932. error = this.vertexError(q, pointResult);
  89933. }
  89934. else {
  89935. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  89936. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  89937. var error1 = this.vertexError(q, vertex1.position);
  89938. var error2 = this.vertexError(q, vertex2.position);
  89939. var error3 = this.vertexError(q, p3);
  89940. error = Math.min(error1, error2, error3);
  89941. if (error === error1) {
  89942. if (pointResult) {
  89943. pointResult.copyFrom(vertex1.position);
  89944. }
  89945. }
  89946. else if (error === error2) {
  89947. if (pointResult) {
  89948. pointResult.copyFrom(vertex2.position);
  89949. }
  89950. }
  89951. else {
  89952. if (pointResult) {
  89953. pointResult.copyFrom(p3);
  89954. }
  89955. }
  89956. }
  89957. return error;
  89958. };
  89959. return QuadraticErrorSimplification;
  89960. }());
  89961. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  89962. })(BABYLON || (BABYLON = {}));
  89963. //# sourceMappingURL=babylon.meshSimplification.js.map
  89964. var BABYLON;
  89965. (function (BABYLON) {
  89966. var MeshLODLevel = /** @class */ (function () {
  89967. function MeshLODLevel(distance, mesh) {
  89968. this.distance = distance;
  89969. this.mesh = mesh;
  89970. }
  89971. return MeshLODLevel;
  89972. }());
  89973. BABYLON.MeshLODLevel = MeshLODLevel;
  89974. })(BABYLON || (BABYLON = {}));
  89975. //# sourceMappingURL=babylon.meshLODLevel.js.map
  89976. var BABYLON;
  89977. (function (BABYLON) {
  89978. /**
  89979. * Defines the root class used to create scene optimization to use with SceneOptimizer
  89980. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89981. */
  89982. var SceneOptimization = /** @class */ (function () {
  89983. /**
  89984. * Creates the SceneOptimization object
  89985. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89986. * @param desc defines the description associated with the optimization
  89987. */
  89988. function SceneOptimization(
  89989. /**
  89990. * Defines the priority of this optimization (0 by default which means first in the list)
  89991. */
  89992. priority) {
  89993. if (priority === void 0) { priority = 0; }
  89994. this.priority = priority;
  89995. }
  89996. /**
  89997. * Gets a string describing the action executed by the current optimization
  89998. * @returns description string
  89999. */
  90000. SceneOptimization.prototype.getDescription = function () {
  90001. return "";
  90002. };
  90003. /**
  90004. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90005. * @param scene defines the current scene where to apply this optimization
  90006. * @param optimizer defines the current optimizer
  90007. * @returns true if everything that can be done was applied
  90008. */
  90009. SceneOptimization.prototype.apply = function (scene, optimizer) {
  90010. return true;
  90011. };
  90012. ;
  90013. return SceneOptimization;
  90014. }());
  90015. BABYLON.SceneOptimization = SceneOptimization;
  90016. /**
  90017. * Defines an optimization used to reduce the size of render target textures
  90018. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90019. */
  90020. var TextureOptimization = /** @class */ (function (_super) {
  90021. __extends(TextureOptimization, _super);
  90022. /**
  90023. * Creates the TextureOptimization object
  90024. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90025. * @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
  90026. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90027. */
  90028. function TextureOptimization(
  90029. /**
  90030. * Defines the priority of this optimization (0 by default which means first in the list)
  90031. */
  90032. priority,
  90033. /**
  90034. * 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
  90035. */
  90036. maximumSize,
  90037. /**
  90038. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90039. */
  90040. step) {
  90041. if (priority === void 0) { priority = 0; }
  90042. if (maximumSize === void 0) { maximumSize = 1024; }
  90043. if (step === void 0) { step = 0.5; }
  90044. var _this = _super.call(this, priority) || this;
  90045. _this.priority = priority;
  90046. _this.maximumSize = maximumSize;
  90047. _this.step = step;
  90048. return _this;
  90049. }
  90050. /**
  90051. * Gets a string describing the action executed by the current optimization
  90052. * @returns description string
  90053. */
  90054. TextureOptimization.prototype.getDescription = function () {
  90055. return "Reducing render target texture size to " + this.maximumSize;
  90056. };
  90057. /**
  90058. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90059. * @param scene defines the current scene where to apply this optimization
  90060. * @param optimizer defines the current optimizer
  90061. * @returns true if everything that can be done was applied
  90062. */
  90063. TextureOptimization.prototype.apply = function (scene, optimizer) {
  90064. var allDone = true;
  90065. for (var index = 0; index < scene.textures.length; index++) {
  90066. var texture = scene.textures[index];
  90067. if (!texture.canRescale || texture.getContext) {
  90068. continue;
  90069. }
  90070. var currentSize = texture.getSize();
  90071. var maxDimension = Math.max(currentSize.width, currentSize.height);
  90072. if (maxDimension > this.maximumSize) {
  90073. texture.scale(this.step);
  90074. allDone = false;
  90075. }
  90076. }
  90077. return allDone;
  90078. };
  90079. return TextureOptimization;
  90080. }(SceneOptimization));
  90081. BABYLON.TextureOptimization = TextureOptimization;
  90082. /**
  90083. * Defines an optimization used to increase or decrease the rendering resolution
  90084. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90085. */
  90086. var HardwareScalingOptimization = /** @class */ (function (_super) {
  90087. __extends(HardwareScalingOptimization, _super);
  90088. /**
  90089. * Creates the HardwareScalingOptimization object
  90090. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90091. * @param maximumScale defines the maximum scale to use (2 by default)
  90092. * @param step defines the step to use between two passes (0.5 by default)
  90093. */
  90094. function HardwareScalingOptimization(
  90095. /**
  90096. * Defines the priority of this optimization (0 by default which means first in the list)
  90097. */
  90098. priority,
  90099. /**
  90100. * Defines the maximum scale to use (2 by default)
  90101. */
  90102. maximumScale,
  90103. /**
  90104. * Defines the step to use between two passes (0.5 by default)
  90105. */
  90106. step) {
  90107. if (priority === void 0) { priority = 0; }
  90108. if (maximumScale === void 0) { maximumScale = 2; }
  90109. if (step === void 0) { step = 0.25; }
  90110. var _this = _super.call(this, priority) || this;
  90111. _this.priority = priority;
  90112. _this.maximumScale = maximumScale;
  90113. _this.step = step;
  90114. _this._currentScale = -1;
  90115. _this._directionOffset = 1;
  90116. return _this;
  90117. }
  90118. /**
  90119. * Gets a string describing the action executed by the current optimization
  90120. * @return description string
  90121. */
  90122. HardwareScalingOptimization.prototype.getDescription = function () {
  90123. return "Setting hardware scaling level to " + this._currentScale;
  90124. };
  90125. /**
  90126. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90127. * @param scene defines the current scene where to apply this optimization
  90128. * @param optimizer defines the current optimizer
  90129. * @returns true if everything that can be done was applied
  90130. */
  90131. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  90132. if (this._currentScale === -1) {
  90133. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  90134. if (this._currentScale > this.maximumScale) {
  90135. this._directionOffset = -1;
  90136. }
  90137. }
  90138. this._currentScale += this._directionOffset * this.step;
  90139. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  90140. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  90141. };
  90142. ;
  90143. return HardwareScalingOptimization;
  90144. }(SceneOptimization));
  90145. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  90146. /**
  90147. * Defines an optimization used to remove shadows
  90148. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90149. */
  90150. var ShadowsOptimization = /** @class */ (function (_super) {
  90151. __extends(ShadowsOptimization, _super);
  90152. function ShadowsOptimization() {
  90153. return _super !== null && _super.apply(this, arguments) || this;
  90154. }
  90155. /**
  90156. * Gets a string describing the action executed by the current optimization
  90157. * @return description string
  90158. */
  90159. ShadowsOptimization.prototype.getDescription = function () {
  90160. return "Turning shadows on/off";
  90161. };
  90162. /**
  90163. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90164. * @param scene defines the current scene where to apply this optimization
  90165. * @param optimizer defines the current optimizer
  90166. * @returns true if everything that can be done was applied
  90167. */
  90168. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  90169. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90170. return true;
  90171. };
  90172. ;
  90173. return ShadowsOptimization;
  90174. }(SceneOptimization));
  90175. BABYLON.ShadowsOptimization = ShadowsOptimization;
  90176. /**
  90177. * Defines an optimization used to turn post-processes off
  90178. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90179. */
  90180. var PostProcessesOptimization = /** @class */ (function (_super) {
  90181. __extends(PostProcessesOptimization, _super);
  90182. function PostProcessesOptimization() {
  90183. return _super !== null && _super.apply(this, arguments) || this;
  90184. }
  90185. /**
  90186. * Gets a string describing the action executed by the current optimization
  90187. * @return description string
  90188. */
  90189. PostProcessesOptimization.prototype.getDescription = function () {
  90190. return "Turning post-processes on/off";
  90191. };
  90192. /**
  90193. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90194. * @param scene defines the current scene where to apply this optimization
  90195. * @param optimizer defines the current optimizer
  90196. * @returns true if everything that can be done was applied
  90197. */
  90198. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  90199. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  90200. return true;
  90201. };
  90202. ;
  90203. return PostProcessesOptimization;
  90204. }(SceneOptimization));
  90205. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  90206. /**
  90207. * Defines an optimization used to turn lens flares off
  90208. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90209. */
  90210. var LensFlaresOptimization = /** @class */ (function (_super) {
  90211. __extends(LensFlaresOptimization, _super);
  90212. function LensFlaresOptimization() {
  90213. return _super !== null && _super.apply(this, arguments) || this;
  90214. }
  90215. /**
  90216. * Gets a string describing the action executed by the current optimization
  90217. * @return description string
  90218. */
  90219. LensFlaresOptimization.prototype.getDescription = function () {
  90220. return "Turning lens flares on/off";
  90221. };
  90222. /**
  90223. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90224. * @param scene defines the current scene where to apply this optimization
  90225. * @param optimizer defines the current optimizer
  90226. * @returns true if everything that can be done was applied
  90227. */
  90228. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  90229. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  90230. return true;
  90231. };
  90232. ;
  90233. return LensFlaresOptimization;
  90234. }(SceneOptimization));
  90235. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  90236. /**
  90237. * Defines an optimization based on user defined callback.
  90238. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90239. */
  90240. var CustomOptimization = /** @class */ (function (_super) {
  90241. __extends(CustomOptimization, _super);
  90242. function CustomOptimization() {
  90243. return _super !== null && _super.apply(this, arguments) || this;
  90244. }
  90245. /**
  90246. * Gets a string describing the action executed by the current optimization
  90247. * @returns description string
  90248. */
  90249. CustomOptimization.prototype.getDescription = function () {
  90250. if (this.onGetDescription) {
  90251. return this.onGetDescription();
  90252. }
  90253. return "Running user defined callback";
  90254. };
  90255. /**
  90256. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90257. * @param scene defines the current scene where to apply this optimization
  90258. * @param optimizer defines the current optimizer
  90259. * @returns true if everything that can be done was applied
  90260. */
  90261. CustomOptimization.prototype.apply = function (scene, optimizer) {
  90262. if (this.onApply) {
  90263. return this.onApply(scene, optimizer);
  90264. }
  90265. return true;
  90266. };
  90267. ;
  90268. return CustomOptimization;
  90269. }(SceneOptimization));
  90270. BABYLON.CustomOptimization = CustomOptimization;
  90271. /**
  90272. * Defines an optimization used to turn particles off
  90273. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90274. */
  90275. var ParticlesOptimization = /** @class */ (function (_super) {
  90276. __extends(ParticlesOptimization, _super);
  90277. function ParticlesOptimization() {
  90278. return _super !== null && _super.apply(this, arguments) || this;
  90279. }
  90280. /**
  90281. * Gets a string describing the action executed by the current optimization
  90282. * @return description string
  90283. */
  90284. ParticlesOptimization.prototype.getDescription = function () {
  90285. return "Turning particles on/off";
  90286. };
  90287. /**
  90288. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90289. * @param scene defines the current scene where to apply this optimization
  90290. * @param optimizer defines the current optimizer
  90291. * @returns true if everything that can be done was applied
  90292. */
  90293. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  90294. scene.particlesEnabled = optimizer.isInImprovementMode;
  90295. return true;
  90296. };
  90297. ;
  90298. return ParticlesOptimization;
  90299. }(SceneOptimization));
  90300. BABYLON.ParticlesOptimization = ParticlesOptimization;
  90301. /**
  90302. * Defines an optimization used to turn render targets off
  90303. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90304. */
  90305. var RenderTargetsOptimization = /** @class */ (function (_super) {
  90306. __extends(RenderTargetsOptimization, _super);
  90307. function RenderTargetsOptimization() {
  90308. return _super !== null && _super.apply(this, arguments) || this;
  90309. }
  90310. /**
  90311. * Gets a string describing the action executed by the current optimization
  90312. * @return description string
  90313. */
  90314. RenderTargetsOptimization.prototype.getDescription = function () {
  90315. return "Turning render targets off";
  90316. };
  90317. /**
  90318. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90319. * @param scene defines the current scene where to apply this optimization
  90320. * @param optimizer defines the current optimizer
  90321. * @returns true if everything that can be done was applied
  90322. */
  90323. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  90324. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  90325. return true;
  90326. };
  90327. ;
  90328. return RenderTargetsOptimization;
  90329. }(SceneOptimization));
  90330. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  90331. /**
  90332. * Defines an optimization used to merge meshes with compatible materials
  90333. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90334. */
  90335. var MergeMeshesOptimization = /** @class */ (function (_super) {
  90336. __extends(MergeMeshesOptimization, _super);
  90337. function MergeMeshesOptimization() {
  90338. var _this = _super !== null && _super.apply(this, arguments) || this;
  90339. _this._canBeMerged = function (abstractMesh) {
  90340. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  90341. return false;
  90342. }
  90343. var mesh = abstractMesh;
  90344. if (!mesh.isVisible || !mesh.isEnabled()) {
  90345. return false;
  90346. }
  90347. if (mesh.instances.length > 0) {
  90348. return false;
  90349. }
  90350. if (mesh.skeleton || mesh.hasLODLevels) {
  90351. return false;
  90352. }
  90353. if (mesh.parent) {
  90354. return false;
  90355. }
  90356. return true;
  90357. };
  90358. return _this;
  90359. }
  90360. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  90361. /**
  90362. * Gets or sets a boolean which defines if optimization octree has to be updated
  90363. */
  90364. get: function () {
  90365. return MergeMeshesOptimization._UpdateSelectionTree;
  90366. },
  90367. /**
  90368. * Gets or sets a boolean which defines if optimization octree has to be updated
  90369. */
  90370. set: function (value) {
  90371. MergeMeshesOptimization._UpdateSelectionTree = value;
  90372. },
  90373. enumerable: true,
  90374. configurable: true
  90375. });
  90376. /**
  90377. * Gets a string describing the action executed by the current optimization
  90378. * @return description string
  90379. */
  90380. MergeMeshesOptimization.prototype.getDescription = function () {
  90381. return "Merging similar meshes together";
  90382. };
  90383. /**
  90384. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90385. * @param scene defines the current scene where to apply this optimization
  90386. * @param optimizer defines the current optimizer
  90387. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  90388. * @returns true if everything that can be done was applied
  90389. */
  90390. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  90391. var globalPool = scene.meshes.slice(0);
  90392. var globalLength = globalPool.length;
  90393. for (var index = 0; index < globalLength; index++) {
  90394. var currentPool = new Array();
  90395. var current = globalPool[index];
  90396. // Checks
  90397. if (!this._canBeMerged(current)) {
  90398. continue;
  90399. }
  90400. currentPool.push(current);
  90401. // Find compatible meshes
  90402. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  90403. var otherMesh = globalPool[subIndex];
  90404. if (!this._canBeMerged(otherMesh)) {
  90405. continue;
  90406. }
  90407. if (otherMesh.material !== current.material) {
  90408. continue;
  90409. }
  90410. if (otherMesh.checkCollisions !== current.checkCollisions) {
  90411. continue;
  90412. }
  90413. currentPool.push(otherMesh);
  90414. globalLength--;
  90415. globalPool.splice(subIndex, 1);
  90416. subIndex--;
  90417. }
  90418. if (currentPool.length < 2) {
  90419. continue;
  90420. }
  90421. // Merge meshes
  90422. BABYLON.Mesh.MergeMeshes(currentPool);
  90423. }
  90424. if (updateSelectionTree != undefined) {
  90425. if (updateSelectionTree) {
  90426. scene.createOrUpdateSelectionOctree();
  90427. }
  90428. }
  90429. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  90430. scene.createOrUpdateSelectionOctree();
  90431. }
  90432. return true;
  90433. };
  90434. ;
  90435. MergeMeshesOptimization._UpdateSelectionTree = false;
  90436. return MergeMeshesOptimization;
  90437. }(SceneOptimization));
  90438. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  90439. /**
  90440. * Defines a list of options used by SceneOptimizer
  90441. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90442. */
  90443. var SceneOptimizerOptions = /** @class */ (function () {
  90444. /**
  90445. * Creates a new list of options used by SceneOptimizer
  90446. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  90447. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  90448. */
  90449. function SceneOptimizerOptions(
  90450. /**
  90451. * Defines the target frame rate to reach (60 by default)
  90452. */
  90453. targetFrameRate,
  90454. /**
  90455. * Defines the interval between two checkes (2000ms by default)
  90456. */
  90457. trackerDuration) {
  90458. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  90459. if (trackerDuration === void 0) { trackerDuration = 2000; }
  90460. this.targetFrameRate = targetFrameRate;
  90461. this.trackerDuration = trackerDuration;
  90462. /**
  90463. * Gets the list of optimizations to apply
  90464. */
  90465. this.optimizations = new Array();
  90466. }
  90467. /**
  90468. * Add a new optimization
  90469. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  90470. * @returns the current SceneOptimizerOptions
  90471. */
  90472. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  90473. this.optimizations.push(optimization);
  90474. return this;
  90475. };
  90476. /**
  90477. * Add a new custom optimization
  90478. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  90479. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  90480. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90481. * @returns the current SceneOptimizerOptions
  90482. */
  90483. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  90484. if (priority === void 0) { priority = 0; }
  90485. var optimization = new CustomOptimization(priority);
  90486. optimization.onApply = onApply;
  90487. optimization.onGetDescription = onGetDescription;
  90488. this.optimizations.push(optimization);
  90489. return this;
  90490. };
  90491. /**
  90492. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  90493. * @param targetFrameRate defines the target frame rate (60 by default)
  90494. * @returns a SceneOptimizerOptions object
  90495. */
  90496. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  90497. var result = new SceneOptimizerOptions(targetFrameRate);
  90498. var priority = 0;
  90499. result.addOptimization(new MergeMeshesOptimization(priority));
  90500. result.addOptimization(new ShadowsOptimization(priority));
  90501. result.addOptimization(new LensFlaresOptimization(priority));
  90502. // Next priority
  90503. priority++;
  90504. result.addOptimization(new PostProcessesOptimization(priority));
  90505. result.addOptimization(new ParticlesOptimization(priority));
  90506. // Next priority
  90507. priority++;
  90508. result.addOptimization(new TextureOptimization(priority, 1024));
  90509. return result;
  90510. };
  90511. /**
  90512. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  90513. * @param targetFrameRate defines the target frame rate (60 by default)
  90514. * @returns a SceneOptimizerOptions object
  90515. */
  90516. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  90517. var result = new SceneOptimizerOptions(targetFrameRate);
  90518. var priority = 0;
  90519. result.addOptimization(new MergeMeshesOptimization(priority));
  90520. result.addOptimization(new ShadowsOptimization(priority));
  90521. result.addOptimization(new LensFlaresOptimization(priority));
  90522. // Next priority
  90523. priority++;
  90524. result.addOptimization(new PostProcessesOptimization(priority));
  90525. result.addOptimization(new ParticlesOptimization(priority));
  90526. // Next priority
  90527. priority++;
  90528. result.addOptimization(new TextureOptimization(priority, 512));
  90529. // Next priority
  90530. priority++;
  90531. result.addOptimization(new RenderTargetsOptimization(priority));
  90532. // Next priority
  90533. priority++;
  90534. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  90535. return result;
  90536. };
  90537. /**
  90538. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  90539. * @param targetFrameRate defines the target frame rate (60 by default)
  90540. * @returns a SceneOptimizerOptions object
  90541. */
  90542. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  90543. var result = new SceneOptimizerOptions(targetFrameRate);
  90544. var priority = 0;
  90545. result.addOptimization(new MergeMeshesOptimization(priority));
  90546. result.addOptimization(new ShadowsOptimization(priority));
  90547. result.addOptimization(new LensFlaresOptimization(priority));
  90548. // Next priority
  90549. priority++;
  90550. result.addOptimization(new PostProcessesOptimization(priority));
  90551. result.addOptimization(new ParticlesOptimization(priority));
  90552. // Next priority
  90553. priority++;
  90554. result.addOptimization(new TextureOptimization(priority, 256));
  90555. // Next priority
  90556. priority++;
  90557. result.addOptimization(new RenderTargetsOptimization(priority));
  90558. // Next priority
  90559. priority++;
  90560. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  90561. return result;
  90562. };
  90563. return SceneOptimizerOptions;
  90564. }());
  90565. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  90566. /**
  90567. * Class used to run optimizations in order to reach a target frame rate
  90568. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90569. */
  90570. var SceneOptimizer = /** @class */ (function () {
  90571. /**
  90572. * Creates a new SceneOptimizer
  90573. * @param scene defines the scene to work on
  90574. * @param options defines the options to use with the SceneOptimizer
  90575. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  90576. * @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)
  90577. */
  90578. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  90579. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  90580. if (improvementMode === void 0) { improvementMode = false; }
  90581. var _this = this;
  90582. this._isRunning = false;
  90583. this._currentPriorityLevel = 0;
  90584. this._targetFrameRate = 60;
  90585. this._trackerDuration = 2000;
  90586. this._currentFrameRate = 0;
  90587. this._improvementMode = false;
  90588. /**
  90589. * Defines an observable called when the optimizer reaches the target frame rate
  90590. */
  90591. this.onSuccessObservable = new BABYLON.Observable();
  90592. /**
  90593. * Defines an observable called when the optimizer enables an optimization
  90594. */
  90595. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  90596. /**
  90597. * Defines an observable called when the optimizer is not able to reach the target frame rate
  90598. */
  90599. this.onFailureObservable = new BABYLON.Observable();
  90600. if (!options) {
  90601. this._options = new SceneOptimizerOptions();
  90602. }
  90603. else {
  90604. this._options = options;
  90605. }
  90606. if (this._options.targetFrameRate) {
  90607. this._targetFrameRate = this._options.targetFrameRate;
  90608. }
  90609. if (this._options.trackerDuration) {
  90610. this._trackerDuration = this._options.trackerDuration;
  90611. }
  90612. if (autoGeneratePriorities) {
  90613. var priority = 0;
  90614. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  90615. var optim = _a[_i];
  90616. optim.priority = priority++;
  90617. }
  90618. }
  90619. this._improvementMode = improvementMode;
  90620. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90621. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  90622. _this._sceneDisposeObserver = null;
  90623. _this.dispose();
  90624. });
  90625. }
  90626. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  90627. /**
  90628. * Gets a boolean indicating if the optimizer is in improvement mode
  90629. */
  90630. get: function () {
  90631. return this._improvementMode;
  90632. },
  90633. enumerable: true,
  90634. configurable: true
  90635. });
  90636. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  90637. /**
  90638. * Gets the current priority level (0 at start)
  90639. */
  90640. get: function () {
  90641. return this._currentPriorityLevel;
  90642. },
  90643. enumerable: true,
  90644. configurable: true
  90645. });
  90646. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  90647. /**
  90648. * Gets the current frame rate checked by the SceneOptimizer
  90649. */
  90650. get: function () {
  90651. return this._currentFrameRate;
  90652. },
  90653. enumerable: true,
  90654. configurable: true
  90655. });
  90656. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  90657. /**
  90658. * Gets or sets the current target frame rate (60 by default)
  90659. */
  90660. get: function () {
  90661. return this._targetFrameRate;
  90662. },
  90663. /**
  90664. * Gets or sets the current target frame rate (60 by default)
  90665. */
  90666. set: function (value) {
  90667. this._targetFrameRate = value;
  90668. },
  90669. enumerable: true,
  90670. configurable: true
  90671. });
  90672. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  90673. /**
  90674. * Gets or sets the current interval between two checks (every 2000ms by default)
  90675. */
  90676. get: function () {
  90677. return this._trackerDuration;
  90678. },
  90679. /**
  90680. * Gets or sets the current interval between two checks (every 2000ms by default)
  90681. */
  90682. set: function (value) {
  90683. this._trackerDuration = value;
  90684. },
  90685. enumerable: true,
  90686. configurable: true
  90687. });
  90688. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  90689. /**
  90690. * Gets the list of active optimizations
  90691. */
  90692. get: function () {
  90693. return this._options.optimizations;
  90694. },
  90695. enumerable: true,
  90696. configurable: true
  90697. });
  90698. /**
  90699. * Stops the current optimizer
  90700. */
  90701. SceneOptimizer.prototype.stop = function () {
  90702. this._isRunning = false;
  90703. };
  90704. /**
  90705. * Reset the optimizer to initial step (current priority level = 0)
  90706. */
  90707. SceneOptimizer.prototype.reset = function () {
  90708. this._currentPriorityLevel = 0;
  90709. };
  90710. /**
  90711. * Start the optimizer. By default it will try to reach a specific framerate
  90712. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  90713. */
  90714. SceneOptimizer.prototype.start = function () {
  90715. var _this = this;
  90716. if (this._isRunning) {
  90717. return;
  90718. }
  90719. this._isRunning = true;
  90720. // Let's wait for the scene to be ready before running our check
  90721. this._scene.executeWhenReady(function () {
  90722. setTimeout(function () {
  90723. _this._checkCurrentState();
  90724. }, _this._trackerDuration);
  90725. });
  90726. };
  90727. SceneOptimizer.prototype._checkCurrentState = function () {
  90728. var _this = this;
  90729. if (!this._isRunning) {
  90730. return;
  90731. }
  90732. var scene = this._scene;
  90733. var options = this._options;
  90734. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  90735. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  90736. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  90737. this._isRunning = false;
  90738. this.onSuccessObservable.notifyObservers(this);
  90739. return;
  90740. }
  90741. // Apply current level of optimizations
  90742. var allDone = true;
  90743. var noOptimizationApplied = true;
  90744. for (var index = 0; index < options.optimizations.length; index++) {
  90745. var optimization = options.optimizations[index];
  90746. if (optimization.priority === this._currentPriorityLevel) {
  90747. noOptimizationApplied = false;
  90748. allDone = allDone && optimization.apply(scene, this);
  90749. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  90750. }
  90751. }
  90752. // If no optimization was applied, this is a failure :(
  90753. if (noOptimizationApplied) {
  90754. this._isRunning = false;
  90755. this.onFailureObservable.notifyObservers(this);
  90756. return;
  90757. }
  90758. // If all optimizations were done, move to next level
  90759. if (allDone) {
  90760. this._currentPriorityLevel++;
  90761. }
  90762. // Let's the system running for a specific amount of time before checking FPS
  90763. scene.executeWhenReady(function () {
  90764. setTimeout(function () {
  90765. _this._checkCurrentState();
  90766. }, _this._trackerDuration);
  90767. });
  90768. };
  90769. /**
  90770. * Release all resources
  90771. */
  90772. SceneOptimizer.prototype.dispose = function () {
  90773. this.stop();
  90774. this.onSuccessObservable.clear();
  90775. this.onFailureObservable.clear();
  90776. this.onNewOptimizationAppliedObservable.clear();
  90777. if (this._sceneDisposeObserver) {
  90778. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  90779. }
  90780. };
  90781. /**
  90782. * Helper function to create a SceneOptimizer with one single line of code
  90783. * @param scene defines the scene to work on
  90784. * @param options defines the options to use with the SceneOptimizer
  90785. * @param onSuccess defines a callback to call on success
  90786. * @param onFailure defines a callback to call on failure
  90787. * @returns the new SceneOptimizer object
  90788. */
  90789. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  90790. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  90791. if (onSuccess) {
  90792. optimizer.onSuccessObservable.add(function () {
  90793. onSuccess();
  90794. });
  90795. }
  90796. if (onFailure) {
  90797. optimizer.onFailureObservable.add(function () {
  90798. onFailure();
  90799. });
  90800. }
  90801. optimizer.start();
  90802. return optimizer;
  90803. };
  90804. return SceneOptimizer;
  90805. }());
  90806. BABYLON.SceneOptimizer = SceneOptimizer;
  90807. })(BABYLON || (BABYLON = {}));
  90808. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  90809. var BABYLON;
  90810. (function (BABYLON) {
  90811. var OutlineRenderer = /** @class */ (function () {
  90812. function OutlineRenderer(scene) {
  90813. this.zOffset = 1;
  90814. this._scene = scene;
  90815. }
  90816. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  90817. var _this = this;
  90818. if (useOverlay === void 0) { useOverlay = false; }
  90819. var scene = this._scene;
  90820. var engine = this._scene.getEngine();
  90821. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90822. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  90823. return;
  90824. }
  90825. var mesh = subMesh.getRenderingMesh();
  90826. var material = subMesh.getMaterial();
  90827. if (!material || !scene.activeCamera) {
  90828. return;
  90829. }
  90830. engine.enableEffect(this._effect);
  90831. // Logarithmic depth
  90832. if (material.useLogarithmicDepth) {
  90833. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  90834. }
  90835. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  90836. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  90837. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  90838. // Bones
  90839. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90840. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90841. }
  90842. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  90843. // Alpha test
  90844. if (material && material.needAlphaTesting()) {
  90845. var alphaTexture = material.getAlphaTestTexture();
  90846. if (alphaTexture) {
  90847. this._effect.setTexture("diffuseSampler", alphaTexture);
  90848. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90849. }
  90850. }
  90851. engine.setZOffset(-this.zOffset);
  90852. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  90853. engine.setZOffset(0);
  90854. };
  90855. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  90856. var defines = [];
  90857. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  90858. var mesh = subMesh.getMesh();
  90859. var material = subMesh.getMaterial();
  90860. if (material) {
  90861. // Alpha test
  90862. if (material.needAlphaTesting()) {
  90863. defines.push("#define ALPHATEST");
  90864. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90865. attribs.push(BABYLON.VertexBuffer.UVKind);
  90866. defines.push("#define UV1");
  90867. }
  90868. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90869. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90870. defines.push("#define UV2");
  90871. }
  90872. }
  90873. //Logarithmic depth
  90874. if (material.useLogarithmicDepth) {
  90875. defines.push("#define LOGARITHMICDEPTH");
  90876. }
  90877. }
  90878. // Bones
  90879. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90880. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90881. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90882. if (mesh.numBoneInfluencers > 4) {
  90883. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90884. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90885. }
  90886. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90887. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  90888. }
  90889. else {
  90890. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90891. }
  90892. // Instances
  90893. if (useInstances) {
  90894. defines.push("#define INSTANCES");
  90895. attribs.push("world0");
  90896. attribs.push("world1");
  90897. attribs.push("world2");
  90898. attribs.push("world3");
  90899. }
  90900. // Get correct effect
  90901. var join = defines.join("\n");
  90902. if (this._cachedDefines !== join) {
  90903. this._cachedDefines = join;
  90904. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  90905. }
  90906. return this._effect.isReady();
  90907. };
  90908. return OutlineRenderer;
  90909. }());
  90910. BABYLON.OutlineRenderer = OutlineRenderer;
  90911. })(BABYLON || (BABYLON = {}));
  90912. //# sourceMappingURL=babylon.outlineRenderer.js.map
  90913. var BABYLON;
  90914. (function (BABYLON) {
  90915. var FaceAdjacencies = /** @class */ (function () {
  90916. function FaceAdjacencies() {
  90917. this.edges = new Array();
  90918. this.edgesConnectedCount = 0;
  90919. }
  90920. return FaceAdjacencies;
  90921. }());
  90922. var EdgesRenderer = /** @class */ (function () {
  90923. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  90924. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  90925. if (epsilon === void 0) { epsilon = 0.95; }
  90926. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  90927. this.edgesWidthScalerForOrthographic = 1000.0;
  90928. this.edgesWidthScalerForPerspective = 50.0;
  90929. this._linesPositions = new Array();
  90930. this._linesNormals = new Array();
  90931. this._linesIndices = new Array();
  90932. this._buffers = {};
  90933. this._checkVerticesInsteadOfIndices = false;
  90934. this._source = source;
  90935. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  90936. this._epsilon = epsilon;
  90937. this._prepareRessources();
  90938. this._generateEdgesLines();
  90939. }
  90940. EdgesRenderer.prototype._prepareRessources = function () {
  90941. if (this._lineShader) {
  90942. return;
  90943. }
  90944. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  90945. attributes: ["position", "normal"],
  90946. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  90947. });
  90948. this._lineShader.disableDepthWrite = true;
  90949. this._lineShader.backFaceCulling = false;
  90950. };
  90951. EdgesRenderer.prototype._rebuild = function () {
  90952. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90953. if (buffer) {
  90954. buffer._rebuild();
  90955. }
  90956. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90957. if (buffer) {
  90958. buffer._rebuild();
  90959. }
  90960. var scene = this._source.getScene();
  90961. var engine = scene.getEngine();
  90962. this._ib = engine.createIndexBuffer(this._linesIndices);
  90963. };
  90964. EdgesRenderer.prototype.dispose = function () {
  90965. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90966. if (buffer) {
  90967. buffer.dispose();
  90968. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  90969. }
  90970. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90971. if (buffer) {
  90972. buffer.dispose();
  90973. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  90974. }
  90975. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  90976. this._lineShader.dispose();
  90977. };
  90978. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  90979. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  90980. return 0;
  90981. }
  90982. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  90983. return 1;
  90984. }
  90985. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  90986. return 2;
  90987. }
  90988. return -1;
  90989. };
  90990. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  90991. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  90992. return 0;
  90993. }
  90994. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  90995. return 1;
  90996. }
  90997. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  90998. return 2;
  90999. }
  91000. return -1;
  91001. };
  91002. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  91003. var needToCreateLine;
  91004. if (edge === undefined) {
  91005. needToCreateLine = true;
  91006. }
  91007. else {
  91008. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  91009. needToCreateLine = dotProduct < this._epsilon;
  91010. }
  91011. if (needToCreateLine) {
  91012. var offset = this._linesPositions.length / 3;
  91013. var normal = p0.subtract(p1);
  91014. normal.normalize();
  91015. // Positions
  91016. this._linesPositions.push(p0.x);
  91017. this._linesPositions.push(p0.y);
  91018. this._linesPositions.push(p0.z);
  91019. this._linesPositions.push(p0.x);
  91020. this._linesPositions.push(p0.y);
  91021. this._linesPositions.push(p0.z);
  91022. this._linesPositions.push(p1.x);
  91023. this._linesPositions.push(p1.y);
  91024. this._linesPositions.push(p1.z);
  91025. this._linesPositions.push(p1.x);
  91026. this._linesPositions.push(p1.y);
  91027. this._linesPositions.push(p1.z);
  91028. // Normals
  91029. this._linesNormals.push(p1.x);
  91030. this._linesNormals.push(p1.y);
  91031. this._linesNormals.push(p1.z);
  91032. this._linesNormals.push(-1);
  91033. this._linesNormals.push(p1.x);
  91034. this._linesNormals.push(p1.y);
  91035. this._linesNormals.push(p1.z);
  91036. this._linesNormals.push(1);
  91037. this._linesNormals.push(p0.x);
  91038. this._linesNormals.push(p0.y);
  91039. this._linesNormals.push(p0.z);
  91040. this._linesNormals.push(-1);
  91041. this._linesNormals.push(p0.x);
  91042. this._linesNormals.push(p0.y);
  91043. this._linesNormals.push(p0.z);
  91044. this._linesNormals.push(1);
  91045. // Indices
  91046. this._linesIndices.push(offset);
  91047. this._linesIndices.push(offset + 1);
  91048. this._linesIndices.push(offset + 2);
  91049. this._linesIndices.push(offset);
  91050. this._linesIndices.push(offset + 2);
  91051. this._linesIndices.push(offset + 3);
  91052. }
  91053. };
  91054. EdgesRenderer.prototype._generateEdgesLines = function () {
  91055. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91056. var indices = this._source.getIndices();
  91057. if (!indices || !positions) {
  91058. return;
  91059. }
  91060. // First let's find adjacencies
  91061. var adjacencies = new Array();
  91062. var faceNormals = new Array();
  91063. var index;
  91064. var faceAdjacencies;
  91065. // Prepare faces
  91066. for (index = 0; index < indices.length; index += 3) {
  91067. faceAdjacencies = new FaceAdjacencies();
  91068. var p0Index = indices[index];
  91069. var p1Index = indices[index + 1];
  91070. var p2Index = indices[index + 2];
  91071. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  91072. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  91073. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  91074. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  91075. faceNormal.normalize();
  91076. faceNormals.push(faceNormal);
  91077. adjacencies.push(faceAdjacencies);
  91078. }
  91079. // Scan
  91080. for (index = 0; index < adjacencies.length; index++) {
  91081. faceAdjacencies = adjacencies[index];
  91082. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  91083. var otherFaceAdjacencies = adjacencies[otherIndex];
  91084. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  91085. break;
  91086. }
  91087. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  91088. continue;
  91089. }
  91090. var otherP0 = indices[otherIndex * 3];
  91091. var otherP1 = indices[otherIndex * 3 + 1];
  91092. var otherP2 = indices[otherIndex * 3 + 2];
  91093. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  91094. var otherEdgeIndex = 0;
  91095. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  91096. continue;
  91097. }
  91098. switch (edgeIndex) {
  91099. case 0:
  91100. if (this._checkVerticesInsteadOfIndices) {
  91101. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91102. }
  91103. else {
  91104. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  91105. }
  91106. break;
  91107. case 1:
  91108. if (this._checkVerticesInsteadOfIndices) {
  91109. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91110. }
  91111. else {
  91112. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  91113. }
  91114. break;
  91115. case 2:
  91116. if (this._checkVerticesInsteadOfIndices) {
  91117. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91118. }
  91119. else {
  91120. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  91121. }
  91122. break;
  91123. }
  91124. if (otherEdgeIndex === -1) {
  91125. continue;
  91126. }
  91127. faceAdjacencies.edges[edgeIndex] = otherIndex;
  91128. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  91129. faceAdjacencies.edgesConnectedCount++;
  91130. otherFaceAdjacencies.edgesConnectedCount++;
  91131. if (faceAdjacencies.edgesConnectedCount === 3) {
  91132. break;
  91133. }
  91134. }
  91135. }
  91136. }
  91137. // Create lines
  91138. for (index = 0; index < adjacencies.length; index++) {
  91139. // 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
  91140. var current = adjacencies[index];
  91141. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  91142. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  91143. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  91144. }
  91145. // Merge into a single mesh
  91146. var engine = this._source.getScene().getEngine();
  91147. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  91148. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  91149. this._ib = engine.createIndexBuffer(this._linesIndices);
  91150. this._indicesCount = this._linesIndices.length;
  91151. };
  91152. EdgesRenderer.prototype.render = function () {
  91153. var scene = this._source.getScene();
  91154. if (!this._lineShader.isReady() || !scene.activeCamera) {
  91155. return;
  91156. }
  91157. var engine = scene.getEngine();
  91158. this._lineShader._preBind();
  91159. // VBOs
  91160. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  91161. scene.resetCachedMaterial();
  91162. this._lineShader.setColor4("color", this._source.edgesColor);
  91163. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  91164. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  91165. }
  91166. else {
  91167. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  91168. }
  91169. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  91170. this._lineShader.bind(this._source.getWorldMatrix());
  91171. // Draw order
  91172. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  91173. this._lineShader.unbind();
  91174. engine.setDepthWrite(true);
  91175. };
  91176. return EdgesRenderer;
  91177. }());
  91178. BABYLON.EdgesRenderer = EdgesRenderer;
  91179. })(BABYLON || (BABYLON = {}));
  91180. //# sourceMappingURL=babylon.edgesRenderer.js.map
  91181. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91182. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91183. s = arguments[i];
  91184. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91185. t[p] = s[p];
  91186. }
  91187. return t;
  91188. };
  91189. var BABYLON;
  91190. (function (BABYLON) {
  91191. /**
  91192. * The effect layer Helps adding post process effect blended with the main pass.
  91193. *
  91194. * This can be for instance use to generate glow or higlight effects on the scene.
  91195. *
  91196. * The effect layer class can not be used directly and is intented to inherited from to be
  91197. * customized per effects.
  91198. */
  91199. var EffectLayer = /** @class */ (function () {
  91200. /**
  91201. * Instantiates a new effect Layer and references it in the scene.
  91202. * @param name The name of the layer
  91203. * @param scene The scene to use the layer in
  91204. */
  91205. function EffectLayer(
  91206. /** The Friendly of the effect in the scene */
  91207. name, scene) {
  91208. this._vertexBuffers = {};
  91209. this._maxSize = 0;
  91210. this._mainTextureDesiredSize = { width: 0, height: 0 };
  91211. this._shouldRender = true;
  91212. this._postProcesses = [];
  91213. this._textures = [];
  91214. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  91215. /**
  91216. * The clear color of the texture used to generate the glow map.
  91217. */
  91218. this.neutralColor = new BABYLON.Color4();
  91219. /**
  91220. * Specifies wether the highlight layer is enabled or not.
  91221. */
  91222. this.isEnabled = true;
  91223. /**
  91224. * An event triggered when the effect layer has been disposed.
  91225. */
  91226. this.onDisposeObservable = new BABYLON.Observable();
  91227. /**
  91228. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  91229. */
  91230. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  91231. /**
  91232. * An event triggered when the generated texture is being merged in the scene.
  91233. */
  91234. this.onBeforeComposeObservable = new BABYLON.Observable();
  91235. /**
  91236. * An event triggered when the generated texture has been merged in the scene.
  91237. */
  91238. this.onAfterComposeObservable = new BABYLON.Observable();
  91239. /**
  91240. * An event triggered when the efffect layer changes its size.
  91241. */
  91242. this.onSizeChangedObservable = new BABYLON.Observable();
  91243. this.name = name;
  91244. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91245. this._engine = scene.getEngine();
  91246. this._maxSize = this._engine.getCaps().maxTextureSize;
  91247. this._scene.effectLayers.push(this);
  91248. // Generate Buffers
  91249. this._generateIndexBuffer();
  91250. this._genrateVertexBuffer();
  91251. }
  91252. Object.defineProperty(EffectLayer.prototype, "camera", {
  91253. /**
  91254. * Gets the camera attached to the layer.
  91255. */
  91256. get: function () {
  91257. return this._effectLayerOptions.camera;
  91258. },
  91259. enumerable: true,
  91260. configurable: true
  91261. });
  91262. /**
  91263. * Initializes the effect layer with the required options.
  91264. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  91265. */
  91266. EffectLayer.prototype._init = function (options) {
  91267. // Adapt options
  91268. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91269. this._setMainTextureSize();
  91270. this._createMainTexture();
  91271. this._createTextureAndPostProcesses();
  91272. this._mergeEffect = this._createMergeEffect();
  91273. };
  91274. /**
  91275. * Generates the index buffer of the full screen quad blending to the main canvas.
  91276. */
  91277. EffectLayer.prototype._generateIndexBuffer = function () {
  91278. // Indices
  91279. var indices = [];
  91280. indices.push(0);
  91281. indices.push(1);
  91282. indices.push(2);
  91283. indices.push(0);
  91284. indices.push(2);
  91285. indices.push(3);
  91286. this._indexBuffer = this._engine.createIndexBuffer(indices);
  91287. };
  91288. /**
  91289. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  91290. */
  91291. EffectLayer.prototype._genrateVertexBuffer = function () {
  91292. // VBO
  91293. var vertices = [];
  91294. vertices.push(1, 1);
  91295. vertices.push(-1, 1);
  91296. vertices.push(-1, -1);
  91297. vertices.push(1, -1);
  91298. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91299. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91300. };
  91301. /**
  91302. * Sets the main texture desired size which is the closest power of two
  91303. * of the engine canvas size.
  91304. */
  91305. EffectLayer.prototype._setMainTextureSize = function () {
  91306. if (this._effectLayerOptions.mainTextureFixedSize) {
  91307. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  91308. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  91309. }
  91310. else {
  91311. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  91312. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  91313. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  91314. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  91315. }
  91316. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  91317. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  91318. };
  91319. /**
  91320. * Creates the main texture for the effect layer.
  91321. */
  91322. EffectLayer.prototype._createMainTexture = function () {
  91323. var _this = this;
  91324. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  91325. width: this._mainTextureDesiredSize.width,
  91326. height: this._mainTextureDesiredSize.height
  91327. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91328. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  91329. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91330. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91331. this._mainTexture.anisotropicFilteringLevel = 1;
  91332. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91333. this._mainTexture.renderParticles = false;
  91334. this._mainTexture.renderList = null;
  91335. this._mainTexture.ignoreCameraViewport = true;
  91336. // Custom render function
  91337. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  91338. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  91339. var index;
  91340. var engine = _this._scene.getEngine();
  91341. if (depthOnlySubMeshes.length) {
  91342. engine.setColorWrite(false);
  91343. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  91344. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  91345. }
  91346. engine.setColorWrite(true);
  91347. }
  91348. for (index = 0; index < opaqueSubMeshes.length; index++) {
  91349. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  91350. }
  91351. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  91352. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  91353. }
  91354. for (index = 0; index < transparentSubMeshes.length; index++) {
  91355. _this._renderSubMesh(transparentSubMeshes.data[index]);
  91356. }
  91357. };
  91358. this._mainTexture.onClearObservable.add(function (engine) {
  91359. engine.clear(_this.neutralColor, true, true, true);
  91360. });
  91361. };
  91362. /**
  91363. * Checks for the readiness of the element composing the layer.
  91364. * @param subMesh the mesh to check for
  91365. * @param useInstances specify wether or not to use instances to render the mesh
  91366. * @param emissiveTexture the associated emissive texture used to generate the glow
  91367. * @return true if ready otherwise, false
  91368. */
  91369. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  91370. var material = subMesh.getMaterial();
  91371. if (!material) {
  91372. return false;
  91373. }
  91374. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  91375. return false;
  91376. }
  91377. var defines = [];
  91378. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91379. var mesh = subMesh.getMesh();
  91380. var uv1 = false;
  91381. var uv2 = false;
  91382. // Alpha test
  91383. if (material && material.needAlphaTesting()) {
  91384. var alphaTexture = material.getAlphaTestTexture();
  91385. if (alphaTexture) {
  91386. defines.push("#define ALPHATEST");
  91387. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91388. alphaTexture.coordinatesIndex === 1) {
  91389. defines.push("#define DIFFUSEUV2");
  91390. uv2 = true;
  91391. }
  91392. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91393. defines.push("#define DIFFUSEUV1");
  91394. uv1 = true;
  91395. }
  91396. }
  91397. }
  91398. // Emissive
  91399. if (emissiveTexture) {
  91400. defines.push("#define EMISSIVE");
  91401. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91402. emissiveTexture.coordinatesIndex === 1) {
  91403. defines.push("#define EMISSIVEUV2");
  91404. uv2 = true;
  91405. }
  91406. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91407. defines.push("#define EMISSIVEUV1");
  91408. uv1 = true;
  91409. }
  91410. }
  91411. if (uv1) {
  91412. attribs.push(BABYLON.VertexBuffer.UVKind);
  91413. defines.push("#define UV1");
  91414. }
  91415. if (uv2) {
  91416. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91417. defines.push("#define UV2");
  91418. }
  91419. // Bones
  91420. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91421. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91422. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91423. if (mesh.numBoneInfluencers > 4) {
  91424. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91425. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91426. }
  91427. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91428. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  91429. }
  91430. else {
  91431. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91432. }
  91433. // Morph targets
  91434. var manager = mesh.morphTargetManager;
  91435. var morphInfluencers = 0;
  91436. if (manager) {
  91437. if (manager.numInfluencers > 0) {
  91438. defines.push("#define MORPHTARGETS");
  91439. morphInfluencers = manager.numInfluencers;
  91440. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  91441. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  91442. }
  91443. }
  91444. // Instances
  91445. if (useInstances) {
  91446. defines.push("#define INSTANCES");
  91447. attribs.push("world0");
  91448. attribs.push("world1");
  91449. attribs.push("world2");
  91450. attribs.push("world3");
  91451. }
  91452. // Get correct effect
  91453. var join = defines.join("\n");
  91454. if (this._cachedDefines !== join) {
  91455. this._cachedDefines = join;
  91456. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  91457. }
  91458. return this._effectLayerMapGenerationEffect.isReady();
  91459. };
  91460. /**
  91461. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  91462. */
  91463. EffectLayer.prototype.render = function () {
  91464. var currentEffect = this._mergeEffect;
  91465. // Check
  91466. if (!currentEffect.isReady())
  91467. return;
  91468. for (var i = 0; i < this._postProcesses.length; i++) {
  91469. if (!this._postProcesses[i].isReady()) {
  91470. return;
  91471. }
  91472. }
  91473. var engine = this._scene.getEngine();
  91474. this.onBeforeComposeObservable.notifyObservers(this);
  91475. // Render
  91476. engine.enableEffect(currentEffect);
  91477. engine.setState(false);
  91478. // VBOs
  91479. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91480. // Cache
  91481. var previousAlphaMode = engine.getAlphaMode();
  91482. // Go Blend.
  91483. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  91484. // Blends the map on the main canvas.
  91485. this._internalRender(currentEffect);
  91486. // Restore Alpha
  91487. engine.setAlphaMode(previousAlphaMode);
  91488. this.onAfterComposeObservable.notifyObservers(this);
  91489. // Handle size changes.
  91490. var size = this._mainTexture.getSize();
  91491. this._setMainTextureSize();
  91492. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  91493. // Recreate RTT and post processes on size change.
  91494. this.onSizeChangedObservable.notifyObservers(this);
  91495. this._disposeTextureAndPostProcesses();
  91496. this._createMainTexture();
  91497. this._createTextureAndPostProcesses();
  91498. }
  91499. };
  91500. /**
  91501. * Determine if a given mesh will be used in the current effect.
  91502. * @param mesh mesh to test
  91503. * @returns true if the mesh will be used
  91504. */
  91505. EffectLayer.prototype.hasMesh = function (mesh) {
  91506. return true;
  91507. };
  91508. /**
  91509. * Returns true if the layer contains information to display, otherwise false.
  91510. * @returns true if the glow layer should be rendered
  91511. */
  91512. EffectLayer.prototype.shouldRender = function () {
  91513. return this.isEnabled && this._shouldRender;
  91514. };
  91515. /**
  91516. * Returns true if the mesh should render, otherwise false.
  91517. * @param mesh The mesh to render
  91518. * @returns true if it should render otherwise false
  91519. */
  91520. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  91521. return true;
  91522. };
  91523. /**
  91524. * Returns true if the mesh should render, otherwise false.
  91525. * @param mesh The mesh to render
  91526. * @returns true if it should render otherwise false
  91527. */
  91528. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  91529. return true;
  91530. };
  91531. /**
  91532. * Renders the submesh passed in parameter to the generation map.
  91533. */
  91534. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  91535. var _this = this;
  91536. if (!this.shouldRender()) {
  91537. return;
  91538. }
  91539. var material = subMesh.getMaterial();
  91540. var mesh = subMesh.getRenderingMesh();
  91541. var scene = this._scene;
  91542. var engine = scene.getEngine();
  91543. if (!material) {
  91544. return;
  91545. }
  91546. // Do not block in blend mode.
  91547. if (material.needAlphaBlendingForMesh(mesh)) {
  91548. return;
  91549. }
  91550. // Culling
  91551. engine.setState(material.backFaceCulling);
  91552. // Managing instances
  91553. var batch = mesh._getInstancesRenderList(subMesh._id);
  91554. if (batch.mustReturn) {
  91555. return;
  91556. }
  91557. // Early Exit per mesh
  91558. if (!this._shouldRenderMesh(mesh)) {
  91559. return;
  91560. }
  91561. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91562. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  91563. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  91564. engine.enableEffect(this._effectLayerMapGenerationEffect);
  91565. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  91566. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  91567. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  91568. // Alpha test
  91569. if (material && material.needAlphaTesting()) {
  91570. var alphaTexture = material.getAlphaTestTexture();
  91571. if (alphaTexture) {
  91572. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  91573. var textureMatrix = alphaTexture.getTextureMatrix();
  91574. if (textureMatrix) {
  91575. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  91576. }
  91577. }
  91578. }
  91579. // Glow emissive only
  91580. if (this._emissiveTextureAndColor.texture) {
  91581. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  91582. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  91583. }
  91584. // Bones
  91585. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91586. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91587. }
  91588. // Morph targets
  91589. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  91590. // Draw
  91591. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  91592. }
  91593. else {
  91594. // Need to reset refresh rate of the shadowMap
  91595. this._mainTexture.resetRefreshCounter();
  91596. }
  91597. };
  91598. /**
  91599. * Rebuild the required buffers.
  91600. * @hidden Internal use only.
  91601. */
  91602. EffectLayer.prototype._rebuild = function () {
  91603. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91604. if (vb) {
  91605. vb._rebuild();
  91606. }
  91607. this._generateIndexBuffer();
  91608. };
  91609. /**
  91610. * Dispose only the render target textures and post process.
  91611. */
  91612. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  91613. this._mainTexture.dispose();
  91614. for (var i = 0; i < this._postProcesses.length; i++) {
  91615. if (this._postProcesses[i]) {
  91616. this._postProcesses[i].dispose();
  91617. }
  91618. }
  91619. this._postProcesses = [];
  91620. for (var i = 0; i < this._textures.length; i++) {
  91621. if (this._textures[i]) {
  91622. this._textures[i].dispose();
  91623. }
  91624. }
  91625. this._textures = [];
  91626. };
  91627. /**
  91628. * Dispose the highlight layer and free resources.
  91629. */
  91630. EffectLayer.prototype.dispose = function () {
  91631. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91632. if (vertexBuffer) {
  91633. vertexBuffer.dispose();
  91634. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91635. }
  91636. if (this._indexBuffer) {
  91637. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91638. this._indexBuffer = null;
  91639. }
  91640. // Clean textures and post processes
  91641. this._disposeTextureAndPostProcesses();
  91642. // Remove from scene
  91643. var index = this._scene.effectLayers.indexOf(this, 0);
  91644. if (index > -1) {
  91645. this._scene.effectLayers.splice(index, 1);
  91646. }
  91647. // Callback
  91648. this.onDisposeObservable.notifyObservers(this);
  91649. this.onDisposeObservable.clear();
  91650. this.onBeforeRenderMainTextureObservable.clear();
  91651. this.onBeforeComposeObservable.clear();
  91652. this.onAfterComposeObservable.clear();
  91653. this.onSizeChangedObservable.clear();
  91654. };
  91655. /**
  91656. * Gets the class name of the effect layer
  91657. * @returns the string with the class name of the effect layer
  91658. */
  91659. EffectLayer.prototype.getClassName = function () {
  91660. return "EffectLayer";
  91661. };
  91662. /**
  91663. * Creates an effect layer from parsed effect layer data
  91664. * @param parsedEffectLayer defines effect layer data
  91665. * @param scene defines the current scene
  91666. * @param rootUrl defines the root URL containing the effect layer information
  91667. * @returns a parsed effect Layer
  91668. */
  91669. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  91670. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  91671. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  91672. };
  91673. __decorate([
  91674. BABYLON.serialize()
  91675. ], EffectLayer.prototype, "name", void 0);
  91676. __decorate([
  91677. BABYLON.serializeAsColor4()
  91678. ], EffectLayer.prototype, "neutralColor", void 0);
  91679. __decorate([
  91680. BABYLON.serialize()
  91681. ], EffectLayer.prototype, "isEnabled", void 0);
  91682. __decorate([
  91683. BABYLON.serializeAsCameraReference()
  91684. ], EffectLayer.prototype, "camera", null);
  91685. return EffectLayer;
  91686. }());
  91687. BABYLON.EffectLayer = EffectLayer;
  91688. })(BABYLON || (BABYLON = {}));
  91689. //# sourceMappingURL=babylon.effectLayer.js.map
  91690. var BABYLON;
  91691. (function (BABYLON) {
  91692. /**
  91693. * Special Glow Blur post process only blurring the alpha channel
  91694. * It enforces keeping the most luminous color in the color channel.
  91695. */
  91696. var GlowBlurPostProcess = /** @class */ (function (_super) {
  91697. __extends(GlowBlurPostProcess, _super);
  91698. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  91699. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91700. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  91701. _this.direction = direction;
  91702. _this.kernel = kernel;
  91703. _this.onApplyObservable.add(function (effect) {
  91704. effect.setFloat2("screenSize", _this.width, _this.height);
  91705. effect.setVector2("direction", _this.direction);
  91706. effect.setFloat("blurWidth", _this.kernel);
  91707. });
  91708. return _this;
  91709. }
  91710. return GlowBlurPostProcess;
  91711. }(BABYLON.PostProcess));
  91712. /**
  91713. * The highlight layer Helps adding a glow effect around a mesh.
  91714. *
  91715. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91716. * glowy meshes to your scene.
  91717. *
  91718. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  91719. */
  91720. var HighlightLayer = /** @class */ (function (_super) {
  91721. __extends(HighlightLayer, _super);
  91722. /**
  91723. * Instantiates a new highlight Layer and references it to the scene..
  91724. * @param name The name of the layer
  91725. * @param scene The scene to use the layer in
  91726. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  91727. */
  91728. function HighlightLayer(name, scene, options) {
  91729. var _this = _super.call(this, name, scene) || this;
  91730. _this.name = name;
  91731. /**
  91732. * Specifies whether or not the inner glow is ACTIVE in the layer.
  91733. */
  91734. _this.innerGlow = true;
  91735. /**
  91736. * Specifies whether or not the outer glow is ACTIVE in the layer.
  91737. */
  91738. _this.outerGlow = true;
  91739. /**
  91740. * An event triggered when the highlight layer is being blurred.
  91741. */
  91742. _this.onBeforeBlurObservable = new BABYLON.Observable();
  91743. /**
  91744. * An event triggered when the highlight layer has been blurred.
  91745. */
  91746. _this.onAfterBlurObservable = new BABYLON.Observable();
  91747. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  91748. _this._meshes = {};
  91749. _this._excludedMeshes = {};
  91750. _this.neutralColor = HighlightLayer.NeutralColor;
  91751. // Warn on stencil
  91752. if (!_this._engine.isStencilEnable) {
  91753. 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 }");
  91754. }
  91755. // Adapt options
  91756. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91757. // Initialize the layer
  91758. _this._init({
  91759. alphaBlendingMode: _this._options.alphaBlendingMode,
  91760. camera: _this._options.camera,
  91761. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91762. mainTextureRatio: _this._options.mainTextureRatio
  91763. });
  91764. // Do not render as long as no meshes have been added
  91765. _this._shouldRender = false;
  91766. return _this;
  91767. }
  91768. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  91769. /**
  91770. * Gets the horizontal size of the blur.
  91771. */
  91772. get: function () {
  91773. return this._horizontalBlurPostprocess.kernel;
  91774. },
  91775. /**
  91776. * Specifies the horizontal size of the blur.
  91777. */
  91778. set: function (value) {
  91779. this._horizontalBlurPostprocess.kernel = value;
  91780. },
  91781. enumerable: true,
  91782. configurable: true
  91783. });
  91784. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  91785. /**
  91786. * Gets the vertical size of the blur.
  91787. */
  91788. get: function () {
  91789. return this._verticalBlurPostprocess.kernel;
  91790. },
  91791. /**
  91792. * Specifies the vertical size of the blur.
  91793. */
  91794. set: function (value) {
  91795. this._verticalBlurPostprocess.kernel = value;
  91796. },
  91797. enumerable: true,
  91798. configurable: true
  91799. });
  91800. /**
  91801. * Get the effect name of the layer.
  91802. * @return The effect name
  91803. */
  91804. HighlightLayer.prototype.getEffectName = function () {
  91805. return HighlightLayer.EffectName;
  91806. };
  91807. /**
  91808. * Create the merge effect. This is the shader use to blit the information back
  91809. * to the main canvas at the end of the scene rendering.
  91810. */
  91811. HighlightLayer.prototype._createMergeEffect = function () {
  91812. // Effect
  91813. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  91814. };
  91815. /**
  91816. * Creates the render target textures and post processes used in the highlight layer.
  91817. */
  91818. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  91819. var _this = this;
  91820. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  91821. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  91822. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91823. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91824. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  91825. width: blurTextureWidth,
  91826. height: blurTextureHeight
  91827. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91828. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91829. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91830. this._blurTexture.anisotropicFilteringLevel = 16;
  91831. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  91832. this._blurTexture.renderParticles = false;
  91833. this._blurTexture.ignoreCameraViewport = true;
  91834. this._textures = [this._blurTexture];
  91835. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  91836. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91837. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  91838. effect.setTexture("textureSampler", _this._mainTexture);
  91839. });
  91840. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91841. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91842. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91843. });
  91844. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91845. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  91846. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91847. });
  91848. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91849. }
  91850. else {
  91851. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  91852. width: blurTextureWidth,
  91853. height: blurTextureHeight
  91854. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91855. this._horizontalBlurPostprocess.width = blurTextureWidth;
  91856. this._horizontalBlurPostprocess.height = blurTextureHeight;
  91857. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91858. effect.setTexture("textureSampler", _this._mainTexture);
  91859. });
  91860. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  91861. width: blurTextureWidth,
  91862. height: blurTextureHeight
  91863. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91864. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91865. }
  91866. this._mainTexture.onAfterUnbindObservable.add(function () {
  91867. _this.onBeforeBlurObservable.notifyObservers(_this);
  91868. var internalTexture = _this._blurTexture.getInternalTexture();
  91869. if (internalTexture) {
  91870. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  91871. }
  91872. _this.onAfterBlurObservable.notifyObservers(_this);
  91873. });
  91874. // Prevent autoClear.
  91875. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91876. };
  91877. /**
  91878. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91879. */
  91880. HighlightLayer.prototype.needStencil = function () {
  91881. return true;
  91882. };
  91883. /**
  91884. * Checks for the readiness of the element composing the layer.
  91885. * @param subMesh the mesh to check for
  91886. * @param useInstances specify wether or not to use instances to render the mesh
  91887. * @param emissiveTexture the associated emissive texture used to generate the glow
  91888. * @return true if ready otherwise, false
  91889. */
  91890. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  91891. var material = subMesh.getMaterial();
  91892. var mesh = subMesh.getRenderingMesh();
  91893. if (!material || !mesh || !this._meshes) {
  91894. return false;
  91895. }
  91896. var emissiveTexture = null;
  91897. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91898. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91899. emissiveTexture = material.emissiveTexture;
  91900. }
  91901. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91902. };
  91903. /**
  91904. * Implementation specific of rendering the generating effect on the main canvas.
  91905. * @param effect The effect used to render through
  91906. */
  91907. HighlightLayer.prototype._internalRender = function (effect) {
  91908. // Texture
  91909. effect.setTexture("textureSampler", this._blurTexture);
  91910. // Cache
  91911. var engine = this._engine;
  91912. var previousStencilBuffer = engine.getStencilBuffer();
  91913. var previousStencilFunction = engine.getStencilFunction();
  91914. var previousStencilMask = engine.getStencilMask();
  91915. var previousStencilOperationPass = engine.getStencilOperationPass();
  91916. var previousStencilOperationFail = engine.getStencilOperationFail();
  91917. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  91918. var previousStencilReference = engine.getStencilFunctionReference();
  91919. // Stencil operations
  91920. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  91921. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  91922. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  91923. // Draw order
  91924. engine.setStencilMask(0x00);
  91925. engine.setStencilBuffer(true);
  91926. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  91927. // 2 passes inner outer
  91928. if (this.outerGlow) {
  91929. effect.setFloat("offset", 0);
  91930. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  91931. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91932. }
  91933. if (this.innerGlow) {
  91934. effect.setFloat("offset", 1);
  91935. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  91936. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91937. }
  91938. // Restore Cache
  91939. engine.setStencilFunction(previousStencilFunction);
  91940. engine.setStencilMask(previousStencilMask);
  91941. engine.setStencilBuffer(previousStencilBuffer);
  91942. engine.setStencilOperationPass(previousStencilOperationPass);
  91943. engine.setStencilOperationFail(previousStencilOperationFail);
  91944. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  91945. engine.setStencilFunctionReference(previousStencilReference);
  91946. };
  91947. /**
  91948. * Returns true if the layer contains information to display, otherwise false.
  91949. */
  91950. HighlightLayer.prototype.shouldRender = function () {
  91951. if (_super.prototype.shouldRender.call(this)) {
  91952. return this._meshes ? true : false;
  91953. }
  91954. return false;
  91955. };
  91956. /**
  91957. * Returns true if the mesh should render, otherwise false.
  91958. * @param mesh The mesh to render
  91959. * @returns true if it should render otherwise false
  91960. */
  91961. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  91962. // Excluded Mesh
  91963. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  91964. return false;
  91965. }
  91966. ;
  91967. return true;
  91968. };
  91969. /**
  91970. * Sets the required values for both the emissive texture and and the main color.
  91971. */
  91972. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  91973. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91974. if (highlightLayerMesh) {
  91975. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  91976. }
  91977. else {
  91978. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  91979. }
  91980. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91981. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  91982. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  91983. }
  91984. else {
  91985. this._emissiveTextureAndColor.texture = null;
  91986. }
  91987. };
  91988. /**
  91989. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  91990. * @param mesh The mesh to exclude from the highlight layer
  91991. */
  91992. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  91993. if (!this._excludedMeshes) {
  91994. return;
  91995. }
  91996. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91997. if (!meshExcluded) {
  91998. this._excludedMeshes[mesh.uniqueId] = {
  91999. mesh: mesh,
  92000. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  92001. mesh.getEngine().setStencilBuffer(false);
  92002. }),
  92003. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  92004. mesh.getEngine().setStencilBuffer(true);
  92005. }),
  92006. };
  92007. }
  92008. };
  92009. /**
  92010. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  92011. * @param mesh The mesh to highlight
  92012. */
  92013. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  92014. if (!this._excludedMeshes) {
  92015. return;
  92016. }
  92017. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92018. if (meshExcluded) {
  92019. if (meshExcluded.beforeRender) {
  92020. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  92021. }
  92022. if (meshExcluded.afterRender) {
  92023. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  92024. }
  92025. }
  92026. this._excludedMeshes[mesh.uniqueId] = null;
  92027. };
  92028. /**
  92029. * Determine if a given mesh will be highlighted by the current HighlightLayer
  92030. * @param mesh mesh to test
  92031. * @returns true if the mesh will be highlighted by the current HighlightLayer
  92032. */
  92033. HighlightLayer.prototype.hasMesh = function (mesh) {
  92034. if (!this._meshes) {
  92035. return false;
  92036. }
  92037. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  92038. };
  92039. /**
  92040. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  92041. * @param mesh The mesh to highlight
  92042. * @param color The color of the highlight
  92043. * @param glowEmissiveOnly Extract the glow from the emissive texture
  92044. */
  92045. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  92046. var _this = this;
  92047. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  92048. if (!this._meshes) {
  92049. return;
  92050. }
  92051. var meshHighlight = this._meshes[mesh.uniqueId];
  92052. if (meshHighlight) {
  92053. meshHighlight.color = color;
  92054. }
  92055. else {
  92056. this._meshes[mesh.uniqueId] = {
  92057. mesh: mesh,
  92058. color: color,
  92059. // Lambda required for capture due to Observable this context
  92060. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  92061. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  92062. _this._defaultStencilReference(mesh);
  92063. }
  92064. else {
  92065. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  92066. }
  92067. }),
  92068. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  92069. glowEmissiveOnly: glowEmissiveOnly
  92070. };
  92071. }
  92072. this._shouldRender = true;
  92073. };
  92074. /**
  92075. * Remove a mesh from the highlight layer in order to make it stop glowing.
  92076. * @param mesh The mesh to highlight
  92077. */
  92078. HighlightLayer.prototype.removeMesh = function (mesh) {
  92079. if (!this._meshes) {
  92080. return;
  92081. }
  92082. var meshHighlight = this._meshes[mesh.uniqueId];
  92083. if (meshHighlight) {
  92084. if (meshHighlight.observerHighlight) {
  92085. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92086. }
  92087. if (meshHighlight.observerDefault) {
  92088. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92089. }
  92090. delete this._meshes[mesh.uniqueId];
  92091. }
  92092. this._shouldRender = false;
  92093. for (var meshHighlightToCheck in this._meshes) {
  92094. if (this._meshes[meshHighlightToCheck]) {
  92095. this._shouldRender = true;
  92096. break;
  92097. }
  92098. }
  92099. };
  92100. /**
  92101. * Force the stencil to the normal expected value for none glowing parts
  92102. */
  92103. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  92104. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  92105. };
  92106. /**
  92107. * Free any resources and references associated to a mesh.
  92108. * Internal use
  92109. * @param mesh The mesh to free.
  92110. */
  92111. HighlightLayer.prototype._disposeMesh = function (mesh) {
  92112. this.removeMesh(mesh);
  92113. this.removeExcludedMesh(mesh);
  92114. };
  92115. /**
  92116. * Dispose the highlight layer and free resources.
  92117. */
  92118. HighlightLayer.prototype.dispose = function () {
  92119. if (this._meshes) {
  92120. // Clean mesh references
  92121. for (var id in this._meshes) {
  92122. var meshHighlight = this._meshes[id];
  92123. if (meshHighlight && meshHighlight.mesh) {
  92124. if (meshHighlight.observerHighlight) {
  92125. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92126. }
  92127. if (meshHighlight.observerDefault) {
  92128. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92129. }
  92130. }
  92131. }
  92132. this._meshes = null;
  92133. }
  92134. if (this._excludedMeshes) {
  92135. for (var id in this._excludedMeshes) {
  92136. var meshHighlight = this._excludedMeshes[id];
  92137. if (meshHighlight) {
  92138. if (meshHighlight.beforeRender) {
  92139. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  92140. }
  92141. if (meshHighlight.afterRender) {
  92142. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  92143. }
  92144. }
  92145. }
  92146. this._excludedMeshes = null;
  92147. }
  92148. _super.prototype.dispose.call(this);
  92149. };
  92150. /**
  92151. * Gets the class name of the effect layer
  92152. * @returns the string with the class name of the effect layer
  92153. */
  92154. HighlightLayer.prototype.getClassName = function () {
  92155. return "HighlightLayer";
  92156. };
  92157. /**
  92158. * Serializes this Highlight layer
  92159. * @returns a serialized Highlight layer object
  92160. */
  92161. HighlightLayer.prototype.serialize = function () {
  92162. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92163. serializationObject.customType = "BABYLON.HighlightLayer";
  92164. // Highlighted meshes
  92165. serializationObject.meshes = [];
  92166. if (this._meshes) {
  92167. for (var m in this._meshes) {
  92168. var mesh = this._meshes[m];
  92169. if (mesh) {
  92170. serializationObject.meshes.push({
  92171. glowEmissiveOnly: mesh.glowEmissiveOnly,
  92172. color: mesh.color.asArray(),
  92173. meshId: mesh.mesh.id
  92174. });
  92175. }
  92176. }
  92177. }
  92178. // Excluded meshes
  92179. serializationObject.excludedMeshes = [];
  92180. if (this._excludedMeshes) {
  92181. for (var e in this._excludedMeshes) {
  92182. var excludedMesh = this._excludedMeshes[e];
  92183. if (excludedMesh) {
  92184. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  92185. }
  92186. }
  92187. }
  92188. return serializationObject;
  92189. };
  92190. /**
  92191. * Creates a Highlight layer from parsed Highlight layer data
  92192. * @param parsedHightlightLayer defines the Highlight layer data
  92193. * @param scene defines the current scene
  92194. * @param rootUrl defines the root URL containing the Highlight layer information
  92195. * @returns a parsed Highlight layer
  92196. */
  92197. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  92198. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  92199. var index;
  92200. // Excluded meshes
  92201. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  92202. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  92203. if (mesh) {
  92204. hl.addExcludedMesh(mesh);
  92205. }
  92206. }
  92207. // Included meshes
  92208. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  92209. var highlightedMesh = parsedHightlightLayer.meshes[index];
  92210. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  92211. if (mesh) {
  92212. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  92213. }
  92214. }
  92215. return hl;
  92216. };
  92217. /**
  92218. * Effect Name of the highlight layer.
  92219. */
  92220. HighlightLayer.EffectName = "HighlightLayer";
  92221. /**
  92222. * The neutral color used during the preparation of the glow effect.
  92223. * This is black by default as the blend operation is a blend operation.
  92224. */
  92225. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  92226. /**
  92227. * Stencil value used for glowing meshes.
  92228. */
  92229. HighlightLayer.GlowingMeshStencilReference = 0x02;
  92230. /**
  92231. * Stencil value used for the other meshes in the scene.
  92232. */
  92233. HighlightLayer.NormalMeshStencilReference = 0x01;
  92234. __decorate([
  92235. BABYLON.serialize()
  92236. ], HighlightLayer.prototype, "innerGlow", void 0);
  92237. __decorate([
  92238. BABYLON.serialize()
  92239. ], HighlightLayer.prototype, "outerGlow", void 0);
  92240. __decorate([
  92241. BABYLON.serialize()
  92242. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  92243. __decorate([
  92244. BABYLON.serialize()
  92245. ], HighlightLayer.prototype, "blurVerticalSize", null);
  92246. __decorate([
  92247. BABYLON.serialize("options")
  92248. ], HighlightLayer.prototype, "_options", void 0);
  92249. return HighlightLayer;
  92250. }(BABYLON.EffectLayer));
  92251. BABYLON.HighlightLayer = HighlightLayer;
  92252. })(BABYLON || (BABYLON = {}));
  92253. //# sourceMappingURL=babylon.highlightLayer.js.map
  92254. var BABYLON;
  92255. (function (BABYLON) {
  92256. /**
  92257. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  92258. *
  92259. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92260. * glowy meshes to your scene.
  92261. *
  92262. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  92263. */
  92264. var GlowLayer = /** @class */ (function (_super) {
  92265. __extends(GlowLayer, _super);
  92266. /**
  92267. * Instantiates a new glow Layer and references it to the scene.
  92268. * @param name The name of the layer
  92269. * @param scene The scene to use the layer in
  92270. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  92271. */
  92272. function GlowLayer(name, scene, options) {
  92273. var _this = _super.call(this, name, scene) || this;
  92274. _this._intensity = 1.0;
  92275. _this._includedOnlyMeshes = [];
  92276. _this._excludedMeshes = [];
  92277. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  92278. // Adapt options
  92279. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  92280. // Initialize the layer
  92281. _this._init({
  92282. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  92283. camera: _this._options.camera,
  92284. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92285. mainTextureRatio: _this._options.mainTextureRatio
  92286. });
  92287. return _this;
  92288. }
  92289. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  92290. /**
  92291. * Gets the kernel size of the blur.
  92292. */
  92293. get: function () {
  92294. return this._horizontalBlurPostprocess1.kernel;
  92295. },
  92296. /**
  92297. * Sets the kernel size of the blur.
  92298. */
  92299. set: function (value) {
  92300. this._horizontalBlurPostprocess1.kernel = value;
  92301. this._verticalBlurPostprocess1.kernel = value;
  92302. this._horizontalBlurPostprocess2.kernel = value;
  92303. this._verticalBlurPostprocess2.kernel = value;
  92304. },
  92305. enumerable: true,
  92306. configurable: true
  92307. });
  92308. Object.defineProperty(GlowLayer.prototype, "intensity", {
  92309. /**
  92310. * Gets the glow intensity.
  92311. */
  92312. get: function () {
  92313. return this._intensity;
  92314. },
  92315. /**
  92316. * Sets the glow intensity.
  92317. */
  92318. set: function (value) {
  92319. this._intensity = value;
  92320. },
  92321. enumerable: true,
  92322. configurable: true
  92323. });
  92324. /**
  92325. * Get the effect name of the layer.
  92326. * @return The effect name
  92327. */
  92328. GlowLayer.prototype.getEffectName = function () {
  92329. return GlowLayer.EffectName;
  92330. };
  92331. /**
  92332. * Create the merge effect. This is the shader use to blit the information back
  92333. * to the main canvas at the end of the scene rendering.
  92334. */
  92335. GlowLayer.prototype._createMergeEffect = function () {
  92336. // Effect
  92337. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  92338. };
  92339. /**
  92340. * Creates the render target textures and post processes used in the glow layer.
  92341. */
  92342. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  92343. var _this = this;
  92344. var blurTextureWidth = this._mainTextureDesiredSize.width;
  92345. var blurTextureHeight = this._mainTextureDesiredSize.height;
  92346. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92347. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92348. var textureType = 0;
  92349. if (this._engine.getCaps().textureHalfFloatRender) {
  92350. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92351. }
  92352. else {
  92353. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92354. }
  92355. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  92356. width: blurTextureWidth,
  92357. height: blurTextureHeight
  92358. }, this._scene, false, true, textureType);
  92359. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92360. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92361. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92362. this._blurTexture1.renderParticles = false;
  92363. this._blurTexture1.ignoreCameraViewport = true;
  92364. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  92365. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  92366. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  92367. width: blurTextureWidth2,
  92368. height: blurTextureHeight2
  92369. }, this._scene, false, true, textureType);
  92370. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92371. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92372. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92373. this._blurTexture2.renderParticles = false;
  92374. this._blurTexture2.ignoreCameraViewport = true;
  92375. this._textures = [this._blurTexture1, this._blurTexture2];
  92376. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92377. width: blurTextureWidth,
  92378. height: blurTextureHeight
  92379. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92380. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  92381. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  92382. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  92383. effect.setTexture("textureSampler", _this._mainTexture);
  92384. });
  92385. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92386. width: blurTextureWidth,
  92387. height: blurTextureHeight
  92388. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92389. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92390. width: blurTextureWidth2,
  92391. height: blurTextureHeight2
  92392. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92393. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  92394. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  92395. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  92396. effect.setTexture("textureSampler", _this._blurTexture1);
  92397. });
  92398. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92399. width: blurTextureWidth2,
  92400. height: blurTextureHeight2
  92401. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92402. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92403. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  92404. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92405. this._mainTexture.samples = this._options.mainTextureSamples;
  92406. this._mainTexture.onAfterUnbindObservable.add(function () {
  92407. var internalTexture = _this._blurTexture1.getInternalTexture();
  92408. if (internalTexture) {
  92409. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  92410. internalTexture = _this._blurTexture2.getInternalTexture();
  92411. if (internalTexture) {
  92412. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  92413. }
  92414. }
  92415. });
  92416. // Prevent autoClear.
  92417. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92418. };
  92419. /**
  92420. * Checks for the readiness of the element composing the layer.
  92421. * @param subMesh the mesh to check for
  92422. * @param useInstances specify wether or not to use instances to render the mesh
  92423. * @param emissiveTexture the associated emissive texture used to generate the glow
  92424. * @return true if ready otherwise, false
  92425. */
  92426. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  92427. var material = subMesh.getMaterial();
  92428. var mesh = subMesh.getRenderingMesh();
  92429. if (!material || !mesh) {
  92430. return false;
  92431. }
  92432. var emissiveTexture = material.emissiveTexture;
  92433. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92434. };
  92435. /**
  92436. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92437. */
  92438. GlowLayer.prototype.needStencil = function () {
  92439. return false;
  92440. };
  92441. /**
  92442. * Implementation specific of rendering the generating effect on the main canvas.
  92443. * @param effect The effect used to render through
  92444. */
  92445. GlowLayer.prototype._internalRender = function (effect) {
  92446. // Texture
  92447. effect.setTexture("textureSampler", this._blurTexture1);
  92448. effect.setTexture("textureSampler2", this._blurTexture2);
  92449. effect.setFloat("offset", this._intensity);
  92450. // Cache
  92451. var engine = this._engine;
  92452. var previousStencilBuffer = engine.getStencilBuffer();
  92453. // Draw order
  92454. engine.setStencilBuffer(false);
  92455. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92456. // Draw order
  92457. engine.setStencilBuffer(previousStencilBuffer);
  92458. };
  92459. /**
  92460. * Sets the required values for both the emissive texture and and the main color.
  92461. */
  92462. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92463. var textureLevel = 1.0;
  92464. if (this.customEmissiveTextureSelector) {
  92465. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  92466. }
  92467. else {
  92468. if (material) {
  92469. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92470. if (this._emissiveTextureAndColor.texture) {
  92471. textureLevel = this._emissiveTextureAndColor.texture.level;
  92472. }
  92473. }
  92474. else {
  92475. this._emissiveTextureAndColor.texture = null;
  92476. }
  92477. }
  92478. if (this.customEmissiveColorSelector) {
  92479. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  92480. }
  92481. else {
  92482. if (material.emissiveColor) {
  92483. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  92484. }
  92485. else {
  92486. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92487. }
  92488. }
  92489. };
  92490. /**
  92491. * Returns true if the mesh should render, otherwise false.
  92492. * @param mesh The mesh to render
  92493. * @returns true if it should render otherwise false
  92494. */
  92495. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  92496. return this.hasMesh(mesh);
  92497. };
  92498. /**
  92499. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  92500. * @param mesh The mesh to exclude from the glow layer
  92501. */
  92502. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  92503. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  92504. this._excludedMeshes.push(mesh.uniqueId);
  92505. }
  92506. };
  92507. /**
  92508. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  92509. * @param mesh The mesh to remove
  92510. */
  92511. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  92512. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  92513. if (index !== -1) {
  92514. this._excludedMeshes.splice(index, 1);
  92515. }
  92516. };
  92517. /**
  92518. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  92519. * @param mesh The mesh to include in the glow layer
  92520. */
  92521. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  92522. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  92523. this._includedOnlyMeshes.push(mesh.uniqueId);
  92524. }
  92525. };
  92526. /**
  92527. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  92528. * @param mesh The mesh to remove
  92529. */
  92530. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  92531. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  92532. if (index !== -1) {
  92533. this._includedOnlyMeshes.splice(index, 1);
  92534. }
  92535. };
  92536. /**
  92537. * Determine if a given mesh will be used in the glow layer
  92538. * @param mesh The mesh to test
  92539. * @returns true if the mesh will be highlighted by the current glow layer
  92540. */
  92541. GlowLayer.prototype.hasMesh = function (mesh) {
  92542. // Included Mesh
  92543. if (this._includedOnlyMeshes.length) {
  92544. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  92545. }
  92546. ;
  92547. // Excluded Mesh
  92548. if (this._excludedMeshes.length) {
  92549. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  92550. }
  92551. ;
  92552. return true;
  92553. };
  92554. /**
  92555. * Free any resources and references associated to a mesh.
  92556. * Internal use
  92557. * @param mesh The mesh to free.
  92558. */
  92559. GlowLayer.prototype._disposeMesh = function (mesh) {
  92560. this.removeIncludedOnlyMesh(mesh);
  92561. this.removeExcludedMesh(mesh);
  92562. };
  92563. /**
  92564. * Gets the class name of the effect layer
  92565. * @returns the string with the class name of the effect layer
  92566. */
  92567. GlowLayer.prototype.getClassName = function () {
  92568. return "GlowLayer";
  92569. };
  92570. /**
  92571. * Serializes this glow layer
  92572. * @returns a serialized glow layer object
  92573. */
  92574. GlowLayer.prototype.serialize = function () {
  92575. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92576. serializationObject.customType = "BABYLON.GlowLayer";
  92577. var index;
  92578. // Included meshes
  92579. serializationObject.includedMeshes = [];
  92580. if (this._includedOnlyMeshes.length) {
  92581. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  92582. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  92583. if (mesh) {
  92584. serializationObject.includedMeshes.push(mesh.id);
  92585. }
  92586. }
  92587. }
  92588. // Excluded meshes
  92589. serializationObject.excludedMeshes = [];
  92590. if (this._excludedMeshes.length) {
  92591. for (index = 0; index < this._excludedMeshes.length; index++) {
  92592. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  92593. if (mesh) {
  92594. serializationObject.excludedMeshes.push(mesh.id);
  92595. }
  92596. }
  92597. }
  92598. return serializationObject;
  92599. };
  92600. /**
  92601. * Creates a Glow Layer from parsed glow layer data
  92602. * @param parsedGlowLayer defines glow layer data
  92603. * @param scene defines the current scene
  92604. * @param rootUrl defines the root URL containing the glow layer information
  92605. * @returns a parsed Glow Layer
  92606. */
  92607. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  92608. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  92609. var index;
  92610. // Excluded meshes
  92611. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  92612. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  92613. if (mesh) {
  92614. gl.addExcludedMesh(mesh);
  92615. }
  92616. }
  92617. // Included meshes
  92618. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  92619. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  92620. if (mesh) {
  92621. gl.addIncludedOnlyMesh(mesh);
  92622. }
  92623. }
  92624. return gl;
  92625. };
  92626. /**
  92627. * Effect Name of the layer.
  92628. */
  92629. GlowLayer.EffectName = "GlowLayer";
  92630. /**
  92631. * The default blur kernel size used for the glow.
  92632. */
  92633. GlowLayer.DefaultBlurKernelSize = 32;
  92634. /**
  92635. * The default texture size ratio used for the glow.
  92636. */
  92637. GlowLayer.DefaultTextureRatio = 0.5;
  92638. __decorate([
  92639. BABYLON.serialize()
  92640. ], GlowLayer.prototype, "blurKernelSize", null);
  92641. __decorate([
  92642. BABYLON.serialize()
  92643. ], GlowLayer.prototype, "intensity", null);
  92644. __decorate([
  92645. BABYLON.serialize("options")
  92646. ], GlowLayer.prototype, "_options", void 0);
  92647. return GlowLayer;
  92648. }(BABYLON.EffectLayer));
  92649. BABYLON.GlowLayer = GlowLayer;
  92650. })(BABYLON || (BABYLON = {}));
  92651. //# sourceMappingURL=babylon.glowLayer.js.map
  92652. var BABYLON;
  92653. (function (BABYLON) {
  92654. /**
  92655. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  92656. */
  92657. var AssetTaskState;
  92658. (function (AssetTaskState) {
  92659. /**
  92660. * Initialization
  92661. */
  92662. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  92663. /**
  92664. * Running
  92665. */
  92666. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  92667. /**
  92668. * Done
  92669. */
  92670. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  92671. /**
  92672. * Error
  92673. */
  92674. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  92675. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  92676. /**
  92677. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  92678. */
  92679. var AbstractAssetTask = /** @class */ (function () {
  92680. /**
  92681. * Creates a new {BABYLON.AssetsManager}
  92682. * @param name defines the name of the task
  92683. */
  92684. function AbstractAssetTask(
  92685. /**
  92686. * Task name
  92687. */ name) {
  92688. this.name = name;
  92689. this._isCompleted = false;
  92690. this._taskState = AssetTaskState.INIT;
  92691. }
  92692. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  92693. /**
  92694. * Get if the task is completed
  92695. */
  92696. get: function () {
  92697. return this._isCompleted;
  92698. },
  92699. enumerable: true,
  92700. configurable: true
  92701. });
  92702. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  92703. /**
  92704. * Gets the current state of the task
  92705. */
  92706. get: function () {
  92707. return this._taskState;
  92708. },
  92709. enumerable: true,
  92710. configurable: true
  92711. });
  92712. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  92713. /**
  92714. * Gets the current error object (if task is in error)
  92715. */
  92716. get: function () {
  92717. return this._errorObject;
  92718. },
  92719. enumerable: true,
  92720. configurable: true
  92721. });
  92722. /**
  92723. * Internal only
  92724. * @hidden
  92725. */
  92726. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  92727. if (this._errorObject) {
  92728. return;
  92729. }
  92730. this._errorObject = {
  92731. message: message,
  92732. exception: exception
  92733. };
  92734. };
  92735. /**
  92736. * Execute the current task
  92737. * @param scene defines the scene where you want your assets to be loaded
  92738. * @param onSuccess is a callback called when the task is successfully executed
  92739. * @param onError is a callback called if an error occurs
  92740. */
  92741. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92742. var _this = this;
  92743. this._taskState = AssetTaskState.RUNNING;
  92744. this.runTask(scene, function () {
  92745. _this.onDoneCallback(onSuccess, onError);
  92746. }, function (msg, exception) {
  92747. _this.onErrorCallback(onError, msg, exception);
  92748. });
  92749. };
  92750. /**
  92751. * Execute the current task
  92752. * @param scene defines the scene where you want your assets to be loaded
  92753. * @param onSuccess is a callback called when the task is successfully executed
  92754. * @param onError is a callback called if an error occurs
  92755. */
  92756. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92757. throw new Error("runTask is not implemented");
  92758. };
  92759. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  92760. this._taskState = AssetTaskState.ERROR;
  92761. this._errorObject = {
  92762. message: message,
  92763. exception: exception
  92764. };
  92765. if (this.onError) {
  92766. this.onError(this, message, exception);
  92767. }
  92768. onError();
  92769. };
  92770. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  92771. try {
  92772. this._taskState = AssetTaskState.DONE;
  92773. this._isCompleted = true;
  92774. if (this.onSuccess) {
  92775. this.onSuccess(this);
  92776. }
  92777. onSuccess();
  92778. }
  92779. catch (e) {
  92780. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  92781. }
  92782. };
  92783. return AbstractAssetTask;
  92784. }());
  92785. BABYLON.AbstractAssetTask = AbstractAssetTask;
  92786. /**
  92787. * Class used to share progress information about assets loading
  92788. */
  92789. var AssetsProgressEvent = /** @class */ (function () {
  92790. /**
  92791. * Creates a {BABYLON.AssetsProgressEvent}
  92792. * @param remainingCount defines the number of remaining tasks to process
  92793. * @param totalCount defines the total number of tasks
  92794. * @param task defines the task that was just processed
  92795. */
  92796. function AssetsProgressEvent(remainingCount, totalCount, task) {
  92797. this.remainingCount = remainingCount;
  92798. this.totalCount = totalCount;
  92799. this.task = task;
  92800. }
  92801. return AssetsProgressEvent;
  92802. }());
  92803. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  92804. /**
  92805. * Define a task used by {BABYLON.AssetsManager} to load meshes
  92806. */
  92807. var MeshAssetTask = /** @class */ (function (_super) {
  92808. __extends(MeshAssetTask, _super);
  92809. /**
  92810. * Creates a new {BABYLON.MeshAssetTask}
  92811. * @param name defines the name of the task
  92812. * @param meshesNames defines the list of mesh's names you want to load
  92813. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  92814. * @param sceneFilename defines the filename of the scene to load from
  92815. */
  92816. function MeshAssetTask(
  92817. /**
  92818. * Defines the name of the task
  92819. */
  92820. name,
  92821. /**
  92822. * Defines the list of mesh's names you want to load
  92823. */
  92824. meshesNames,
  92825. /**
  92826. * Defines the root url to use as a base to load your meshes and associated resources
  92827. */
  92828. rootUrl,
  92829. /**
  92830. * Defines the filename of the scene to load from
  92831. */
  92832. sceneFilename) {
  92833. var _this = _super.call(this, name) || this;
  92834. _this.name = name;
  92835. _this.meshesNames = meshesNames;
  92836. _this.rootUrl = rootUrl;
  92837. _this.sceneFilename = sceneFilename;
  92838. return _this;
  92839. }
  92840. /**
  92841. * Execute the current task
  92842. * @param scene defines the scene where you want your assets to be loaded
  92843. * @param onSuccess is a callback called when the task is successfully executed
  92844. * @param onError is a callback called if an error occurs
  92845. */
  92846. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92847. var _this = this;
  92848. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  92849. _this.loadedMeshes = meshes;
  92850. _this.loadedParticleSystems = particleSystems;
  92851. _this.loadedSkeletons = skeletons;
  92852. onSuccess();
  92853. }, null, function (scene, message, exception) {
  92854. onError(message, exception);
  92855. });
  92856. };
  92857. return MeshAssetTask;
  92858. }(AbstractAssetTask));
  92859. BABYLON.MeshAssetTask = MeshAssetTask;
  92860. /**
  92861. * Define a task used by {BABYLON.AssetsManager} to load text content
  92862. */
  92863. var TextFileAssetTask = /** @class */ (function (_super) {
  92864. __extends(TextFileAssetTask, _super);
  92865. /**
  92866. * Creates a new TextFileAssetTask object
  92867. * @param name defines the name of the task
  92868. * @param url defines the location of the file to load
  92869. */
  92870. function TextFileAssetTask(
  92871. /**
  92872. * Defines the name of the task
  92873. */
  92874. name,
  92875. /**
  92876. * Defines the location of the file to load
  92877. */
  92878. url) {
  92879. var _this = _super.call(this, name) || this;
  92880. _this.name = name;
  92881. _this.url = url;
  92882. return _this;
  92883. }
  92884. /**
  92885. * Execute the current task
  92886. * @param scene defines the scene where you want your assets to be loaded
  92887. * @param onSuccess is a callback called when the task is successfully executed
  92888. * @param onError is a callback called if an error occurs
  92889. */
  92890. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92891. var _this = this;
  92892. scene._loadFile(this.url, function (data) {
  92893. _this.text = data;
  92894. onSuccess();
  92895. }, undefined, false, false, function (request, exception) {
  92896. if (request) {
  92897. onError(request.status + " " + request.statusText, exception);
  92898. }
  92899. });
  92900. };
  92901. return TextFileAssetTask;
  92902. }(AbstractAssetTask));
  92903. BABYLON.TextFileAssetTask = TextFileAssetTask;
  92904. /**
  92905. * Define a task used by {BABYLON.AssetsManager} to load binary data
  92906. */
  92907. var BinaryFileAssetTask = /** @class */ (function (_super) {
  92908. __extends(BinaryFileAssetTask, _super);
  92909. /**
  92910. * Creates a new BinaryFileAssetTask object
  92911. * @param name defines the name of the new task
  92912. * @param url defines the location of the file to load
  92913. */
  92914. function BinaryFileAssetTask(
  92915. /**
  92916. * Defines the name of the task
  92917. */
  92918. name,
  92919. /**
  92920. * Defines the location of the file to load
  92921. */
  92922. url) {
  92923. var _this = _super.call(this, name) || this;
  92924. _this.name = name;
  92925. _this.url = url;
  92926. return _this;
  92927. }
  92928. /**
  92929. * Execute the current task
  92930. * @param scene defines the scene where you want your assets to be loaded
  92931. * @param onSuccess is a callback called when the task is successfully executed
  92932. * @param onError is a callback called if an error occurs
  92933. */
  92934. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92935. var _this = this;
  92936. scene._loadFile(this.url, function (data) {
  92937. _this.data = data;
  92938. onSuccess();
  92939. }, undefined, true, true, function (request, exception) {
  92940. if (request) {
  92941. onError(request.status + " " + request.statusText, exception);
  92942. }
  92943. });
  92944. };
  92945. return BinaryFileAssetTask;
  92946. }(AbstractAssetTask));
  92947. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  92948. /**
  92949. * Define a task used by {BABYLON.AssetsManager} to load images
  92950. */
  92951. var ImageAssetTask = /** @class */ (function (_super) {
  92952. __extends(ImageAssetTask, _super);
  92953. /**
  92954. * Creates a new ImageAssetTask
  92955. * @param name defines the name of the task
  92956. * @param url defines the location of the image to load
  92957. */
  92958. function ImageAssetTask(
  92959. /**
  92960. * Defines the name of the task
  92961. */
  92962. name,
  92963. /**
  92964. * Defines the location of the image to load
  92965. */
  92966. url) {
  92967. var _this = _super.call(this, name) || this;
  92968. _this.name = name;
  92969. _this.url = url;
  92970. return _this;
  92971. }
  92972. /**
  92973. * Execute the current task
  92974. * @param scene defines the scene where you want your assets to be loaded
  92975. * @param onSuccess is a callback called when the task is successfully executed
  92976. * @param onError is a callback called if an error occurs
  92977. */
  92978. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92979. var _this = this;
  92980. var img = new Image();
  92981. BABYLON.Tools.SetCorsBehavior(this.url, img);
  92982. img.onload = function () {
  92983. _this.image = img;
  92984. onSuccess();
  92985. };
  92986. img.onerror = function (err) {
  92987. onError("Error loading image", err);
  92988. };
  92989. img.src = this.url;
  92990. };
  92991. return ImageAssetTask;
  92992. }(AbstractAssetTask));
  92993. BABYLON.ImageAssetTask = ImageAssetTask;
  92994. /**
  92995. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  92996. */
  92997. var TextureAssetTask = /** @class */ (function (_super) {
  92998. __extends(TextureAssetTask, _super);
  92999. /**
  93000. * Creates a new TextureAssetTask object
  93001. * @param name defines the name of the task
  93002. * @param url defines the location of the file to load
  93003. * @param noMipmap defines if mipmap should not be generated (default is false)
  93004. * @param invertY defines if texture must be inverted on Y axis (default is false)
  93005. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93006. */
  93007. function TextureAssetTask(
  93008. /**
  93009. * Defines the name of the task
  93010. */
  93011. name,
  93012. /**
  93013. * Defines the location of the file to load
  93014. */
  93015. url,
  93016. /**
  93017. * Defines if mipmap should not be generated (default is false)
  93018. */
  93019. noMipmap,
  93020. /**
  93021. * Defines if texture must be inverted on Y axis (default is false)
  93022. */
  93023. invertY,
  93024. /**
  93025. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93026. */
  93027. samplingMode) {
  93028. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93029. var _this = _super.call(this, name) || this;
  93030. _this.name = name;
  93031. _this.url = url;
  93032. _this.noMipmap = noMipmap;
  93033. _this.invertY = invertY;
  93034. _this.samplingMode = samplingMode;
  93035. return _this;
  93036. }
  93037. /**
  93038. * Execute the current task
  93039. * @param scene defines the scene where you want your assets to be loaded
  93040. * @param onSuccess is a callback called when the task is successfully executed
  93041. * @param onError is a callback called if an error occurs
  93042. */
  93043. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93044. var onload = function () {
  93045. onSuccess();
  93046. };
  93047. var onerror = function (message, exception) {
  93048. onError(message, exception);
  93049. };
  93050. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  93051. };
  93052. return TextureAssetTask;
  93053. }(AbstractAssetTask));
  93054. BABYLON.TextureAssetTask = TextureAssetTask;
  93055. /**
  93056. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  93057. */
  93058. var CubeTextureAssetTask = /** @class */ (function (_super) {
  93059. __extends(CubeTextureAssetTask, _super);
  93060. /**
  93061. * Creates a new CubeTextureAssetTask
  93062. * @param name defines the name of the task
  93063. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93064. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93065. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93066. * @param files defines the explicit list of files (undefined by default)
  93067. */
  93068. function CubeTextureAssetTask(
  93069. /**
  93070. * Defines the name of the task
  93071. */
  93072. name,
  93073. /**
  93074. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93075. */
  93076. url,
  93077. /**
  93078. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93079. */
  93080. extensions,
  93081. /**
  93082. * Defines if mipmaps should not be generated (default is false)
  93083. */
  93084. noMipmap,
  93085. /**
  93086. * Defines the explicit list of files (undefined by default)
  93087. */
  93088. files) {
  93089. var _this = _super.call(this, name) || this;
  93090. _this.name = name;
  93091. _this.url = url;
  93092. _this.extensions = extensions;
  93093. _this.noMipmap = noMipmap;
  93094. _this.files = files;
  93095. return _this;
  93096. }
  93097. /**
  93098. * Execute the current task
  93099. * @param scene defines the scene where you want your assets to be loaded
  93100. * @param onSuccess is a callback called when the task is successfully executed
  93101. * @param onError is a callback called if an error occurs
  93102. */
  93103. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93104. var onload = function () {
  93105. onSuccess();
  93106. };
  93107. var onerror = function (message, exception) {
  93108. onError(message, exception);
  93109. };
  93110. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  93111. };
  93112. return CubeTextureAssetTask;
  93113. }(AbstractAssetTask));
  93114. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  93115. /**
  93116. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  93117. */
  93118. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  93119. __extends(HDRCubeTextureAssetTask, _super);
  93120. /**
  93121. * Creates a new HDRCubeTextureAssetTask object
  93122. * @param name defines the name of the task
  93123. * @param url defines the location of the file to load
  93124. * @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.
  93125. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93126. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93127. * @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)
  93128. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  93129. */
  93130. function HDRCubeTextureAssetTask(
  93131. /**
  93132. * Defines the name of the task
  93133. */
  93134. name,
  93135. /**
  93136. * Defines the location of the file to load
  93137. */
  93138. url,
  93139. /**
  93140. * 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.
  93141. */
  93142. size,
  93143. /**
  93144. * Defines if mipmaps should not be generated (default is false)
  93145. */
  93146. noMipmap,
  93147. /**
  93148. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93149. */
  93150. generateHarmonics,
  93151. /**
  93152. * 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)
  93153. */
  93154. useInGammaSpace,
  93155. /**
  93156. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  93157. */
  93158. usePMREMGenerator) {
  93159. if (noMipmap === void 0) { noMipmap = false; }
  93160. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93161. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  93162. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  93163. var _this = _super.call(this, name) || this;
  93164. _this.name = name;
  93165. _this.url = url;
  93166. _this.size = size;
  93167. _this.noMipmap = noMipmap;
  93168. _this.generateHarmonics = generateHarmonics;
  93169. _this.useInGammaSpace = useInGammaSpace;
  93170. _this.usePMREMGenerator = usePMREMGenerator;
  93171. return _this;
  93172. }
  93173. /**
  93174. * Execute the current task
  93175. * @param scene defines the scene where you want your assets to be loaded
  93176. * @param onSuccess is a callback called when the task is successfully executed
  93177. * @param onError is a callback called if an error occurs
  93178. */
  93179. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93180. var onload = function () {
  93181. onSuccess();
  93182. };
  93183. var onerror = function (message, exception) {
  93184. onError(message, exception);
  93185. };
  93186. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  93187. };
  93188. return HDRCubeTextureAssetTask;
  93189. }(AbstractAssetTask));
  93190. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  93191. /**
  93192. * This class can be used to easily import assets into a scene
  93193. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  93194. */
  93195. var AssetsManager = /** @class */ (function () {
  93196. /**
  93197. * Creates a new AssetsManager
  93198. * @param scene defines the scene to work on
  93199. */
  93200. function AssetsManager(scene) {
  93201. this._isLoading = false;
  93202. this._tasks = new Array();
  93203. this._waitingTasksCount = 0;
  93204. this._totalTasksCount = 0;
  93205. /**
  93206. * Observable called when all tasks are processed
  93207. */
  93208. this.onTaskSuccessObservable = new BABYLON.Observable();
  93209. /**
  93210. * Observable called when a task had an error
  93211. */
  93212. this.onTaskErrorObservable = new BABYLON.Observable();
  93213. /**
  93214. * Observable called when a task is successful
  93215. */
  93216. this.onTasksDoneObservable = new BABYLON.Observable();
  93217. /**
  93218. * Observable called when a task is done (whatever the result is)
  93219. */
  93220. this.onProgressObservable = new BABYLON.Observable();
  93221. /**
  93222. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  93223. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  93224. */
  93225. this.useDefaultLoadingScreen = true;
  93226. this._scene = scene;
  93227. }
  93228. /**
  93229. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  93230. * @param taskName defines the name of the new task
  93231. * @param meshesNames defines the name of meshes to load
  93232. * @param rootUrl defines the root url to use to locate files
  93233. * @param sceneFilename defines the filename of the scene file
  93234. * @returns a new {BABYLON.MeshAssetTask} object
  93235. */
  93236. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  93237. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  93238. this._tasks.push(task);
  93239. return task;
  93240. };
  93241. /**
  93242. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  93243. * @param taskName defines the name of the new task
  93244. * @param url defines the url of the file to load
  93245. * @returns a new {BABYLON.TextFileAssetTask} object
  93246. */
  93247. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  93248. var task = new TextFileAssetTask(taskName, url);
  93249. this._tasks.push(task);
  93250. return task;
  93251. };
  93252. /**
  93253. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  93254. * @param taskName defines the name of the new task
  93255. * @param url defines the url of the file to load
  93256. * @returns a new {BABYLON.BinaryFileAssetTask} object
  93257. */
  93258. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  93259. var task = new BinaryFileAssetTask(taskName, url);
  93260. this._tasks.push(task);
  93261. return task;
  93262. };
  93263. /**
  93264. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  93265. * @param taskName defines the name of the new task
  93266. * @param url defines the url of the file to load
  93267. * @returns a new {BABYLON.ImageAssetTask} object
  93268. */
  93269. AssetsManager.prototype.addImageTask = function (taskName, url) {
  93270. var task = new ImageAssetTask(taskName, url);
  93271. this._tasks.push(task);
  93272. return task;
  93273. };
  93274. /**
  93275. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  93276. * @param taskName defines the name of the new task
  93277. * @param url defines the url of the file to load
  93278. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93279. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  93280. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  93281. * @returns a new {BABYLON.TextureAssetTask} object
  93282. */
  93283. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  93284. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93285. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  93286. this._tasks.push(task);
  93287. return task;
  93288. };
  93289. /**
  93290. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  93291. * @param taskName defines the name of the new task
  93292. * @param url defines the url of the file to load
  93293. * @param extensions defines the extension to use to load the cube map (can be null)
  93294. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93295. * @param files defines the list of files to load (can be null)
  93296. * @returns a new {BABYLON.CubeTextureAssetTask} object
  93297. */
  93298. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  93299. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  93300. this._tasks.push(task);
  93301. return task;
  93302. };
  93303. /**
  93304. *
  93305. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  93306. * @param taskName defines the name of the new task
  93307. * @param url defines the url of the file to load
  93308. * @param size defines the size you want for the cubemap (can be null)
  93309. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93310. * @param generateHarmonics defines if you want to automatically generate (true by default)
  93311. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  93312. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  93313. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  93314. */
  93315. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  93316. if (noMipmap === void 0) { noMipmap = false; }
  93317. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93318. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  93319. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  93320. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  93321. this._tasks.push(task);
  93322. return task;
  93323. };
  93324. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  93325. var _this = this;
  93326. this._waitingTasksCount--;
  93327. try {
  93328. if (task.taskState === AssetTaskState.DONE) {
  93329. // Let's remove successfull tasks
  93330. BABYLON.Tools.SetImmediate(function () {
  93331. var index = _this._tasks.indexOf(task);
  93332. if (index > -1) {
  93333. _this._tasks.splice(index, 1);
  93334. }
  93335. });
  93336. }
  93337. if (this.onProgress) {
  93338. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  93339. }
  93340. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  93341. }
  93342. catch (e) {
  93343. BABYLON.Tools.Error("Error running progress callbacks.");
  93344. console.log(e);
  93345. }
  93346. if (this._waitingTasksCount === 0) {
  93347. try {
  93348. if (this.onFinish) {
  93349. this.onFinish(this._tasks);
  93350. }
  93351. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93352. }
  93353. catch (e) {
  93354. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  93355. console.log(e);
  93356. }
  93357. this._isLoading = false;
  93358. this._scene.getEngine().hideLoadingUI();
  93359. }
  93360. };
  93361. AssetsManager.prototype._runTask = function (task) {
  93362. var _this = this;
  93363. var done = function () {
  93364. try {
  93365. if (_this.onTaskSuccess) {
  93366. _this.onTaskSuccess(task);
  93367. }
  93368. _this.onTaskSuccessObservable.notifyObservers(task);
  93369. _this._decreaseWaitingTasksCount(task);
  93370. }
  93371. catch (e) {
  93372. error("Error executing task success callbacks", e);
  93373. }
  93374. };
  93375. var error = function (message, exception) {
  93376. task._setErrorObject(message, exception);
  93377. if (_this.onTaskError) {
  93378. _this.onTaskError(task);
  93379. }
  93380. _this.onTaskErrorObservable.notifyObservers(task);
  93381. _this._decreaseWaitingTasksCount(task);
  93382. };
  93383. task.run(this._scene, done, error);
  93384. };
  93385. /**
  93386. * Reset the {BABYLON.AssetsManager} and remove all tasks
  93387. * @return the current instance of the {BABYLON.AssetsManager}
  93388. */
  93389. AssetsManager.prototype.reset = function () {
  93390. this._isLoading = false;
  93391. this._tasks = new Array();
  93392. return this;
  93393. };
  93394. /**
  93395. * Start the loading process
  93396. * @return the current instance of the {BABYLON.AssetsManager}
  93397. */
  93398. AssetsManager.prototype.load = function () {
  93399. if (this._isLoading) {
  93400. return this;
  93401. }
  93402. this._isLoading = true;
  93403. this._waitingTasksCount = this._tasks.length;
  93404. this._totalTasksCount = this._tasks.length;
  93405. if (this._waitingTasksCount === 0) {
  93406. this._isLoading = false;
  93407. if (this.onFinish) {
  93408. this.onFinish(this._tasks);
  93409. }
  93410. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93411. return this;
  93412. }
  93413. if (this.useDefaultLoadingScreen) {
  93414. this._scene.getEngine().displayLoadingUI();
  93415. }
  93416. for (var index = 0; index < this._tasks.length; index++) {
  93417. var task = this._tasks[index];
  93418. this._runTask(task);
  93419. }
  93420. return this;
  93421. };
  93422. return AssetsManager;
  93423. }());
  93424. BABYLON.AssetsManager = AssetsManager;
  93425. })(BABYLON || (BABYLON = {}));
  93426. //# sourceMappingURL=babylon.assetsManager.js.map
  93427. var BABYLON;
  93428. (function (BABYLON) {
  93429. var serializedGeometries = [];
  93430. var serializeGeometry = function (geometry, serializationGeometries) {
  93431. if (serializedGeometries[geometry.id]) {
  93432. return;
  93433. }
  93434. if (geometry.doNotSerialize) {
  93435. return;
  93436. }
  93437. if (geometry instanceof BABYLON.BoxGeometry) {
  93438. serializationGeometries.boxes.push(geometry.serialize());
  93439. }
  93440. else if (geometry instanceof BABYLON.SphereGeometry) {
  93441. serializationGeometries.spheres.push(geometry.serialize());
  93442. }
  93443. else if (geometry instanceof BABYLON.CylinderGeometry) {
  93444. serializationGeometries.cylinders.push(geometry.serialize());
  93445. }
  93446. else if (geometry instanceof BABYLON.TorusGeometry) {
  93447. serializationGeometries.toruses.push(geometry.serialize());
  93448. }
  93449. else if (geometry instanceof BABYLON.GroundGeometry) {
  93450. serializationGeometries.grounds.push(geometry.serialize());
  93451. }
  93452. else if (geometry instanceof BABYLON.Plane) {
  93453. serializationGeometries.planes.push(geometry.serialize());
  93454. }
  93455. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  93456. serializationGeometries.torusKnots.push(geometry.serialize());
  93457. }
  93458. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  93459. throw new Error("Unknown primitive type");
  93460. }
  93461. else {
  93462. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  93463. }
  93464. serializedGeometries[geometry.id] = true;
  93465. };
  93466. var serializeMesh = function (mesh, serializationScene) {
  93467. var serializationObject = {};
  93468. // Geometry
  93469. var geometry = mesh._geometry;
  93470. if (geometry) {
  93471. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  93472. // 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
  93473. serializeGeometry(geometry, serializationScene.geometries);
  93474. }
  93475. }
  93476. // Custom
  93477. if (mesh.serialize) {
  93478. mesh.serialize(serializationObject);
  93479. }
  93480. return serializationObject;
  93481. };
  93482. var finalizeSingleMesh = function (mesh, serializationObject) {
  93483. //only works if the mesh is already loaded
  93484. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93485. //serialize material
  93486. if (mesh.material) {
  93487. if (mesh.material instanceof BABYLON.StandardMaterial) {
  93488. serializationObject.materials = serializationObject.materials || [];
  93489. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93490. serializationObject.materials.push(mesh.material.serialize());
  93491. }
  93492. }
  93493. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  93494. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  93495. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93496. serializationObject.multiMaterials.push(mesh.material.serialize());
  93497. }
  93498. }
  93499. }
  93500. //serialize geometry
  93501. var geometry = mesh._geometry;
  93502. if (geometry) {
  93503. if (!serializationObject.geometries) {
  93504. serializationObject.geometries = {};
  93505. serializationObject.geometries.boxes = [];
  93506. serializationObject.geometries.spheres = [];
  93507. serializationObject.geometries.cylinders = [];
  93508. serializationObject.geometries.toruses = [];
  93509. serializationObject.geometries.grounds = [];
  93510. serializationObject.geometries.planes = [];
  93511. serializationObject.geometries.torusKnots = [];
  93512. serializationObject.geometries.vertexData = [];
  93513. }
  93514. serializeGeometry(geometry, serializationObject.geometries);
  93515. }
  93516. // Skeletons
  93517. if (mesh.skeleton) {
  93518. serializationObject.skeletons = serializationObject.skeletons || [];
  93519. serializationObject.skeletons.push(mesh.skeleton.serialize());
  93520. }
  93521. //serialize the actual mesh
  93522. serializationObject.meshes = serializationObject.meshes || [];
  93523. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93524. }
  93525. };
  93526. var SceneSerializer = /** @class */ (function () {
  93527. function SceneSerializer() {
  93528. }
  93529. SceneSerializer.ClearCache = function () {
  93530. serializedGeometries = [];
  93531. };
  93532. SceneSerializer.Serialize = function (scene) {
  93533. var serializationObject = {};
  93534. SceneSerializer.ClearCache();
  93535. // Scene
  93536. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  93537. serializationObject.autoClear = scene.autoClear;
  93538. serializationObject.clearColor = scene.clearColor.asArray();
  93539. serializationObject.ambientColor = scene.ambientColor.asArray();
  93540. serializationObject.gravity = scene.gravity.asArray();
  93541. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  93542. serializationObject.workerCollisions = scene.workerCollisions;
  93543. // Fog
  93544. if (scene.fogMode && scene.fogMode !== 0) {
  93545. serializationObject.fogMode = scene.fogMode;
  93546. serializationObject.fogColor = scene.fogColor.asArray();
  93547. serializationObject.fogStart = scene.fogStart;
  93548. serializationObject.fogEnd = scene.fogEnd;
  93549. serializationObject.fogDensity = scene.fogDensity;
  93550. }
  93551. //Physics
  93552. if (scene.isPhysicsEnabled()) {
  93553. var physicEngine = scene.getPhysicsEngine();
  93554. if (physicEngine) {
  93555. serializationObject.physicsEnabled = true;
  93556. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  93557. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  93558. }
  93559. }
  93560. // Metadata
  93561. if (scene.metadata) {
  93562. serializationObject.metadata = scene.metadata;
  93563. }
  93564. // Morph targets
  93565. serializationObject.morphTargetManagers = [];
  93566. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  93567. var abstractMesh = _a[_i];
  93568. var manager = abstractMesh.morphTargetManager;
  93569. if (manager) {
  93570. serializationObject.morphTargetManagers.push(manager.serialize());
  93571. }
  93572. }
  93573. // Lights
  93574. serializationObject.lights = [];
  93575. var index;
  93576. var light;
  93577. for (index = 0; index < scene.lights.length; index++) {
  93578. light = scene.lights[index];
  93579. if (!light.doNotSerialize) {
  93580. serializationObject.lights.push(light.serialize());
  93581. }
  93582. }
  93583. // Cameras
  93584. serializationObject.cameras = [];
  93585. for (index = 0; index < scene.cameras.length; index++) {
  93586. var camera = scene.cameras[index];
  93587. if (!camera.doNotSerialize) {
  93588. serializationObject.cameras.push(camera.serialize());
  93589. }
  93590. }
  93591. if (scene.activeCamera) {
  93592. serializationObject.activeCameraID = scene.activeCamera.id;
  93593. }
  93594. // Animations
  93595. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  93596. // Materials
  93597. serializationObject.materials = [];
  93598. serializationObject.multiMaterials = [];
  93599. var material;
  93600. for (index = 0; index < scene.materials.length; index++) {
  93601. material = scene.materials[index];
  93602. if (!material.doNotSerialize) {
  93603. serializationObject.materials.push(material.serialize());
  93604. }
  93605. }
  93606. // MultiMaterials
  93607. serializationObject.multiMaterials = [];
  93608. for (index = 0; index < scene.multiMaterials.length; index++) {
  93609. var multiMaterial = scene.multiMaterials[index];
  93610. serializationObject.multiMaterials.push(multiMaterial.serialize());
  93611. }
  93612. // Environment texture
  93613. if (scene.environmentTexture) {
  93614. serializationObject.environmentTexture = scene.environmentTexture.name;
  93615. }
  93616. // Skeletons
  93617. serializationObject.skeletons = [];
  93618. for (index = 0; index < scene.skeletons.length; index++) {
  93619. var skeleton = scene.skeletons[index];
  93620. if (!skeleton.doNotSerialize) {
  93621. serializationObject.skeletons.push(skeleton.serialize());
  93622. }
  93623. }
  93624. // Transform nodes
  93625. serializationObject.transformNodes = [];
  93626. for (index = 0; index < scene.transformNodes.length; index++) {
  93627. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  93628. }
  93629. // Geometries
  93630. serializationObject.geometries = {};
  93631. serializationObject.geometries.boxes = [];
  93632. serializationObject.geometries.spheres = [];
  93633. serializationObject.geometries.cylinders = [];
  93634. serializationObject.geometries.toruses = [];
  93635. serializationObject.geometries.grounds = [];
  93636. serializationObject.geometries.planes = [];
  93637. serializationObject.geometries.torusKnots = [];
  93638. serializationObject.geometries.vertexData = [];
  93639. serializedGeometries = [];
  93640. var geometries = scene.getGeometries();
  93641. for (index = 0; index < geometries.length; index++) {
  93642. var geometry = geometries[index];
  93643. if (geometry.isReady()) {
  93644. serializeGeometry(geometry, serializationObject.geometries);
  93645. }
  93646. }
  93647. // Meshes
  93648. serializationObject.meshes = [];
  93649. for (index = 0; index < scene.meshes.length; index++) {
  93650. var abstractMesh = scene.meshes[index];
  93651. if (abstractMesh instanceof BABYLON.Mesh) {
  93652. var mesh = abstractMesh;
  93653. if (!mesh.doNotSerialize) {
  93654. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93655. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93656. }
  93657. }
  93658. }
  93659. }
  93660. // Particles Systems
  93661. serializationObject.particleSystems = [];
  93662. for (index = 0; index < scene.particleSystems.length; index++) {
  93663. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  93664. }
  93665. // Lens flares
  93666. serializationObject.lensFlareSystems = [];
  93667. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  93668. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  93669. }
  93670. // Shadows
  93671. serializationObject.shadowGenerators = [];
  93672. for (index = 0; index < scene.lights.length; index++) {
  93673. light = scene.lights[index];
  93674. var shadowGenerator = light.getShadowGenerator();
  93675. if (shadowGenerator) {
  93676. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  93677. }
  93678. }
  93679. // Action Manager
  93680. if (scene.actionManager) {
  93681. serializationObject.actions = scene.actionManager.serialize("scene");
  93682. }
  93683. // Audio
  93684. serializationObject.sounds = [];
  93685. for (index = 0; index < scene.soundTracks.length; index++) {
  93686. var soundtrack = scene.soundTracks[index];
  93687. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  93688. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  93689. }
  93690. }
  93691. // Effect layers
  93692. serializationObject.effectLayers = [];
  93693. for (index = 0; index < scene.effectLayers.length; index++) {
  93694. var layer = scene.effectLayers[index];
  93695. if (layer.serialize) {
  93696. serializationObject.effectLayers.push(layer.serialize());
  93697. }
  93698. }
  93699. return serializationObject;
  93700. };
  93701. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  93702. if (withParents === void 0) { withParents = false; }
  93703. if (withChildren === void 0) { withChildren = false; }
  93704. var serializationObject = {};
  93705. SceneSerializer.ClearCache();
  93706. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  93707. if (withParents || withChildren) {
  93708. //deliberate for loop! not for each, appended should be processed as well.
  93709. for (var i = 0; i < toSerialize.length; ++i) {
  93710. if (withChildren) {
  93711. toSerialize[i].getDescendants().forEach(function (node) {
  93712. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  93713. toSerialize.push(node);
  93714. }
  93715. });
  93716. }
  93717. //make sure the array doesn't contain the object already
  93718. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  93719. toSerialize.push(toSerialize[i].parent);
  93720. }
  93721. }
  93722. }
  93723. toSerialize.forEach(function (mesh) {
  93724. finalizeSingleMesh(mesh, serializationObject);
  93725. });
  93726. return serializationObject;
  93727. };
  93728. return SceneSerializer;
  93729. }());
  93730. BABYLON.SceneSerializer = SceneSerializer;
  93731. })(BABYLON || (BABYLON = {}));
  93732. //# sourceMappingURL=babylon.sceneSerializer.js.map
  93733. var BABYLON;
  93734. (function (BABYLON) {
  93735. var ReflectionProbe = /** @class */ (function () {
  93736. function ReflectionProbe(name, size, scene, generateMipMaps) {
  93737. if (generateMipMaps === void 0) { generateMipMaps = true; }
  93738. var _this = this;
  93739. this.name = name;
  93740. this._viewMatrix = BABYLON.Matrix.Identity();
  93741. this._target = BABYLON.Vector3.Zero();
  93742. this._add = BABYLON.Vector3.Zero();
  93743. this._invertYAxis = false;
  93744. this.position = BABYLON.Vector3.Zero();
  93745. this._scene = scene;
  93746. this._scene.reflectionProbes.push(this);
  93747. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  93748. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  93749. switch (faceIndex) {
  93750. case 0:
  93751. _this._add.copyFromFloats(1, 0, 0);
  93752. break;
  93753. case 1:
  93754. _this._add.copyFromFloats(-1, 0, 0);
  93755. break;
  93756. case 2:
  93757. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  93758. break;
  93759. case 3:
  93760. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  93761. break;
  93762. case 4:
  93763. _this._add.copyFromFloats(0, 0, 1);
  93764. break;
  93765. case 5:
  93766. _this._add.copyFromFloats(0, 0, -1);
  93767. break;
  93768. }
  93769. if (_this._attachedMesh) {
  93770. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  93771. }
  93772. _this.position.addToRef(_this._add, _this._target);
  93773. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  93774. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  93775. scene._forcedViewPosition = _this.position;
  93776. });
  93777. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  93778. scene._forcedViewPosition = null;
  93779. scene.updateTransformMatrix(true);
  93780. });
  93781. if (scene.activeCamera) {
  93782. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  93783. }
  93784. }
  93785. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  93786. get: function () {
  93787. return this._renderTargetTexture.samples;
  93788. },
  93789. set: function (value) {
  93790. this._renderTargetTexture.samples = value;
  93791. },
  93792. enumerable: true,
  93793. configurable: true
  93794. });
  93795. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  93796. get: function () {
  93797. return this._renderTargetTexture.refreshRate;
  93798. },
  93799. set: function (value) {
  93800. this._renderTargetTexture.refreshRate = value;
  93801. },
  93802. enumerable: true,
  93803. configurable: true
  93804. });
  93805. ReflectionProbe.prototype.getScene = function () {
  93806. return this._scene;
  93807. };
  93808. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  93809. get: function () {
  93810. return this._renderTargetTexture;
  93811. },
  93812. enumerable: true,
  93813. configurable: true
  93814. });
  93815. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  93816. get: function () {
  93817. return this._renderTargetTexture.renderList;
  93818. },
  93819. enumerable: true,
  93820. configurable: true
  93821. });
  93822. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  93823. this._attachedMesh = mesh;
  93824. };
  93825. /**
  93826. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  93827. *
  93828. * @param renderingGroupId The rendering group id corresponding to its index
  93829. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  93830. */
  93831. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  93832. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  93833. };
  93834. ReflectionProbe.prototype.dispose = function () {
  93835. var index = this._scene.reflectionProbes.indexOf(this);
  93836. if (index !== -1) {
  93837. // Remove from the scene if found
  93838. this._scene.reflectionProbes.splice(index, 1);
  93839. }
  93840. if (this._renderTargetTexture) {
  93841. this._renderTargetTexture.dispose();
  93842. this._renderTargetTexture = null;
  93843. }
  93844. };
  93845. return ReflectionProbe;
  93846. }());
  93847. BABYLON.ReflectionProbe = ReflectionProbe;
  93848. })(BABYLON || (BABYLON = {}));
  93849. //# sourceMappingURL=babylon.reflectionProbe.js.map
  93850. var BABYLON;
  93851. (function (BABYLON) {
  93852. var Layer = /** @class */ (function () {
  93853. function Layer(name, imgUrl, scene, isBackground, color) {
  93854. this.name = name;
  93855. this.scale = new BABYLON.Vector2(1, 1);
  93856. this.offset = new BABYLON.Vector2(0, 0);
  93857. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  93858. this.layerMask = 0x0FFFFFFF;
  93859. this._vertexBuffers = {};
  93860. // Events
  93861. /**
  93862. * An event triggered when the layer is disposed.
  93863. */
  93864. this.onDisposeObservable = new BABYLON.Observable();
  93865. /**
  93866. * An event triggered before rendering the scene
  93867. */
  93868. this.onBeforeRenderObservable = new BABYLON.Observable();
  93869. /**
  93870. * An event triggered after rendering the scene
  93871. */
  93872. this.onAfterRenderObservable = new BABYLON.Observable();
  93873. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  93874. this.isBackground = isBackground === undefined ? true : isBackground;
  93875. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  93876. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  93877. this._scene.layers.push(this);
  93878. var engine = this._scene.getEngine();
  93879. // VBO
  93880. var vertices = [];
  93881. vertices.push(1, 1);
  93882. vertices.push(-1, 1);
  93883. vertices.push(-1, -1);
  93884. vertices.push(1, -1);
  93885. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93886. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93887. this._createIndexBuffer();
  93888. // Effects
  93889. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  93890. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  93891. }
  93892. Object.defineProperty(Layer.prototype, "onDispose", {
  93893. set: function (callback) {
  93894. if (this._onDisposeObserver) {
  93895. this.onDisposeObservable.remove(this._onDisposeObserver);
  93896. }
  93897. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  93898. },
  93899. enumerable: true,
  93900. configurable: true
  93901. });
  93902. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  93903. set: function (callback) {
  93904. if (this._onBeforeRenderObserver) {
  93905. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  93906. }
  93907. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  93908. },
  93909. enumerable: true,
  93910. configurable: true
  93911. });
  93912. Object.defineProperty(Layer.prototype, "onAfterRender", {
  93913. set: function (callback) {
  93914. if (this._onAfterRenderObserver) {
  93915. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  93916. }
  93917. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  93918. },
  93919. enumerable: true,
  93920. configurable: true
  93921. });
  93922. Layer.prototype._createIndexBuffer = function () {
  93923. var engine = this._scene.getEngine();
  93924. // Indices
  93925. var indices = [];
  93926. indices.push(0);
  93927. indices.push(1);
  93928. indices.push(2);
  93929. indices.push(0);
  93930. indices.push(2);
  93931. indices.push(3);
  93932. this._indexBuffer = engine.createIndexBuffer(indices);
  93933. };
  93934. Layer.prototype._rebuild = function () {
  93935. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93936. if (vb) {
  93937. vb._rebuild();
  93938. }
  93939. this._createIndexBuffer();
  93940. };
  93941. Layer.prototype.render = function () {
  93942. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  93943. // Check
  93944. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  93945. return;
  93946. var engine = this._scene.getEngine();
  93947. this.onBeforeRenderObservable.notifyObservers(this);
  93948. // Render
  93949. engine.enableEffect(currentEffect);
  93950. engine.setState(false);
  93951. // Texture
  93952. currentEffect.setTexture("textureSampler", this.texture);
  93953. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  93954. // Color
  93955. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  93956. // Scale / offset
  93957. currentEffect.setVector2("offset", this.offset);
  93958. currentEffect.setVector2("scale", this.scale);
  93959. // VBOs
  93960. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  93961. // Draw order
  93962. if (!this.alphaTest) {
  93963. engine.setAlphaMode(this.alphaBlendingMode);
  93964. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93965. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  93966. }
  93967. else {
  93968. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93969. }
  93970. this.onAfterRenderObservable.notifyObservers(this);
  93971. };
  93972. Layer.prototype.dispose = function () {
  93973. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93974. if (vertexBuffer) {
  93975. vertexBuffer.dispose();
  93976. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93977. }
  93978. if (this._indexBuffer) {
  93979. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93980. this._indexBuffer = null;
  93981. }
  93982. if (this.texture) {
  93983. this.texture.dispose();
  93984. this.texture = null;
  93985. }
  93986. // Remove from scene
  93987. var index = this._scene.layers.indexOf(this);
  93988. this._scene.layers.splice(index, 1);
  93989. // Callback
  93990. this.onDisposeObservable.notifyObservers(this);
  93991. this.onDisposeObservable.clear();
  93992. this.onAfterRenderObservable.clear();
  93993. this.onBeforeRenderObservable.clear();
  93994. };
  93995. return Layer;
  93996. }());
  93997. BABYLON.Layer = Layer;
  93998. })(BABYLON || (BABYLON = {}));
  93999. //# sourceMappingURL=babylon.layer.js.map
  94000. var BABYLON;
  94001. (function (BABYLON) {
  94002. var TextureTools = /** @class */ (function () {
  94003. function TextureTools() {
  94004. }
  94005. /**
  94006. * Uses the GPU to create a copy texture rescaled at a given size
  94007. * @param texture Texture to copy from
  94008. * @param width Desired width
  94009. * @param height Desired height
  94010. * @return Generated texture
  94011. */
  94012. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  94013. if (useBilinearMode === void 0) { useBilinearMode = true; }
  94014. var scene = texture.getScene();
  94015. var engine = scene.getEngine();
  94016. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  94017. rtt.wrapU = texture.wrapU;
  94018. rtt.wrapV = texture.wrapV;
  94019. rtt.uOffset = texture.uOffset;
  94020. rtt.vOffset = texture.vOffset;
  94021. rtt.uScale = texture.uScale;
  94022. rtt.vScale = texture.vScale;
  94023. rtt.uAng = texture.uAng;
  94024. rtt.vAng = texture.vAng;
  94025. rtt.wAng = texture.wAng;
  94026. rtt.coordinatesIndex = texture.coordinatesIndex;
  94027. rtt.level = texture.level;
  94028. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  94029. rtt._texture.isReady = false;
  94030. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94031. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94032. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94033. passPostProcess.getEffect().executeWhenCompiled(function () {
  94034. passPostProcess.onApply = function (effect) {
  94035. effect.setTexture("textureSampler", texture);
  94036. };
  94037. var internalTexture = rtt.getInternalTexture();
  94038. if (internalTexture) {
  94039. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  94040. engine.unBindFramebuffer(internalTexture);
  94041. rtt.disposeFramebufferObjects();
  94042. passPostProcess.dispose();
  94043. internalTexture.isReady = true;
  94044. }
  94045. });
  94046. return rtt;
  94047. };
  94048. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  94049. if (!scene._environmentBRDFTexture) {
  94050. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94051. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94052. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94053. scene._environmentBRDFTexture = texture;
  94054. }
  94055. return scene._environmentBRDFTexture;
  94056. };
  94057. 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=";
  94058. return TextureTools;
  94059. }());
  94060. BABYLON.TextureTools = TextureTools;
  94061. })(BABYLON || (BABYLON = {}));
  94062. //# sourceMappingURL=babylon.textureTools.js.map
  94063. var BABYLON;
  94064. (function (BABYLON) {
  94065. var FramingBehavior = /** @class */ (function () {
  94066. function FramingBehavior() {
  94067. this._mode = FramingBehavior.FitFrustumSidesMode;
  94068. this._radiusScale = 1.0;
  94069. this._positionScale = 0.5;
  94070. this._defaultElevation = 0.3;
  94071. this._elevationReturnTime = 1500;
  94072. this._elevationReturnWaitTime = 1000;
  94073. this._zoomStopsAnimation = false;
  94074. this._framingTime = 1500;
  94075. this._isPointerDown = false;
  94076. this._lastInteractionTime = -Infinity;
  94077. // Framing control
  94078. this._animatables = new Array();
  94079. this._betaIsAnimating = false;
  94080. }
  94081. Object.defineProperty(FramingBehavior.prototype, "name", {
  94082. get: function () {
  94083. return "Framing";
  94084. },
  94085. enumerable: true,
  94086. configurable: true
  94087. });
  94088. Object.defineProperty(FramingBehavior.prototype, "mode", {
  94089. /**
  94090. * Gets current mode used by the behavior.
  94091. */
  94092. get: function () {
  94093. return this._mode;
  94094. },
  94095. /**
  94096. * Sets the current mode used by the behavior
  94097. */
  94098. set: function (mode) {
  94099. this._mode = mode;
  94100. },
  94101. enumerable: true,
  94102. configurable: true
  94103. });
  94104. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  94105. /**
  94106. * Gets the scale applied to the radius
  94107. */
  94108. get: function () {
  94109. return this._radiusScale;
  94110. },
  94111. /**
  94112. * Sets the scale applied to the radius (1 by default)
  94113. */
  94114. set: function (radius) {
  94115. this._radiusScale = radius;
  94116. },
  94117. enumerable: true,
  94118. configurable: true
  94119. });
  94120. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  94121. /**
  94122. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94123. */
  94124. get: function () {
  94125. return this._positionScale;
  94126. },
  94127. /**
  94128. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94129. */
  94130. set: function (scale) {
  94131. this._positionScale = scale;
  94132. },
  94133. enumerable: true,
  94134. configurable: true
  94135. });
  94136. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  94137. /**
  94138. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94139. * behaviour is triggered, in radians.
  94140. */
  94141. get: function () {
  94142. return this._defaultElevation;
  94143. },
  94144. /**
  94145. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94146. * behaviour is triggered, in radians.
  94147. */
  94148. set: function (elevation) {
  94149. this._defaultElevation = elevation;
  94150. },
  94151. enumerable: true,
  94152. configurable: true
  94153. });
  94154. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  94155. /**
  94156. * Gets the time (in milliseconds) taken to return to the default beta position.
  94157. * Negative value indicates camera should not return to default.
  94158. */
  94159. get: function () {
  94160. return this._elevationReturnTime;
  94161. },
  94162. /**
  94163. * Sets the time (in milliseconds) taken to return to the default beta position.
  94164. * Negative value indicates camera should not return to default.
  94165. */
  94166. set: function (speed) {
  94167. this._elevationReturnTime = speed;
  94168. },
  94169. enumerable: true,
  94170. configurable: true
  94171. });
  94172. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  94173. /**
  94174. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94175. */
  94176. get: function () {
  94177. return this._elevationReturnWaitTime;
  94178. },
  94179. /**
  94180. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94181. */
  94182. set: function (time) {
  94183. this._elevationReturnWaitTime = time;
  94184. },
  94185. enumerable: true,
  94186. configurable: true
  94187. });
  94188. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  94189. /**
  94190. * Gets the flag that indicates if user zooming should stop animation.
  94191. */
  94192. get: function () {
  94193. return this._zoomStopsAnimation;
  94194. },
  94195. /**
  94196. * Sets the flag that indicates if user zooming should stop animation.
  94197. */
  94198. set: function (flag) {
  94199. this._zoomStopsAnimation = flag;
  94200. },
  94201. enumerable: true,
  94202. configurable: true
  94203. });
  94204. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  94205. /**
  94206. * Gets the transition time when framing the mesh, in milliseconds
  94207. */
  94208. get: function () {
  94209. return this._framingTime;
  94210. },
  94211. /**
  94212. * Sets the transition time when framing the mesh, in milliseconds
  94213. */
  94214. set: function (time) {
  94215. this._framingTime = time;
  94216. },
  94217. enumerable: true,
  94218. configurable: true
  94219. });
  94220. FramingBehavior.prototype.init = function () {
  94221. // Do notihng
  94222. };
  94223. FramingBehavior.prototype.attach = function (camera) {
  94224. var _this = this;
  94225. this._attachedCamera = camera;
  94226. var scene = this._attachedCamera.getScene();
  94227. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  94228. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94229. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94230. _this._isPointerDown = true;
  94231. return;
  94232. }
  94233. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94234. _this._isPointerDown = false;
  94235. }
  94236. });
  94237. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94238. if (mesh) {
  94239. _this.zoomOnMesh(mesh);
  94240. }
  94241. });
  94242. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94243. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94244. _this._applyUserInteraction();
  94245. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  94246. // back to the default position after a given timeout
  94247. _this._maintainCameraAboveGround();
  94248. });
  94249. };
  94250. FramingBehavior.prototype.detach = function () {
  94251. if (!this._attachedCamera) {
  94252. return;
  94253. }
  94254. var scene = this._attachedCamera.getScene();
  94255. if (this._onPrePointerObservableObserver) {
  94256. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94257. }
  94258. if (this._onAfterCheckInputsObserver) {
  94259. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94260. }
  94261. if (this._onMeshTargetChangedObserver) {
  94262. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94263. }
  94264. this._attachedCamera = null;
  94265. };
  94266. /**
  94267. * Targets the given mesh and updates zoom level accordingly.
  94268. * @param mesh The mesh to target.
  94269. * @param radius Optional. If a cached radius position already exists, overrides default.
  94270. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94271. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94272. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94273. */
  94274. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94275. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94276. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94277. mesh.computeWorldMatrix(true);
  94278. var boundingBox = mesh.getBoundingInfo().boundingBox;
  94279. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  94280. };
  94281. /**
  94282. * Targets the given mesh with its children and updates zoom level accordingly.
  94283. * @param mesh The mesh to target.
  94284. * @param radius Optional. If a cached radius position already exists, overrides default.
  94285. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94286. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94287. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94288. */
  94289. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94290. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94291. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94292. mesh.computeWorldMatrix(true);
  94293. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  94294. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  94295. };
  94296. /**
  94297. * Targets the given meshes with their children and updates zoom level accordingly.
  94298. * @param meshes The mesh to target.
  94299. * @param radius Optional. If a cached radius position already exists, overrides default.
  94300. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94301. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94302. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94303. */
  94304. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  94305. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94306. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94307. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  94308. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  94309. for (var i = 0; i < meshes.length; i++) {
  94310. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  94311. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  94312. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  94313. }
  94314. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  94315. };
  94316. /**
  94317. * Targets the given mesh and updates zoom level accordingly.
  94318. * @param mesh The mesh to target.
  94319. * @param radius Optional. If a cached radius position already exists, overrides default.
  94320. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94321. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94322. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94323. */
  94324. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  94325. var _this = this;
  94326. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94327. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94328. var zoomTarget;
  94329. if (!this._attachedCamera) {
  94330. return;
  94331. }
  94332. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  94333. var bottom = minimumWorld.y;
  94334. var top = maximumWorld.y;
  94335. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  94336. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  94337. if (focusOnOriginXZ) {
  94338. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  94339. }
  94340. else {
  94341. var centerWorld = minimumWorld.add(radiusWorld);
  94342. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  94343. }
  94344. if (!this._vectorTransition) {
  94345. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  94346. }
  94347. this._betaIsAnimating = true;
  94348. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  94349. if (animatable) {
  94350. this._animatables.push(animatable);
  94351. }
  94352. // sets the radius and lower radius bounds
  94353. // Small delta ensures camera is not always at lower zoom limit.
  94354. var radius = 0;
  94355. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  94356. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94357. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  94358. radius = position;
  94359. }
  94360. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94361. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94362. if (this._attachedCamera.lowerRadiusLimit === null) {
  94363. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  94364. }
  94365. }
  94366. // Set sensibilities
  94367. var extend = maximumWorld.subtract(minimumWorld).length();
  94368. this._attachedCamera.panningSensibility = 5000 / extend;
  94369. this._attachedCamera.wheelPrecision = 100 / radius;
  94370. // transition to new radius
  94371. if (!this._radiusTransition) {
  94372. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94373. }
  94374. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  94375. _this.stopAllAnimations();
  94376. if (onAnimationEnd) {
  94377. onAnimationEnd();
  94378. }
  94379. if (_this._attachedCamera) {
  94380. _this._attachedCamera.storeState();
  94381. }
  94382. });
  94383. if (animatable) {
  94384. this._animatables.push(animatable);
  94385. }
  94386. };
  94387. /**
  94388. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  94389. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  94390. * frustum width.
  94391. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  94392. * to fully enclose the mesh in the viewing frustum.
  94393. */
  94394. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  94395. var size = maximumWorld.subtract(minimumWorld);
  94396. var boxVectorGlobalDiagonal = size.length();
  94397. var frustumSlope = this._getFrustumSlope();
  94398. // Formula for setting distance
  94399. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  94400. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  94401. // Horizon distance
  94402. var radius = radiusWithoutFraming * this._radiusScale;
  94403. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  94404. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  94405. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  94406. var camera = this._attachedCamera;
  94407. if (!camera) {
  94408. return 0;
  94409. }
  94410. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94411. // Don't exceed the requested limit
  94412. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  94413. }
  94414. // Don't exceed the upper radius limit
  94415. if (camera.upperRadiusLimit) {
  94416. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  94417. }
  94418. return distance;
  94419. };
  94420. /**
  94421. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  94422. * is automatically returned to its default position (expected to be above ground plane).
  94423. */
  94424. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  94425. var _this = this;
  94426. if (this._elevationReturnTime < 0) {
  94427. return;
  94428. }
  94429. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  94430. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  94431. var limitBeta = Math.PI * 0.5;
  94432. // Bring the camera back up if below the ground plane
  94433. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  94434. this._betaIsAnimating = true;
  94435. //Transition to new position
  94436. this.stopAllAnimations();
  94437. if (!this._betaTransition) {
  94438. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94439. }
  94440. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  94441. _this._clearAnimationLocks();
  94442. _this.stopAllAnimations();
  94443. });
  94444. if (animatabe) {
  94445. this._animatables.push(animatabe);
  94446. }
  94447. }
  94448. };
  94449. /**
  94450. * Returns the frustum slope based on the canvas ratio and camera FOV
  94451. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  94452. */
  94453. FramingBehavior.prototype._getFrustumSlope = function () {
  94454. // Calculate the viewport ratio
  94455. // Aspect Ratio is Height/Width.
  94456. var camera = this._attachedCamera;
  94457. if (!camera) {
  94458. return BABYLON.Vector2.Zero();
  94459. }
  94460. var engine = camera.getScene().getEngine();
  94461. var aspectRatio = engine.getAspectRatio(camera);
  94462. // Camera FOV is the vertical field of view (top-bottom) in radians.
  94463. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  94464. var frustumSlopeY = Math.tan(camera.fov / 2);
  94465. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  94466. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  94467. // along the forward vector.
  94468. var frustumSlopeX = frustumSlopeY * aspectRatio;
  94469. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  94470. };
  94471. /**
  94472. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  94473. */
  94474. FramingBehavior.prototype._clearAnimationLocks = function () {
  94475. this._betaIsAnimating = false;
  94476. };
  94477. /**
  94478. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94479. */
  94480. FramingBehavior.prototype._applyUserInteraction = function () {
  94481. if (this.isUserIsMoving) {
  94482. this._lastInteractionTime = BABYLON.Tools.Now;
  94483. this.stopAllAnimations();
  94484. this._clearAnimationLocks();
  94485. }
  94486. };
  94487. /**
  94488. * Stops and removes all animations that have been applied to the camera
  94489. */
  94490. FramingBehavior.prototype.stopAllAnimations = function () {
  94491. if (this._attachedCamera) {
  94492. this._attachedCamera.animations = [];
  94493. }
  94494. while (this._animatables.length) {
  94495. if (this._animatables[0]) {
  94496. this._animatables[0].onAnimationEnd = null;
  94497. this._animatables[0].stop();
  94498. }
  94499. this._animatables.shift();
  94500. }
  94501. };
  94502. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  94503. /**
  94504. * Gets a value indicating if the user is moving the camera
  94505. */
  94506. get: function () {
  94507. if (!this._attachedCamera) {
  94508. return false;
  94509. }
  94510. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94511. this._attachedCamera.inertialBetaOffset !== 0 ||
  94512. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94513. this._attachedCamera.inertialPanningX !== 0 ||
  94514. this._attachedCamera.inertialPanningY !== 0 ||
  94515. this._isPointerDown;
  94516. },
  94517. enumerable: true,
  94518. configurable: true
  94519. });
  94520. /**
  94521. * The easing function used by animations
  94522. */
  94523. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  94524. /**
  94525. * The easing mode used by animations
  94526. */
  94527. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  94528. // Statics
  94529. /**
  94530. * The camera can move all the way towards the mesh.
  94531. */
  94532. FramingBehavior.IgnoreBoundsSizeMode = 0;
  94533. /**
  94534. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  94535. */
  94536. FramingBehavior.FitFrustumSidesMode = 1;
  94537. return FramingBehavior;
  94538. }());
  94539. BABYLON.FramingBehavior = FramingBehavior;
  94540. })(BABYLON || (BABYLON = {}));
  94541. //# sourceMappingURL=babylon.framingBehavior.js.map
  94542. var BABYLON;
  94543. (function (BABYLON) {
  94544. /**
  94545. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  94546. */
  94547. var BouncingBehavior = /** @class */ (function () {
  94548. function BouncingBehavior() {
  94549. /**
  94550. * The duration of the animation, in milliseconds
  94551. */
  94552. this.transitionDuration = 450;
  94553. /**
  94554. * Length of the distance animated by the transition when lower radius is reached
  94555. */
  94556. this.lowerRadiusTransitionRange = 2;
  94557. /**
  94558. * Length of the distance animated by the transition when upper radius is reached
  94559. */
  94560. this.upperRadiusTransitionRange = -2;
  94561. this._autoTransitionRange = false;
  94562. // Animations
  94563. this._radiusIsAnimating = false;
  94564. this._radiusBounceTransition = null;
  94565. this._animatables = new Array();
  94566. }
  94567. Object.defineProperty(BouncingBehavior.prototype, "name", {
  94568. get: function () {
  94569. return "Bouncing";
  94570. },
  94571. enumerable: true,
  94572. configurable: true
  94573. });
  94574. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  94575. /**
  94576. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94577. */
  94578. get: function () {
  94579. return this._autoTransitionRange;
  94580. },
  94581. /**
  94582. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94583. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  94584. */
  94585. set: function (value) {
  94586. var _this = this;
  94587. if (this._autoTransitionRange === value) {
  94588. return;
  94589. }
  94590. this._autoTransitionRange = value;
  94591. var camera = this._attachedCamera;
  94592. if (!camera) {
  94593. return;
  94594. }
  94595. if (value) {
  94596. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94597. if (!mesh) {
  94598. return;
  94599. }
  94600. mesh.computeWorldMatrix(true);
  94601. var diagonal = mesh.getBoundingInfo().diagonalLength;
  94602. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  94603. _this.upperRadiusTransitionRange = diagonal * 0.05;
  94604. });
  94605. }
  94606. else if (this._onMeshTargetChangedObserver) {
  94607. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94608. }
  94609. },
  94610. enumerable: true,
  94611. configurable: true
  94612. });
  94613. BouncingBehavior.prototype.init = function () {
  94614. // Do notihng
  94615. };
  94616. BouncingBehavior.prototype.attach = function (camera) {
  94617. var _this = this;
  94618. this._attachedCamera = camera;
  94619. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94620. if (!_this._attachedCamera) {
  94621. return;
  94622. }
  94623. // Add the bounce animation to the lower radius limit
  94624. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  94625. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  94626. }
  94627. // Add the bounce animation to the upper radius limit
  94628. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  94629. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  94630. }
  94631. });
  94632. };
  94633. BouncingBehavior.prototype.detach = function () {
  94634. if (!this._attachedCamera) {
  94635. return;
  94636. }
  94637. if (this._onAfterCheckInputsObserver) {
  94638. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94639. }
  94640. if (this._onMeshTargetChangedObserver) {
  94641. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94642. }
  94643. this._attachedCamera = null;
  94644. };
  94645. /**
  94646. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  94647. * @param radiusLimit The limit to check against.
  94648. * @return Bool to indicate if at limit.
  94649. */
  94650. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  94651. if (!this._attachedCamera) {
  94652. return false;
  94653. }
  94654. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  94655. return true;
  94656. }
  94657. return false;
  94658. };
  94659. /**
  94660. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  94661. * @param radiusDelta The delta by which to animate to. Can be negative.
  94662. */
  94663. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  94664. var _this = this;
  94665. if (!this._attachedCamera) {
  94666. return;
  94667. }
  94668. if (!this._radiusBounceTransition) {
  94669. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  94670. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  94671. }
  94672. // Prevent zoom until bounce has completed
  94673. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  94674. this._attachedCamera.wheelPrecision = Infinity;
  94675. this._attachedCamera.inertialRadiusOffset = 0;
  94676. // Animate to the radius limit
  94677. this.stopAllAnimations();
  94678. this._radiusIsAnimating = true;
  94679. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  94680. if (animatable) {
  94681. this._animatables.push(animatable);
  94682. }
  94683. };
  94684. /**
  94685. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  94686. */
  94687. BouncingBehavior.prototype._clearAnimationLocks = function () {
  94688. this._radiusIsAnimating = false;
  94689. if (this._attachedCamera) {
  94690. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  94691. }
  94692. };
  94693. /**
  94694. * Stops and removes all animations that have been applied to the camera
  94695. */
  94696. BouncingBehavior.prototype.stopAllAnimations = function () {
  94697. if (this._attachedCamera) {
  94698. this._attachedCamera.animations = [];
  94699. }
  94700. while (this._animatables.length) {
  94701. this._animatables[0].onAnimationEnd = null;
  94702. this._animatables[0].stop();
  94703. this._animatables.shift();
  94704. }
  94705. };
  94706. /**
  94707. * The easing function used by animations
  94708. */
  94709. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  94710. /**
  94711. * The easing mode used by animations
  94712. */
  94713. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  94714. return BouncingBehavior;
  94715. }());
  94716. BABYLON.BouncingBehavior = BouncingBehavior;
  94717. })(BABYLON || (BABYLON = {}));
  94718. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  94719. var BABYLON;
  94720. (function (BABYLON) {
  94721. var AutoRotationBehavior = /** @class */ (function () {
  94722. function AutoRotationBehavior() {
  94723. this._zoomStopsAnimation = false;
  94724. this._idleRotationSpeed = 0.05;
  94725. this._idleRotationWaitTime = 2000;
  94726. this._idleRotationSpinupTime = 2000;
  94727. this._isPointerDown = false;
  94728. this._lastFrameTime = null;
  94729. this._lastInteractionTime = -Infinity;
  94730. this._cameraRotationSpeed = 0;
  94731. this._lastFrameRadius = 0;
  94732. }
  94733. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  94734. get: function () {
  94735. return "AutoRotation";
  94736. },
  94737. enumerable: true,
  94738. configurable: true
  94739. });
  94740. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  94741. /**
  94742. * Gets the flag that indicates if user zooming should stop animation.
  94743. */
  94744. get: function () {
  94745. return this._zoomStopsAnimation;
  94746. },
  94747. /**
  94748. * Sets the flag that indicates if user zooming should stop animation.
  94749. */
  94750. set: function (flag) {
  94751. this._zoomStopsAnimation = flag;
  94752. },
  94753. enumerable: true,
  94754. configurable: true
  94755. });
  94756. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  94757. /**
  94758. * Gets the default speed at which the camera rotates around the model.
  94759. */
  94760. get: function () {
  94761. return this._idleRotationSpeed;
  94762. },
  94763. /**
  94764. * Sets the default speed at which the camera rotates around the model.
  94765. */
  94766. set: function (speed) {
  94767. this._idleRotationSpeed = speed;
  94768. },
  94769. enumerable: true,
  94770. configurable: true
  94771. });
  94772. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  94773. /**
  94774. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  94775. */
  94776. get: function () {
  94777. return this._idleRotationWaitTime;
  94778. },
  94779. /**
  94780. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  94781. */
  94782. set: function (time) {
  94783. this._idleRotationWaitTime = time;
  94784. },
  94785. enumerable: true,
  94786. configurable: true
  94787. });
  94788. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  94789. /**
  94790. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94791. */
  94792. get: function () {
  94793. return this._idleRotationSpinupTime;
  94794. },
  94795. /**
  94796. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94797. */
  94798. set: function (time) {
  94799. this._idleRotationSpinupTime = time;
  94800. },
  94801. enumerable: true,
  94802. configurable: true
  94803. });
  94804. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  94805. /**
  94806. * Gets a value indicating if the camera is currently rotating because of this behavior
  94807. */
  94808. get: function () {
  94809. return Math.abs(this._cameraRotationSpeed) > 0;
  94810. },
  94811. enumerable: true,
  94812. configurable: true
  94813. });
  94814. AutoRotationBehavior.prototype.init = function () {
  94815. // Do notihng
  94816. };
  94817. AutoRotationBehavior.prototype.attach = function (camera) {
  94818. var _this = this;
  94819. this._attachedCamera = camera;
  94820. var scene = this._attachedCamera.getScene();
  94821. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94822. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94823. _this._isPointerDown = true;
  94824. return;
  94825. }
  94826. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94827. _this._isPointerDown = false;
  94828. }
  94829. });
  94830. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94831. var now = BABYLON.Tools.Now;
  94832. var dt = 0;
  94833. if (_this._lastFrameTime != null) {
  94834. dt = now - _this._lastFrameTime;
  94835. }
  94836. _this._lastFrameTime = now;
  94837. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94838. _this._applyUserInteraction();
  94839. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  94840. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  94841. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  94842. // Step camera rotation by rotation speed
  94843. if (_this._attachedCamera) {
  94844. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  94845. }
  94846. });
  94847. };
  94848. AutoRotationBehavior.prototype.detach = function () {
  94849. if (!this._attachedCamera) {
  94850. return;
  94851. }
  94852. var scene = this._attachedCamera.getScene();
  94853. if (this._onPrePointerObservableObserver) {
  94854. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94855. }
  94856. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94857. this._attachedCamera = null;
  94858. };
  94859. /**
  94860. * Returns true if user is scrolling.
  94861. * @return true if user is scrolling.
  94862. */
  94863. AutoRotationBehavior.prototype._userIsZooming = function () {
  94864. if (!this._attachedCamera) {
  94865. return false;
  94866. }
  94867. return this._attachedCamera.inertialRadiusOffset !== 0;
  94868. };
  94869. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  94870. if (!this._attachedCamera) {
  94871. return false;
  94872. }
  94873. var zoomHasHitLimit = false;
  94874. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  94875. zoomHasHitLimit = true;
  94876. }
  94877. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  94878. this._lastFrameRadius = this._attachedCamera.radius;
  94879. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  94880. };
  94881. /**
  94882. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94883. */
  94884. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  94885. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  94886. this._lastInteractionTime = BABYLON.Tools.Now;
  94887. }
  94888. };
  94889. // Tools
  94890. AutoRotationBehavior.prototype._userIsMoving = function () {
  94891. if (!this._attachedCamera) {
  94892. return false;
  94893. }
  94894. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94895. this._attachedCamera.inertialBetaOffset !== 0 ||
  94896. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94897. this._attachedCamera.inertialPanningX !== 0 ||
  94898. this._attachedCamera.inertialPanningY !== 0 ||
  94899. this._isPointerDown;
  94900. };
  94901. return AutoRotationBehavior;
  94902. }());
  94903. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  94904. })(BABYLON || (BABYLON = {}));
  94905. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  94906. var BABYLON;
  94907. (function (BABYLON) {
  94908. var NullEngineOptions = /** @class */ (function () {
  94909. function NullEngineOptions() {
  94910. this.renderWidth = 512;
  94911. this.renderHeight = 256;
  94912. this.textureSize = 512;
  94913. this.deterministicLockstep = false;
  94914. this.lockstepMaxSteps = 4;
  94915. }
  94916. return NullEngineOptions;
  94917. }());
  94918. BABYLON.NullEngineOptions = NullEngineOptions;
  94919. /**
  94920. * The null engine class provides support for headless version of babylon.js.
  94921. * This can be used in server side scenario or for testing purposes
  94922. */
  94923. var NullEngine = /** @class */ (function (_super) {
  94924. __extends(NullEngine, _super);
  94925. function NullEngine(options) {
  94926. if (options === void 0) { options = new NullEngineOptions(); }
  94927. var _this = _super.call(this, null) || this;
  94928. if (options.deterministicLockstep === undefined) {
  94929. options.deterministicLockstep = false;
  94930. }
  94931. if (options.lockstepMaxSteps === undefined) {
  94932. options.lockstepMaxSteps = 4;
  94933. }
  94934. _this._options = options;
  94935. // Init caps
  94936. // We consider we are on a webgl1 capable device
  94937. _this._caps = new BABYLON.EngineCapabilities();
  94938. _this._caps.maxTexturesImageUnits = 16;
  94939. _this._caps.maxVertexTextureImageUnits = 16;
  94940. _this._caps.maxTextureSize = 512;
  94941. _this._caps.maxCubemapTextureSize = 512;
  94942. _this._caps.maxRenderTextureSize = 512;
  94943. _this._caps.maxVertexAttribs = 16;
  94944. _this._caps.maxVaryingVectors = 16;
  94945. _this._caps.maxFragmentUniformVectors = 16;
  94946. _this._caps.maxVertexUniformVectors = 16;
  94947. // Extensions
  94948. _this._caps.standardDerivatives = false;
  94949. _this._caps.astc = null;
  94950. _this._caps.s3tc = null;
  94951. _this._caps.pvrtc = null;
  94952. _this._caps.etc1 = null;
  94953. _this._caps.etc2 = null;
  94954. _this._caps.textureAnisotropicFilterExtension = null;
  94955. _this._caps.maxAnisotropy = 0;
  94956. _this._caps.uintIndices = false;
  94957. _this._caps.fragmentDepthSupported = false;
  94958. _this._caps.highPrecisionShaderSupported = true;
  94959. _this._caps.colorBufferFloat = false;
  94960. _this._caps.textureFloat = false;
  94961. _this._caps.textureFloatLinearFiltering = false;
  94962. _this._caps.textureFloatRender = false;
  94963. _this._caps.textureHalfFloat = false;
  94964. _this._caps.textureHalfFloatLinearFiltering = false;
  94965. _this._caps.textureHalfFloatRender = false;
  94966. _this._caps.textureLOD = false;
  94967. _this._caps.drawBuffersExtension = false;
  94968. _this._caps.depthTextureExtension = false;
  94969. _this._caps.vertexArrayObject = false;
  94970. _this._caps.instancedArrays = false;
  94971. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  94972. // Wrappers
  94973. if (typeof URL === "undefined") {
  94974. URL = {
  94975. createObjectURL: function () { },
  94976. revokeObjectURL: function () { }
  94977. };
  94978. }
  94979. if (typeof Blob === "undefined") {
  94980. Blob = function () { };
  94981. }
  94982. return _this;
  94983. }
  94984. NullEngine.prototype.isDeterministicLockStep = function () {
  94985. return this._options.deterministicLockstep;
  94986. };
  94987. NullEngine.prototype.getLockstepMaxSteps = function () {
  94988. return this._options.lockstepMaxSteps;
  94989. };
  94990. NullEngine.prototype.getHardwareScalingLevel = function () {
  94991. return 1.0;
  94992. };
  94993. NullEngine.prototype.createVertexBuffer = function (vertices) {
  94994. return {
  94995. capacity: 0,
  94996. references: 1,
  94997. is32Bits: false
  94998. };
  94999. };
  95000. NullEngine.prototype.createIndexBuffer = function (indices) {
  95001. return {
  95002. capacity: 0,
  95003. references: 1,
  95004. is32Bits: false
  95005. };
  95006. };
  95007. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  95008. if (stencil === void 0) { stencil = false; }
  95009. };
  95010. NullEngine.prototype.getRenderWidth = function (useScreen) {
  95011. if (useScreen === void 0) { useScreen = false; }
  95012. if (!useScreen && this._currentRenderTarget) {
  95013. return this._currentRenderTarget.width;
  95014. }
  95015. return this._options.renderWidth;
  95016. };
  95017. NullEngine.prototype.getRenderHeight = function (useScreen) {
  95018. if (useScreen === void 0) { useScreen = false; }
  95019. if (!useScreen && this._currentRenderTarget) {
  95020. return this._currentRenderTarget.height;
  95021. }
  95022. return this._options.renderHeight;
  95023. };
  95024. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  95025. this._cachedViewport = viewport;
  95026. };
  95027. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  95028. return {
  95029. transformFeedback: null,
  95030. __SPECTOR_rebuildProgram: null
  95031. };
  95032. };
  95033. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  95034. return [];
  95035. };
  95036. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  95037. return [];
  95038. };
  95039. NullEngine.prototype.bindSamplers = function (effect) {
  95040. this._currentEffect = null;
  95041. };
  95042. NullEngine.prototype.enableEffect = function (effect) {
  95043. this._currentEffect = effect;
  95044. if (effect.onBind) {
  95045. effect.onBind(effect);
  95046. }
  95047. effect.onBindObservable.notifyObservers(effect);
  95048. };
  95049. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  95050. if (zOffset === void 0) { zOffset = 0; }
  95051. if (reverseSide === void 0) { reverseSide = false; }
  95052. };
  95053. NullEngine.prototype.setIntArray = function (uniform, array) {
  95054. };
  95055. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  95056. };
  95057. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  95058. };
  95059. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  95060. };
  95061. NullEngine.prototype.setFloatArray = function (uniform, array) {
  95062. };
  95063. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  95064. };
  95065. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  95066. };
  95067. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  95068. };
  95069. NullEngine.prototype.setArray = function (uniform, array) {
  95070. };
  95071. NullEngine.prototype.setArray2 = function (uniform, array) {
  95072. };
  95073. NullEngine.prototype.setArray3 = function (uniform, array) {
  95074. };
  95075. NullEngine.prototype.setArray4 = function (uniform, array) {
  95076. };
  95077. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  95078. };
  95079. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  95080. };
  95081. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  95082. };
  95083. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  95084. };
  95085. NullEngine.prototype.setFloat = function (uniform, value) {
  95086. };
  95087. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  95088. };
  95089. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  95090. };
  95091. NullEngine.prototype.setBool = function (uniform, bool) {
  95092. };
  95093. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  95094. };
  95095. NullEngine.prototype.setColor3 = function (uniform, color3) {
  95096. };
  95097. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  95098. };
  95099. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  95100. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  95101. if (this._alphaMode === mode) {
  95102. return;
  95103. }
  95104. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  95105. if (!noDepthWriteChange) {
  95106. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  95107. }
  95108. this._alphaMode = mode;
  95109. };
  95110. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  95111. };
  95112. NullEngine.prototype.wipeCaches = function (bruteForce) {
  95113. if (this.preventCacheWipeBetweenFrames) {
  95114. return;
  95115. }
  95116. this.resetTextureCache();
  95117. this._currentEffect = null;
  95118. if (bruteForce) {
  95119. this._currentProgram = null;
  95120. this._stencilState.reset();
  95121. this._depthCullingState.reset();
  95122. this._alphaState.reset();
  95123. }
  95124. this._cachedVertexBuffers = null;
  95125. this._cachedIndexBuffer = null;
  95126. this._cachedEffectForVertexBuffers = null;
  95127. };
  95128. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  95129. };
  95130. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  95131. };
  95132. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  95133. };
  95134. NullEngine.prototype._createTexture = function () {
  95135. return {};
  95136. };
  95137. NullEngine.prototype._releaseTexture = function (texture) {
  95138. };
  95139. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  95140. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95141. if (onLoad === void 0) { onLoad = null; }
  95142. if (onError === void 0) { onError = null; }
  95143. if (buffer === void 0) { buffer = null; }
  95144. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  95145. var url = String(urlArg);
  95146. texture.url = url;
  95147. texture.generateMipMaps = !noMipmap;
  95148. texture.samplingMode = samplingMode;
  95149. texture.invertY = invertY;
  95150. texture.baseWidth = this._options.textureSize;
  95151. texture.baseHeight = this._options.textureSize;
  95152. texture.width = this._options.textureSize;
  95153. texture.height = this._options.textureSize;
  95154. if (format) {
  95155. texture.format = format;
  95156. }
  95157. texture.isReady = true;
  95158. if (onLoad) {
  95159. onLoad();
  95160. }
  95161. return texture;
  95162. };
  95163. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  95164. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  95165. if (options !== undefined && typeof options === "object") {
  95166. fullOptions.generateMipMaps = options.generateMipMaps;
  95167. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  95168. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  95169. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  95170. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  95171. }
  95172. else {
  95173. fullOptions.generateMipMaps = options;
  95174. fullOptions.generateDepthBuffer = true;
  95175. fullOptions.generateStencilBuffer = false;
  95176. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95177. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  95178. }
  95179. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  95180. var width = size.width || size;
  95181. var height = size.height || size;
  95182. texture._depthStencilBuffer = {};
  95183. texture._framebuffer = {};
  95184. texture.baseWidth = width;
  95185. texture.baseHeight = height;
  95186. texture.width = width;
  95187. texture.height = height;
  95188. texture.isReady = true;
  95189. texture.samples = 1;
  95190. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  95191. texture.samplingMode = fullOptions.samplingMode;
  95192. texture.type = fullOptions.type;
  95193. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  95194. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  95195. return texture;
  95196. };
  95197. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  95198. texture.samplingMode = samplingMode;
  95199. };
  95200. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  95201. if (this._currentRenderTarget) {
  95202. this.unBindFramebuffer(this._currentRenderTarget);
  95203. }
  95204. this._currentRenderTarget = texture;
  95205. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  95206. if (this._cachedViewport && !forceFullscreenViewport) {
  95207. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  95208. }
  95209. };
  95210. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  95211. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  95212. this._currentRenderTarget = null;
  95213. if (onBeforeUnbind) {
  95214. if (texture._MSAAFramebuffer) {
  95215. this._currentFramebuffer = texture._framebuffer;
  95216. }
  95217. onBeforeUnbind();
  95218. }
  95219. this._currentFramebuffer = null;
  95220. };
  95221. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  95222. var vbo = {
  95223. capacity: 1,
  95224. references: 1,
  95225. is32Bits: false
  95226. };
  95227. return vbo;
  95228. };
  95229. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  95230. if (offset === void 0) { offset = 0; }
  95231. };
  95232. /**
  95233. * Updates a dynamic vertex buffer.
  95234. * @param vertexBuffer the vertex buffer to update
  95235. * @param data the data used to update the vertex buffer
  95236. * @param byteOffset the byte offset of the data (optional)
  95237. * @param byteLength the byte length of the data (optional)
  95238. */
  95239. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  95240. };
  95241. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  95242. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  95243. this._boundTexturesCache[this._activeChannel] = texture;
  95244. }
  95245. };
  95246. NullEngine.prototype._bindTexture = function (channel, texture) {
  95247. if (channel < 0) {
  95248. return;
  95249. }
  95250. this._bindTextureDirectly(0, texture);
  95251. };
  95252. NullEngine.prototype._releaseBuffer = function (buffer) {
  95253. buffer.references--;
  95254. if (buffer.references === 0) {
  95255. return true;
  95256. }
  95257. return false;
  95258. };
  95259. return NullEngine;
  95260. }(BABYLON.Engine));
  95261. BABYLON.NullEngine = NullEngine;
  95262. })(BABYLON || (BABYLON = {}));
  95263. //# sourceMappingURL=babylon.nullEngine.js.map
  95264. var BABYLON;
  95265. (function (BABYLON) {
  95266. /**
  95267. * This class can be used to get instrumentation data from a Babylon engine
  95268. */
  95269. var EngineInstrumentation = /** @class */ (function () {
  95270. function EngineInstrumentation(engine) {
  95271. this.engine = engine;
  95272. this._captureGPUFrameTime = false;
  95273. this._gpuFrameTime = new BABYLON.PerfCounter();
  95274. this._captureShaderCompilationTime = false;
  95275. this._shaderCompilationTime = new BABYLON.PerfCounter();
  95276. // Observers
  95277. this._onBeginFrameObserver = null;
  95278. this._onEndFrameObserver = null;
  95279. this._onBeforeShaderCompilationObserver = null;
  95280. this._onAfterShaderCompilationObserver = null;
  95281. }
  95282. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  95283. // Properties
  95284. /**
  95285. * Gets the perf counter used for GPU frame time
  95286. */
  95287. get: function () {
  95288. return this._gpuFrameTime;
  95289. },
  95290. enumerable: true,
  95291. configurable: true
  95292. });
  95293. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  95294. /**
  95295. * Gets the GPU frame time capture status
  95296. */
  95297. get: function () {
  95298. return this._captureGPUFrameTime;
  95299. },
  95300. /**
  95301. * Enable or disable the GPU frame time capture
  95302. */
  95303. set: function (value) {
  95304. var _this = this;
  95305. if (value === this._captureGPUFrameTime) {
  95306. return;
  95307. }
  95308. this._captureGPUFrameTime = value;
  95309. if (value) {
  95310. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  95311. if (!_this._gpuFrameTimeToken) {
  95312. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  95313. }
  95314. });
  95315. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  95316. if (!_this._gpuFrameTimeToken) {
  95317. return;
  95318. }
  95319. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  95320. if (time > -1) {
  95321. _this._gpuFrameTimeToken = null;
  95322. _this._gpuFrameTime.fetchNewFrame();
  95323. _this._gpuFrameTime.addCount(time, true);
  95324. }
  95325. });
  95326. }
  95327. else {
  95328. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95329. this._onBeginFrameObserver = null;
  95330. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95331. this._onEndFrameObserver = null;
  95332. }
  95333. },
  95334. enumerable: true,
  95335. configurable: true
  95336. });
  95337. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  95338. /**
  95339. * Gets the perf counter used for shader compilation time
  95340. */
  95341. get: function () {
  95342. return this._shaderCompilationTime;
  95343. },
  95344. enumerable: true,
  95345. configurable: true
  95346. });
  95347. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  95348. /**
  95349. * Gets the shader compilation time capture status
  95350. */
  95351. get: function () {
  95352. return this._captureShaderCompilationTime;
  95353. },
  95354. /**
  95355. * Enable or disable the shader compilation time capture
  95356. */
  95357. set: function (value) {
  95358. var _this = this;
  95359. if (value === this._captureShaderCompilationTime) {
  95360. return;
  95361. }
  95362. this._captureShaderCompilationTime = value;
  95363. if (value) {
  95364. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  95365. _this._shaderCompilationTime.fetchNewFrame();
  95366. _this._shaderCompilationTime.beginMonitoring();
  95367. });
  95368. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  95369. _this._shaderCompilationTime.endMonitoring();
  95370. });
  95371. }
  95372. else {
  95373. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95374. this._onBeforeShaderCompilationObserver = null;
  95375. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95376. this._onAfterShaderCompilationObserver = null;
  95377. }
  95378. },
  95379. enumerable: true,
  95380. configurable: true
  95381. });
  95382. EngineInstrumentation.prototype.dispose = function () {
  95383. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95384. this._onBeginFrameObserver = null;
  95385. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95386. this._onEndFrameObserver = null;
  95387. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95388. this._onBeforeShaderCompilationObserver = null;
  95389. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95390. this._onAfterShaderCompilationObserver = null;
  95391. this.engine = null;
  95392. };
  95393. return EngineInstrumentation;
  95394. }());
  95395. BABYLON.EngineInstrumentation = EngineInstrumentation;
  95396. })(BABYLON || (BABYLON = {}));
  95397. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  95398. var BABYLON;
  95399. (function (BABYLON) {
  95400. /**
  95401. * This class can be used to get instrumentation data from a Babylon engine
  95402. */
  95403. var SceneInstrumentation = /** @class */ (function () {
  95404. function SceneInstrumentation(scene) {
  95405. var _this = this;
  95406. this.scene = scene;
  95407. this._captureActiveMeshesEvaluationTime = false;
  95408. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  95409. this._captureRenderTargetsRenderTime = false;
  95410. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  95411. this._captureFrameTime = false;
  95412. this._frameTime = new BABYLON.PerfCounter();
  95413. this._captureRenderTime = false;
  95414. this._renderTime = new BABYLON.PerfCounter();
  95415. this._captureInterFrameTime = false;
  95416. this._interFrameTime = new BABYLON.PerfCounter();
  95417. this._captureParticlesRenderTime = false;
  95418. this._particlesRenderTime = new BABYLON.PerfCounter();
  95419. this._captureSpritesRenderTime = false;
  95420. this._spritesRenderTime = new BABYLON.PerfCounter();
  95421. this._capturePhysicsTime = false;
  95422. this._physicsTime = new BABYLON.PerfCounter();
  95423. this._captureAnimationsTime = false;
  95424. this._animationsTime = new BABYLON.PerfCounter();
  95425. // Observers
  95426. this._onBeforeActiveMeshesEvaluationObserver = null;
  95427. this._onAfterActiveMeshesEvaluationObserver = null;
  95428. this._onBeforeRenderTargetsRenderObserver = null;
  95429. this._onAfterRenderTargetsRenderObserver = null;
  95430. this._onAfterRenderObserver = null;
  95431. this._onBeforeDrawPhaseObserver = null;
  95432. this._onAfterDrawPhaseObserver = null;
  95433. this._onBeforeAnimationsObserver = null;
  95434. this._onBeforeParticlesRenderingObserver = null;
  95435. this._onAfterParticlesRenderingObserver = null;
  95436. this._onBeforeSpritesRenderingObserver = null;
  95437. this._onAfterSpritesRenderingObserver = null;
  95438. this._onBeforePhysicsObserver = null;
  95439. this._onAfterPhysicsObserver = null;
  95440. this._onAfterAnimationsObserver = null;
  95441. // Before render
  95442. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  95443. if (_this._captureActiveMeshesEvaluationTime) {
  95444. _this._activeMeshesEvaluationTime.fetchNewFrame();
  95445. }
  95446. if (_this._captureRenderTargetsRenderTime) {
  95447. _this._renderTargetsRenderTime.fetchNewFrame();
  95448. }
  95449. if (_this._captureFrameTime) {
  95450. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  95451. _this._frameTime.beginMonitoring();
  95452. }
  95453. if (_this._captureInterFrameTime) {
  95454. _this._interFrameTime.endMonitoring();
  95455. }
  95456. if (_this._captureParticlesRenderTime) {
  95457. _this._particlesRenderTime.fetchNewFrame();
  95458. }
  95459. if (_this._captureSpritesRenderTime) {
  95460. _this._spritesRenderTime.fetchNewFrame();
  95461. }
  95462. if (_this._captureAnimationsTime) {
  95463. _this._animationsTime.beginMonitoring();
  95464. }
  95465. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  95466. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  95467. });
  95468. // After render
  95469. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  95470. if (_this._captureFrameTime) {
  95471. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  95472. _this._frameTime.endMonitoring();
  95473. }
  95474. if (_this._captureRenderTime) {
  95475. _this._renderTime.endMonitoring(false);
  95476. }
  95477. if (_this._captureInterFrameTime) {
  95478. _this._interFrameTime.beginMonitoring();
  95479. }
  95480. });
  95481. }
  95482. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  95483. // Properties
  95484. /**
  95485. * Gets the perf counter used for active meshes evaluation time
  95486. */
  95487. get: function () {
  95488. return this._activeMeshesEvaluationTime;
  95489. },
  95490. enumerable: true,
  95491. configurable: true
  95492. });
  95493. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  95494. /**
  95495. * Gets the active meshes evaluation time capture status
  95496. */
  95497. get: function () {
  95498. return this._captureActiveMeshesEvaluationTime;
  95499. },
  95500. /**
  95501. * Enable or disable the active meshes evaluation time capture
  95502. */
  95503. set: function (value) {
  95504. var _this = this;
  95505. if (value === this._captureActiveMeshesEvaluationTime) {
  95506. return;
  95507. }
  95508. this._captureActiveMeshesEvaluationTime = value;
  95509. if (value) {
  95510. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  95511. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  95512. _this._activeMeshesEvaluationTime.beginMonitoring();
  95513. });
  95514. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  95515. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  95516. _this._activeMeshesEvaluationTime.endMonitoring();
  95517. });
  95518. }
  95519. else {
  95520. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95521. this._onBeforeActiveMeshesEvaluationObserver = null;
  95522. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95523. this._onAfterActiveMeshesEvaluationObserver = null;
  95524. }
  95525. },
  95526. enumerable: true,
  95527. configurable: true
  95528. });
  95529. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  95530. /**
  95531. * Gets the perf counter used for render targets render time
  95532. */
  95533. get: function () {
  95534. return this._renderTargetsRenderTime;
  95535. },
  95536. enumerable: true,
  95537. configurable: true
  95538. });
  95539. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  95540. /**
  95541. * Gets the render targets render time capture status
  95542. */
  95543. get: function () {
  95544. return this._captureRenderTargetsRenderTime;
  95545. },
  95546. /**
  95547. * Enable or disable the render targets render time capture
  95548. */
  95549. set: function (value) {
  95550. var _this = this;
  95551. if (value === this._captureRenderTargetsRenderTime) {
  95552. return;
  95553. }
  95554. this._captureRenderTargetsRenderTime = value;
  95555. if (value) {
  95556. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  95557. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  95558. _this._renderTargetsRenderTime.beginMonitoring();
  95559. });
  95560. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  95561. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  95562. _this._renderTargetsRenderTime.endMonitoring(false);
  95563. });
  95564. }
  95565. else {
  95566. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95567. this._onBeforeRenderTargetsRenderObserver = null;
  95568. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95569. this._onAfterRenderTargetsRenderObserver = null;
  95570. }
  95571. },
  95572. enumerable: true,
  95573. configurable: true
  95574. });
  95575. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  95576. /**
  95577. * Gets the perf counter used for particles render time
  95578. */
  95579. get: function () {
  95580. return this._particlesRenderTime;
  95581. },
  95582. enumerable: true,
  95583. configurable: true
  95584. });
  95585. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  95586. /**
  95587. * Gets the particles render time capture status
  95588. */
  95589. get: function () {
  95590. return this._captureParticlesRenderTime;
  95591. },
  95592. /**
  95593. * Enable or disable the particles render time capture
  95594. */
  95595. set: function (value) {
  95596. var _this = this;
  95597. if (value === this._captureParticlesRenderTime) {
  95598. return;
  95599. }
  95600. this._captureParticlesRenderTime = value;
  95601. if (value) {
  95602. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  95603. BABYLON.Tools.StartPerformanceCounter("Particles");
  95604. _this._particlesRenderTime.beginMonitoring();
  95605. });
  95606. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  95607. BABYLON.Tools.EndPerformanceCounter("Particles");
  95608. _this._particlesRenderTime.endMonitoring(false);
  95609. });
  95610. }
  95611. else {
  95612. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95613. this._onBeforeParticlesRenderingObserver = null;
  95614. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95615. this._onAfterParticlesRenderingObserver = null;
  95616. }
  95617. },
  95618. enumerable: true,
  95619. configurable: true
  95620. });
  95621. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  95622. /**
  95623. * Gets the perf counter used for sprites render time
  95624. */
  95625. get: function () {
  95626. return this._spritesRenderTime;
  95627. },
  95628. enumerable: true,
  95629. configurable: true
  95630. });
  95631. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  95632. /**
  95633. * Gets the sprites render time capture status
  95634. */
  95635. get: function () {
  95636. return this._captureSpritesRenderTime;
  95637. },
  95638. /**
  95639. * Enable or disable the sprites render time capture
  95640. */
  95641. set: function (value) {
  95642. var _this = this;
  95643. if (value === this._captureSpritesRenderTime) {
  95644. return;
  95645. }
  95646. this._captureSpritesRenderTime = value;
  95647. if (value) {
  95648. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  95649. BABYLON.Tools.StartPerformanceCounter("Sprites");
  95650. _this._spritesRenderTime.beginMonitoring();
  95651. });
  95652. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  95653. BABYLON.Tools.EndPerformanceCounter("Sprites");
  95654. _this._spritesRenderTime.endMonitoring(false);
  95655. });
  95656. }
  95657. else {
  95658. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95659. this._onBeforeSpritesRenderingObserver = null;
  95660. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95661. this._onAfterSpritesRenderingObserver = null;
  95662. }
  95663. },
  95664. enumerable: true,
  95665. configurable: true
  95666. });
  95667. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  95668. /**
  95669. * Gets the perf counter used for physics time
  95670. */
  95671. get: function () {
  95672. return this._physicsTime;
  95673. },
  95674. enumerable: true,
  95675. configurable: true
  95676. });
  95677. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  95678. /**
  95679. * Gets the physics time capture status
  95680. */
  95681. get: function () {
  95682. return this._capturePhysicsTime;
  95683. },
  95684. /**
  95685. * Enable or disable the physics time capture
  95686. */
  95687. set: function (value) {
  95688. var _this = this;
  95689. if (value === this._capturePhysicsTime) {
  95690. return;
  95691. }
  95692. this._capturePhysicsTime = value;
  95693. if (value) {
  95694. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  95695. BABYLON.Tools.StartPerformanceCounter("Physics");
  95696. _this._physicsTime.beginMonitoring();
  95697. });
  95698. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  95699. BABYLON.Tools.EndPerformanceCounter("Physics");
  95700. _this._physicsTime.endMonitoring();
  95701. });
  95702. }
  95703. else {
  95704. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95705. this._onBeforePhysicsObserver = null;
  95706. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95707. this._onAfterPhysicsObserver = null;
  95708. }
  95709. },
  95710. enumerable: true,
  95711. configurable: true
  95712. });
  95713. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  95714. /**
  95715. * Gets the perf counter used for animations time
  95716. */
  95717. get: function () {
  95718. return this._animationsTime;
  95719. },
  95720. enumerable: true,
  95721. configurable: true
  95722. });
  95723. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  95724. /**
  95725. * Gets the animations time capture status
  95726. */
  95727. get: function () {
  95728. return this._captureAnimationsTime;
  95729. },
  95730. /**
  95731. * Enable or disable the animations time capture
  95732. */
  95733. set: function (value) {
  95734. var _this = this;
  95735. if (value === this._captureAnimationsTime) {
  95736. return;
  95737. }
  95738. this._captureAnimationsTime = value;
  95739. if (value) {
  95740. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  95741. _this._animationsTime.endMonitoring();
  95742. });
  95743. }
  95744. else {
  95745. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95746. this._onAfterAnimationsObserver = null;
  95747. }
  95748. },
  95749. enumerable: true,
  95750. configurable: true
  95751. });
  95752. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  95753. /**
  95754. * Gets the perf counter used for frame time capture
  95755. */
  95756. get: function () {
  95757. return this._frameTime;
  95758. },
  95759. enumerable: true,
  95760. configurable: true
  95761. });
  95762. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  95763. /**
  95764. * Gets the frame time capture status
  95765. */
  95766. get: function () {
  95767. return this._captureFrameTime;
  95768. },
  95769. /**
  95770. * Enable or disable the frame time capture
  95771. */
  95772. set: function (value) {
  95773. this._captureFrameTime = value;
  95774. },
  95775. enumerable: true,
  95776. configurable: true
  95777. });
  95778. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  95779. /**
  95780. * Gets the perf counter used for inter-frames time capture
  95781. */
  95782. get: function () {
  95783. return this._interFrameTime;
  95784. },
  95785. enumerable: true,
  95786. configurable: true
  95787. });
  95788. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  95789. /**
  95790. * Gets the inter-frames time capture status
  95791. */
  95792. get: function () {
  95793. return this._captureInterFrameTime;
  95794. },
  95795. /**
  95796. * Enable or disable the inter-frames time capture
  95797. */
  95798. set: function (value) {
  95799. this._captureInterFrameTime = value;
  95800. },
  95801. enumerable: true,
  95802. configurable: true
  95803. });
  95804. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  95805. /**
  95806. * Gets the perf counter used for render time capture
  95807. */
  95808. get: function () {
  95809. return this._renderTime;
  95810. },
  95811. enumerable: true,
  95812. configurable: true
  95813. });
  95814. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  95815. /**
  95816. * Gets the render time capture status
  95817. */
  95818. get: function () {
  95819. return this._captureRenderTime;
  95820. },
  95821. /**
  95822. * Enable or disable the render time capture
  95823. */
  95824. set: function (value) {
  95825. var _this = this;
  95826. if (value === this._captureRenderTime) {
  95827. return;
  95828. }
  95829. this._captureRenderTime = value;
  95830. if (value) {
  95831. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  95832. _this._renderTime.beginMonitoring();
  95833. BABYLON.Tools.StartPerformanceCounter("Main render");
  95834. });
  95835. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  95836. _this._renderTime.endMonitoring(false);
  95837. BABYLON.Tools.EndPerformanceCounter("Main render");
  95838. });
  95839. }
  95840. else {
  95841. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95842. this._onBeforeDrawPhaseObserver = null;
  95843. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95844. this._onAfterDrawPhaseObserver = null;
  95845. }
  95846. },
  95847. enumerable: true,
  95848. configurable: true
  95849. });
  95850. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  95851. /**
  95852. * Gets the perf counter used for draw calls
  95853. */
  95854. get: function () {
  95855. return this.scene.getEngine()._drawCalls;
  95856. },
  95857. enumerable: true,
  95858. configurable: true
  95859. });
  95860. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  95861. /**
  95862. * Gets the perf counter used for texture collisions
  95863. */
  95864. get: function () {
  95865. return this.scene.getEngine()._textureCollisions;
  95866. },
  95867. enumerable: true,
  95868. configurable: true
  95869. });
  95870. SceneInstrumentation.prototype.dispose = function () {
  95871. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  95872. this._onAfterRenderObserver = null;
  95873. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95874. this._onBeforeActiveMeshesEvaluationObserver = null;
  95875. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95876. this._onAfterActiveMeshesEvaluationObserver = null;
  95877. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95878. this._onBeforeRenderTargetsRenderObserver = null;
  95879. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95880. this._onAfterRenderTargetsRenderObserver = null;
  95881. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  95882. this._onBeforeAnimationsObserver = null;
  95883. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95884. this._onBeforeParticlesRenderingObserver = null;
  95885. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95886. this._onAfterParticlesRenderingObserver = null;
  95887. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95888. this._onBeforeSpritesRenderingObserver = null;
  95889. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95890. this._onAfterSpritesRenderingObserver = null;
  95891. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95892. this._onBeforeDrawPhaseObserver = null;
  95893. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95894. this._onAfterDrawPhaseObserver = null;
  95895. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95896. this._onBeforePhysicsObserver = null;
  95897. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95898. this._onAfterPhysicsObserver = null;
  95899. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95900. this._onAfterAnimationsObserver = null;
  95901. this.scene = null;
  95902. };
  95903. return SceneInstrumentation;
  95904. }());
  95905. BABYLON.SceneInstrumentation = SceneInstrumentation;
  95906. })(BABYLON || (BABYLON = {}));
  95907. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  95908. var BABYLON;
  95909. (function (BABYLON) {
  95910. /**
  95911. * @hidden
  95912. **/
  95913. var _TimeToken = /** @class */ (function () {
  95914. function _TimeToken() {
  95915. this._timeElapsedQueryEnded = false;
  95916. }
  95917. return _TimeToken;
  95918. }());
  95919. BABYLON._TimeToken = _TimeToken;
  95920. })(BABYLON || (BABYLON = {}));
  95921. //# sourceMappingURL=babylon.timeToken.js.map
  95922. var BABYLON;
  95923. (function (BABYLON) {
  95924. /**
  95925. * Background material defines definition.
  95926. * @hidden Mainly internal Use
  95927. */
  95928. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  95929. __extends(BackgroundMaterialDefines, _super);
  95930. /**
  95931. * Constructor of the defines.
  95932. */
  95933. function BackgroundMaterialDefines() {
  95934. var _this = _super.call(this) || this;
  95935. /**
  95936. * True if the diffuse texture is in use.
  95937. */
  95938. _this.DIFFUSE = false;
  95939. /**
  95940. * The direct UV channel to use.
  95941. */
  95942. _this.DIFFUSEDIRECTUV = 0;
  95943. /**
  95944. * True if the diffuse texture is in gamma space.
  95945. */
  95946. _this.GAMMADIFFUSE = false;
  95947. /**
  95948. * True if the diffuse texture has opacity in the alpha channel.
  95949. */
  95950. _this.DIFFUSEHASALPHA = false;
  95951. /**
  95952. * True if you want the material to fade to transparent at grazing angle.
  95953. */
  95954. _this.OPACITYFRESNEL = false;
  95955. /**
  95956. * True if an extra blur needs to be added in the reflection.
  95957. */
  95958. _this.REFLECTIONBLUR = false;
  95959. /**
  95960. * True if you want the material to fade to reflection at grazing angle.
  95961. */
  95962. _this.REFLECTIONFRESNEL = false;
  95963. /**
  95964. * True if you want the material to falloff as far as you move away from the scene center.
  95965. */
  95966. _this.REFLECTIONFALLOFF = false;
  95967. /**
  95968. * False if the current Webgl implementation does not support the texture lod extension.
  95969. */
  95970. _this.TEXTURELODSUPPORT = false;
  95971. /**
  95972. * True to ensure the data are premultiplied.
  95973. */
  95974. _this.PREMULTIPLYALPHA = false;
  95975. /**
  95976. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  95977. */
  95978. _this.USERGBCOLOR = false;
  95979. /**
  95980. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  95981. * stays aligned with the desired configuration.
  95982. */
  95983. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  95984. /**
  95985. * True to add noise in order to reduce the banding effect.
  95986. */
  95987. _this.NOISE = false;
  95988. /**
  95989. * is the reflection texture in BGR color scheme?
  95990. * Mainly used to solve a bug in ios10 video tag
  95991. */
  95992. _this.REFLECTIONBGR = false;
  95993. _this.IMAGEPROCESSING = false;
  95994. _this.VIGNETTE = false;
  95995. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  95996. _this.VIGNETTEBLENDMODEOPAQUE = false;
  95997. _this.TONEMAPPING = false;
  95998. _this.CONTRAST = false;
  95999. _this.COLORCURVES = false;
  96000. _this.COLORGRADING = false;
  96001. _this.COLORGRADING3D = false;
  96002. _this.SAMPLER3DGREENDEPTH = false;
  96003. _this.SAMPLER3DBGRMAP = false;
  96004. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  96005. _this.EXPOSURE = false;
  96006. // Reflection.
  96007. _this.REFLECTION = false;
  96008. _this.REFLECTIONMAP_3D = false;
  96009. _this.REFLECTIONMAP_SPHERICAL = false;
  96010. _this.REFLECTIONMAP_PLANAR = false;
  96011. _this.REFLECTIONMAP_CUBIC = false;
  96012. _this.REFLECTIONMAP_PROJECTION = false;
  96013. _this.REFLECTIONMAP_SKYBOX = false;
  96014. _this.REFLECTIONMAP_EXPLICIT = false;
  96015. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96016. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96017. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96018. _this.INVERTCUBICMAP = false;
  96019. _this.REFLECTIONMAP_OPPOSITEZ = false;
  96020. _this.LODINREFLECTIONALPHA = false;
  96021. _this.GAMMAREFLECTION = false;
  96022. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  96023. // Default BJS.
  96024. _this.MAINUV1 = false;
  96025. _this.MAINUV2 = false;
  96026. _this.UV1 = false;
  96027. _this.UV2 = false;
  96028. _this.CLIPPLANE = false;
  96029. _this.POINTSIZE = false;
  96030. _this.FOG = false;
  96031. _this.NORMAL = false;
  96032. _this.NUM_BONE_INFLUENCERS = 0;
  96033. _this.BonesPerMesh = 0;
  96034. _this.INSTANCES = false;
  96035. _this.SHADOWFLOAT = false;
  96036. _this.rebuild();
  96037. return _this;
  96038. }
  96039. return BackgroundMaterialDefines;
  96040. }(BABYLON.MaterialDefines));
  96041. /**
  96042. * Background material used to create an efficient environement around your scene.
  96043. */
  96044. var BackgroundMaterial = /** @class */ (function (_super) {
  96045. __extends(BackgroundMaterial, _super);
  96046. /**
  96047. * Instantiates a Background Material in the given scene
  96048. * @param name The friendly name of the material
  96049. * @param scene The scene to add the material to
  96050. */
  96051. function BackgroundMaterial(name, scene) {
  96052. var _this = _super.call(this, name, scene) || this;
  96053. /**
  96054. * Key light Color (multiply against the environement texture)
  96055. */
  96056. _this.primaryColor = BABYLON.Color3.White();
  96057. _this._primaryColorShadowLevel = 0;
  96058. _this._primaryColorHighlightLevel = 0;
  96059. /**
  96060. * Reflection Texture used in the material.
  96061. * Should be author in a specific way for the best result (refer to the documentation).
  96062. */
  96063. _this.reflectionTexture = null;
  96064. /**
  96065. * Reflection Texture level of blur.
  96066. *
  96067. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  96068. * texture twice.
  96069. */
  96070. _this.reflectionBlur = 0;
  96071. /**
  96072. * Diffuse Texture used in the material.
  96073. * Should be author in a specific way for the best result (refer to the documentation).
  96074. */
  96075. _this.diffuseTexture = null;
  96076. _this._shadowLights = null;
  96077. /**
  96078. * Specify the list of lights casting shadow on the material.
  96079. * All scene shadow lights will be included if null.
  96080. */
  96081. _this.shadowLights = null;
  96082. /**
  96083. * Helps adjusting the shadow to a softer level if required.
  96084. * 0 means black shadows and 1 means no shadows.
  96085. */
  96086. _this.shadowLevel = 0;
  96087. /**
  96088. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  96089. * It is usually zero but might be interesting to modify according to your setup.
  96090. */
  96091. _this.sceneCenter = BABYLON.Vector3.Zero();
  96092. /**
  96093. * This helps specifying that the material is falling off to the sky box at grazing angle.
  96094. * This helps ensuring a nice transition when the camera goes under the ground.
  96095. */
  96096. _this.opacityFresnel = true;
  96097. /**
  96098. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  96099. * This helps adding a mirror texture on the ground.
  96100. */
  96101. _this.reflectionFresnel = false;
  96102. /**
  96103. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  96104. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  96105. */
  96106. _this.reflectionFalloffDistance = 0.0;
  96107. /**
  96108. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  96109. */
  96110. _this.reflectionAmount = 1.0;
  96111. /**
  96112. * This specifies the weight of the reflection at grazing angle.
  96113. */
  96114. _this.reflectionReflectance0 = 0.05;
  96115. /**
  96116. * This specifies the weight of the reflection at a perpendicular point of view.
  96117. */
  96118. _this.reflectionReflectance90 = 0.5;
  96119. /**
  96120. * Helps to directly use the maps channels instead of their level.
  96121. */
  96122. _this.useRGBColor = true;
  96123. /**
  96124. * This helps reducing the banding effect that could occur on the background.
  96125. */
  96126. _this.enableNoise = false;
  96127. _this._fovMultiplier = 1.0;
  96128. /**
  96129. * Enable the FOV adjustment feature controlled by fovMultiplier.
  96130. */
  96131. _this.useEquirectangularFOV = false;
  96132. _this._maxSimultaneousLights = 4;
  96133. /**
  96134. * Number of Simultaneous lights allowed on the material.
  96135. */
  96136. _this.maxSimultaneousLights = 4;
  96137. /**
  96138. * Keep track of the image processing observer to allow dispose and replace.
  96139. */
  96140. _this._imageProcessingObserver = null;
  96141. /**
  96142. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  96143. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  96144. */
  96145. _this.switchToBGR = false;
  96146. // Temp values kept as cache in the material.
  96147. _this._renderTargets = new BABYLON.SmartArray(16);
  96148. _this._reflectionControls = BABYLON.Vector4.Zero();
  96149. _this._white = BABYLON.Color3.White();
  96150. _this._primaryShadowColor = BABYLON.Color3.Black();
  96151. _this._primaryHighlightColor = BABYLON.Color3.Black();
  96152. // Setup the default processing configuration to the scene.
  96153. _this._attachImageProcessingConfiguration(null);
  96154. _this.getRenderTargetTextures = function () {
  96155. _this._renderTargets.reset();
  96156. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  96157. _this._renderTargets.push(_this._diffuseTexture);
  96158. }
  96159. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  96160. _this._renderTargets.push(_this._reflectionTexture);
  96161. }
  96162. return _this._renderTargets;
  96163. };
  96164. return _this;
  96165. }
  96166. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  96167. /**
  96168. * Experimental Internal Use Only.
  96169. *
  96170. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  96171. * This acts as a helper to set the primary color to a more "human friendly" value.
  96172. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  96173. * output color as close as possible from the chosen value.
  96174. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  96175. * part of lighting setup.)
  96176. */
  96177. get: function () {
  96178. return this.__perceptualColor;
  96179. },
  96180. set: function (value) {
  96181. this.__perceptualColor = value;
  96182. this._computePrimaryColorFromPerceptualColor();
  96183. this._markAllSubMeshesAsLightsDirty();
  96184. },
  96185. enumerable: true,
  96186. configurable: true
  96187. });
  96188. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  96189. /**
  96190. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  96191. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  96192. */
  96193. get: function () {
  96194. return this._primaryColorShadowLevel;
  96195. },
  96196. set: function (value) {
  96197. this._primaryColorShadowLevel = value;
  96198. this._computePrimaryColors();
  96199. this._markAllSubMeshesAsLightsDirty();
  96200. },
  96201. enumerable: true,
  96202. configurable: true
  96203. });
  96204. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  96205. /**
  96206. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  96207. * The primary color is used at the level chosen to define what the white area would look.
  96208. */
  96209. get: function () {
  96210. return this._primaryColorHighlightLevel;
  96211. },
  96212. set: function (value) {
  96213. this._primaryColorHighlightLevel = value;
  96214. this._computePrimaryColors();
  96215. this._markAllSubMeshesAsLightsDirty();
  96216. },
  96217. enumerable: true,
  96218. configurable: true
  96219. });
  96220. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  96221. /**
  96222. * Sets the reflection reflectance fresnel values according to the default standard
  96223. * empirically know to work well :-)
  96224. */
  96225. set: function (value) {
  96226. var reflectionWeight = value;
  96227. if (reflectionWeight < 0.5) {
  96228. reflectionWeight = reflectionWeight * 2.0;
  96229. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  96230. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  96231. }
  96232. else {
  96233. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  96234. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  96235. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  96236. }
  96237. },
  96238. enumerable: true,
  96239. configurable: true
  96240. });
  96241. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  96242. /**
  96243. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96244. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  96245. * Recommended to be keep at 1.0 except for special cases.
  96246. */
  96247. get: function () {
  96248. return this._fovMultiplier;
  96249. },
  96250. set: function (value) {
  96251. if (isNaN(value)) {
  96252. value = 1.0;
  96253. }
  96254. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  96255. },
  96256. enumerable: true,
  96257. configurable: true
  96258. });
  96259. /**
  96260. * Attaches a new image processing configuration to the PBR Material.
  96261. * @param configuration (if null the scene configuration will be use)
  96262. */
  96263. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  96264. var _this = this;
  96265. if (configuration === this._imageProcessingConfiguration) {
  96266. return;
  96267. }
  96268. // Detaches observer.
  96269. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96270. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96271. }
  96272. // Pick the scene configuration if needed.
  96273. if (!configuration) {
  96274. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  96275. }
  96276. else {
  96277. this._imageProcessingConfiguration = configuration;
  96278. }
  96279. // Attaches observer.
  96280. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  96281. _this._computePrimaryColorFromPerceptualColor();
  96282. _this._markAllSubMeshesAsImageProcessingDirty();
  96283. });
  96284. };
  96285. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  96286. /**
  96287. * Gets the image processing configuration used either in this material.
  96288. */
  96289. get: function () {
  96290. return this._imageProcessingConfiguration;
  96291. },
  96292. /**
  96293. * Sets the Default image processing configuration used either in the this material.
  96294. *
  96295. * If sets to null, the scene one is in use.
  96296. */
  96297. set: function (value) {
  96298. this._attachImageProcessingConfiguration(value);
  96299. // Ensure the effect will be rebuilt.
  96300. this._markAllSubMeshesAsTexturesDirty();
  96301. },
  96302. enumerable: true,
  96303. configurable: true
  96304. });
  96305. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  96306. /**
  96307. * Gets wether the color curves effect is enabled.
  96308. */
  96309. get: function () {
  96310. return this.imageProcessingConfiguration.colorCurvesEnabled;
  96311. },
  96312. /**
  96313. * Sets wether the color curves effect is enabled.
  96314. */
  96315. set: function (value) {
  96316. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  96317. },
  96318. enumerable: true,
  96319. configurable: true
  96320. });
  96321. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  96322. /**
  96323. * Gets wether the color grading effect is enabled.
  96324. */
  96325. get: function () {
  96326. return this.imageProcessingConfiguration.colorGradingEnabled;
  96327. },
  96328. /**
  96329. * Gets wether the color grading effect is enabled.
  96330. */
  96331. set: function (value) {
  96332. this.imageProcessingConfiguration.colorGradingEnabled = value;
  96333. },
  96334. enumerable: true,
  96335. configurable: true
  96336. });
  96337. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  96338. /**
  96339. * Gets wether tonemapping is enabled or not.
  96340. */
  96341. get: function () {
  96342. return this._imageProcessingConfiguration.toneMappingEnabled;
  96343. },
  96344. /**
  96345. * Sets wether tonemapping is enabled or not
  96346. */
  96347. set: function (value) {
  96348. this._imageProcessingConfiguration.toneMappingEnabled = value;
  96349. },
  96350. enumerable: true,
  96351. configurable: true
  96352. });
  96353. ;
  96354. ;
  96355. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  96356. /**
  96357. * The camera exposure used on this material.
  96358. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96359. * This corresponds to a photographic exposure.
  96360. */
  96361. get: function () {
  96362. return this._imageProcessingConfiguration.exposure;
  96363. },
  96364. /**
  96365. * The camera exposure used on this material.
  96366. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96367. * This corresponds to a photographic exposure.
  96368. */
  96369. set: function (value) {
  96370. this._imageProcessingConfiguration.exposure = value;
  96371. },
  96372. enumerable: true,
  96373. configurable: true
  96374. });
  96375. ;
  96376. ;
  96377. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  96378. /**
  96379. * Gets The camera contrast used on this material.
  96380. */
  96381. get: function () {
  96382. return this._imageProcessingConfiguration.contrast;
  96383. },
  96384. /**
  96385. * Sets The camera contrast used on this material.
  96386. */
  96387. set: function (value) {
  96388. this._imageProcessingConfiguration.contrast = value;
  96389. },
  96390. enumerable: true,
  96391. configurable: true
  96392. });
  96393. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  96394. /**
  96395. * Gets the Color Grading 2D Lookup Texture.
  96396. */
  96397. get: function () {
  96398. return this._imageProcessingConfiguration.colorGradingTexture;
  96399. },
  96400. /**
  96401. * Sets the Color Grading 2D Lookup Texture.
  96402. */
  96403. set: function (value) {
  96404. this.imageProcessingConfiguration.colorGradingTexture = value;
  96405. },
  96406. enumerable: true,
  96407. configurable: true
  96408. });
  96409. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  96410. /**
  96411. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96412. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96413. * 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;
  96414. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96415. */
  96416. get: function () {
  96417. return this.imageProcessingConfiguration.colorCurves;
  96418. },
  96419. /**
  96420. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96421. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96422. * 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;
  96423. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96424. */
  96425. set: function (value) {
  96426. this.imageProcessingConfiguration.colorCurves = value;
  96427. },
  96428. enumerable: true,
  96429. configurable: true
  96430. });
  96431. /**
  96432. * The entire material has been created in order to prevent overdraw.
  96433. * @returns false
  96434. */
  96435. BackgroundMaterial.prototype.needAlphaTesting = function () {
  96436. return true;
  96437. };
  96438. /**
  96439. * The entire material has been created in order to prevent overdraw.
  96440. * @returns true if blending is enable
  96441. */
  96442. BackgroundMaterial.prototype.needAlphaBlending = function () {
  96443. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  96444. };
  96445. /**
  96446. * Checks wether the material is ready to be rendered for a given mesh.
  96447. * @param mesh The mesh to render
  96448. * @param subMesh The submesh to check against
  96449. * @param useInstances Specify wether or not the material is used with instances
  96450. * @returns true if all the dependencies are ready (Textures, Effects...)
  96451. */
  96452. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  96453. var _this = this;
  96454. if (useInstances === void 0) { useInstances = false; }
  96455. if (subMesh.effect && this.isFrozen) {
  96456. if (this._wasPreviouslyReady) {
  96457. return true;
  96458. }
  96459. }
  96460. if (!subMesh._materialDefines) {
  96461. subMesh._materialDefines = new BackgroundMaterialDefines();
  96462. }
  96463. var scene = this.getScene();
  96464. var defines = subMesh._materialDefines;
  96465. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  96466. if (defines._renderId === scene.getRenderId()) {
  96467. return true;
  96468. }
  96469. }
  96470. var engine = scene.getEngine();
  96471. // Lights
  96472. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  96473. defines._needNormals = true;
  96474. // Textures
  96475. if (defines._areTexturesDirty) {
  96476. defines._needUVs = false;
  96477. if (scene.texturesEnabled) {
  96478. if (scene.getEngine().getCaps().textureLOD) {
  96479. defines.TEXTURELODSUPPORT = true;
  96480. }
  96481. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96482. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  96483. return false;
  96484. }
  96485. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  96486. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  96487. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  96488. defines.OPACITYFRESNEL = this._opacityFresnel;
  96489. }
  96490. else {
  96491. defines.DIFFUSE = false;
  96492. defines.DIFFUSEHASALPHA = false;
  96493. defines.GAMMADIFFUSE = false;
  96494. defines.OPACITYFRESNEL = false;
  96495. }
  96496. var reflectionTexture = this._reflectionTexture;
  96497. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96498. if (!reflectionTexture.isReadyOrNotBlocking()) {
  96499. return false;
  96500. }
  96501. defines.REFLECTION = true;
  96502. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  96503. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  96504. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  96505. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  96506. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  96507. defines.REFLECTIONBGR = this.switchToBGR;
  96508. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  96509. defines.INVERTCUBICMAP = true;
  96510. }
  96511. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  96512. switch (reflectionTexture.coordinatesMode) {
  96513. case BABYLON.Texture.CUBIC_MODE:
  96514. case BABYLON.Texture.INVCUBIC_MODE:
  96515. defines.REFLECTIONMAP_CUBIC = true;
  96516. break;
  96517. case BABYLON.Texture.EXPLICIT_MODE:
  96518. defines.REFLECTIONMAP_EXPLICIT = true;
  96519. break;
  96520. case BABYLON.Texture.PLANAR_MODE:
  96521. defines.REFLECTIONMAP_PLANAR = true;
  96522. break;
  96523. case BABYLON.Texture.PROJECTION_MODE:
  96524. defines.REFLECTIONMAP_PROJECTION = true;
  96525. break;
  96526. case BABYLON.Texture.SKYBOX_MODE:
  96527. defines.REFLECTIONMAP_SKYBOX = true;
  96528. break;
  96529. case BABYLON.Texture.SPHERICAL_MODE:
  96530. defines.REFLECTIONMAP_SPHERICAL = true;
  96531. break;
  96532. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  96533. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  96534. break;
  96535. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  96536. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  96537. break;
  96538. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  96539. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  96540. break;
  96541. }
  96542. if (this.reflectionFresnel) {
  96543. defines.REFLECTIONFRESNEL = true;
  96544. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  96545. this._reflectionControls.x = this.reflectionAmount;
  96546. this._reflectionControls.y = this.reflectionReflectance0;
  96547. this._reflectionControls.z = this.reflectionReflectance90;
  96548. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  96549. }
  96550. else {
  96551. defines.REFLECTIONFRESNEL = false;
  96552. defines.REFLECTIONFALLOFF = false;
  96553. }
  96554. }
  96555. else {
  96556. defines.REFLECTION = false;
  96557. defines.REFLECTIONFRESNEL = false;
  96558. defines.REFLECTIONFALLOFF = false;
  96559. defines.REFLECTIONBLUR = false;
  96560. defines.REFLECTIONMAP_3D = false;
  96561. defines.REFLECTIONMAP_SPHERICAL = false;
  96562. defines.REFLECTIONMAP_PLANAR = false;
  96563. defines.REFLECTIONMAP_CUBIC = false;
  96564. defines.REFLECTIONMAP_PROJECTION = false;
  96565. defines.REFLECTIONMAP_SKYBOX = false;
  96566. defines.REFLECTIONMAP_EXPLICIT = false;
  96567. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96568. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96569. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96570. defines.INVERTCUBICMAP = false;
  96571. defines.REFLECTIONMAP_OPPOSITEZ = false;
  96572. defines.LODINREFLECTIONALPHA = false;
  96573. defines.GAMMAREFLECTION = false;
  96574. }
  96575. }
  96576. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  96577. defines.USERGBCOLOR = this._useRGBColor;
  96578. defines.NOISE = this._enableNoise;
  96579. }
  96580. if (defines._areLightsDirty) {
  96581. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  96582. }
  96583. if (defines._areImageProcessingDirty) {
  96584. if (!this._imageProcessingConfiguration.isReady()) {
  96585. return false;
  96586. }
  96587. this._imageProcessingConfiguration.prepareDefines(defines);
  96588. }
  96589. // Misc.
  96590. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  96591. // Values that need to be evaluated on every frame
  96592. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  96593. // Attribs
  96594. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  96595. if (mesh) {
  96596. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  96597. mesh.createNormals(true);
  96598. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  96599. }
  96600. }
  96601. }
  96602. // Get correct effect
  96603. if (defines.isDirty) {
  96604. defines.markAsProcessed();
  96605. scene.resetCachedMaterial();
  96606. // Fallbacks
  96607. var fallbacks = new BABYLON.EffectFallbacks();
  96608. if (defines.FOG) {
  96609. fallbacks.addFallback(0, "FOG");
  96610. }
  96611. if (defines.POINTSIZE) {
  96612. fallbacks.addFallback(1, "POINTSIZE");
  96613. }
  96614. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  96615. if (defines.NUM_BONE_INFLUENCERS > 0) {
  96616. fallbacks.addCPUSkinningFallback(0, mesh);
  96617. }
  96618. //Attributes
  96619. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96620. if (defines.NORMAL) {
  96621. attribs.push(BABYLON.VertexBuffer.NormalKind);
  96622. }
  96623. if (defines.UV1) {
  96624. attribs.push(BABYLON.VertexBuffer.UVKind);
  96625. }
  96626. if (defines.UV2) {
  96627. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96628. }
  96629. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  96630. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  96631. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  96632. "vFogInfos", "vFogColor", "pointSize",
  96633. "vClipPlane", "mBones",
  96634. "vPrimaryColor", "vPrimaryColorShadow",
  96635. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  96636. "shadowLevel", "alpha",
  96637. "vBackgroundCenter", "vReflectionControl",
  96638. "vDiffuseInfos", "diffuseMatrix",
  96639. ];
  96640. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  96641. var uniformBuffers = ["Material", "Scene"];
  96642. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  96643. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  96644. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  96645. uniformsNames: uniforms,
  96646. uniformBuffersNames: uniformBuffers,
  96647. samplers: samplers,
  96648. defines: defines,
  96649. maxSimultaneousLights: this._maxSimultaneousLights
  96650. });
  96651. var onCompiled = function (effect) {
  96652. if (_this.onCompiled) {
  96653. _this.onCompiled(effect);
  96654. }
  96655. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  96656. };
  96657. var join = defines.toString();
  96658. subMesh.setEffect(scene.getEngine().createEffect("background", {
  96659. attributes: attribs,
  96660. uniformsNames: uniforms,
  96661. uniformBuffersNames: uniformBuffers,
  96662. samplers: samplers,
  96663. defines: join,
  96664. fallbacks: fallbacks,
  96665. onCompiled: onCompiled,
  96666. onError: this.onError,
  96667. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  96668. }, engine), defines);
  96669. this.buildUniformLayout();
  96670. }
  96671. if (!subMesh.effect || !subMesh.effect.isReady()) {
  96672. return false;
  96673. }
  96674. defines._renderId = scene.getRenderId();
  96675. this._wasPreviouslyReady = true;
  96676. return true;
  96677. };
  96678. /**
  96679. * Compute the primary color according to the chosen perceptual color.
  96680. */
  96681. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  96682. if (!this.__perceptualColor) {
  96683. return;
  96684. }
  96685. this._primaryColor.copyFrom(this.__perceptualColor);
  96686. // Revert gamma space.
  96687. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  96688. // Revert image processing configuration.
  96689. if (this._imageProcessingConfiguration) {
  96690. // Revert Exposure.
  96691. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  96692. }
  96693. this._computePrimaryColors();
  96694. };
  96695. /**
  96696. * Compute the highlights and shadow colors according to their chosen levels.
  96697. */
  96698. BackgroundMaterial.prototype._computePrimaryColors = function () {
  96699. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  96700. return;
  96701. }
  96702. // Find the highlight color based on the configuration.
  96703. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  96704. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  96705. // Find the shadow color based on the configuration.
  96706. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  96707. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  96708. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  96709. };
  96710. /**
  96711. * Build the uniform buffer used in the material.
  96712. */
  96713. BackgroundMaterial.prototype.buildUniformLayout = function () {
  96714. // Order is important !
  96715. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  96716. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  96717. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  96718. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  96719. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  96720. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  96721. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  96722. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  96723. this._uniformBuffer.addUniform("pointSize", 1);
  96724. this._uniformBuffer.addUniform("shadowLevel", 1);
  96725. this._uniformBuffer.addUniform("alpha", 1);
  96726. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  96727. this._uniformBuffer.addUniform("vReflectionControl", 4);
  96728. this._uniformBuffer.create();
  96729. };
  96730. /**
  96731. * Unbind the material.
  96732. */
  96733. BackgroundMaterial.prototype.unbind = function () {
  96734. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  96735. this._uniformBuffer.setTexture("diffuseSampler", null);
  96736. }
  96737. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  96738. this._uniformBuffer.setTexture("reflectionSampler", null);
  96739. }
  96740. _super.prototype.unbind.call(this);
  96741. };
  96742. /**
  96743. * Bind only the world matrix to the material.
  96744. * @param world The world matrix to bind.
  96745. */
  96746. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  96747. this._activeEffect.setMatrix("world", world);
  96748. };
  96749. /**
  96750. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  96751. * @param world The world matrix to bind.
  96752. * @param subMesh The submesh to bind for.
  96753. */
  96754. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  96755. var scene = this.getScene();
  96756. var defines = subMesh._materialDefines;
  96757. if (!defines) {
  96758. return;
  96759. }
  96760. var effect = subMesh.effect;
  96761. if (!effect) {
  96762. return;
  96763. }
  96764. this._activeEffect = effect;
  96765. // Matrices
  96766. this.bindOnlyWorldMatrix(world);
  96767. // Bones
  96768. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  96769. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  96770. if (mustRebind) {
  96771. this._uniformBuffer.bindToEffect(effect, "Material");
  96772. this.bindViewProjection(effect);
  96773. var reflectionTexture = this._reflectionTexture;
  96774. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  96775. // Texture uniforms
  96776. if (scene.texturesEnabled) {
  96777. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96778. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  96779. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  96780. }
  96781. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96782. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  96783. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  96784. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  96785. }
  96786. }
  96787. if (this.shadowLevel > 0) {
  96788. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  96789. }
  96790. this._uniformBuffer.updateFloat("alpha", this.alpha);
  96791. // Point size
  96792. if (this.pointsCloud) {
  96793. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  96794. }
  96795. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  96796. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  96797. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  96798. }
  96799. else {
  96800. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  96801. }
  96802. }
  96803. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  96804. // Textures
  96805. if (scene.texturesEnabled) {
  96806. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96807. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  96808. }
  96809. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96810. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  96811. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96812. }
  96813. else if (!defines.REFLECTIONBLUR) {
  96814. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96815. }
  96816. else {
  96817. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  96818. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  96819. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  96820. }
  96821. if (defines.REFLECTIONFRESNEL) {
  96822. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  96823. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  96824. }
  96825. }
  96826. }
  96827. // Clip plane
  96828. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  96829. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  96830. }
  96831. if (mustRebind || !this.isFrozen) {
  96832. if (scene.lightsEnabled) {
  96833. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  96834. }
  96835. // View
  96836. this.bindView(effect);
  96837. // Fog
  96838. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  96839. // image processing
  96840. this._imageProcessingConfiguration.bind(this._activeEffect);
  96841. }
  96842. this._uniformBuffer.update();
  96843. this._afterBind(mesh);
  96844. };
  96845. /**
  96846. * Dispose the material.
  96847. * @param forceDisposeEffect Force disposal of the associated effect.
  96848. * @param forceDisposeTextures Force disposal of the associated textures.
  96849. */
  96850. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  96851. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  96852. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  96853. if (forceDisposeTextures) {
  96854. if (this.diffuseTexture) {
  96855. this.diffuseTexture.dispose();
  96856. }
  96857. if (this.reflectionTexture) {
  96858. this.reflectionTexture.dispose();
  96859. }
  96860. }
  96861. this._renderTargets.dispose();
  96862. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96863. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96864. }
  96865. _super.prototype.dispose.call(this, forceDisposeEffect);
  96866. };
  96867. /**
  96868. * Clones the material.
  96869. * @param name The cloned name.
  96870. * @returns The cloned material.
  96871. */
  96872. BackgroundMaterial.prototype.clone = function (name) {
  96873. var _this = this;
  96874. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  96875. };
  96876. /**
  96877. * Serializes the current material to its JSON representation.
  96878. * @returns The JSON representation.
  96879. */
  96880. BackgroundMaterial.prototype.serialize = function () {
  96881. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96882. serializationObject.customType = "BABYLON.BackgroundMaterial";
  96883. return serializationObject;
  96884. };
  96885. /**
  96886. * Gets the class name of the material
  96887. * @returns "BackgroundMaterial"
  96888. */
  96889. BackgroundMaterial.prototype.getClassName = function () {
  96890. return "BackgroundMaterial";
  96891. };
  96892. /**
  96893. * Parse a JSON input to create back a background material.
  96894. * @param source The JSON data to parse
  96895. * @param scene The scene to create the parsed material in
  96896. * @param rootUrl The root url of the assets the material depends upon
  96897. * @returns the instantiated BackgroundMaterial.
  96898. */
  96899. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  96900. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  96901. };
  96902. /**
  96903. * Standard reflectance value at parallel view angle.
  96904. */
  96905. BackgroundMaterial.StandardReflectance0 = 0.05;
  96906. /**
  96907. * Standard reflectance value at grazing angle.
  96908. */
  96909. BackgroundMaterial.StandardReflectance90 = 0.5;
  96910. __decorate([
  96911. BABYLON.serializeAsColor3()
  96912. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  96913. __decorate([
  96914. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96915. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  96916. __decorate([
  96917. BABYLON.serializeAsColor3()
  96918. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  96919. __decorate([
  96920. BABYLON.serialize()
  96921. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  96922. __decorate([
  96923. BABYLON.serialize()
  96924. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  96925. __decorate([
  96926. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96927. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  96928. __decorate([
  96929. BABYLON.serializeAsTexture()
  96930. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  96931. __decorate([
  96932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96933. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  96934. __decorate([
  96935. BABYLON.serialize()
  96936. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  96937. __decorate([
  96938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96939. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  96940. __decorate([
  96941. BABYLON.serializeAsTexture()
  96942. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  96943. __decorate([
  96944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96945. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  96946. __decorate([
  96947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96948. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  96949. __decorate([
  96950. BABYLON.serialize()
  96951. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  96952. __decorate([
  96953. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96954. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  96955. __decorate([
  96956. BABYLON.serializeAsVector3()
  96957. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  96958. __decorate([
  96959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96960. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  96961. __decorate([
  96962. BABYLON.serialize()
  96963. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  96964. __decorate([
  96965. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96966. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  96967. __decorate([
  96968. BABYLON.serialize()
  96969. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  96970. __decorate([
  96971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96972. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  96973. __decorate([
  96974. BABYLON.serialize()
  96975. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  96976. __decorate([
  96977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96978. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  96979. __decorate([
  96980. BABYLON.serialize()
  96981. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  96982. __decorate([
  96983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96984. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  96985. __decorate([
  96986. BABYLON.serialize()
  96987. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  96988. __decorate([
  96989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96990. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  96991. __decorate([
  96992. BABYLON.serialize()
  96993. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  96994. __decorate([
  96995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96996. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  96997. __decorate([
  96998. BABYLON.serialize()
  96999. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  97000. __decorate([
  97001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97002. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  97003. __decorate([
  97004. BABYLON.serialize()
  97005. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  97006. __decorate([
  97007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97008. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  97009. __decorate([
  97010. BABYLON.serialize()
  97011. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  97012. __decorate([
  97013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97014. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  97015. __decorate([
  97016. BABYLON.serializeAsImageProcessingConfiguration()
  97017. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  97018. return BackgroundMaterial;
  97019. }(BABYLON.PushMaterial));
  97020. BABYLON.BackgroundMaterial = BackgroundMaterial;
  97021. })(BABYLON || (BABYLON = {}));
  97022. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  97023. var __assign = (this && this.__assign) || Object.assign || function(t) {
  97024. for (var s, i = 1, n = arguments.length; i < n; i++) {
  97025. s = arguments[i];
  97026. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  97027. t[p] = s[p];
  97028. }
  97029. return t;
  97030. };
  97031. var BABYLON;
  97032. (function (BABYLON) {
  97033. /**
  97034. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  97035. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  97036. * It also helps with the default setup of your imageProcessing configuration.
  97037. */
  97038. var EnvironmentHelper = /** @class */ (function () {
  97039. /**
  97040. * constructor
  97041. * @param options
  97042. * @param scene The scene to add the material to
  97043. */
  97044. function EnvironmentHelper(options, scene) {
  97045. var _this = this;
  97046. this._errorHandler = function (message, exception) {
  97047. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  97048. };
  97049. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  97050. this._scene = scene;
  97051. this.onErrorObservable = new BABYLON.Observable();
  97052. this._setupBackground();
  97053. this._setupImageProcessing();
  97054. }
  97055. /**
  97056. * Creates the default options for the helper.
  97057. */
  97058. EnvironmentHelper._getDefaultOptions = function () {
  97059. return {
  97060. createGround: true,
  97061. groundSize: 15,
  97062. groundTexture: this._groundTextureCDNUrl,
  97063. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97064. groundOpacity: 0.9,
  97065. enableGroundShadow: true,
  97066. groundShadowLevel: 0.5,
  97067. enableGroundMirror: false,
  97068. groundMirrorSizeRatio: 0.3,
  97069. groundMirrorBlurKernel: 64,
  97070. groundMirrorAmount: 1,
  97071. groundMirrorFresnelWeight: 1,
  97072. groundMirrorFallOffDistance: 0,
  97073. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  97074. groundYBias: 0.00001,
  97075. createSkybox: true,
  97076. skyboxSize: 20,
  97077. skyboxTexture: this._skyboxTextureCDNUrl,
  97078. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97079. backgroundYRotation: 0,
  97080. sizeAuto: true,
  97081. rootPosition: BABYLON.Vector3.Zero(),
  97082. setupImageProcessing: true,
  97083. environmentTexture: this._environmentTextureCDNUrl,
  97084. cameraExposure: 0.8,
  97085. cameraContrast: 1.2,
  97086. toneMappingEnabled: true,
  97087. };
  97088. };
  97089. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  97090. /**
  97091. * Gets the root mesh created by the helper.
  97092. */
  97093. get: function () {
  97094. return this._rootMesh;
  97095. },
  97096. enumerable: true,
  97097. configurable: true
  97098. });
  97099. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  97100. /**
  97101. * Gets the skybox created by the helper.
  97102. */
  97103. get: function () {
  97104. return this._skybox;
  97105. },
  97106. enumerable: true,
  97107. configurable: true
  97108. });
  97109. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  97110. /**
  97111. * Gets the skybox texture created by the helper.
  97112. */
  97113. get: function () {
  97114. return this._skyboxTexture;
  97115. },
  97116. enumerable: true,
  97117. configurable: true
  97118. });
  97119. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  97120. /**
  97121. * Gets the skybox material created by the helper.
  97122. */
  97123. get: function () {
  97124. return this._skyboxMaterial;
  97125. },
  97126. enumerable: true,
  97127. configurable: true
  97128. });
  97129. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  97130. /**
  97131. * Gets the ground mesh created by the helper.
  97132. */
  97133. get: function () {
  97134. return this._ground;
  97135. },
  97136. enumerable: true,
  97137. configurable: true
  97138. });
  97139. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  97140. /**
  97141. * Gets the ground texture created by the helper.
  97142. */
  97143. get: function () {
  97144. return this._groundTexture;
  97145. },
  97146. enumerable: true,
  97147. configurable: true
  97148. });
  97149. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  97150. /**
  97151. * Gets the ground mirror created by the helper.
  97152. */
  97153. get: function () {
  97154. return this._groundMirror;
  97155. },
  97156. enumerable: true,
  97157. configurable: true
  97158. });
  97159. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  97160. /**
  97161. * Gets the ground mirror render list to helps pushing the meshes
  97162. * you wish in the ground reflection.
  97163. */
  97164. get: function () {
  97165. if (this._groundMirror) {
  97166. return this._groundMirror.renderList;
  97167. }
  97168. return null;
  97169. },
  97170. enumerable: true,
  97171. configurable: true
  97172. });
  97173. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  97174. /**
  97175. * Gets the ground material created by the helper.
  97176. */
  97177. get: function () {
  97178. return this._groundMaterial;
  97179. },
  97180. enumerable: true,
  97181. configurable: true
  97182. });
  97183. /**
  97184. * Updates the background according to the new options
  97185. * @param options
  97186. */
  97187. EnvironmentHelper.prototype.updateOptions = function (options) {
  97188. var newOptions = __assign({}, this._options, options);
  97189. if (this._ground && !newOptions.createGround) {
  97190. this._ground.dispose();
  97191. this._ground = null;
  97192. }
  97193. if (this._groundMaterial && !newOptions.createGround) {
  97194. this._groundMaterial.dispose();
  97195. this._groundMaterial = null;
  97196. }
  97197. if (this._groundTexture) {
  97198. if (this._options.groundTexture != newOptions.groundTexture) {
  97199. this._groundTexture.dispose();
  97200. this._groundTexture = null;
  97201. }
  97202. }
  97203. if (this._skybox && !newOptions.createSkybox) {
  97204. this._skybox.dispose();
  97205. this._skybox = null;
  97206. }
  97207. if (this._skyboxMaterial && !newOptions.createSkybox) {
  97208. this._skyboxMaterial.dispose();
  97209. this._skyboxMaterial = null;
  97210. }
  97211. if (this._skyboxTexture) {
  97212. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  97213. this._skyboxTexture.dispose();
  97214. this._skyboxTexture = null;
  97215. }
  97216. }
  97217. if (this._groundMirror && !newOptions.enableGroundMirror) {
  97218. this._groundMirror.dispose();
  97219. this._groundMirror = null;
  97220. }
  97221. if (this._scene.environmentTexture) {
  97222. if (this._options.environmentTexture != newOptions.environmentTexture) {
  97223. this._scene.environmentTexture.dispose();
  97224. }
  97225. }
  97226. this._options = newOptions;
  97227. this._setupBackground();
  97228. this._setupImageProcessing();
  97229. };
  97230. /**
  97231. * Sets the primary color of all the available elements.
  97232. * @param color the main color to affect to the ground and the background
  97233. */
  97234. EnvironmentHelper.prototype.setMainColor = function (color) {
  97235. if (this.groundMaterial) {
  97236. this.groundMaterial.primaryColor = color;
  97237. }
  97238. if (this.skyboxMaterial) {
  97239. this.skyboxMaterial.primaryColor = color;
  97240. }
  97241. if (this.groundMirror) {
  97242. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  97243. }
  97244. };
  97245. /**
  97246. * Setup the image processing according to the specified options.
  97247. */
  97248. EnvironmentHelper.prototype._setupImageProcessing = function () {
  97249. if (this._options.setupImageProcessing) {
  97250. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  97251. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  97252. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  97253. this._setupEnvironmentTexture();
  97254. }
  97255. };
  97256. /**
  97257. * Setup the environment texture according to the specified options.
  97258. */
  97259. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  97260. if (this._scene.environmentTexture) {
  97261. return;
  97262. }
  97263. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  97264. this._scene.environmentTexture = this._options.environmentTexture;
  97265. return;
  97266. }
  97267. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  97268. this._scene.environmentTexture = environmentTexture;
  97269. };
  97270. /**
  97271. * Setup the background according to the specified options.
  97272. */
  97273. EnvironmentHelper.prototype._setupBackground = function () {
  97274. if (!this._rootMesh) {
  97275. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  97276. }
  97277. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  97278. var sceneSize = this._getSceneSize();
  97279. if (this._options.createGround) {
  97280. this._setupGround(sceneSize);
  97281. this._setupGroundMaterial();
  97282. this._setupGroundDiffuseTexture();
  97283. if (this._options.enableGroundMirror) {
  97284. this._setupGroundMirrorTexture(sceneSize);
  97285. }
  97286. this._setupMirrorInGroundMaterial();
  97287. }
  97288. if (this._options.createSkybox) {
  97289. this._setupSkybox(sceneSize);
  97290. this._setupSkyboxMaterial();
  97291. this._setupSkyboxReflectionTexture();
  97292. }
  97293. this._rootMesh.position.x = sceneSize.rootPosition.x;
  97294. this._rootMesh.position.z = sceneSize.rootPosition.z;
  97295. this._rootMesh.position.y = sceneSize.rootPosition.y;
  97296. };
  97297. /**
  97298. * Get the scene sizes according to the setup.
  97299. */
  97300. EnvironmentHelper.prototype._getSceneSize = function () {
  97301. var _this = this;
  97302. var groundSize = this._options.groundSize;
  97303. var skyboxSize = this._options.skyboxSize;
  97304. var rootPosition = this._options.rootPosition;
  97305. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  97306. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97307. }
  97308. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  97309. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  97310. });
  97311. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97312. if (this._options.sizeAuto) {
  97313. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  97314. this._scene.activeCamera.upperRadiusLimit) {
  97315. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  97316. skyboxSize = groundSize;
  97317. }
  97318. var sceneDiagonalLenght = sceneDiagonal.length();
  97319. if (sceneDiagonalLenght > groundSize) {
  97320. groundSize = sceneDiagonalLenght * 2;
  97321. skyboxSize = groundSize;
  97322. }
  97323. // 10 % bigger.
  97324. groundSize *= 1.1;
  97325. skyboxSize *= 1.5;
  97326. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  97327. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  97328. }
  97329. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97330. };
  97331. /**
  97332. * Setup the ground according to the specified options.
  97333. */
  97334. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  97335. var _this = this;
  97336. if (!this._ground) {
  97337. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  97338. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  97339. this._ground.parent = this._rootMesh;
  97340. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  97341. }
  97342. this._ground.receiveShadows = this._options.enableGroundShadow;
  97343. };
  97344. /**
  97345. * Setup the ground material according to the specified options.
  97346. */
  97347. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  97348. if (!this._groundMaterial) {
  97349. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  97350. }
  97351. this._groundMaterial.alpha = this._options.groundOpacity;
  97352. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  97353. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  97354. this._groundMaterial.primaryColor = this._options.groundColor;
  97355. this._groundMaterial.useRGBColor = false;
  97356. this._groundMaterial.enableNoise = true;
  97357. if (this._ground) {
  97358. this._ground.material = this._groundMaterial;
  97359. }
  97360. };
  97361. /**
  97362. * Setup the ground diffuse texture according to the specified options.
  97363. */
  97364. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  97365. if (!this._groundMaterial) {
  97366. return;
  97367. }
  97368. if (this._groundTexture) {
  97369. return;
  97370. }
  97371. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  97372. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  97373. return;
  97374. }
  97375. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97376. diffuseTexture.gammaSpace = false;
  97377. diffuseTexture.hasAlpha = true;
  97378. this._groundMaterial.diffuseTexture = diffuseTexture;
  97379. };
  97380. /**
  97381. * Setup the ground mirror texture according to the specified options.
  97382. */
  97383. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  97384. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97385. if (!this._groundMirror) {
  97386. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  97387. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  97388. this._groundMirror.anisotropicFilteringLevel = 1;
  97389. this._groundMirror.wrapU = wrapping;
  97390. this._groundMirror.wrapV = wrapping;
  97391. this._groundMirror.gammaSpace = false;
  97392. if (this._groundMirror.renderList) {
  97393. for (var i = 0; i < this._scene.meshes.length; i++) {
  97394. var mesh = this._scene.meshes[i];
  97395. if (mesh !== this._ground &&
  97396. mesh !== this._skybox &&
  97397. mesh !== this._rootMesh) {
  97398. this._groundMirror.renderList.push(mesh);
  97399. }
  97400. }
  97401. }
  97402. }
  97403. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  97404. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  97405. };
  97406. /**
  97407. * Setup the ground to receive the mirror texture.
  97408. */
  97409. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  97410. if (this._groundMaterial) {
  97411. this._groundMaterial.reflectionTexture = this._groundMirror;
  97412. this._groundMaterial.reflectionFresnel = true;
  97413. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  97414. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  97415. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  97416. }
  97417. };
  97418. /**
  97419. * Setup the skybox according to the specified options.
  97420. */
  97421. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  97422. var _this = this;
  97423. if (!this._skybox) {
  97424. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  97425. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  97426. }
  97427. this._skybox.parent = this._rootMesh;
  97428. };
  97429. /**
  97430. * Setup the skybox material according to the specified options.
  97431. */
  97432. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  97433. if (!this._skybox) {
  97434. return;
  97435. }
  97436. if (!this._skyboxMaterial) {
  97437. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  97438. }
  97439. this._skyboxMaterial.useRGBColor = false;
  97440. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  97441. this._skyboxMaterial.enableNoise = true;
  97442. this._skybox.material = this._skyboxMaterial;
  97443. };
  97444. /**
  97445. * Setup the skybox reflection texture according to the specified options.
  97446. */
  97447. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  97448. if (!this._skyboxMaterial) {
  97449. return;
  97450. }
  97451. if (this._skyboxTexture) {
  97452. return;
  97453. }
  97454. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  97455. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  97456. return;
  97457. }
  97458. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97459. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  97460. this._skyboxTexture.gammaSpace = false;
  97461. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  97462. };
  97463. /**
  97464. * Dispose all the elements created by the Helper.
  97465. */
  97466. EnvironmentHelper.prototype.dispose = function () {
  97467. if (this._groundMaterial) {
  97468. this._groundMaterial.dispose(true, true);
  97469. }
  97470. if (this._skyboxMaterial) {
  97471. this._skyboxMaterial.dispose(true, true);
  97472. }
  97473. this._rootMesh.dispose(false);
  97474. };
  97475. /**
  97476. * Default ground texture URL.
  97477. */
  97478. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  97479. /**
  97480. * Default skybox texture URL.
  97481. */
  97482. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  97483. /**
  97484. * Default environment texture URL.
  97485. */
  97486. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  97487. return EnvironmentHelper;
  97488. }());
  97489. BABYLON.EnvironmentHelper = EnvironmentHelper;
  97490. })(BABYLON || (BABYLON = {}));
  97491. //# sourceMappingURL=babylon.environmentHelper.js.map
  97492. var BABYLON;
  97493. (function (BABYLON) {
  97494. /**
  97495. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  97496. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  97497. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  97498. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  97499. */
  97500. var VideoDome = /** @class */ (function (_super) {
  97501. __extends(VideoDome, _super);
  97502. /**
  97503. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  97504. * @param name Element's name, child elements will append suffixes for their own names.
  97505. * @param urlsOrVideo
  97506. * @param options An object containing optional or exposed sub element properties:
  97507. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  97508. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  97509. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  97510. * @param options **loop=true** Automatically loop video on end.
  97511. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  97512. */
  97513. function VideoDome(name, urlsOrVideo, options, scene) {
  97514. var _this = _super.call(this, name, scene) || this;
  97515. // set defaults and manage values
  97516. name = name || "videoDome";
  97517. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  97518. options.clickToPlay = Boolean(options.clickToPlay);
  97519. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  97520. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  97521. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  97522. // create
  97523. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  97524. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  97525. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  97526. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  97527. flat: false,
  97528. radius: options.size,
  97529. subdivisions: options.resolution,
  97530. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  97531. }, scene);
  97532. // configure material
  97533. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  97534. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  97535. material.reflectionTexture = _this._videoTexture;
  97536. material.useEquirectangularFOV = true;
  97537. material.fovMultiplier = 1.0;
  97538. // configure mesh
  97539. _this._mesh.material = material;
  97540. _this._mesh.parent = _this;
  97541. // optional configuration
  97542. if (options.clickToPlay) {
  97543. scene.onPointerUp = function () {
  97544. _this._videoTexture.video.play();
  97545. };
  97546. }
  97547. return _this;
  97548. }
  97549. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  97550. /**
  97551. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97552. * Also see the options.resolution property.
  97553. */
  97554. get: function () {
  97555. return this._material.fovMultiplier;
  97556. },
  97557. set: function (value) {
  97558. this._material.fovMultiplier = value;
  97559. },
  97560. enumerable: true,
  97561. configurable: true
  97562. });
  97563. /**
  97564. * Releases resources associated with this node.
  97565. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  97566. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  97567. */
  97568. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  97569. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  97570. this._videoTexture.dispose();
  97571. this._mesh.dispose();
  97572. this._material.dispose();
  97573. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  97574. };
  97575. return VideoDome;
  97576. }(BABYLON.Node));
  97577. BABYLON.VideoDome = VideoDome;
  97578. })(BABYLON || (BABYLON = {}));
  97579. //# sourceMappingURL=babylon.videoDome.js.map
  97580. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  97581. 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;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  97582. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  97583. globalObject["BABYLON"] = BABYLON;
  97584. //backwards compatibility
  97585. if(typeof earcut !== 'undefined') {
  97586. globalObject["Earcut"] = {
  97587. earcut: earcut
  97588. };
  97589. }
  97590. return BABYLON;
  97591. });