babylon.max.js 4.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095930969309793098930999310093101931029310393104931059310693107931089310993110931119311293113931149311593116931179311893119931209312193122931239312493125931269312793128931299313093131931329313393134931359313693137931389313993140931419314293143931449314593146931479314893149931509315193152931539315493155931569315793158931599316093161931629316393164931659316693167931689316993170931719317293173931749317593176931779317893179931809318193182931839318493185931869318793188931899319093191931929319393194931959319693197931989319993200932019320293203932049320593206932079320893209932109321193212932139321493215932169321793218932199322093221932229322393224932259322693227932289322993230932319323293233932349323593236932379323893239932409324193242932439324493245932469324793248932499325093251932529325393254932559325693257932589325993260932619326293263932649326593266932679326893269932709327193272932739327493275932769327793278932799328093281932829328393284932859328693287932889328993290932919329293293932949329593296932979329893299933009330193302933039330493305933069330793308933099331093311933129331393314933159331693317933189331993320933219332293323933249332593326933279332893329933309333193332933339333493335933369333793338933399334093341933429334393344933459334693347933489334993350933519335293353933549335593356933579335893359933609336193362933639336493365933669336793368933699337093371933729337393374933759337693377933789337993380933819338293383933849338593386933879338893389933909339193392933939339493395933969339793398933999340093401934029340393404934059340693407934089340993410934119341293413934149341593416934179341893419934209342193422934239342493425934269342793428934299343093431934329343393434934359343693437934389343993440934419344293443934449344593446934479344893449934509345193452934539345493455934569345793458934599346093461934629346393464934659346693467934689346993470934719347293473934749347593476934779347893479934809348193482934839348493485934869348793488934899349093491934929349393494934959349693497934989349993500935019350293503935049350593506935079350893509935109351193512935139351493515935169351793518935199352093521935229352393524935259352693527935289352993530935319353293533935349353593536935379353893539935409354193542935439354493545935469354793548935499355093551935529355393554935559355693557935589355993560935619356293563935649356593566935679356893569935709357193572935739357493575935769357793578935799358093581935829358393584935859358693587935889358993590935919359293593935949359593596935979359893599936009360193602936039360493605936069360793608936099361093611936129361393614936159361693617936189361993620936219362293623936249362593626936279362893629936309363193632936339363493635936369363793638936399364093641936429364393644936459364693647936489364993650936519365293653936549365593656936579365893659936609366193662936639366493665936669366793668936699367093671936729367393674936759367693677936789367993680936819368293683936849368593686936879368893689936909369193692936939369493695936969369793698936999370093701937029370393704937059370693707937089370993710937119371293713937149371593716937179371893719937209372193722937239372493725937269372793728937299373093731937329373393734937359373693737937389373993740937419374293743937449374593746937479374893749937509375193752937539375493755937569375793758937599376093761937629376393764937659376693767937689376993770937719377293773937749377593776937779377893779937809378193782937839378493785937869378793788937899379093791937929379393794937959379693797937989379993800938019380293803938049380593806938079380893809938109381193812938139381493815938169381793818938199382093821938229382393824938259382693827938289382993830938319383293833938349383593836938379383893839938409384193842938439384493845938469384793848938499385093851938529385393854938559385693857938589385993860938619386293863938649386593866938679386893869938709387193872938739387493875938769387793878938799388093881938829388393884938859388693887938889388993890938919389293893938949389593896938979389893899939009390193902939039390493905939069390793908939099391093911939129391393914939159391693917939189391993920939219392293923939249392593926939279392893929939309393193932939339393493935939369393793938939399394093941939429394393944939459394693947939489394993950939519395293953939549395593956939579395893959939609396193962939639396493965939669396793968939699397093971939729397393974939759397693977939789397993980939819398293983939849398593986939879398893989939909399193992939939399493995939969399793998939999400094001940029400394004940059400694007940089400994010940119401294013940149401594016940179401894019940209402194022940239402494025940269402794028940299403094031940329403394034940359403694037940389403994040940419404294043940449404594046940479404894049940509405194052940539405494055940569405794058940599406094061940629406394064940659406694067940689406994070940719407294073940749407594076940779407894079940809408194082940839408494085940869408794088940899409094091940929409394094940959409694097940989409994100941019410294103941049410594106941079410894109941109411194112941139411494115941169411794118941199412094121941229412394124941259412694127941289412994130941319413294133941349413594136941379413894139941409414194142941439414494145941469414794148941499415094151941529415394154941559415694157941589415994160941619416294163941649416594166941679416894169941709417194172941739417494175941769417794178941799418094181941829418394184941859418694187941889418994190941919419294193941949419594196941979419894199942009420194202942039420494205942069420794208942099421094211942129421394214942159421694217942189421994220942219422294223942249422594226942279422894229942309423194232942339423494235942369423794238942399424094241942429424394244942459424694247942489424994250942519425294253942549425594256942579425894259942609426194262942639426494265942669426794268942699427094271942729427394274942759427694277942789427994280942819428294283942849428594286942879428894289942909429194292942939429494295942969429794298942999430094301943029430394304943059430694307943089430994310943119431294313943149431594316943179431894319943209432194322943239432494325943269432794328943299433094331943329433394334943359433694337943389433994340943419434294343943449434594346943479434894349943509435194352943539435494355943569435794358943599436094361943629436394364943659436694367943689436994370943719437294373943749437594376943779437894379943809438194382943839438494385943869438794388943899439094391943929439394394943959439694397943989439994400944019440294403944049440594406944079440894409944109441194412944139441494415944169441794418944199442094421944229442394424944259442694427944289442994430944319443294433944349443594436944379443894439944409444194442944439444494445944469444794448944499445094451944529445394454944559445694457944589445994460944619446294463944649446594466944679446894469944709447194472944739447494475944769447794478944799448094481944829448394484944859448694487944889448994490944919449294493944949449594496944979449894499945009450194502945039450494505945069450794508945099451094511945129451394514945159451694517945189451994520945219452294523945249452594526945279452894529945309453194532945339453494535945369453794538945399454094541945429454394544945459454694547945489454994550945519455294553945549455594556945579455894559945609456194562945639456494565945669456794568945699457094571945729457394574945759457694577945789457994580945819458294583945849458594586945879458894589945909459194592945939459494595945969459794598945999460094601946029460394604946059460694607946089460994610946119461294613946149461594616946179461894619946209462194622946239462494625946269462794628946299463094631946329463394634946359463694637946389463994640946419464294643946449464594646946479464894649946509465194652946539465494655946569465794658946599466094661946629466394664946659466694667946689466994670946719467294673946749467594676946779467894679946809468194682946839468494685946869468794688946899469094691946929469394694946959469694697946989469994700947019470294703947049470594706947079470894709947109471194712947139471494715947169471794718947199472094721947229472394724947259472694727947289472994730947319473294733947349473594736947379473894739947409474194742947439474494745947469474794748947499475094751947529475394754947559475694757947589475994760947619476294763947649476594766947679476894769947709477194772947739477494775947769477794778947799478094781947829478394784947859478694787947889478994790947919479294793947949479594796947979479894799948009480194802948039480494805948069480794808948099481094811948129481394814948159481694817948189481994820948219482294823948249482594826948279482894829948309483194832948339483494835948369483794838948399484094841948429484394844948459484694847948489484994850948519485294853948549485594856948579485894859948609486194862948639486494865948669486794868948699487094871948729487394874948759487694877948789487994880948819488294883948849488594886948879488894889948909489194892948939489494895948969489794898948999490094901949029490394904949059490694907949089490994910949119491294913949149491594916949179491894919949209492194922949239492494925949269492794928949299493094931949329493394934949359493694937949389493994940949419494294943949449494594946949479494894949949509495194952949539495494955949569495794958949599496094961949629496394964949659496694967949689496994970949719497294973949749497594976949779497894979949809498194982949839498494985949869498794988949899499094991949929499394994949959499694997949989499995000950019500295003950049500595006950079500895009950109501195012950139501495015950169501795018950199502095021950229502395024950259502695027950289502995030950319503295033950349503595036950379503895039950409504195042950439504495045950469504795048950499505095051950529505395054950559505695057950589505995060950619506295063950649506595066950679506895069950709507195072950739507495075950769507795078950799508095081950829508395084950859508695087950889508995090950919509295093950949509595096950979509895099951009510195102951039510495105951069510795108951099511095111951129511395114951159511695117951189511995120951219512295123951249512595126951279512895129951309513195132951339513495135951369513795138951399514095141951429514395144951459514695147951489514995150951519515295153951549515595156951579515895159951609516195162951639516495165951669516795168951699517095171951729517395174951759517695177951789517995180951819518295183951849518595186951879518895189951909519195192951939519495195951969519795198951999520095201952029520395204952059520695207952089520995210952119521295213952149521595216952179521895219952209522195222952239522495225952269522795228952299523095231952329523395234952359523695237952389523995240952419524295243952449524595246952479524895249952509525195252952539525495255952569525795258952599526095261952629526395264952659526695267952689526995270952719527295273952749527595276952779527895279952809528195282952839528495285952869528795288952899529095291952929529395294952959529695297952989529995300953019530295303953049530595306953079530895309953109531195312953139531495315953169531795318953199532095321953229532395324953259532695327953289532995330953319533295333953349533595336953379533895339953409534195342953439534495345953469534795348953499535095351953529535395354953559535695357953589535995360953619536295363953649536595366953679536895369953709537195372953739537495375953769537795378953799538095381953829538395384953859538695387953889538995390953919539295393953949539595396953979539895399954009540195402954039540495405954069540795408954099541095411954129541395414954159541695417954189541995420954219542295423954249542595426954279542895429954309543195432954339543495435954369543795438954399544095441954429544395444954459544695447954489544995450954519545295453954549545595456954579545895459954609546195462954639546495465954669546795468954699547095471954729547395474954759547695477954789547995480954819548295483954849548595486954879548895489954909549195492954939549495495954969549795498954999550095501955029550395504955059550695507955089550995510955119551295513955149551595516955179551895519955209552195522955239552495525955269552795528955299553095531955329553395534955359553695537955389553995540955419554295543955449554595546955479554895549955509555195552955539555495555955569555795558955599556095561955629556395564955659556695567955689556995570955719557295573955749557595576955779557895579955809558195582955839558495585955869558795588955899559095591955929559395594955959559695597955989559995600956019560295603956049560595606956079560895609956109561195612956139561495615956169561795618956199562095621956229562395624956259562695627956289562995630956319563295633956349563595636956379563895639956409564195642956439564495645956469564795648956499565095651956529565395654956559565695657956589565995660956619566295663956649566595666956679566895669956709567195672956739567495675956769567795678956799568095681956829568395684956859568695687956889568995690956919569295693956949569595696956979569895699957009570195702957039570495705957069570795708957099571095711957129571395714957159571695717957189571995720957219572295723957249572595726957279572895729957309573195732957339573495735957369573795738957399574095741957429574395744957459574695747957489574995750957519575295753957549575595756957579575895759957609576195762957639576495765957669576795768957699577095771957729577395774957759577695777957789577995780957819578295783957849578595786957879578895789957909579195792957939579495795957969579795798957999580095801958029580395804958059580695807958089580995810958119581295813958149581595816958179581895819958209582195822958239582495825958269582795828958299583095831958329583395834958359583695837958389583995840958419584295843958449584595846958479584895849958509585195852958539585495855958569585795858958599586095861958629586395864958659586695867958689586995870958719587295873958749587595876958779587895879958809588195882958839588495885958869588795888958899589095891958929589395894958959589695897958989589995900959019590295903959049590595906959079590895909959109591195912959139591495915959169591795918959199592095921959229592395924959259592695927959289592995930959319593295933959349593595936959379593895939959409594195942959439594495945959469594795948959499595095951959529595395954959559595695957959589595995960959619596295963959649596595966959679596895969959709597195972959739597495975959769597795978959799598095981959829598395984959859598695987959889598995990959919599295993959949599595996959979599895999960009600196002960039600496005960069600796008960099601096011960129601396014960159601696017960189601996020960219602296023960249602596026960279602896029960309603196032960339603496035960369603796038960399604096041960429604396044960459604696047960489604996050960519605296053960549605596056960579605896059960609606196062960639606496065960669606796068960699607096071960729607396074960759607696077960789607996080960819608296083960849608596086960879608896089960909609196092960939609496095960969609796098960999610096101961029610396104961059610696107961089610996110961119611296113961149611596116961179611896119961209612196122961239612496125961269612796128961299613096131961329613396134961359613696137961389613996140961419614296143961449614596146961479614896149961509615196152961539615496155961569615796158961599616096161961629616396164961659616696167961689616996170961719617296173961749617596176961779617896179961809618196182961839618496185961869618796188961899619096191961929619396194961959619696197961989619996200962019620296203962049620596206962079620896209962109621196212962139621496215962169621796218962199622096221962229622396224962259622696227962289622996230962319623296233962349623596236962379623896239962409624196242962439624496245962469624796248962499625096251962529625396254962559625696257962589625996260962619626296263962649626596266962679626896269962709627196272962739627496275962769627796278962799628096281962829628396284962859628696287962889628996290962919629296293962949629596296962979629896299963009630196302963039630496305963069630796308963099631096311963129631396314963159631696317963189631996320963219632296323963249632596326963279632896329963309633196332963339633496335963369633796338963399634096341963429634396344963459634696347963489634996350963519635296353963549635596356963579635896359963609636196362963639636496365963669636796368963699637096371963729637396374963759637696377963789637996380963819638296383963849638596386963879638896389963909639196392963939639496395963969639796398963999640096401964029640396404964059640696407964089640996410964119641296413964149641596416964179641896419964209642196422964239642496425964269642796428964299643096431964329643396434964359643696437964389643996440964419644296443964449644596446964479644896449964509645196452964539645496455964569645796458964599646096461964629646396464964659646696467964689646996470964719647296473964749647596476964779647896479964809648196482964839648496485964869648796488964899649096491964929649396494964959649696497964989649996500965019650296503965049650596506965079650896509965109651196512965139651496515965169651796518965199652096521965229652396524965259652696527965289652996530965319653296533965349653596536965379653896539965409654196542965439654496545965469654796548965499655096551965529655396554965559655696557965589655996560965619656296563965649656596566965679656896569965709657196572965739657496575965769657796578965799658096581965829658396584965859658696587965889658996590965919659296593965949659596596965979659896599966009660196602966039660496605966069660796608966099661096611966129661396614966159661696617966189661996620966219662296623966249662596626966279662896629966309663196632966339663496635966369663796638966399664096641966429664396644966459664696647966489664996650966519665296653966549665596656966579665896659966609666196662966639666496665966669666796668966699667096671966729667396674966759667696677966789667996680966819668296683966849668596686966879668896689966909669196692966939669496695966969669796698966999670096701967029670396704967059670696707967089670996710967119671296713967149671596716967179671896719967209672196722967239672496725967269672796728967299673096731967329673396734967359673696737967389673996740967419674296743967449674596746967479674896749967509675196752967539675496755967569675796758967599676096761967629676396764967659676696767967689676996770967719677296773967749677596776967779677896779967809678196782967839678496785967869678796788967899679096791967929679396794967959679696797967989679996800968019680296803968049680596806968079680896809968109681196812968139681496815968169681796818968199682096821968229682396824968259682696827968289682996830968319683296833968349683596836968379683896839968409684196842968439684496845968469684796848968499685096851968529685396854968559685696857968589685996860968619686296863968649686596866968679686896869968709687196872968739687496875968769687796878968799688096881968829688396884968859688696887968889688996890968919689296893968949689596896968979689896899969009690196902969039690496905969069690796908969099691096911969129691396914969159691696917969189691996920969219692296923969249692596926969279692896929969309693196932969339693496935969369693796938969399694096941969429694396944969459694696947969489694996950969519695296953969549695596956969579695896959969609696196962969639696496965969669696796968969699697096971969729697396974969759697696977969789697996980969819698296983969849698596986969879698896989969909699196992969939699496995969969699796998969999700097001970029700397004970059700697007970089700997010970119701297013970149701597016970179701897019970209702197022970239702497025970269702797028970299703097031970329703397034970359703697037970389703997040970419704297043970449704597046970479704897049970509705197052970539705497055970569705797058970599706097061970629706397064970659706697067970689706997070970719707297073970749707597076970779707897079970809708197082970839708497085970869708797088970899709097091970929709397094970959709697097970989709997100971019710297103971049710597106971079710897109971109711197112971139711497115971169711797118971199712097121971229712397124971259712697127971289712997130971319713297133971349713597136971379713897139971409714197142971439714497145971469714797148971499715097151971529715397154971559715697157971589715997160971619716297163971649716597166971679716897169971709717197172971739717497175971769717797178971799718097181971829718397184971859718697187971889718997190971919719297193971949719597196971979719897199972009720197202972039720497205972069720797208972099721097211972129721397214972159721697217972189721997220972219722297223972249722597226972279722897229972309723197232972339723497235972369723797238972399724097241972429724397244972459724697247972489724997250972519725297253972549725597256972579725897259972609726197262972639726497265972669726797268972699727097271972729727397274972759727697277972789727997280972819728297283972849728597286972879728897289972909729197292972939729497295972969729797298972999730097301973029730397304973059730697307973089730997310973119731297313973149731597316973179731897319973209732197322973239732497325973269732797328973299733097331973329733397334973359733697337973389733997340973419734297343973449734597346973479734897349973509735197352973539735497355973569735797358973599736097361973629736397364973659736697367973689736997370973719737297373973749737597376973779737897379973809738197382973839738497385973869738797388973899739097391973929739397394973959739697397973989739997400974019740297403974049740597406974079740897409974109741197412974139741497415974169741797418974199742097421974229742397424974259742697427974289742997430974319743297433974349743597436974379743897439974409744197442974439744497445974469744797448974499745097451974529745397454974559745697457974589745997460974619746297463974649746597466974679746897469974709747197472974739747497475974769747797478974799748097481974829748397484974859748697487974889748997490974919749297493974949749597496974979749897499975009750197502975039750497505975069750797508975099751097511975129751397514975159751697517975189751997520975219752297523975249752597526975279752897529975309753197532975339753497535975369753797538975399754097541975429754397544975459754697547975489754997550975519755297553975549755597556975579755897559975609756197562975639756497565975669756797568975699757097571975729757397574975759757697577975789757997580975819758297583975849758597586975879758897589975909759197592975939759497595975969759797598975999760097601976029760397604976059760697607976089760997610976119761297613976149761597616976179761897619976209762197622976239762497625976269762797628976299763097631976329763397634976359763697637976389763997640976419764297643976449764597646976479764897649976509765197652976539765497655976569765797658976599766097661976629766397664976659766697667976689766997670976719767297673976749767597676976779767897679976809768197682976839768497685976869768797688976899769097691976929769397694976959769697697976989769997700977019770297703977049770597706977079770897709977109771197712977139771497715977169771797718977199772097721977229772397724977259772697727977289772997730977319773297733977349773597736977379773897739977409774197742977439774497745977469774797748977499775097751977529775397754977559775697757977589775997760977619776297763977649776597766977679776897769977709777197772977739777497775977769777797778977799778097781977829778397784977859778697787977889778997790977919779297793977949779597796977979779897799978009780197802978039780497805978069780797808978099781097811978129781397814978159781697817978189781997820978219782297823978249782597826978279782897829978309783197832978339783497835978369783797838978399784097841978429784397844978459784697847978489784997850978519785297853978549785597856978579785897859978609786197862978639786497865978669786797868978699787097871978729787397874978759787697877978789787997880978819788297883978849788597886978879788897889978909789197892978939789497895978969789797898978999790097901979029790397904979059790697907979089790997910979119791297913979149791597916979179791897919979209792197922979239792497925979269792797928979299793097931979329793397934979359793697937979389793997940979419794297943979449794597946979479794897949979509795197952979539795497955979569795797958979599796097961979629796397964979659796697967979689796997970979719797297973979749797597976979779797897979979809798197982979839798497985979869798797988979899799097991979929799397994979959799697997979989799998000980019800298003980049800598006980079800898009980109801198012980139801498015980169801798018980199802098021980229802398024980259802698027980289802998030980319803298033980349803598036980379803898039980409804198042980439804498045980469804798048980499805098051980529805398054980559805698057980589805998060980619806298063980649806598066980679806898069980709807198072980739807498075980769807798078980799808098081980829808398084980859808698087980889808998090980919809298093980949809598096980979809898099981009810198102981039810498105981069810798108981099811098111981129811398114981159811698117981189811998120981219812298123981249812598126981279812898129981309813198132981339813498135981369813798138981399814098141981429814398144981459814698147981489814998150981519815298153981549815598156981579815898159981609816198162981639816498165981669816798168981699817098171981729817398174981759817698177981789817998180981819818298183981849818598186981879818898189981909819198192981939819498195981969819798198981999820098201982029820398204982059820698207982089820998210982119821298213982149821598216982179821898219982209822198222982239822498225982269822798228982299823098231982329823398234982359823698237982389823998240982419824298243982449824598246982479824898249982509825198252982539825498255982569825798258982599826098261982629826398264982659826698267982689826998270982719827298273982749827598276982779827898279982809828198282982839828498285982869828798288982899829098291982929829398294982959829698297982989829998300983019830298303983049830598306983079830898309983109831198312983139831498315983169831798318983199832098321983229832398324983259832698327983289832998330983319833298333983349833598336983379833898339983409834198342983439834498345983469834798348983499835098351983529835398354983559835698357983589835998360983619836298363983649836598366983679836898369983709837198372983739837498375983769837798378983799838098381983829838398384983859838698387983889838998390983919839298393983949839598396983979839898399984009840198402984039840498405984069840798408984099841098411984129841398414984159841698417984189841998420984219842298423984249842598426984279842898429984309843198432984339843498435984369843798438984399844098441984429844398444984459844698447984489844998450984519845298453984549845598456984579845898459984609846198462984639846498465984669846798468984699847098471984729847398474984759847698477984789847998480984819848298483984849848598486984879848898489984909849198492984939849498495984969849798498984999850098501985029850398504985059850698507985089850998510985119851298513985149851598516985179851898519985209852198522985239852498525985269852798528985299853098531985329853398534985359853698537985389853998540985419854298543985449854598546985479854898549985509855198552985539855498555985569855798558985599856098561985629856398564985659856698567985689856998570985719857298573985749857598576985779857898579985809858198582985839858498585985869858798588985899859098591985929859398594985959859698597985989859998600986019860298603986049860598606986079860898609986109861198612986139861498615986169861798618986199862098621986229862398624986259862698627986289862998630986319863298633986349863598636986379863898639986409864198642986439864498645986469864798648986499865098651986529865398654986559865698657986589865998660986619866298663986649866598666986679866898669986709867198672986739867498675986769867798678986799868098681986829868398684986859868698687986889868998690986919869298693986949869598696986979869898699987009870198702987039870498705987069870798708987099871098711987129871398714987159871698717987189871998720987219872298723987249872598726987279872898729987309873198732987339873498735987369873798738987399874098741987429874398744987459874698747987489874998750987519875298753987549875598756987579875898759987609876198762987639876498765987669876798768987699877098771987729877398774987759877698777987789877998780987819878298783987849878598786987879878898789987909879198792987939879498795987969879798798987999880098801988029880398804988059880698807988089880998810988119881298813988149881598816988179881898819988209882198822988239882498825988269882798828988299883098831988329883398834988359883698837988389883998840988419884298843988449884598846988479884898849988509885198852988539885498855988569885798858988599886098861988629886398864988659886698867988689886998870988719887298873988749887598876988779887898879988809888198882988839888498885988869888798888988899889098891988929889398894988959889698897988989889998900989019890298903989049890598906989079890898909989109891198912989139891498915989169891798918989199892098921989229892398924989259892698927989289892998930989319893298933989349893598936989379893898939989409894198942989439894498945989469894798948989499895098951989529895398954989559895698957989589895998960
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. effect._bonesComputationForcedToCPU = true;
  101. var scene = this._mesh.getScene();
  102. for (var index = 0; index < scene.meshes.length; index++) {
  103. var otherMesh = scene.meshes[index];
  104. if (!otherMesh.material) {
  105. continue;
  106. }
  107. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  108. continue;
  109. }
  110. if (otherMesh.material.getEffect() === effect) {
  111. otherMesh.computeBonesUsingShaders = false;
  112. }
  113. else if (otherMesh.subMeshes) {
  114. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  115. var subMesh = _a[_i];
  116. var subMeshEffect = subMesh.effect;
  117. if (subMeshEffect === effect) {
  118. otherMesh.computeBonesUsingShaders = false;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. }
  125. else {
  126. var currentFallbacks = this._defines[this._currentRank];
  127. if (currentFallbacks) {
  128. for (var index = 0; index < currentFallbacks.length; index++) {
  129. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  130. }
  131. }
  132. this._currentRank++;
  133. }
  134. return currentDefines;
  135. };
  136. return EffectFallbacks;
  137. }());
  138. BABYLON.EffectFallbacks = EffectFallbacks;
  139. /**
  140. * Options to be used when creating an effect.
  141. */
  142. var EffectCreationOptions = /** @class */ (function () {
  143. function EffectCreationOptions() {
  144. }
  145. return EffectCreationOptions;
  146. }());
  147. BABYLON.EffectCreationOptions = EffectCreationOptions;
  148. /**
  149. * Effect containing vertex and fragment shader that can be executed on an object.
  150. */
  151. var Effect = /** @class */ (function () {
  152. /**
  153. * Instantiates an effect.
  154. * An effect can be used to create/manage/execute vertex and fragment shaders.
  155. * @param baseName Name of the effect.
  156. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  157. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  158. * @param samplers List of sampler variables that will be passed to the shader.
  159. * @param engine Engine to be used to render the effect
  160. * @param defines Define statements to be added to the shader.
  161. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  162. * @param onCompiled Callback that will be called when the shader is compiled.
  163. * @param onError Callback that will be called if an error occurs during shader compilation.
  164. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  165. */
  166. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  167. if (samplers === void 0) { samplers = null; }
  168. if (defines === void 0) { defines = null; }
  169. if (fallbacks === void 0) { fallbacks = null; }
  170. if (onCompiled === void 0) { onCompiled = null; }
  171. if (onError === void 0) { onError = null; }
  172. var _this = this;
  173. /**
  174. * Unique ID of the effect.
  175. */
  176. this.uniqueId = 0;
  177. /**
  178. * Observable that will be called when the shader is compiled.
  179. */
  180. this.onCompileObservable = new BABYLON.Observable();
  181. /**
  182. * Observable that will be called if an error occurs during shader compilation.
  183. */
  184. this.onErrorObservable = new BABYLON.Observable();
  185. /**
  186. * Observable that will be called when effect is bound.
  187. */
  188. this.onBindObservable = new BABYLON.Observable();
  189. /** @hidden */
  190. this._bonesComputationForcedToCPU = false;
  191. this._uniformBuffersNames = {};
  192. this._isReady = false;
  193. this._compilationError = "";
  194. this.name = baseName;
  195. if (attributesNamesOrOptions.attributes) {
  196. var options = attributesNamesOrOptions;
  197. this._engine = uniformsNamesOrEngine;
  198. this._attributesNames = options.attributes;
  199. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  200. this._samplers = options.samplers.slice();
  201. this.defines = options.defines;
  202. this.onError = options.onError;
  203. this.onCompiled = options.onCompiled;
  204. this._fallbacks = options.fallbacks;
  205. this._indexParameters = options.indexParameters;
  206. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  207. if (options.uniformBuffersNames) {
  208. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  209. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  210. }
  211. }
  212. }
  213. else {
  214. this._engine = engine;
  215. this.defines = defines;
  216. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  217. this._samplers = samplers ? samplers.slice() : [];
  218. this._attributesNames = attributesNamesOrOptions;
  219. this.onError = onError;
  220. this.onCompiled = onCompiled;
  221. this._indexParameters = indexParameters;
  222. this._fallbacks = fallbacks;
  223. }
  224. this.uniqueId = Effect._uniqueIdSeed++;
  225. var vertexSource;
  226. var fragmentSource;
  227. if (baseName.vertexElement) {
  228. vertexSource = document.getElementById(baseName.vertexElement);
  229. if (!vertexSource) {
  230. vertexSource = baseName.vertexElement;
  231. }
  232. }
  233. else {
  234. vertexSource = baseName.vertex || baseName;
  235. }
  236. if (baseName.fragmentElement) {
  237. fragmentSource = document.getElementById(baseName.fragmentElement);
  238. if (!fragmentSource) {
  239. fragmentSource = baseName.fragmentElement;
  240. }
  241. }
  242. else {
  243. fragmentSource = baseName.fragment || baseName;
  244. }
  245. this._loadVertexShader(vertexSource, function (vertexCode) {
  246. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  247. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  248. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  249. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  250. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  251. if (baseName) {
  252. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  253. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  254. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  255. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  256. }
  257. else {
  258. _this._vertexSourceCode = migratedVertexCode;
  259. _this._fragmentSourceCode = migratedFragmentCode;
  260. }
  261. _this._prepareEffect();
  262. });
  263. });
  264. });
  265. });
  266. });
  267. });
  268. }
  269. Object.defineProperty(Effect.prototype, "key", {
  270. /**
  271. * Unique key for this effect
  272. */
  273. get: function () {
  274. return this._key;
  275. },
  276. enumerable: true,
  277. configurable: true
  278. });
  279. /**
  280. * If the effect has been compiled and prepared.
  281. * @returns if the effect is compiled and prepared.
  282. */
  283. Effect.prototype.isReady = function () {
  284. return this._isReady;
  285. };
  286. /**
  287. * The engine the effect was initialized with.
  288. * @returns the engine.
  289. */
  290. Effect.prototype.getEngine = function () {
  291. return this._engine;
  292. };
  293. /**
  294. * The compiled webGL program for the effect
  295. * @returns the webGL program.
  296. */
  297. Effect.prototype.getProgram = function () {
  298. return this._program;
  299. };
  300. /**
  301. * The set of names of attribute variables for the shader.
  302. * @returns An array of attribute names.
  303. */
  304. Effect.prototype.getAttributesNames = function () {
  305. return this._attributesNames;
  306. };
  307. /**
  308. * Returns the attribute at the given index.
  309. * @param index The index of the attribute.
  310. * @returns The location of the attribute.
  311. */
  312. Effect.prototype.getAttributeLocation = function (index) {
  313. return this._attributes[index];
  314. };
  315. /**
  316. * Returns the attribute based on the name of the variable.
  317. * @param name of the attribute to look up.
  318. * @returns the attribute location.
  319. */
  320. Effect.prototype.getAttributeLocationByName = function (name) {
  321. var index = this._attributesNames.indexOf(name);
  322. return this._attributes[index];
  323. };
  324. /**
  325. * The number of attributes.
  326. * @returns the numnber of attributes.
  327. */
  328. Effect.prototype.getAttributesCount = function () {
  329. return this._attributes.length;
  330. };
  331. /**
  332. * Gets the index of a uniform variable.
  333. * @param uniformName of the uniform to look up.
  334. * @returns the index.
  335. */
  336. Effect.prototype.getUniformIndex = function (uniformName) {
  337. return this._uniformsNames.indexOf(uniformName);
  338. };
  339. /**
  340. * Returns the attribute based on the name of the variable.
  341. * @param uniformName of the uniform to look up.
  342. * @returns the location of the uniform.
  343. */
  344. Effect.prototype.getUniform = function (uniformName) {
  345. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  346. };
  347. /**
  348. * Returns an array of sampler variable names
  349. * @returns The array of sampler variable neames.
  350. */
  351. Effect.prototype.getSamplers = function () {
  352. return this._samplers;
  353. };
  354. /**
  355. * The error from the last compilation.
  356. * @returns the error string.
  357. */
  358. Effect.prototype.getCompilationError = function () {
  359. return this._compilationError;
  360. };
  361. /**
  362. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  363. * @param func The callback to be used.
  364. */
  365. Effect.prototype.executeWhenCompiled = function (func) {
  366. if (this.isReady()) {
  367. func(this);
  368. return;
  369. }
  370. this.onCompileObservable.add(function (effect) {
  371. func(effect);
  372. });
  373. };
  374. /** @hidden */
  375. Effect.prototype._loadVertexShader = function (vertex, callback) {
  376. if (BABYLON.Tools.IsWindowObjectExist()) {
  377. // DOM element ?
  378. if (vertex instanceof HTMLElement) {
  379. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  380. callback(vertexCode);
  381. return;
  382. }
  383. }
  384. // Base64 encoded ?
  385. if (vertex.substr(0, 7) === "base64:") {
  386. var vertexBinary = window.atob(vertex.substr(7));
  387. callback(vertexBinary);
  388. return;
  389. }
  390. // Is in local store ?
  391. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  392. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  393. return;
  394. }
  395. var vertexShaderUrl;
  396. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  397. vertexShaderUrl = vertex;
  398. }
  399. else {
  400. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  401. }
  402. // Vertex shader
  403. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  404. };
  405. /** @hidden */
  406. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  407. if (BABYLON.Tools.IsWindowObjectExist()) {
  408. // DOM element ?
  409. if (fragment instanceof HTMLElement) {
  410. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  411. callback(fragmentCode);
  412. return;
  413. }
  414. }
  415. // Base64 encoded ?
  416. if (fragment.substr(0, 7) === "base64:") {
  417. var fragmentBinary = window.atob(fragment.substr(7));
  418. callback(fragmentBinary);
  419. return;
  420. }
  421. // Is in local store ?
  422. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  423. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  424. return;
  425. }
  426. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  427. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  428. return;
  429. }
  430. var fragmentShaderUrl;
  431. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  432. fragmentShaderUrl = fragment;
  433. }
  434. else {
  435. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  436. }
  437. // Fragment shader
  438. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  439. };
  440. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  441. // Rebuild shaders source code
  442. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  443. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  444. vertexCode = prefix + vertexCode;
  445. fragmentCode = prefix + fragmentCode;
  446. // Number lines of shaders source code
  447. var i = 2;
  448. var regex = /\n/gm;
  449. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  450. i = 2;
  451. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  452. // Dump shaders name and formatted source code
  453. if (this.name.vertexElement) {
  454. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  455. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  456. }
  457. else if (this.name.vertex) {
  458. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  459. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  460. }
  461. else {
  462. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  463. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  464. }
  465. };
  466. ;
  467. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  468. var preparedSourceCode = this._processPrecision(sourceCode);
  469. if (this._engine.webGLVersion == 1) {
  470. callback(preparedSourceCode);
  471. return;
  472. }
  473. // Already converted
  474. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  475. callback(preparedSourceCode.replace("#version 300 es", ""));
  476. return;
  477. }
  478. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  479. // Remove extensions
  480. // #extension GL_OES_standard_derivatives : enable
  481. // #extension GL_EXT_shader_texture_lod : enable
  482. // #extension GL_EXT_frag_depth : enable
  483. // #extension GL_EXT_draw_buffers : require
  484. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  485. var result = preparedSourceCode.replace(regex, "");
  486. // Migrate to GLSL v300
  487. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  488. result = result.replace(/attribute[ \t]/g, "in ");
  489. result = result.replace(/[ \t]attribute/g, " in");
  490. if (isFragment) {
  491. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  492. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  493. result = result.replace(/texture2D\s*\(/g, "texture(");
  494. result = result.replace(/textureCube\s*\(/g, "texture(");
  495. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  496. result = result.replace(/gl_FragColor/g, "glFragColor");
  497. result = result.replace(/gl_FragData/g, "glFragData");
  498. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  499. }
  500. callback(result);
  501. };
  502. Effect.prototype._processIncludes = function (sourceCode, callback) {
  503. var _this = this;
  504. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  505. var match = regex.exec(sourceCode);
  506. var returnValue = new String(sourceCode);
  507. while (match != null) {
  508. var includeFile = match[1];
  509. // Uniform declaration
  510. if (includeFile.indexOf("__decl__") !== -1) {
  511. includeFile = includeFile.replace(/__decl__/, "");
  512. if (this._engine.supportsUniformBuffers) {
  513. includeFile = includeFile.replace(/Vertex/, "Ubo");
  514. includeFile = includeFile.replace(/Fragment/, "Ubo");
  515. }
  516. includeFile = includeFile + "Declaration";
  517. }
  518. if (Effect.IncludesShadersStore[includeFile]) {
  519. // Substitution
  520. var includeContent = Effect.IncludesShadersStore[includeFile];
  521. if (match[2]) {
  522. var splits = match[3].split(",");
  523. for (var index = 0; index < splits.length; index += 2) {
  524. var source = new RegExp(splits[index], "g");
  525. var dest = splits[index + 1];
  526. includeContent = includeContent.replace(source, dest);
  527. }
  528. }
  529. if (match[4]) {
  530. var indexString = match[5];
  531. if (indexString.indexOf("..") !== -1) {
  532. var indexSplits = indexString.split("..");
  533. var minIndex = parseInt(indexSplits[0]);
  534. var maxIndex = parseInt(indexSplits[1]);
  535. var sourceIncludeContent = includeContent.slice(0);
  536. includeContent = "";
  537. if (isNaN(maxIndex)) {
  538. maxIndex = this._indexParameters[indexSplits[1]];
  539. }
  540. for (var i = minIndex; i < maxIndex; i++) {
  541. if (!this._engine.supportsUniformBuffers) {
  542. // Ubo replacement
  543. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  544. return p1 + "{X}";
  545. });
  546. }
  547. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  548. }
  549. }
  550. else {
  551. if (!this._engine.supportsUniformBuffers) {
  552. // Ubo replacement
  553. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  554. return p1 + "{X}";
  555. });
  556. }
  557. includeContent = includeContent.replace(/\{X\}/g, indexString);
  558. }
  559. }
  560. // Replace
  561. returnValue = returnValue.replace(match[0], includeContent);
  562. }
  563. else {
  564. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  565. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  566. Effect.IncludesShadersStore[includeFile] = fileContent;
  567. _this._processIncludes(returnValue, callback);
  568. });
  569. return;
  570. }
  571. match = regex.exec(sourceCode);
  572. }
  573. callback(returnValue);
  574. };
  575. Effect.prototype._processPrecision = function (source) {
  576. if (source.indexOf("precision highp float") === -1) {
  577. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  578. source = "precision mediump float;\n" + source;
  579. }
  580. else {
  581. source = "precision highp float;\n" + source;
  582. }
  583. }
  584. else {
  585. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  586. source = source.replace("precision highp float", "precision mediump float");
  587. }
  588. }
  589. return source;
  590. };
  591. /**
  592. * Recompiles the webGL program
  593. * @param vertexSourceCode The source code for the vertex shader.
  594. * @param fragmentSourceCode The source code for the fragment shader.
  595. * @param onCompiled Callback called when completed.
  596. * @param onError Callback called on error.
  597. */
  598. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  599. var _this = this;
  600. this._isReady = false;
  601. this._vertexSourceCodeOverride = vertexSourceCode;
  602. this._fragmentSourceCodeOverride = fragmentSourceCode;
  603. this.onError = function (effect, error) {
  604. if (onError) {
  605. onError(error);
  606. }
  607. };
  608. this.onCompiled = function () {
  609. var scenes = _this.getEngine().scenes;
  610. for (var i = 0; i < scenes.length; i++) {
  611. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  612. }
  613. if (onCompiled) {
  614. onCompiled(_this._program);
  615. }
  616. };
  617. this._fallbacks = null;
  618. this._prepareEffect();
  619. };
  620. /**
  621. * Gets the uniform locations of the the specified variable names
  622. * @param names THe names of the variables to lookup.
  623. * @returns Array of locations in the same order as variable names.
  624. */
  625. Effect.prototype.getSpecificUniformLocations = function (names) {
  626. var engine = this._engine;
  627. return engine.getUniforms(this._program, names);
  628. };
  629. /**
  630. * Prepares the effect
  631. */
  632. Effect.prototype._prepareEffect = function () {
  633. var attributesNames = this._attributesNames;
  634. var defines = this.defines;
  635. var fallbacks = this._fallbacks;
  636. this._valueCache = {};
  637. var previousProgram = this._program;
  638. try {
  639. var engine = this._engine;
  640. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  641. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  642. }
  643. else {
  644. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  645. }
  646. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  647. if (engine.supportsUniformBuffers) {
  648. for (var name in this._uniformBuffersNames) {
  649. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  650. }
  651. }
  652. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  653. this._attributes = engine.getAttributes(this._program, attributesNames);
  654. var index;
  655. for (index = 0; index < this._samplers.length; index++) {
  656. var sampler = this.getUniform(this._samplers[index]);
  657. if (sampler == null) {
  658. this._samplers.splice(index, 1);
  659. index--;
  660. }
  661. }
  662. engine.bindSamplers(this);
  663. this._compilationError = "";
  664. this._isReady = true;
  665. if (this.onCompiled) {
  666. this.onCompiled(this);
  667. }
  668. this.onCompileObservable.notifyObservers(this);
  669. this.onCompileObservable.clear();
  670. // Unbind mesh reference in fallbacks
  671. if (this._fallbacks) {
  672. this._fallbacks.unBindMesh();
  673. }
  674. if (previousProgram) {
  675. this.getEngine()._deleteProgram(previousProgram);
  676. }
  677. }
  678. catch (e) {
  679. this._compilationError = e.message;
  680. // Let's go through fallbacks then
  681. BABYLON.Tools.Error("Unable to compile effect:");
  682. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  683. return " " + uniform;
  684. }));
  685. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  686. return " " + attribute;
  687. }));
  688. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  689. BABYLON.Tools.Error("Error: " + this._compilationError);
  690. if (previousProgram) {
  691. this._program = previousProgram;
  692. this._isReady = true;
  693. if (this.onError) {
  694. this.onError(this, this._compilationError);
  695. }
  696. this.onErrorObservable.notifyObservers(this);
  697. }
  698. if (fallbacks && fallbacks.isMoreFallbacks) {
  699. BABYLON.Tools.Error("Trying next fallback.");
  700. this.defines = fallbacks.reduce(this.defines, this);
  701. this._prepareEffect();
  702. }
  703. else { // Sorry we did everything we can
  704. if (this.onError) {
  705. this.onError(this, this._compilationError);
  706. }
  707. this.onErrorObservable.notifyObservers(this);
  708. this.onErrorObservable.clear();
  709. // Unbind mesh reference in fallbacks
  710. if (this._fallbacks) {
  711. this._fallbacks.unBindMesh();
  712. }
  713. }
  714. }
  715. };
  716. Object.defineProperty(Effect.prototype, "isSupported", {
  717. /**
  718. * Checks if the effect is supported. (Must be called after compilation)
  719. */
  720. get: function () {
  721. return this._compilationError === "";
  722. },
  723. enumerable: true,
  724. configurable: true
  725. });
  726. /**
  727. * Binds a texture to the engine to be used as output of the shader.
  728. * @param channel Name of the output variable.
  729. * @param texture Texture to bind.
  730. */
  731. Effect.prototype._bindTexture = function (channel, texture) {
  732. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  733. };
  734. /**
  735. * Sets a texture on the engine to be used in the shader.
  736. * @param channel Name of the sampler variable.
  737. * @param texture Texture to set.
  738. */
  739. Effect.prototype.setTexture = function (channel, texture) {
  740. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  741. };
  742. /**
  743. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  744. * @param channel Name of the sampler variable.
  745. * @param texture Texture to set.
  746. */
  747. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  748. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  749. };
  750. /**
  751. * Sets an array of textures on the engine to be used in the shader.
  752. * @param channel Name of the variable.
  753. * @param textures Textures to set.
  754. */
  755. Effect.prototype.setTextureArray = function (channel, textures) {
  756. if (this._samplers.indexOf(channel + "Ex") === -1) {
  757. var initialPos = this._samplers.indexOf(channel);
  758. for (var index = 1; index < textures.length; index++) {
  759. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  760. }
  761. }
  762. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  763. };
  764. /**
  765. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  766. * @param channel Name of the sampler variable.
  767. * @param postProcess Post process to get the input texture from.
  768. */
  769. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  770. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  771. };
  772. /**
  773. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  774. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  775. * @param channel Name of the sampler variable.
  776. * @param postProcess Post process to get the output texture from.
  777. */
  778. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  779. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  780. };
  781. /** @hidden */
  782. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  783. var cache = this._valueCache[uniformName];
  784. var flag = matrix.updateFlag;
  785. if (cache !== undefined && cache === flag) {
  786. return false;
  787. }
  788. this._valueCache[uniformName] = flag;
  789. return true;
  790. };
  791. /** @hidden */
  792. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  793. var cache = this._valueCache[uniformName];
  794. if (!cache) {
  795. cache = [x, y];
  796. this._valueCache[uniformName] = cache;
  797. return true;
  798. }
  799. var changed = false;
  800. if (cache[0] !== x) {
  801. cache[0] = x;
  802. changed = true;
  803. }
  804. if (cache[1] !== y) {
  805. cache[1] = y;
  806. changed = true;
  807. }
  808. return changed;
  809. };
  810. /** @hidden */
  811. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  812. var cache = this._valueCache[uniformName];
  813. if (!cache) {
  814. cache = [x, y, z];
  815. this._valueCache[uniformName] = cache;
  816. return true;
  817. }
  818. var changed = false;
  819. if (cache[0] !== x) {
  820. cache[0] = x;
  821. changed = true;
  822. }
  823. if (cache[1] !== y) {
  824. cache[1] = y;
  825. changed = true;
  826. }
  827. if (cache[2] !== z) {
  828. cache[2] = z;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /** @hidden */
  834. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  835. var cache = this._valueCache[uniformName];
  836. if (!cache) {
  837. cache = [x, y, z, w];
  838. this._valueCache[uniformName] = cache;
  839. return true;
  840. }
  841. var changed = false;
  842. if (cache[0] !== x) {
  843. cache[0] = x;
  844. changed = true;
  845. }
  846. if (cache[1] !== y) {
  847. cache[1] = y;
  848. changed = true;
  849. }
  850. if (cache[2] !== z) {
  851. cache[2] = z;
  852. changed = true;
  853. }
  854. if (cache[3] !== w) {
  855. cache[3] = w;
  856. changed = true;
  857. }
  858. return changed;
  859. };
  860. /**
  861. * Binds a buffer to a uniform.
  862. * @param buffer Buffer to bind.
  863. * @param name Name of the uniform variable to bind to.
  864. */
  865. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  866. var bufferName = this._uniformBuffersNames[name];
  867. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  868. return;
  869. }
  870. Effect._baseCache[bufferName] = buffer;
  871. this._engine.bindUniformBufferBase(buffer, bufferName);
  872. };
  873. /**
  874. * Binds block to a uniform.
  875. * @param blockName Name of the block to bind.
  876. * @param index Index to bind.
  877. */
  878. Effect.prototype.bindUniformBlock = function (blockName, index) {
  879. this._engine.bindUniformBlock(this._program, blockName, index);
  880. };
  881. /**
  882. * Sets an interger value on a uniform variable.
  883. * @param uniformName Name of the variable.
  884. * @param value Value to be set.
  885. * @returns this effect.
  886. */
  887. Effect.prototype.setInt = function (uniformName, value) {
  888. var cache = this._valueCache[uniformName];
  889. if (cache !== undefined && cache === value)
  890. return this;
  891. this._valueCache[uniformName] = value;
  892. this._engine.setInt(this.getUniform(uniformName), value);
  893. return this;
  894. };
  895. /**
  896. * Sets an int array on a uniform variable.
  897. * @param uniformName Name of the variable.
  898. * @param array array to be set.
  899. * @returns this effect.
  900. */
  901. Effect.prototype.setIntArray = function (uniformName, array) {
  902. this._valueCache[uniformName] = null;
  903. this._engine.setIntArray(this.getUniform(uniformName), array);
  904. return this;
  905. };
  906. /**
  907. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  908. * @param uniformName Name of the variable.
  909. * @param array array to be set.
  910. * @returns this effect.
  911. */
  912. Effect.prototype.setIntArray2 = function (uniformName, array) {
  913. this._valueCache[uniformName] = null;
  914. this._engine.setIntArray2(this.getUniform(uniformName), array);
  915. return this;
  916. };
  917. /**
  918. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  919. * @param uniformName Name of the variable.
  920. * @param array array to be set.
  921. * @returns this effect.
  922. */
  923. Effect.prototype.setIntArray3 = function (uniformName, array) {
  924. this._valueCache[uniformName] = null;
  925. this._engine.setIntArray3(this.getUniform(uniformName), array);
  926. return this;
  927. };
  928. /**
  929. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  930. * @param uniformName Name of the variable.
  931. * @param array array to be set.
  932. * @returns this effect.
  933. */
  934. Effect.prototype.setIntArray4 = function (uniformName, array) {
  935. this._valueCache[uniformName] = null;
  936. this._engine.setIntArray4(this.getUniform(uniformName), array);
  937. return this;
  938. };
  939. /**
  940. * Sets an float array on a uniform variable.
  941. * @param uniformName Name of the variable.
  942. * @param array array to be set.
  943. * @returns this effect.
  944. */
  945. Effect.prototype.setFloatArray = function (uniformName, array) {
  946. this._valueCache[uniformName] = null;
  947. this._engine.setFloatArray(this.getUniform(uniformName), array);
  948. return this;
  949. };
  950. /**
  951. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  952. * @param uniformName Name of the variable.
  953. * @param array array to be set.
  954. * @returns this effect.
  955. */
  956. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  957. this._valueCache[uniformName] = null;
  958. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  959. return this;
  960. };
  961. /**
  962. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  963. * @param uniformName Name of the variable.
  964. * @param array array to be set.
  965. * @returns this effect.
  966. */
  967. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  968. this._valueCache[uniformName] = null;
  969. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  970. return this;
  971. };
  972. /**
  973. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  974. * @param uniformName Name of the variable.
  975. * @param array array to be set.
  976. * @returns this effect.
  977. */
  978. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  979. this._valueCache[uniformName] = null;
  980. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  981. return this;
  982. };
  983. /**
  984. * Sets an array on a uniform variable.
  985. * @param uniformName Name of the variable.
  986. * @param array array to be set.
  987. * @returns this effect.
  988. */
  989. Effect.prototype.setArray = function (uniformName, array) {
  990. this._valueCache[uniformName] = null;
  991. this._engine.setArray(this.getUniform(uniformName), array);
  992. return this;
  993. };
  994. /**
  995. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  996. * @param uniformName Name of the variable.
  997. * @param array array to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setArray2 = function (uniformName, array) {
  1001. this._valueCache[uniformName] = null;
  1002. this._engine.setArray2(this.getUniform(uniformName), array);
  1003. return this;
  1004. };
  1005. /**
  1006. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1007. * @param uniformName Name of the variable.
  1008. * @param array array to be set.
  1009. * @returns this effect.
  1010. */
  1011. Effect.prototype.setArray3 = function (uniformName, array) {
  1012. this._valueCache[uniformName] = null;
  1013. this._engine.setArray3(this.getUniform(uniformName), array);
  1014. return this;
  1015. };
  1016. /**
  1017. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1018. * @param uniformName Name of the variable.
  1019. * @param array array to be set.
  1020. * @returns this effect.
  1021. */
  1022. Effect.prototype.setArray4 = function (uniformName, array) {
  1023. this._valueCache[uniformName] = null;
  1024. this._engine.setArray4(this.getUniform(uniformName), array);
  1025. return this;
  1026. };
  1027. /**
  1028. * Sets matrices on a uniform variable.
  1029. * @param uniformName Name of the variable.
  1030. * @param matrices matrices to be set.
  1031. * @returns this effect.
  1032. */
  1033. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1034. if (!matrices) {
  1035. return this;
  1036. }
  1037. this._valueCache[uniformName] = null;
  1038. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1039. return this;
  1040. };
  1041. /**
  1042. * Sets matrix on a uniform variable.
  1043. * @param uniformName Name of the variable.
  1044. * @param matrix matrix to be set.
  1045. * @returns this effect.
  1046. */
  1047. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1048. if (this._cacheMatrix(uniformName, matrix)) {
  1049. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1050. }
  1051. return this;
  1052. };
  1053. /**
  1054. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1055. * @param uniformName Name of the variable.
  1056. * @param matrix matrix to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1060. this._valueCache[uniformName] = null;
  1061. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1062. return this;
  1063. };
  1064. /**
  1065. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1066. * @param uniformName Name of the variable.
  1067. * @param matrix matrix to be set.
  1068. * @returns this effect.
  1069. */
  1070. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1071. this._valueCache[uniformName] = null;
  1072. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1073. return this;
  1074. };
  1075. /**
  1076. * Sets a float on a uniform variable.
  1077. * @param uniformName Name of the variable.
  1078. * @param value value to be set.
  1079. * @returns this effect.
  1080. */
  1081. Effect.prototype.setFloat = function (uniformName, value) {
  1082. var cache = this._valueCache[uniformName];
  1083. if (cache !== undefined && cache === value)
  1084. return this;
  1085. this._valueCache[uniformName] = value;
  1086. this._engine.setFloat(this.getUniform(uniformName), value);
  1087. return this;
  1088. };
  1089. /**
  1090. * Sets a boolean on a uniform variable.
  1091. * @param uniformName Name of the variable.
  1092. * @param bool value to be set.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setBool = function (uniformName, bool) {
  1096. var cache = this._valueCache[uniformName];
  1097. if (cache !== undefined && cache === bool)
  1098. return this;
  1099. this._valueCache[uniformName] = bool;
  1100. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1101. return this;
  1102. };
  1103. /**
  1104. * Sets a Vector2 on a uniform variable.
  1105. * @param uniformName Name of the variable.
  1106. * @param vector2 vector2 to be set.
  1107. * @returns this effect.
  1108. */
  1109. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1110. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1111. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1112. }
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a float2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param x First float in float2.
  1119. * @param y Second float in float2.
  1120. * @returns this effect.
  1121. */
  1122. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1123. if (this._cacheFloat2(uniformName, x, y)) {
  1124. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1125. }
  1126. return this;
  1127. };
  1128. /**
  1129. * Sets a Vector3 on a uniform variable.
  1130. * @param uniformName Name of the variable.
  1131. * @param vector3 Value to be set.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1135. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1136. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a float3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param x First float in float3.
  1144. * @param y Second float in float3.
  1145. * @param z Third float in float3.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1149. if (this._cacheFloat3(uniformName, x, y, z)) {
  1150. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Vector4 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param vector4 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1161. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a float4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param x First float in float4.
  1170. * @param y Second float in float4.
  1171. * @param z Third float in float4.
  1172. * @param w Fourth float in float4.
  1173. * @returns this effect.
  1174. */
  1175. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1176. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1177. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1178. }
  1179. return this;
  1180. };
  1181. /**
  1182. * Sets a Color3 on a uniform variable.
  1183. * @param uniformName Name of the variable.
  1184. * @param color3 Value to be set.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setColor3 = function (uniformName, color3) {
  1188. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1189. this._engine.setColor3(this.getUniform(uniformName), color3);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color4 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @param alpha Alpha value to be set.
  1198. * @returns this effect.
  1199. */
  1200. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1201. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1202. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1203. }
  1204. return this;
  1205. };
  1206. /**
  1207. * Sets a Color4 on a uniform variable
  1208. * @param uniformName defines the name of the variable
  1209. * @param color4 defines the value to be set
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1213. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1214. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Resets the cache of effects.
  1220. */
  1221. Effect.ResetCache = function () {
  1222. Effect._baseCache = {};
  1223. };
  1224. Effect._uniqueIdSeed = 0;
  1225. Effect._baseCache = {};
  1226. /**
  1227. * Store of each shader (The can be looked up using effect.key)
  1228. */
  1229. Effect.ShadersStore = {};
  1230. /**
  1231. * Store of each included file for a shader (The can be looked up using effect.key)
  1232. */
  1233. Effect.IncludesShadersStore = {};
  1234. return Effect;
  1235. }());
  1236. BABYLON.Effect = Effect;
  1237. })(BABYLON || (BABYLON = {}));
  1238. //# sourceMappingURL=babylon.effect.js.map
  1239. //# sourceMappingURL=babylon.types.js.map
  1240. var BABYLON;
  1241. (function (BABYLON) {
  1242. var KeyboardEventTypes = /** @class */ (function () {
  1243. function KeyboardEventTypes() {
  1244. }
  1245. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1246. get: function () {
  1247. return KeyboardEventTypes._KEYDOWN;
  1248. },
  1249. enumerable: true,
  1250. configurable: true
  1251. });
  1252. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1253. get: function () {
  1254. return KeyboardEventTypes._KEYUP;
  1255. },
  1256. enumerable: true,
  1257. configurable: true
  1258. });
  1259. KeyboardEventTypes._KEYDOWN = 0x01;
  1260. KeyboardEventTypes._KEYUP = 0x02;
  1261. return KeyboardEventTypes;
  1262. }());
  1263. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1264. var KeyboardInfo = /** @class */ (function () {
  1265. function KeyboardInfo(type, event) {
  1266. this.type = type;
  1267. this.event = event;
  1268. }
  1269. return KeyboardInfo;
  1270. }());
  1271. BABYLON.KeyboardInfo = KeyboardInfo;
  1272. /**
  1273. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1274. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1275. */
  1276. var KeyboardInfoPre = /** @class */ (function (_super) {
  1277. __extends(KeyboardInfoPre, _super);
  1278. function KeyboardInfoPre(type, event) {
  1279. var _this = _super.call(this, type, event) || this;
  1280. _this.skipOnPointerObservable = false;
  1281. return _this;
  1282. }
  1283. return KeyboardInfoPre;
  1284. }(KeyboardInfo));
  1285. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1286. })(BABYLON || (BABYLON = {}));
  1287. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1288. var BABYLON;
  1289. (function (BABYLON) {
  1290. var PointerEventTypes = /** @class */ (function () {
  1291. function PointerEventTypes() {
  1292. }
  1293. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1294. get: function () {
  1295. return PointerEventTypes._POINTERDOWN;
  1296. },
  1297. enumerable: true,
  1298. configurable: true
  1299. });
  1300. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1301. get: function () {
  1302. return PointerEventTypes._POINTERUP;
  1303. },
  1304. enumerable: true,
  1305. configurable: true
  1306. });
  1307. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1308. get: function () {
  1309. return PointerEventTypes._POINTERMOVE;
  1310. },
  1311. enumerable: true,
  1312. configurable: true
  1313. });
  1314. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1315. get: function () {
  1316. return PointerEventTypes._POINTERWHEEL;
  1317. },
  1318. enumerable: true,
  1319. configurable: true
  1320. });
  1321. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1322. get: function () {
  1323. return PointerEventTypes._POINTERPICK;
  1324. },
  1325. enumerable: true,
  1326. configurable: true
  1327. });
  1328. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1329. get: function () {
  1330. return PointerEventTypes._POINTERTAP;
  1331. },
  1332. enumerable: true,
  1333. configurable: true
  1334. });
  1335. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1336. get: function () {
  1337. return PointerEventTypes._POINTERDOUBLETAP;
  1338. },
  1339. enumerable: true,
  1340. configurable: true
  1341. });
  1342. PointerEventTypes._POINTERDOWN = 0x01;
  1343. PointerEventTypes._POINTERUP = 0x02;
  1344. PointerEventTypes._POINTERMOVE = 0x04;
  1345. PointerEventTypes._POINTERWHEEL = 0x08;
  1346. PointerEventTypes._POINTERPICK = 0x10;
  1347. PointerEventTypes._POINTERTAP = 0x20;
  1348. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1349. return PointerEventTypes;
  1350. }());
  1351. BABYLON.PointerEventTypes = PointerEventTypes;
  1352. var PointerInfoBase = /** @class */ (function () {
  1353. function PointerInfoBase(type, event) {
  1354. this.type = type;
  1355. this.event = event;
  1356. }
  1357. return PointerInfoBase;
  1358. }());
  1359. BABYLON.PointerInfoBase = PointerInfoBase;
  1360. /**
  1361. * This class is used to store pointer related info for the onPrePointerObservable event.
  1362. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1363. */
  1364. var PointerInfoPre = /** @class */ (function (_super) {
  1365. __extends(PointerInfoPre, _super);
  1366. function PointerInfoPre(type, event, localX, localY) {
  1367. var _this = _super.call(this, type, event) || this;
  1368. _this.skipOnPointerObservable = false;
  1369. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1370. return _this;
  1371. }
  1372. return PointerInfoPre;
  1373. }(PointerInfoBase));
  1374. BABYLON.PointerInfoPre = PointerInfoPre;
  1375. /**
  1376. * This type contains all the data related to a pointer event in Babylon.js.
  1377. * 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.
  1378. */
  1379. var PointerInfo = /** @class */ (function (_super) {
  1380. __extends(PointerInfo, _super);
  1381. function PointerInfo(type, event, pickInfo) {
  1382. var _this = _super.call(this, type, event) || this;
  1383. _this.pickInfo = pickInfo;
  1384. return _this;
  1385. }
  1386. return PointerInfo;
  1387. }(PointerInfoBase));
  1388. BABYLON.PointerInfo = PointerInfo;
  1389. })(BABYLON || (BABYLON = {}));
  1390. //# sourceMappingURL=babylon.pointerEvents.js.map
  1391. var BABYLON;
  1392. (function (BABYLON) {
  1393. BABYLON.ToGammaSpace = 1 / 2.2;
  1394. BABYLON.ToLinearSpace = 2.2;
  1395. BABYLON.Epsilon = 0.001;
  1396. /**
  1397. * Class used to hold a RBG color
  1398. */
  1399. var Color3 = /** @class */ (function () {
  1400. /**
  1401. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1402. * @param r defines the red component (between 0 and 1, default is 0)
  1403. * @param g defines the green component (between 0 and 1, default is 0)
  1404. * @param b defines the blue component (between 0 and 1, default is 0)
  1405. */
  1406. function Color3(
  1407. /**
  1408. * Defines the red component (between 0 and 1, default is 0)
  1409. */
  1410. r,
  1411. /**
  1412. * Defines the green component (between 0 and 1, default is 0)
  1413. */
  1414. g,
  1415. /**
  1416. * Defines the blue component (between 0 and 1, default is 0)
  1417. */
  1418. b) {
  1419. if (r === void 0) { r = 0; }
  1420. if (g === void 0) { g = 0; }
  1421. if (b === void 0) { b = 0; }
  1422. this.r = r;
  1423. this.g = g;
  1424. this.b = b;
  1425. }
  1426. /**
  1427. * Creates a string with the Color3 current values
  1428. * @returns the string representation of the Color3 object
  1429. */
  1430. Color3.prototype.toString = function () {
  1431. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1432. };
  1433. /**
  1434. * Returns the string "Color3"
  1435. * @returns "Color3"
  1436. */
  1437. Color3.prototype.getClassName = function () {
  1438. return "Color3";
  1439. };
  1440. /**
  1441. * Compute the Color3 hash code
  1442. * @returns an unique number that can be used to hash Color3 objects
  1443. */
  1444. Color3.prototype.getHashCode = function () {
  1445. var hash = this.r || 0;
  1446. hash = (hash * 397) ^ (this.g || 0);
  1447. hash = (hash * 397) ^ (this.b || 0);
  1448. return hash;
  1449. };
  1450. // Operators
  1451. /**
  1452. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1453. * @param array defines the array where to store the r,g,b components
  1454. * @param index defines an optional index in the target array to define where to start storing values
  1455. * @returns the current Color3 object
  1456. */
  1457. Color3.prototype.toArray = function (array, index) {
  1458. if (index === undefined) {
  1459. index = 0;
  1460. }
  1461. array[index] = this.r;
  1462. array[index + 1] = this.g;
  1463. array[index + 2] = this.b;
  1464. return this;
  1465. };
  1466. /**
  1467. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1468. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1469. * @returns a new {BABYLON.Color4} object
  1470. */
  1471. Color3.prototype.toColor4 = function (alpha) {
  1472. if (alpha === void 0) { alpha = 1; }
  1473. return new Color4(this.r, this.g, this.b, alpha);
  1474. };
  1475. /**
  1476. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1477. * @returns the new array
  1478. */
  1479. Color3.prototype.asArray = function () {
  1480. var result = new Array();
  1481. this.toArray(result, 0);
  1482. return result;
  1483. };
  1484. /**
  1485. * Returns the luminance value
  1486. * @returns a float value
  1487. */
  1488. Color3.prototype.toLuminance = function () {
  1489. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1490. };
  1491. /**
  1492. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1493. * @param otherColor defines the second operand
  1494. * @returns the new Color3 object
  1495. */
  1496. Color3.prototype.multiply = function (otherColor) {
  1497. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1498. };
  1499. /**
  1500. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1501. * @param otherColor defines the second operand
  1502. * @param result defines the Color3 object where to store the result
  1503. * @returns the current Color3
  1504. */
  1505. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1506. result.r = this.r * otherColor.r;
  1507. result.g = this.g * otherColor.g;
  1508. result.b = this.b * otherColor.b;
  1509. return this;
  1510. };
  1511. /**
  1512. * Determines equality between Color3 objects
  1513. * @param otherColor defines the second operand
  1514. * @returns true if the rgb values are equal to the given ones
  1515. */
  1516. Color3.prototype.equals = function (otherColor) {
  1517. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1518. };
  1519. /**
  1520. * Determines equality between the current Color3 object and a set of r,b,g values
  1521. * @param r defines the red component to check
  1522. * @param g defines the green component to check
  1523. * @param b defines the blue component to check
  1524. * @returns true if the rgb values are equal to the given ones
  1525. */
  1526. Color3.prototype.equalsFloats = function (r, g, b) {
  1527. return this.r === r && this.g === g && this.b === b;
  1528. };
  1529. /**
  1530. * Multiplies in place each rgb value by scale
  1531. * @param scale defines the scaling factor
  1532. * @returns the updated Color3
  1533. */
  1534. Color3.prototype.scale = function (scale) {
  1535. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1536. };
  1537. /**
  1538. * Multiplies the rgb values by scale and stores the result into "result"
  1539. * @param scale defines the scaling factor
  1540. * @param result defines the Color3 object where to store the result
  1541. * @returns the unmodified current Color3
  1542. */
  1543. Color3.prototype.scaleToRef = function (scale, result) {
  1544. result.r = this.r * scale;
  1545. result.g = this.g * scale;
  1546. result.b = this.b * scale;
  1547. return this;
  1548. };
  1549. /**
  1550. * Scale the current Color3 values by a factor and add the result to a given Color3
  1551. * @param scale defines the scale factor
  1552. * @param result defines color to store the result into
  1553. * @returns the unmodified current Color3
  1554. */
  1555. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1556. result.r += this.r * scale;
  1557. result.g += this.g * scale;
  1558. result.b += this.b * scale;
  1559. return this;
  1560. };
  1561. /**
  1562. * Clamps the rgb values by the min and max values and stores the result into "result"
  1563. * @param min defines minimum clamping value (default is 0)
  1564. * @param max defines maximum clamping value (default is 1)
  1565. * @param result defines color to store the result into
  1566. * @returns the original Color3
  1567. */
  1568. Color3.prototype.clampToRef = function (min, max, result) {
  1569. if (min === void 0) { min = 0; }
  1570. if (max === void 0) { max = 1; }
  1571. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1572. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1573. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1574. return this;
  1575. };
  1576. /**
  1577. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1578. * @param otherColor defines the second operand
  1579. * @returns the new Color3
  1580. */
  1581. Color3.prototype.add = function (otherColor) {
  1582. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1583. };
  1584. /**
  1585. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1586. * @param otherColor defines the second operand
  1587. * @param result defines Color3 object to store the result into
  1588. * @returns the unmodified current Color3
  1589. */
  1590. Color3.prototype.addToRef = function (otherColor, result) {
  1591. result.r = this.r + otherColor.r;
  1592. result.g = this.g + otherColor.g;
  1593. result.b = this.b + otherColor.b;
  1594. return this;
  1595. };
  1596. /**
  1597. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1598. * @param otherColor defines the second operand
  1599. * @returns the new Color3
  1600. */
  1601. Color3.prototype.subtract = function (otherColor) {
  1602. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1603. };
  1604. /**
  1605. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1606. * @param otherColor defines the second operand
  1607. * @param result defines Color3 object to store the result into
  1608. * @returns the unmodified current Color3
  1609. */
  1610. Color3.prototype.subtractToRef = function (otherColor, result) {
  1611. result.r = this.r - otherColor.r;
  1612. result.g = this.g - otherColor.g;
  1613. result.b = this.b - otherColor.b;
  1614. return this;
  1615. };
  1616. /**
  1617. * Copy the current object
  1618. * @returns a new Color3 copied the current one
  1619. */
  1620. Color3.prototype.clone = function () {
  1621. return new Color3(this.r, this.g, this.b);
  1622. };
  1623. /**
  1624. * Copies the rgb values from the source in the current Color3
  1625. * @param source defines the source Color3 object
  1626. * @returns the updated Color3 object
  1627. */
  1628. Color3.prototype.copyFrom = function (source) {
  1629. this.r = source.r;
  1630. this.g = source.g;
  1631. this.b = source.b;
  1632. return this;
  1633. };
  1634. /**
  1635. * Updates the Color3 rgb values from the given floats
  1636. * @param r defines the red component to read from
  1637. * @param g defines the green component to read from
  1638. * @param b defines the blue component to read from
  1639. * @returns the current Color3 object
  1640. */
  1641. Color3.prototype.copyFromFloats = function (r, g, b) {
  1642. this.r = r;
  1643. this.g = g;
  1644. this.b = b;
  1645. return this;
  1646. };
  1647. /**
  1648. * Updates the Color3 rgb values from the given floats
  1649. * @param r defines the red component to read from
  1650. * @param g defines the green component to read from
  1651. * @param b defines the blue component to read from
  1652. * @returns the current Color3 object
  1653. */
  1654. Color3.prototype.set = function (r, g, b) {
  1655. return this.copyFromFloats(r, g, b);
  1656. };
  1657. /**
  1658. * Compute the Color3 hexadecimal code as a string
  1659. * @returns a string containing the hexadecimal representation of the Color3 object
  1660. */
  1661. Color3.prototype.toHexString = function () {
  1662. var intR = (this.r * 255) | 0;
  1663. var intG = (this.g * 255) | 0;
  1664. var intB = (this.b * 255) | 0;
  1665. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1666. };
  1667. /**
  1668. * Computes a new Color3 converted from the current one to linear space
  1669. * @returns a new Color3 object
  1670. */
  1671. Color3.prototype.toLinearSpace = function () {
  1672. var convertedColor = new Color3();
  1673. this.toLinearSpaceToRef(convertedColor);
  1674. return convertedColor;
  1675. };
  1676. /**
  1677. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1678. * @param convertedColor defines the Color3 object where to store the linear space version
  1679. * @returns the unmodified Color3
  1680. */
  1681. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1682. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1683. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1684. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1685. return this;
  1686. };
  1687. /**
  1688. * Computes a new Color3 converted from the current one to gamma space
  1689. * @returns a new Color3 object
  1690. */
  1691. Color3.prototype.toGammaSpace = function () {
  1692. var convertedColor = new Color3();
  1693. this.toGammaSpaceToRef(convertedColor);
  1694. return convertedColor;
  1695. };
  1696. /**
  1697. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1698. * @param convertedColor defines the Color3 object where to store the gamma space version
  1699. * @returns the unmodified Color3
  1700. */
  1701. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1702. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1703. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1704. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1705. return this;
  1706. };
  1707. // Statics
  1708. /**
  1709. * Creates a new Color3 from the string containing valid hexadecimal values
  1710. * @param hex defines a string containing valid hexadecimal values
  1711. * @returns a new Color3 object
  1712. */
  1713. Color3.FromHexString = function (hex) {
  1714. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1715. return new Color3(0, 0, 0);
  1716. }
  1717. var r = parseInt(hex.substring(1, 3), 16);
  1718. var g = parseInt(hex.substring(3, 5), 16);
  1719. var b = parseInt(hex.substring(5, 7), 16);
  1720. return Color3.FromInts(r, g, b);
  1721. };
  1722. /**
  1723. * Creates a new Vector3 from the starting index of the given array
  1724. * @param array defines the source array
  1725. * @param offset defines an offset in the source array
  1726. * @returns a new Color3 object
  1727. */
  1728. Color3.FromArray = function (array, offset) {
  1729. if (offset === void 0) { offset = 0; }
  1730. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1731. };
  1732. /**
  1733. * Creates a new Color3 from integer values (< 256)
  1734. * @param r defines the red component to read from (value between 0 and 255)
  1735. * @param g defines the green component to read from (value between 0 and 255)
  1736. * @param b defines the blue component to read from (value between 0 and 255)
  1737. * @returns a new Color3 object
  1738. */
  1739. Color3.FromInts = function (r, g, b) {
  1740. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1741. };
  1742. /**
  1743. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1744. * @param start defines the start Color3 value
  1745. * @param end defines the end Color3 value
  1746. * @param amount defines the gradient value between start and end
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.Lerp = function (start, end, amount) {
  1750. var r = start.r + ((end.r - start.r) * amount);
  1751. var g = start.g + ((end.g - start.g) * amount);
  1752. var b = start.b + ((end.b - start.b) * amount);
  1753. return new Color3(r, g, b);
  1754. };
  1755. /**
  1756. * Returns a Color3 value containing a red color
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Red = function () { return new Color3(1, 0, 0); };
  1760. /**
  1761. * Returns a Color3 value containing a green color
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.Green = function () { return new Color3(0, 1, 0); };
  1765. /**
  1766. * Returns a Color3 value containing a blue color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1770. /**
  1771. * Returns a Color3 value containing a black color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Black = function () { return new Color3(0, 0, 0); };
  1775. /**
  1776. * Returns a Color3 value containing a white color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.White = function () { return new Color3(1, 1, 1); };
  1780. /**
  1781. * Returns a Color3 value containing a purple color
  1782. * @returns a new Color3 object
  1783. */
  1784. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1785. /**
  1786. * Returns a Color3 value containing a magenta color
  1787. * @returns a new Color3 object
  1788. */
  1789. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1790. /**
  1791. * Returns a Color3 value containing a yellow color
  1792. * @returns a new Color3 object
  1793. */
  1794. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1795. /**
  1796. * Returns a Color3 value containing a gray color
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1800. /**
  1801. * Returns a Color3 value containing a teal color
  1802. * @returns a new Color3 object
  1803. */
  1804. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1805. /**
  1806. * Returns a Color3 value containing a random color
  1807. * @returns a new Color3 object
  1808. */
  1809. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1810. return Color3;
  1811. }());
  1812. BABYLON.Color3 = Color3;
  1813. /**
  1814. * Class used to hold a RBGA color
  1815. */
  1816. var Color4 = /** @class */ (function () {
  1817. /**
  1818. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1819. * @param r defines the red component (between 0 and 1, default is 0)
  1820. * @param g defines the green component (between 0 and 1, default is 0)
  1821. * @param b defines the blue component (between 0 and 1, default is 0)
  1822. * @param a defines the alpha component (between 0 and 1, default is 1)
  1823. */
  1824. function Color4(
  1825. /**
  1826. * Defines the red component (between 0 and 1, default is 0)
  1827. */
  1828. r,
  1829. /**
  1830. * Defines the green component (between 0 and 1, default is 0)
  1831. */
  1832. g,
  1833. /**
  1834. * Defines the blue component (between 0 and 1, default is 0)
  1835. */
  1836. b,
  1837. /**
  1838. * Defines the alpha component (between 0 and 1, default is 1)
  1839. */
  1840. a) {
  1841. if (r === void 0) { r = 0; }
  1842. if (g === void 0) { g = 0; }
  1843. if (b === void 0) { b = 0; }
  1844. if (a === void 0) { a = 1; }
  1845. this.r = r;
  1846. this.g = g;
  1847. this.b = b;
  1848. this.a = a;
  1849. }
  1850. // Operators
  1851. /**
  1852. * Adds in place the given Color4 values to the current Color4 object
  1853. * @param right defines the second operand
  1854. * @returns the current updated Color4 object
  1855. */
  1856. Color4.prototype.addInPlace = function (right) {
  1857. this.r += right.r;
  1858. this.g += right.g;
  1859. this.b += right.b;
  1860. this.a += right.a;
  1861. return this;
  1862. };
  1863. /**
  1864. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1865. * @returns the new array
  1866. */
  1867. Color4.prototype.asArray = function () {
  1868. var result = new Array();
  1869. this.toArray(result, 0);
  1870. return result;
  1871. };
  1872. /**
  1873. * Stores from the starting index in the given array the Color4 successive values
  1874. * @param array defines the array where to store the r,g,b components
  1875. * @param index defines an optional index in the target array to define where to start storing values
  1876. * @returns the current Color4 object
  1877. */
  1878. Color4.prototype.toArray = function (array, index) {
  1879. if (index === undefined) {
  1880. index = 0;
  1881. }
  1882. array[index] = this.r;
  1883. array[index + 1] = this.g;
  1884. array[index + 2] = this.b;
  1885. array[index + 3] = this.a;
  1886. return this;
  1887. };
  1888. /**
  1889. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1890. * @param right defines the second operand
  1891. * @returns a new Color4 object
  1892. */
  1893. Color4.prototype.add = function (right) {
  1894. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1895. };
  1896. /**
  1897. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1898. * @param right defines the second operand
  1899. * @returns a new Color4 object
  1900. */
  1901. Color4.prototype.subtract = function (right) {
  1902. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1903. };
  1904. /**
  1905. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1906. * @param right defines the second operand
  1907. * @param result defines the Color4 object where to store the result
  1908. * @returns the current Color4 object
  1909. */
  1910. Color4.prototype.subtractToRef = function (right, result) {
  1911. result.r = this.r - right.r;
  1912. result.g = this.g - right.g;
  1913. result.b = this.b - right.b;
  1914. result.a = this.a - right.a;
  1915. return this;
  1916. };
  1917. /**
  1918. * Creates a new Color4 with the current Color4 values multiplied by scale
  1919. * @param scale defines the scaling factor to apply
  1920. * @returns a new Color4 object
  1921. */
  1922. Color4.prototype.scale = function (scale) {
  1923. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1924. };
  1925. /**
  1926. * Multiplies the current Color4 values by scale and stores the result in "result"
  1927. * @param scale defines the scaling factor to apply
  1928. * @param result defines the Color4 object where to store the result
  1929. * @returns the current unmodified Color4
  1930. */
  1931. Color4.prototype.scaleToRef = function (scale, result) {
  1932. result.r = this.r * scale;
  1933. result.g = this.g * scale;
  1934. result.b = this.b * scale;
  1935. result.a = this.a * scale;
  1936. return this;
  1937. };
  1938. /**
  1939. * Scale the current Color4 values by a factor and add the result to a given Color4
  1940. * @param scale defines the scale factor
  1941. * @param result defines the Color4 object where to store the result
  1942. * @returns the unmodified current Color4
  1943. */
  1944. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1945. result.r += this.r * scale;
  1946. result.g += this.g * scale;
  1947. result.b += this.b * scale;
  1948. result.a += this.a * scale;
  1949. return this;
  1950. };
  1951. /**
  1952. * Clamps the rgb values by the min and max values and stores the result into "result"
  1953. * @param min defines minimum clamping value (default is 0)
  1954. * @param max defines maximum clamping value (default is 1)
  1955. * @param result defines color to store the result into.
  1956. * @returns the cuurent Color4
  1957. */
  1958. Color4.prototype.clampToRef = function (min, max, result) {
  1959. if (min === void 0) { min = 0; }
  1960. if (max === void 0) { max = 1; }
  1961. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1962. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1963. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1964. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1965. return this;
  1966. };
  1967. /**
  1968. * Multipy an Color4 value by another and return a new Color4 object
  1969. * @param color defines the Color4 value to multiply by
  1970. * @returns a new Color4 object
  1971. */
  1972. Color4.prototype.multiply = function (color) {
  1973. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1974. };
  1975. /**
  1976. * Multipy a Color4 value by another and push the result in a reference value
  1977. * @param color defines the Color4 value to multiply by
  1978. * @param result defines the Color4 to fill the result in
  1979. * @returns the result Color4
  1980. */
  1981. Color4.prototype.multiplyToRef = function (color, result) {
  1982. result.r = this.r * color.r;
  1983. result.g = this.g * color.g;
  1984. result.b = this.b * color.b;
  1985. result.a = this.a * color.a;
  1986. return result;
  1987. };
  1988. /**
  1989. * Creates a string with the Color4 current values
  1990. * @returns the string representation of the Color4 object
  1991. */
  1992. Color4.prototype.toString = function () {
  1993. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1994. };
  1995. /**
  1996. * Returns the string "Color4"
  1997. * @returns "Color4"
  1998. */
  1999. Color4.prototype.getClassName = function () {
  2000. return "Color4";
  2001. };
  2002. /**
  2003. * Compute the Color4 hash code
  2004. * @returns an unique number that can be used to hash Color4 objects
  2005. */
  2006. Color4.prototype.getHashCode = function () {
  2007. var hash = this.r || 0;
  2008. hash = (hash * 397) ^ (this.g || 0);
  2009. hash = (hash * 397) ^ (this.b || 0);
  2010. hash = (hash * 397) ^ (this.a || 0);
  2011. return hash;
  2012. };
  2013. /**
  2014. * Creates a new Color4 copied from the current one
  2015. * @returns a new Color4 object
  2016. */
  2017. Color4.prototype.clone = function () {
  2018. return new Color4(this.r, this.g, this.b, this.a);
  2019. };
  2020. /**
  2021. * Copies the given Color4 values into the current one
  2022. * @param source defines the source Color4 object
  2023. * @returns the current updated Color4 object
  2024. */
  2025. Color4.prototype.copyFrom = function (source) {
  2026. this.r = source.r;
  2027. this.g = source.g;
  2028. this.b = source.b;
  2029. this.a = source.a;
  2030. return this;
  2031. };
  2032. /**
  2033. * Copies the given float values into the current one
  2034. * @param r defines the red component to read from
  2035. * @param g defines the green component to read from
  2036. * @param b defines the blue component to read from
  2037. * @param a defines the alpha component to read from
  2038. * @returns the current updated Color4 object
  2039. */
  2040. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2041. this.r = r;
  2042. this.g = g;
  2043. this.b = b;
  2044. this.a = a;
  2045. return this;
  2046. };
  2047. /**
  2048. * Copies the given float values into the current one
  2049. * @param r defines the red component to read from
  2050. * @param g defines the green component to read from
  2051. * @param b defines the blue component to read from
  2052. * @param a defines the alpha component to read from
  2053. * @returns the current updated Color4 object
  2054. */
  2055. Color4.prototype.set = function (r, g, b, a) {
  2056. return this.copyFromFloats(r, g, b, a);
  2057. };
  2058. /**
  2059. * Compute the Color4 hexadecimal code as a string
  2060. * @returns a string containing the hexadecimal representation of the Color4 object
  2061. */
  2062. Color4.prototype.toHexString = function () {
  2063. var intR = (this.r * 255) | 0;
  2064. var intG = (this.g * 255) | 0;
  2065. var intB = (this.b * 255) | 0;
  2066. var intA = (this.a * 255) | 0;
  2067. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2068. };
  2069. /**
  2070. * Computes a new Color4 converted from the current one to linear space
  2071. * @returns a new Color4 object
  2072. */
  2073. Color4.prototype.toLinearSpace = function () {
  2074. var convertedColor = new Color4();
  2075. this.toLinearSpaceToRef(convertedColor);
  2076. return convertedColor;
  2077. };
  2078. /**
  2079. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2080. * @param convertedColor defines the Color4 object where to store the linear space version
  2081. * @returns the unmodified Color4
  2082. */
  2083. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2084. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2085. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2086. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2087. convertedColor.a = this.a;
  2088. return this;
  2089. };
  2090. /**
  2091. * Computes a new Color4 converted from the current one to gamma space
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.prototype.toGammaSpace = function () {
  2095. var convertedColor = new Color4();
  2096. this.toGammaSpaceToRef(convertedColor);
  2097. return convertedColor;
  2098. };
  2099. /**
  2100. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2101. * @param convertedColor defines the Color4 object where to store the gamma space version
  2102. * @returns the unmodified Color4
  2103. */
  2104. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2105. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2106. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2107. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2108. convertedColor.a = this.a;
  2109. return this;
  2110. };
  2111. // Statics
  2112. /**
  2113. * Creates a new Color4 from the string containing valid hexadecimal values
  2114. * @param hex defines a string containing valid hexadecimal values
  2115. * @returns a new Color4 object
  2116. */
  2117. Color4.FromHexString = function (hex) {
  2118. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2119. return new Color4(0.0, 0.0, 0.0, 0.0);
  2120. }
  2121. var r = parseInt(hex.substring(1, 3), 16);
  2122. var g = parseInt(hex.substring(3, 5), 16);
  2123. var b = parseInt(hex.substring(5, 7), 16);
  2124. var a = parseInt(hex.substring(7, 9), 16);
  2125. return Color4.FromInts(r, g, b, a);
  2126. };
  2127. /**
  2128. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2129. * @param left defines the start value
  2130. * @param right defines the end value
  2131. * @param amount defines the gradient factor
  2132. * @returns a new Color4 object
  2133. */
  2134. Color4.Lerp = function (left, right, amount) {
  2135. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2136. Color4.LerpToRef(left, right, amount, result);
  2137. return result;
  2138. };
  2139. /**
  2140. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2141. * @param left defines the start value
  2142. * @param right defines the end value
  2143. * @param amount defines the gradient factor
  2144. * @param result defines the Color4 object where to store data
  2145. */
  2146. Color4.LerpToRef = function (left, right, amount, result) {
  2147. result.r = left.r + (right.r - left.r) * amount;
  2148. result.g = left.g + (right.g - left.g) * amount;
  2149. result.b = left.b + (right.b - left.b) * amount;
  2150. result.a = left.a + (right.a - left.a) * amount;
  2151. };
  2152. /**
  2153. * Creates a new Color4 from the starting index element of the given array
  2154. * @param array defines the source array to read from
  2155. * @param offset defines the offset in the source array
  2156. * @returns a new Color4 object
  2157. */
  2158. Color4.FromArray = function (array, offset) {
  2159. if (offset === void 0) { offset = 0; }
  2160. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2161. };
  2162. /**
  2163. * Creates a new Color3 from integer values (< 256)
  2164. * @param r defines the red component to read from (value between 0 and 255)
  2165. * @param g defines the green component to read from (value between 0 and 255)
  2166. * @param b defines the blue component to read from (value between 0 and 255)
  2167. * @param a defines the alpha component to read from (value between 0 and 255)
  2168. * @returns a new Color3 object
  2169. */
  2170. Color4.FromInts = function (r, g, b, a) {
  2171. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2172. };
  2173. /**
  2174. * Check the content of a given array and convert it to an array containing RGBA data
  2175. * If the original array was already containing count * 4 values then it is returned directly
  2176. * @param colors defines the array to check
  2177. * @param count defines the number of RGBA data to expect
  2178. * @returns an array containing count * 4 values (RGBA)
  2179. */
  2180. Color4.CheckColors4 = function (colors, count) {
  2181. // Check if color3 was used
  2182. if (colors.length === count * 3) {
  2183. var colors4 = [];
  2184. for (var index = 0; index < colors.length; index += 3) {
  2185. var newIndex = (index / 3) * 4;
  2186. colors4[newIndex] = colors[index];
  2187. colors4[newIndex + 1] = colors[index + 1];
  2188. colors4[newIndex + 2] = colors[index + 2];
  2189. colors4[newIndex + 3] = 1.0;
  2190. }
  2191. return colors4;
  2192. }
  2193. return colors;
  2194. };
  2195. return Color4;
  2196. }());
  2197. BABYLON.Color4 = Color4;
  2198. /**
  2199. * Class representing a vector containing 2 coordinates
  2200. */
  2201. var Vector2 = /** @class */ (function () {
  2202. /**
  2203. * Creates a new Vector2 from the given x and y coordinates
  2204. * @param x defines the first coordinate
  2205. * @param y defines the second coordinate
  2206. */
  2207. function Vector2(
  2208. /** defines the first coordinate */
  2209. x,
  2210. /** defines the second coordinate */
  2211. y) {
  2212. this.x = x;
  2213. this.y = y;
  2214. }
  2215. /**
  2216. * Gets a string with the Vector2 coordinates
  2217. * @returns a string with the Vector2 coordinates
  2218. */
  2219. Vector2.prototype.toString = function () {
  2220. return "{X: " + this.x + " Y:" + this.y + "}";
  2221. };
  2222. /**
  2223. * Gets class name
  2224. * @returns the string "Vector2"
  2225. */
  2226. Vector2.prototype.getClassName = function () {
  2227. return "Vector2";
  2228. };
  2229. /**
  2230. * Gets current vector hash code
  2231. * @returns the Vector2 hash code as a number
  2232. */
  2233. Vector2.prototype.getHashCode = function () {
  2234. var hash = this.x || 0;
  2235. hash = (hash * 397) ^ (this.y || 0);
  2236. return hash;
  2237. };
  2238. // Operators
  2239. /**
  2240. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2241. * @param array defines the source array
  2242. * @param index defines the offset in source array
  2243. * @returns the current Vector2
  2244. */
  2245. Vector2.prototype.toArray = function (array, index) {
  2246. if (index === void 0) { index = 0; }
  2247. array[index] = this.x;
  2248. array[index + 1] = this.y;
  2249. return this;
  2250. };
  2251. /**
  2252. * Copy the current vector to an array
  2253. * @returns a new array with 2 elements: the Vector2 coordinates.
  2254. */
  2255. Vector2.prototype.asArray = function () {
  2256. var result = new Array();
  2257. this.toArray(result, 0);
  2258. return result;
  2259. };
  2260. /**
  2261. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2262. * @param source defines the source Vector2
  2263. * @returns the current updated Vector2
  2264. */
  2265. Vector2.prototype.copyFrom = function (source) {
  2266. this.x = source.x;
  2267. this.y = source.y;
  2268. return this;
  2269. };
  2270. /**
  2271. * Sets the Vector2 coordinates with the given floats
  2272. * @param x defines the first coordinate
  2273. * @param y defines the second coordinate
  2274. * @returns the current updated Vector2
  2275. */
  2276. Vector2.prototype.copyFromFloats = function (x, y) {
  2277. this.x = x;
  2278. this.y = y;
  2279. return this;
  2280. };
  2281. /**
  2282. * Sets the Vector2 coordinates with the given floats
  2283. * @param x defines the first coordinate
  2284. * @param y defines the second coordinate
  2285. * @returns the current updated Vector2
  2286. */
  2287. Vector2.prototype.set = function (x, y) {
  2288. return this.copyFromFloats(x, y);
  2289. };
  2290. /**
  2291. * Add another vector with the current one
  2292. * @param otherVector defines the other vector
  2293. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2294. */
  2295. Vector2.prototype.add = function (otherVector) {
  2296. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2297. };
  2298. /**
  2299. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2300. * @param otherVector defines the other vector
  2301. * @param result defines the target vector
  2302. * @returns the unmodified current Vector2
  2303. */
  2304. Vector2.prototype.addToRef = function (otherVector, result) {
  2305. result.x = this.x + otherVector.x;
  2306. result.y = this.y + otherVector.y;
  2307. return this;
  2308. };
  2309. /**
  2310. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2311. * @param otherVector defines the other vector
  2312. * @returns the current updated Vector2
  2313. */
  2314. Vector2.prototype.addInPlace = function (otherVector) {
  2315. this.x += otherVector.x;
  2316. this.y += otherVector.y;
  2317. return this;
  2318. };
  2319. /**
  2320. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2321. * @param otherVector defines the other vector
  2322. * @returns a new Vector2
  2323. */
  2324. Vector2.prototype.addVector3 = function (otherVector) {
  2325. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2326. };
  2327. /**
  2328. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2329. * @param otherVector defines the other vector
  2330. * @returns a new Vector2
  2331. */
  2332. Vector2.prototype.subtract = function (otherVector) {
  2333. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2334. };
  2335. /**
  2336. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2337. * @param otherVector defines the other vector
  2338. * @param result defines the target vector
  2339. * @returns the unmodified current Vector2
  2340. */
  2341. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2342. result.x = this.x - otherVector.x;
  2343. result.y = this.y - otherVector.y;
  2344. return this;
  2345. };
  2346. /**
  2347. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2348. * @param otherVector defines the other vector
  2349. * @returns the current updated Vector2
  2350. */
  2351. Vector2.prototype.subtractInPlace = function (otherVector) {
  2352. this.x -= otherVector.x;
  2353. this.y -= otherVector.y;
  2354. return this;
  2355. };
  2356. /**
  2357. * Multiplies in place the current Vector2 coordinates by the given ones
  2358. * @param otherVector defines the other vector
  2359. * @returns the current updated Vector2
  2360. */
  2361. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2362. this.x *= otherVector.x;
  2363. this.y *= otherVector.y;
  2364. return this;
  2365. };
  2366. /**
  2367. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2368. * @param otherVector defines the other vector
  2369. * @returns a new Vector2
  2370. */
  2371. Vector2.prototype.multiply = function (otherVector) {
  2372. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2373. };
  2374. /**
  2375. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2376. * @param otherVector defines the other vector
  2377. * @param result defines the target vector
  2378. * @returns the unmodified current Vector2
  2379. */
  2380. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2381. result.x = this.x * otherVector.x;
  2382. result.y = this.y * otherVector.y;
  2383. return this;
  2384. };
  2385. /**
  2386. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2387. * @param x defines the first coordinate
  2388. * @param y defines the second coordinate
  2389. * @returns a new Vector2
  2390. */
  2391. Vector2.prototype.multiplyByFloats = function (x, y) {
  2392. return new Vector2(this.x * x, this.y * y);
  2393. };
  2394. /**
  2395. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2396. * @param otherVector defines the other vector
  2397. * @returns a new Vector2
  2398. */
  2399. Vector2.prototype.divide = function (otherVector) {
  2400. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2401. };
  2402. /**
  2403. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2404. * @param otherVector defines the other vector
  2405. * @param result defines the target vector
  2406. * @returns the unmodified current Vector2
  2407. */
  2408. Vector2.prototype.divideToRef = function (otherVector, result) {
  2409. result.x = this.x / otherVector.x;
  2410. result.y = this.y / otherVector.y;
  2411. return this;
  2412. };
  2413. /**
  2414. * Divides the current Vector3 coordinates by the given ones
  2415. * @param otherVector defines the other vector
  2416. * @returns the current updated Vector2
  2417. */
  2418. Vector2.prototype.divideInPlace = function (otherVector) {
  2419. return this.divideToRef(otherVector, this);
  2420. };
  2421. /**
  2422. * Gets a new Vector2 with current Vector2 negated coordinates
  2423. * @returns a new Vector2
  2424. */
  2425. Vector2.prototype.negate = function () {
  2426. return new Vector2(-this.x, -this.y);
  2427. };
  2428. /**
  2429. * Multiply the Vector2 coordinates by scale
  2430. * @param scale defines the scaling factor
  2431. * @returns the current updated Vector2
  2432. */
  2433. Vector2.prototype.scaleInPlace = function (scale) {
  2434. this.x *= scale;
  2435. this.y *= scale;
  2436. return this;
  2437. };
  2438. /**
  2439. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2440. * @param scale defines the scaling factor
  2441. * @returns a new Vector2
  2442. */
  2443. Vector2.prototype.scale = function (scale) {
  2444. var result = new Vector2(0, 0);
  2445. this.scaleToRef(scale, result);
  2446. return result;
  2447. };
  2448. /**
  2449. * Scale the current Vector2 values by a factor to a given Vector2
  2450. * @param scale defines the scale factor
  2451. * @param result defines the Vector2 object where to store the result
  2452. * @returns the unmodified current Vector2
  2453. */
  2454. Vector2.prototype.scaleToRef = function (scale, result) {
  2455. result.x = this.x * scale;
  2456. result.y = this.y * scale;
  2457. return this;
  2458. };
  2459. /**
  2460. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2461. * @param scale defines the scale factor
  2462. * @param result defines the Vector2 object where to store the result
  2463. * @returns the unmodified current Vector2
  2464. */
  2465. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2466. result.x += this.x * scale;
  2467. result.y += this.y * scale;
  2468. return this;
  2469. };
  2470. /**
  2471. * Gets a boolean if two vectors are equals
  2472. * @param otherVector defines the other vector
  2473. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2474. */
  2475. Vector2.prototype.equals = function (otherVector) {
  2476. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2477. };
  2478. /**
  2479. * Gets a boolean if two vectors are equals (using an epsilon value)
  2480. * @param otherVector defines the other vector
  2481. * @param epsilon defines the minimal distance to consider equality
  2482. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2483. */
  2484. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2485. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2486. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2487. };
  2488. // Properties
  2489. /**
  2490. * Gets the length of the vector
  2491. * @returns the vector length (float)
  2492. */
  2493. Vector2.prototype.length = function () {
  2494. return Math.sqrt(this.x * this.x + this.y * this.y);
  2495. };
  2496. /**
  2497. * Gets the vector squared length
  2498. * @returns the vector squared length (float)
  2499. */
  2500. Vector2.prototype.lengthSquared = function () {
  2501. return (this.x * this.x + this.y * this.y);
  2502. };
  2503. // Methods
  2504. /**
  2505. * Normalize the vector
  2506. * @returns the current updated Vector2
  2507. */
  2508. Vector2.prototype.normalize = function () {
  2509. var len = this.length();
  2510. if (len === 0)
  2511. return this;
  2512. var num = 1.0 / len;
  2513. this.x *= num;
  2514. this.y *= num;
  2515. return this;
  2516. };
  2517. /**
  2518. * Gets a new Vector2 copied from the Vector2
  2519. * @returns a new Vector2
  2520. */
  2521. Vector2.prototype.clone = function () {
  2522. return new Vector2(this.x, this.y);
  2523. };
  2524. // Statics
  2525. /**
  2526. * Gets a new Vector2(0, 0)
  2527. * @returns a new Vector2
  2528. */
  2529. Vector2.Zero = function () {
  2530. return new Vector2(0, 0);
  2531. };
  2532. /**
  2533. * Gets a new Vector2(1, 1)
  2534. * @returns a new Vector2
  2535. */
  2536. Vector2.One = function () {
  2537. return new Vector2(1, 1);
  2538. };
  2539. /**
  2540. * Gets a new Vector2 set from the given index element of the given array
  2541. * @param array defines the data source
  2542. * @param offset defines the offset in the data source
  2543. * @returns a new Vector2
  2544. */
  2545. Vector2.FromArray = function (array, offset) {
  2546. if (offset === void 0) { offset = 0; }
  2547. return new Vector2(array[offset], array[offset + 1]);
  2548. };
  2549. /**
  2550. * Sets "result" from the given index element of the given array
  2551. * @param array defines the data source
  2552. * @param offset defines the offset in the data source
  2553. * @param result defines the target vector
  2554. */
  2555. Vector2.FromArrayToRef = function (array, offset, result) {
  2556. result.x = array[offset];
  2557. result.y = array[offset + 1];
  2558. };
  2559. /**
  2560. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2561. * @param value1 defines 1st point of control
  2562. * @param value2 defines 2nd point of control
  2563. * @param value3 defines 3rd point of control
  2564. * @param value4 defines 4th point of control
  2565. * @param amount defines the interpolation factor
  2566. * @returns a new Vector2
  2567. */
  2568. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2569. var squared = amount * amount;
  2570. var cubed = amount * squared;
  2571. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2572. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2573. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2574. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2575. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2576. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2577. return new Vector2(x, y);
  2578. };
  2579. /**
  2580. * 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".
  2581. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2582. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2583. * @param value defines the value to clamp
  2584. * @param min defines the lower limit
  2585. * @param max defines the upper limit
  2586. * @returns a new Vector2
  2587. */
  2588. Vector2.Clamp = function (value, min, max) {
  2589. var x = value.x;
  2590. x = (x > max.x) ? max.x : x;
  2591. x = (x < min.x) ? min.x : x;
  2592. var y = value.y;
  2593. y = (y > max.y) ? max.y : y;
  2594. y = (y < min.y) ? min.y : y;
  2595. return new Vector2(x, y);
  2596. };
  2597. /**
  2598. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2599. * @param value1 defines the 1st control point
  2600. * @param tangent1 defines the outgoing tangent
  2601. * @param value2 defines the 2nd control point
  2602. * @param tangent2 defines the incoming tangent
  2603. * @param amount defines the interpolation factor
  2604. * @returns a new Vector2
  2605. */
  2606. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2607. var squared = amount * amount;
  2608. var cubed = amount * squared;
  2609. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2610. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2611. var part3 = (cubed - (2.0 * squared)) + amount;
  2612. var part4 = cubed - squared;
  2613. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2614. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2615. return new Vector2(x, y);
  2616. };
  2617. /**
  2618. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2619. * @param start defines the start vector
  2620. * @param end defines the end vector
  2621. * @param amount defines the interpolation factor
  2622. * @returns a new Vector2
  2623. */
  2624. Vector2.Lerp = function (start, end, amount) {
  2625. var x = start.x + ((end.x - start.x) * amount);
  2626. var y = start.y + ((end.y - start.y) * amount);
  2627. return new Vector2(x, y);
  2628. };
  2629. /**
  2630. * Gets the dot product of the vector "left" and the vector "right"
  2631. * @param left defines first vector
  2632. * @param right defines second vector
  2633. * @returns the dot product (float)
  2634. */
  2635. Vector2.Dot = function (left, right) {
  2636. return left.x * right.x + left.y * right.y;
  2637. };
  2638. /**
  2639. * Returns a new Vector2 equal to the normalized given vector
  2640. * @param vector defines the vector to normalize
  2641. * @returns a new Vector2
  2642. */
  2643. Vector2.Normalize = function (vector) {
  2644. var newVector = vector.clone();
  2645. newVector.normalize();
  2646. return newVector;
  2647. };
  2648. /**
  2649. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2650. * @param left defines 1st vector
  2651. * @param right defines 2nd vector
  2652. * @returns a new Vector2
  2653. */
  2654. Vector2.Minimize = function (left, right) {
  2655. var x = (left.x < right.x) ? left.x : right.x;
  2656. var y = (left.y < right.y) ? left.y : right.y;
  2657. return new Vector2(x, y);
  2658. };
  2659. /**
  2660. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2661. * @param left defines 1st vector
  2662. * @param right defines 2nd vector
  2663. * @returns a new Vector2
  2664. */
  2665. Vector2.Maximize = function (left, right) {
  2666. var x = (left.x > right.x) ? left.x : right.x;
  2667. var y = (left.y > right.y) ? left.y : right.y;
  2668. return new Vector2(x, y);
  2669. };
  2670. /**
  2671. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2672. * @param vector defines the vector to transform
  2673. * @param transformation defines the matrix to apply
  2674. * @returns a new Vector2
  2675. */
  2676. Vector2.Transform = function (vector, transformation) {
  2677. var r = Vector2.Zero();
  2678. Vector2.TransformToRef(vector, transformation, r);
  2679. return r;
  2680. };
  2681. /**
  2682. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2683. * @param vector defines the vector to transform
  2684. * @param transformation defines the matrix to apply
  2685. * @param result defines the target vector
  2686. */
  2687. Vector2.TransformToRef = function (vector, transformation, result) {
  2688. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2689. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2690. result.x = x;
  2691. result.y = y;
  2692. };
  2693. /**
  2694. * Determines if a given vector is included in a triangle
  2695. * @param p defines the vector to test
  2696. * @param p0 defines 1st triangle point
  2697. * @param p1 defines 2nd triangle point
  2698. * @param p2 defines 3rd triangle point
  2699. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2700. */
  2701. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2702. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2703. var sign = a < 0 ? -1 : 1;
  2704. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2705. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2706. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2707. };
  2708. /**
  2709. * Gets the distance between the vectors "value1" and "value2"
  2710. * @param value1 defines first vector
  2711. * @param value2 defines second vector
  2712. * @returns the distance between vectors
  2713. */
  2714. Vector2.Distance = function (value1, value2) {
  2715. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2716. };
  2717. /**
  2718. * Returns the squared distance between the vectors "value1" and "value2"
  2719. * @param value1 defines first vector
  2720. * @param value2 defines second vector
  2721. * @returns the squared distance between vectors
  2722. */
  2723. Vector2.DistanceSquared = function (value1, value2) {
  2724. var x = value1.x - value2.x;
  2725. var y = value1.y - value2.y;
  2726. return (x * x) + (y * y);
  2727. };
  2728. /**
  2729. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2730. * @param value1 defines first vector
  2731. * @param value2 defines second vector
  2732. * @returns a new Vector2
  2733. */
  2734. Vector2.Center = function (value1, value2) {
  2735. var center = value1.add(value2);
  2736. center.scaleInPlace(0.5);
  2737. return center;
  2738. };
  2739. /**
  2740. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2741. * @param p defines the middle point
  2742. * @param segA defines one point of the segment
  2743. * @param segB defines the other point of the segment
  2744. * @returns the shortest distance
  2745. */
  2746. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2747. var l2 = Vector2.DistanceSquared(segA, segB);
  2748. if (l2 === 0.0) {
  2749. return Vector2.Distance(p, segA);
  2750. }
  2751. var v = segB.subtract(segA);
  2752. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2753. var proj = segA.add(v.multiplyByFloats(t, t));
  2754. return Vector2.Distance(p, proj);
  2755. };
  2756. return Vector2;
  2757. }());
  2758. BABYLON.Vector2 = Vector2;
  2759. /**
  2760. * Classed used to store (x,y,z) vector representation
  2761. * A Vector3 is the main object used in 3D geometry
  2762. * It can represent etiher the coordinates of a point the space, either a direction
  2763. * Reminder: Babylon.js uses a left handed forward facing system
  2764. */
  2765. var Vector3 = /** @class */ (function () {
  2766. /**
  2767. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2768. * @param x defines the first coordinates (on X axis)
  2769. * @param y defines the second coordinates (on Y axis)
  2770. * @param z defines the third coordinates (on Z axis)
  2771. */
  2772. function Vector3(
  2773. /**
  2774. * Defines the first coordinates (on X axis)
  2775. */
  2776. x,
  2777. /**
  2778. * Defines the second coordinates (on Y axis)
  2779. */
  2780. y,
  2781. /**
  2782. * Defines the third coordinates (on Z axis)
  2783. */
  2784. z) {
  2785. this.x = x;
  2786. this.y = y;
  2787. this.z = z;
  2788. }
  2789. /**
  2790. * Creates a string representation of the Vector3
  2791. * @returns a string with the Vector3 coordinates.
  2792. */
  2793. Vector3.prototype.toString = function () {
  2794. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2795. };
  2796. /**
  2797. * Gets the class name
  2798. * @returns the string "Vector3"
  2799. */
  2800. Vector3.prototype.getClassName = function () {
  2801. return "Vector3";
  2802. };
  2803. /**
  2804. * Creates the Vector3 hash code
  2805. * @returns a number which tends to be unique between Vector3 instances
  2806. */
  2807. Vector3.prototype.getHashCode = function () {
  2808. var hash = this.x || 0;
  2809. hash = (hash * 397) ^ (this.y || 0);
  2810. hash = (hash * 397) ^ (this.z || 0);
  2811. return hash;
  2812. };
  2813. // Operators
  2814. /**
  2815. * Creates an array containing three elements : the coordinates of the Vector3
  2816. * @returns a new array of numbers
  2817. */
  2818. Vector3.prototype.asArray = function () {
  2819. var result = [];
  2820. this.toArray(result, 0);
  2821. return result;
  2822. };
  2823. /**
  2824. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2825. * @param array defines the destination array
  2826. * @param index defines the offset in the destination array
  2827. * @returns the current Vector3
  2828. */
  2829. Vector3.prototype.toArray = function (array, index) {
  2830. if (index === void 0) { index = 0; }
  2831. array[index] = this.x;
  2832. array[index + 1] = this.y;
  2833. array[index + 2] = this.z;
  2834. return this;
  2835. };
  2836. /**
  2837. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2838. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2839. */
  2840. Vector3.prototype.toQuaternion = function () {
  2841. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2842. };
  2843. /**
  2844. * Adds the given vector to the current Vector3
  2845. * @param otherVector defines the second operand
  2846. * @returns the current updated Vector3
  2847. */
  2848. Vector3.prototype.addInPlace = function (otherVector) {
  2849. this.x += otherVector.x;
  2850. this.y += otherVector.y;
  2851. this.z += otherVector.z;
  2852. return this;
  2853. };
  2854. /**
  2855. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2856. * @param otherVector defines the second operand
  2857. * @returns the resulting Vector3
  2858. */
  2859. Vector3.prototype.add = function (otherVector) {
  2860. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2861. };
  2862. /**
  2863. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2864. * @param otherVector defines the second operand
  2865. * @param result defines the Vector3 object where to store the result
  2866. * @returns the current Vector3
  2867. */
  2868. Vector3.prototype.addToRef = function (otherVector, result) {
  2869. result.x = this.x + otherVector.x;
  2870. result.y = this.y + otherVector.y;
  2871. result.z = this.z + otherVector.z;
  2872. return this;
  2873. };
  2874. /**
  2875. * Subtract the given vector from the current Vector3
  2876. * @param otherVector defines the second operand
  2877. * @returns the current updated Vector3
  2878. */
  2879. Vector3.prototype.subtractInPlace = function (otherVector) {
  2880. this.x -= otherVector.x;
  2881. this.y -= otherVector.y;
  2882. this.z -= otherVector.z;
  2883. return this;
  2884. };
  2885. /**
  2886. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2887. * @param otherVector defines the second operand
  2888. * @returns the resulting Vector3
  2889. */
  2890. Vector3.prototype.subtract = function (otherVector) {
  2891. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2892. };
  2893. /**
  2894. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2895. * @param otherVector defines the second operand
  2896. * @param result defines the Vector3 object where to store the result
  2897. * @returns the current Vector3
  2898. */
  2899. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2900. result.x = this.x - otherVector.x;
  2901. result.y = this.y - otherVector.y;
  2902. result.z = this.z - otherVector.z;
  2903. return this;
  2904. };
  2905. /**
  2906. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2907. * @param x defines the x coordinate of the operand
  2908. * @param y defines the y coordinate of the operand
  2909. * @param z defines the z coordinate of the operand
  2910. * @returns the resulting Vector3
  2911. */
  2912. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2913. return new Vector3(this.x - x, this.y - y, this.z - z);
  2914. };
  2915. /**
  2916. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2917. * @param x defines the x coordinate of the operand
  2918. * @param y defines the y coordinate of the operand
  2919. * @param z defines the z coordinate of the operand
  2920. * @param result defines the Vector3 object where to store the result
  2921. * @returns the current Vector3
  2922. */
  2923. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2924. result.x = this.x - x;
  2925. result.y = this.y - y;
  2926. result.z = this.z - z;
  2927. return this;
  2928. };
  2929. /**
  2930. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2931. * @returns a new Vector3
  2932. */
  2933. Vector3.prototype.negate = function () {
  2934. return new Vector3(-this.x, -this.y, -this.z);
  2935. };
  2936. /**
  2937. * Multiplies the Vector3 coordinates by the float "scale"
  2938. * @param scale defines the multiplier factor
  2939. * @returns the current updated Vector3
  2940. */
  2941. Vector3.prototype.scaleInPlace = function (scale) {
  2942. this.x *= scale;
  2943. this.y *= scale;
  2944. this.z *= scale;
  2945. return this;
  2946. };
  2947. /**
  2948. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2949. * @param scale defines the multiplier factor
  2950. * @returns a new Vector3
  2951. */
  2952. Vector3.prototype.scale = function (scale) {
  2953. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2954. };
  2955. /**
  2956. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2957. * @param scale defines the multiplier factor
  2958. * @param result defines the Vector3 object where to store the result
  2959. * @returns the current Vector3
  2960. */
  2961. Vector3.prototype.scaleToRef = function (scale, result) {
  2962. result.x = this.x * scale;
  2963. result.y = this.y * scale;
  2964. result.z = this.z * scale;
  2965. return this;
  2966. };
  2967. /**
  2968. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2969. * @param scale defines the scale factor
  2970. * @param result defines the Vector3 object where to store the result
  2971. * @returns the unmodified current Vector3
  2972. */
  2973. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2974. result.x += this.x * scale;
  2975. result.y += this.y * scale;
  2976. result.z += this.z * scale;
  2977. return this;
  2978. };
  2979. /**
  2980. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2981. * @param otherVector defines the second operand
  2982. * @returns true if both vectors are equals
  2983. */
  2984. Vector3.prototype.equals = function (otherVector) {
  2985. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2986. };
  2987. /**
  2988. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2989. * @param otherVector defines the second operand
  2990. * @param epsilon defines the minimal distance to define values as equals
  2991. * @returns true if both vectors are distant less than epsilon
  2992. */
  2993. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2994. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2995. 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);
  2996. };
  2997. /**
  2998. * Returns true if the current Vector3 coordinates equals the given floats
  2999. * @param x defines the x coordinate of the operand
  3000. * @param y defines the y coordinate of the operand
  3001. * @param z defines the z coordinate of the operand
  3002. * @returns true if both vectors are equals
  3003. */
  3004. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3005. return this.x === x && this.y === y && this.z === z;
  3006. };
  3007. /**
  3008. * Multiplies the current Vector3 coordinates by the given ones
  3009. * @param otherVector defines the second operand
  3010. * @returns the current updated Vector3
  3011. */
  3012. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3013. this.x *= otherVector.x;
  3014. this.y *= otherVector.y;
  3015. this.z *= otherVector.z;
  3016. return this;
  3017. };
  3018. /**
  3019. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3020. * @param otherVector defines the second operand
  3021. * @returns the new Vector3
  3022. */
  3023. Vector3.prototype.multiply = function (otherVector) {
  3024. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3025. };
  3026. /**
  3027. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3028. * @param otherVector defines the second operand
  3029. * @param result defines the Vector3 object where to store the result
  3030. * @returns the current Vector3
  3031. */
  3032. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3033. result.x = this.x * otherVector.x;
  3034. result.y = this.y * otherVector.y;
  3035. result.z = this.z * otherVector.z;
  3036. return this;
  3037. };
  3038. /**
  3039. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3040. * @param x defines the x coordinate of the operand
  3041. * @param y defines the y coordinate of the operand
  3042. * @param z defines the z coordinate of the operand
  3043. * @returns the new Vector3
  3044. */
  3045. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3046. return new Vector3(this.x * x, this.y * y, this.z * z);
  3047. };
  3048. /**
  3049. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3050. * @param otherVector defines the second operand
  3051. * @returns the new Vector3
  3052. */
  3053. Vector3.prototype.divide = function (otherVector) {
  3054. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3055. };
  3056. /**
  3057. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3058. * @param otherVector defines the second operand
  3059. * @param result defines the Vector3 object where to store the result
  3060. * @returns the current Vector3
  3061. */
  3062. Vector3.prototype.divideToRef = function (otherVector, result) {
  3063. result.x = this.x / otherVector.x;
  3064. result.y = this.y / otherVector.y;
  3065. result.z = this.z / otherVector.z;
  3066. return this;
  3067. };
  3068. /**
  3069. * Divides the current Vector3 coordinates by the given ones.
  3070. * @param otherVector defines the second operand
  3071. * @returns the current updated Vector3
  3072. */
  3073. Vector3.prototype.divideInPlace = function (otherVector) {
  3074. return this.divideToRef(otherVector, this);
  3075. };
  3076. /**
  3077. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3078. * @param other defines the second operand
  3079. * @returns the current updated Vector3
  3080. */
  3081. Vector3.prototype.minimizeInPlace = function (other) {
  3082. if (other.x < this.x)
  3083. this.x = other.x;
  3084. if (other.y < this.y)
  3085. this.y = other.y;
  3086. if (other.z < this.z)
  3087. this.z = other.z;
  3088. return this;
  3089. };
  3090. /**
  3091. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3092. * @param other defines the second operand
  3093. * @returns the current updated Vector3
  3094. */
  3095. Vector3.prototype.maximizeInPlace = function (other) {
  3096. if (other.x > this.x)
  3097. this.x = other.x;
  3098. if (other.y > this.y)
  3099. this.y = other.y;
  3100. if (other.z > this.z)
  3101. this.z = other.z;
  3102. return this;
  3103. };
  3104. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3105. /**
  3106. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3107. */
  3108. get: function () {
  3109. var absX = Math.abs(this.x);
  3110. var absY = Math.abs(this.y);
  3111. if (absX !== absY) {
  3112. return true;
  3113. }
  3114. var absZ = Math.abs(this.z);
  3115. if (absX !== absZ) {
  3116. return true;
  3117. }
  3118. if (absY !== absZ) {
  3119. return true;
  3120. }
  3121. return false;
  3122. },
  3123. enumerable: true,
  3124. configurable: true
  3125. });
  3126. // Properties
  3127. /**
  3128. * Gets the length of the Vector3
  3129. * @returns the length of the Vecto3
  3130. */
  3131. Vector3.prototype.length = function () {
  3132. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3133. };
  3134. /**
  3135. * Gets the squared length of the Vector3
  3136. * @returns squared length of the Vector3
  3137. */
  3138. Vector3.prototype.lengthSquared = function () {
  3139. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3140. };
  3141. /**
  3142. * Normalize the current Vector3.
  3143. * Please note that this is an in place operation.
  3144. * @returns the current updated Vector3
  3145. */
  3146. Vector3.prototype.normalize = function () {
  3147. var len = this.length();
  3148. if (len === 0 || len === 1.0)
  3149. return this;
  3150. var num = 1.0 / len;
  3151. this.x *= num;
  3152. this.y *= num;
  3153. this.z *= num;
  3154. return this;
  3155. };
  3156. /**
  3157. * Normalize the current Vector3 to a new vector
  3158. * @returns the new Vector3
  3159. */
  3160. Vector3.prototype.normalizeToNew = function () {
  3161. var normalized = new Vector3(0, 0, 0);
  3162. this.normalizeToRef(normalized);
  3163. return normalized;
  3164. };
  3165. /**
  3166. * Normalize the current Vector3 to the reference
  3167. * @param reference define the Vector3 to update
  3168. * @returns the updated Vector3
  3169. */
  3170. Vector3.prototype.normalizeToRef = function (reference) {
  3171. var len = this.length();
  3172. if (len === 0 || len === 1.0) {
  3173. reference.set(this.x, this.y, this.z);
  3174. return reference;
  3175. }
  3176. var scale = 1.0 / len;
  3177. this.scaleToRef(scale, reference);
  3178. return reference;
  3179. };
  3180. /**
  3181. * Creates a new Vector3 copied from the current Vector3
  3182. * @returns the new Vector3
  3183. */
  3184. Vector3.prototype.clone = function () {
  3185. return new Vector3(this.x, this.y, this.z);
  3186. };
  3187. /**
  3188. * Copies the given vector coordinates to the current Vector3 ones
  3189. * @param source defines the source Vector3
  3190. * @returns the current updated Vector3
  3191. */
  3192. Vector3.prototype.copyFrom = function (source) {
  3193. this.x = source.x;
  3194. this.y = source.y;
  3195. this.z = source.z;
  3196. return this;
  3197. };
  3198. /**
  3199. * Copies the given floats to the current Vector3 coordinates
  3200. * @param x defines the x coordinate of the operand
  3201. * @param y defines the y coordinate of the operand
  3202. * @param z defines the z coordinate of the operand
  3203. * @returns the current updated Vector3
  3204. */
  3205. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3206. this.x = x;
  3207. this.y = y;
  3208. this.z = z;
  3209. return this;
  3210. };
  3211. /**
  3212. * Copies the given floats to the current Vector3 coordinates
  3213. * @param x defines the x coordinate of the operand
  3214. * @param y defines the y coordinate of the operand
  3215. * @param z defines the z coordinate of the operand
  3216. * @returns the current updated Vector3
  3217. */
  3218. Vector3.prototype.set = function (x, y, z) {
  3219. return this.copyFromFloats(x, y, z);
  3220. };
  3221. // Statics
  3222. /**
  3223. * Get the clip factor between two vectors
  3224. * @param vector0 defines the first operand
  3225. * @param vector1 defines the second operand
  3226. * @param axis defines the axis to use
  3227. * @param size defines the size along the axis
  3228. * @returns the clip factor
  3229. */
  3230. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3231. var d0 = Vector3.Dot(vector0, axis) - size;
  3232. var d1 = Vector3.Dot(vector1, axis) - size;
  3233. var s = d0 / (d0 - d1);
  3234. return s;
  3235. };
  3236. /**
  3237. * Get angle between two vectors
  3238. * @param vector0 angle between vector0 and vector1
  3239. * @param vector1 angle between vector0 and vector1
  3240. * @param normal direction of the normal
  3241. * @return the angle between vector0 and vector1
  3242. */
  3243. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3244. var v0 = vector0.clone().normalize();
  3245. var v1 = vector1.clone().normalize();
  3246. var dot = Vector3.Dot(v0, v1);
  3247. var n = Vector3.Cross(v0, v1);
  3248. if (Vector3.Dot(n, normal) > 0) {
  3249. return Math.acos(dot);
  3250. }
  3251. return -Math.acos(dot);
  3252. };
  3253. /**
  3254. * Returns a new Vector3 set from the index "offset" of the given array
  3255. * @param array defines the source array
  3256. * @param offset defines the offset in the source array
  3257. * @returns the new Vector3
  3258. */
  3259. Vector3.FromArray = function (array, offset) {
  3260. if (!offset) {
  3261. offset = 0;
  3262. }
  3263. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3264. };
  3265. /**
  3266. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3267. * This function is deprecated. Use FromArray instead
  3268. * @param array defines the source array
  3269. * @param offset defines the offset in the source array
  3270. * @returns the new Vector3
  3271. */
  3272. Vector3.FromFloatArray = function (array, offset) {
  3273. return Vector3.FromArray(array, offset);
  3274. };
  3275. /**
  3276. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3277. * @param array defines the source array
  3278. * @param offset defines the offset in the source array
  3279. * @param result defines the Vector3 where to store the result
  3280. */
  3281. Vector3.FromArrayToRef = function (array, offset, result) {
  3282. result.x = array[offset];
  3283. result.y = array[offset + 1];
  3284. result.z = array[offset + 2];
  3285. };
  3286. /**
  3287. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3288. * This function is deprecated. Use FromArrayToRef instead.
  3289. * @param array defines the source array
  3290. * @param offset defines the offset in the source array
  3291. * @param result defines the Vector3 where to store the result
  3292. */
  3293. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3294. return Vector3.FromArrayToRef(array, offset, result);
  3295. };
  3296. /**
  3297. * Sets the given vector "result" with the given floats.
  3298. * @param x defines the x coordinate of the source
  3299. * @param y defines the y coordinate of the source
  3300. * @param z defines the z coordinate of the source
  3301. * @param result defines the Vector3 where to store the result
  3302. */
  3303. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3304. result.x = x;
  3305. result.y = y;
  3306. result.z = z;
  3307. };
  3308. /**
  3309. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3310. * @returns a new empty Vector3
  3311. */
  3312. Vector3.Zero = function () {
  3313. return new Vector3(0.0, 0.0, 0.0);
  3314. };
  3315. /**
  3316. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3317. * @returns a new unit Vector3
  3318. */
  3319. Vector3.One = function () {
  3320. return new Vector3(1.0, 1.0, 1.0);
  3321. };
  3322. /**
  3323. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3324. * @returns a new up Vector3
  3325. */
  3326. Vector3.Up = function () {
  3327. return new Vector3(0.0, 1.0, 0.0);
  3328. };
  3329. /**
  3330. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3331. * @returns a new forward Vector3
  3332. */
  3333. Vector3.Forward = function () {
  3334. return new Vector3(0.0, 0.0, 1.0);
  3335. };
  3336. /**
  3337. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3338. * @returns a new right Vector3
  3339. */
  3340. Vector3.Right = function () {
  3341. return new Vector3(1.0, 0.0, 0.0);
  3342. };
  3343. /**
  3344. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3345. * @returns a new left Vector3
  3346. */
  3347. Vector3.Left = function () {
  3348. return new Vector3(-1.0, 0.0, 0.0);
  3349. };
  3350. /**
  3351. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3352. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3353. * @param vector defines the Vector3 to transform
  3354. * @param transformation defines the transformation matrix
  3355. * @returns the transformed Vector3
  3356. */
  3357. Vector3.TransformCoordinates = function (vector, transformation) {
  3358. var result = Vector3.Zero();
  3359. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3360. return result;
  3361. };
  3362. /**
  3363. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3364. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3365. * @param vector defines the Vector3 to transform
  3366. * @param transformation defines the transformation matrix
  3367. * @param result defines the Vector3 where to store the result
  3368. */
  3369. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3370. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3371. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3372. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3373. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3374. result.x = x / w;
  3375. result.y = y / w;
  3376. result.z = z / w;
  3377. };
  3378. /**
  3379. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3380. * This method computes tranformed coordinates only, not transformed direction vectors
  3381. * @param x define the x coordinate of the source vector
  3382. * @param y define the y coordinate of the source vector
  3383. * @param z define the z coordinate of the source vector
  3384. * @param transformation defines the transformation matrix
  3385. * @param result defines the Vector3 where to store the result
  3386. */
  3387. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3388. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3389. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3390. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3391. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3392. result.x = rx / rw;
  3393. result.y = ry / rw;
  3394. result.z = rz / rw;
  3395. };
  3396. /**
  3397. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3398. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3399. * @param vector defines the Vector3 to transform
  3400. * @param transformation defines the transformation matrix
  3401. * @returns the new Vector3
  3402. */
  3403. Vector3.TransformNormal = function (vector, transformation) {
  3404. var result = Vector3.Zero();
  3405. Vector3.TransformNormalToRef(vector, transformation, result);
  3406. return result;
  3407. };
  3408. /**
  3409. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3410. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3411. * @param vector defines the Vector3 to transform
  3412. * @param transformation defines the transformation matrix
  3413. * @param result defines the Vector3 where to store the result
  3414. */
  3415. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3416. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3417. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3418. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3419. result.x = x;
  3420. result.y = y;
  3421. result.z = z;
  3422. };
  3423. /**
  3424. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3425. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3426. * @param x define the x coordinate of the source vector
  3427. * @param y define the y coordinate of the source vector
  3428. * @param z define the z coordinate of the source vector
  3429. * @param transformation defines the transformation matrix
  3430. * @param result defines the Vector3 where to store the result
  3431. */
  3432. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3433. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3434. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3435. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3436. };
  3437. /**
  3438. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3439. * @param value1 defines the first control point
  3440. * @param value2 defines the second control point
  3441. * @param value3 defines the third control point
  3442. * @param value4 defines the fourth control point
  3443. * @param amount defines the amount on the spline to use
  3444. * @returns the new Vector3
  3445. */
  3446. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3447. var squared = amount * amount;
  3448. var cubed = amount * squared;
  3449. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3450. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3451. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3452. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3453. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3454. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3455. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3456. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3457. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3458. return new Vector3(x, y, z);
  3459. };
  3460. /**
  3461. * 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"
  3462. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3463. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3464. * @param value defines the current value
  3465. * @param min defines the lower range value
  3466. * @param max defines the upper range value
  3467. * @returns the new Vector3
  3468. */
  3469. Vector3.Clamp = function (value, min, max) {
  3470. var x = value.x;
  3471. x = (x > max.x) ? max.x : x;
  3472. x = (x < min.x) ? min.x : x;
  3473. var y = value.y;
  3474. y = (y > max.y) ? max.y : y;
  3475. y = (y < min.y) ? min.y : y;
  3476. var z = value.z;
  3477. z = (z > max.z) ? max.z : z;
  3478. z = (z < min.z) ? min.z : z;
  3479. return new Vector3(x, y, z);
  3480. };
  3481. /**
  3482. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3483. * @param value1 defines the first control point
  3484. * @param tangent1 defines the first tangent vector
  3485. * @param value2 defines the second control point
  3486. * @param tangent2 defines the second tangent vector
  3487. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3488. * @returns the new Vector3
  3489. */
  3490. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3491. var squared = amount * amount;
  3492. var cubed = amount * squared;
  3493. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3494. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3495. var part3 = (cubed - (2.0 * squared)) + amount;
  3496. var part4 = cubed - squared;
  3497. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3498. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3499. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3500. return new Vector3(x, y, z);
  3501. };
  3502. /**
  3503. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3504. * @param start defines the start value
  3505. * @param end defines the end value
  3506. * @param amount max defines amount between both (between 0 and 1)
  3507. * @returns the new Vector3
  3508. */
  3509. Vector3.Lerp = function (start, end, amount) {
  3510. var result = new Vector3(0, 0, 0);
  3511. Vector3.LerpToRef(start, end, amount, result);
  3512. return result;
  3513. };
  3514. /**
  3515. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3516. * @param start defines the start value
  3517. * @param end defines the end value
  3518. * @param amount max defines amount between both (between 0 and 1)
  3519. * @param result defines the Vector3 where to store the result
  3520. */
  3521. Vector3.LerpToRef = function (start, end, amount, result) {
  3522. result.x = start.x + ((end.x - start.x) * amount);
  3523. result.y = start.y + ((end.y - start.y) * amount);
  3524. result.z = start.z + ((end.z - start.z) * amount);
  3525. };
  3526. /**
  3527. * Returns the dot product (float) between the vectors "left" and "right"
  3528. * @param left defines the left operand
  3529. * @param right defines the right operand
  3530. * @returns the dot product
  3531. */
  3532. Vector3.Dot = function (left, right) {
  3533. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3534. };
  3535. /**
  3536. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3537. * The cross product is then orthogonal to both "left" and "right"
  3538. * @param left defines the left operand
  3539. * @param right defines the right operand
  3540. * @returns the cross product
  3541. */
  3542. Vector3.Cross = function (left, right) {
  3543. var result = Vector3.Zero();
  3544. Vector3.CrossToRef(left, right, result);
  3545. return result;
  3546. };
  3547. /**
  3548. * Sets the given vector "result" with the cross product of "left" and "right"
  3549. * The cross product is then orthogonal to both "left" and "right"
  3550. * @param left defines the left operand
  3551. * @param right defines the right operand
  3552. * @param result defines the Vector3 where to store the result
  3553. */
  3554. Vector3.CrossToRef = function (left, right, result) {
  3555. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3556. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3557. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3558. result.copyFrom(MathTmp.Vector3[0]);
  3559. };
  3560. /**
  3561. * Returns a new Vector3 as the normalization of the given vector
  3562. * @param vector defines the Vector3 to normalize
  3563. * @returns the new Vector3
  3564. */
  3565. Vector3.Normalize = function (vector) {
  3566. var result = Vector3.Zero();
  3567. Vector3.NormalizeToRef(vector, result);
  3568. return result;
  3569. };
  3570. /**
  3571. * Sets the given vector "result" with the normalization of the given first vector
  3572. * @param vector defines the Vector3 to normalize
  3573. * @param result defines the Vector3 where to store the result
  3574. */
  3575. Vector3.NormalizeToRef = function (vector, result) {
  3576. result.copyFrom(vector);
  3577. result.normalize();
  3578. };
  3579. /**
  3580. * Project a Vector3 onto screen space
  3581. * @param vector defines the Vector3 to project
  3582. * @param world defines the world matrix to use
  3583. * @param transform defines the transform (view x projection) matrix to use
  3584. * @param viewport defines the screen viewport to use
  3585. * @returns the new Vector3
  3586. */
  3587. Vector3.Project = function (vector, world, transform, viewport) {
  3588. var cw = viewport.width;
  3589. var ch = viewport.height;
  3590. var cx = viewport.x;
  3591. var cy = viewport.y;
  3592. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3593. 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);
  3594. var matrix = MathTmp.Matrix[0];
  3595. world.multiplyToRef(transform, matrix);
  3596. matrix.multiplyToRef(viewportMatrix, matrix);
  3597. return Vector3.TransformCoordinates(vector, matrix);
  3598. };
  3599. /**
  3600. * Unproject from screen space to object space
  3601. * @param source defines the screen space Vector3 to use
  3602. * @param viewportWidth defines the current width of the viewport
  3603. * @param viewportHeight defines the current height of the viewport
  3604. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3605. * @param transform defines the transform (view x projection) matrix to use
  3606. * @returns the new Vector3
  3607. */
  3608. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3609. var matrix = MathTmp.Matrix[0];
  3610. world.multiplyToRef(transform, matrix);
  3611. matrix.invert();
  3612. source.x = source.x / viewportWidth * 2 - 1;
  3613. source.y = -(source.y / viewportHeight * 2 - 1);
  3614. var vector = Vector3.TransformCoordinates(source, matrix);
  3615. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3616. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3617. vector = vector.scale(1.0 / num);
  3618. }
  3619. return vector;
  3620. };
  3621. /**
  3622. * Unproject from screen space to object space
  3623. * @param source defines the screen space Vector3 to use
  3624. * @param viewportWidth defines the current width of the viewport
  3625. * @param viewportHeight defines the current height of the viewport
  3626. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3627. * @param view defines the view matrix to use
  3628. * @param projection defines the projection matrix to use
  3629. * @returns the new Vector3
  3630. */
  3631. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3632. var result = Vector3.Zero();
  3633. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3634. return result;
  3635. };
  3636. /**
  3637. * Unproject from screen space to object space
  3638. * @param source defines the screen space Vector3 to use
  3639. * @param viewportWidth defines the current width of the viewport
  3640. * @param viewportHeight defines the current height of the viewport
  3641. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3642. * @param view defines the view matrix to use
  3643. * @param projection defines the projection matrix to use
  3644. * @param result defines the Vector3 where to store the result
  3645. */
  3646. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3647. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3648. };
  3649. /**
  3650. * Unproject from screen space to object space
  3651. * @param sourceX defines the screen space x coordinate to use
  3652. * @param sourceY defines the screen space y coordinate to use
  3653. * @param sourceZ defines the screen space z coordinate to use
  3654. * @param viewportWidth defines the current width of the viewport
  3655. * @param viewportHeight defines the current height of the viewport
  3656. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3657. * @param view defines the view matrix to use
  3658. * @param projection defines the projection matrix to use
  3659. * @param result defines the Vector3 where to store the result
  3660. */
  3661. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3662. var matrix = MathTmp.Matrix[0];
  3663. world.multiplyToRef(view, matrix);
  3664. matrix.multiplyToRef(projection, matrix);
  3665. matrix.invert();
  3666. var screenSource = MathTmp.Vector3[0];
  3667. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3668. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3669. screenSource.z = 2 * sourceZ - 1.0;
  3670. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3671. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3672. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3673. result.scaleInPlace(1.0 / num);
  3674. }
  3675. };
  3676. /**
  3677. * Gets the minimal coordinate values between two Vector3
  3678. * @param left defines the first operand
  3679. * @param right defines the second operand
  3680. * @returns the new Vector3
  3681. */
  3682. Vector3.Minimize = function (left, right) {
  3683. var min = left.clone();
  3684. min.minimizeInPlace(right);
  3685. return min;
  3686. };
  3687. /**
  3688. * Gets the maximal coordinate values between two Vector3
  3689. * @param left defines the first operand
  3690. * @param right defines the second operand
  3691. * @returns the new Vector3
  3692. */
  3693. Vector3.Maximize = function (left, right) {
  3694. var max = left.clone();
  3695. max.maximizeInPlace(right);
  3696. return max;
  3697. };
  3698. /**
  3699. * Returns the distance between the vectors "value1" and "value2"
  3700. * @param value1 defines the first operand
  3701. * @param value2 defines the second operand
  3702. * @returns the distance
  3703. */
  3704. Vector3.Distance = function (value1, value2) {
  3705. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3706. };
  3707. /**
  3708. * Returns the squared distance between the vectors "value1" and "value2"
  3709. * @param value1 defines the first operand
  3710. * @param value2 defines the second operand
  3711. * @returns the squared distance
  3712. */
  3713. Vector3.DistanceSquared = function (value1, value2) {
  3714. var x = value1.x - value2.x;
  3715. var y = value1.y - value2.y;
  3716. var z = value1.z - value2.z;
  3717. return (x * x) + (y * y) + (z * z);
  3718. };
  3719. /**
  3720. * Returns a new Vector3 located at the center between "value1" and "value2"
  3721. * @param value1 defines the first operand
  3722. * @param value2 defines the second operand
  3723. * @returns the new Vector3
  3724. */
  3725. Vector3.Center = function (value1, value2) {
  3726. var center = value1.add(value2);
  3727. center.scaleInPlace(0.5);
  3728. return center;
  3729. };
  3730. /**
  3731. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3732. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3733. * to something in order to rotate it from its local system to the given target system
  3734. * Note: axis1, axis2 and axis3 are normalized during this operation
  3735. * @param axis1 defines the first axis
  3736. * @param axis2 defines the second axis
  3737. * @param axis3 defines the third axis
  3738. * @returns a new Vector3
  3739. */
  3740. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3741. var rotation = Vector3.Zero();
  3742. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3743. return rotation;
  3744. };
  3745. /**
  3746. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3747. * @param axis1 defines the first axis
  3748. * @param axis2 defines the second axis
  3749. * @param axis3 defines the third axis
  3750. * @param ref defines the Vector3 where to store the result
  3751. */
  3752. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3753. var quat = MathTmp.Quaternion[0];
  3754. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3755. quat.toEulerAnglesToRef(ref);
  3756. };
  3757. return Vector3;
  3758. }());
  3759. BABYLON.Vector3 = Vector3;
  3760. //Vector4 class created for EulerAngle class conversion to Quaternion
  3761. var Vector4 = /** @class */ (function () {
  3762. /**
  3763. * Creates a Vector4 object from the given floats.
  3764. */
  3765. function Vector4(x, y, z, w) {
  3766. this.x = x;
  3767. this.y = y;
  3768. this.z = z;
  3769. this.w = w;
  3770. }
  3771. /**
  3772. * Returns the string with the Vector4 coordinates.
  3773. */
  3774. Vector4.prototype.toString = function () {
  3775. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3776. };
  3777. /**
  3778. * Returns the string "Vector4".
  3779. */
  3780. Vector4.prototype.getClassName = function () {
  3781. return "Vector4";
  3782. };
  3783. /**
  3784. * Returns the Vector4 hash code.
  3785. */
  3786. Vector4.prototype.getHashCode = function () {
  3787. var hash = this.x || 0;
  3788. hash = (hash * 397) ^ (this.y || 0);
  3789. hash = (hash * 397) ^ (this.z || 0);
  3790. hash = (hash * 397) ^ (this.w || 0);
  3791. return hash;
  3792. };
  3793. // Operators
  3794. /**
  3795. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3796. */
  3797. Vector4.prototype.asArray = function () {
  3798. var result = new Array();
  3799. this.toArray(result, 0);
  3800. return result;
  3801. };
  3802. /**
  3803. * Populates the given array from the given index with the Vector4 coordinates.
  3804. * Returns the Vector4.
  3805. */
  3806. Vector4.prototype.toArray = function (array, index) {
  3807. if (index === undefined) {
  3808. index = 0;
  3809. }
  3810. array[index] = this.x;
  3811. array[index + 1] = this.y;
  3812. array[index + 2] = this.z;
  3813. array[index + 3] = this.w;
  3814. return this;
  3815. };
  3816. /**
  3817. * Adds the given vector to the current Vector4.
  3818. * Returns the updated Vector4.
  3819. */
  3820. Vector4.prototype.addInPlace = function (otherVector) {
  3821. this.x += otherVector.x;
  3822. this.y += otherVector.y;
  3823. this.z += otherVector.z;
  3824. this.w += otherVector.w;
  3825. return this;
  3826. };
  3827. /**
  3828. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3829. */
  3830. Vector4.prototype.add = function (otherVector) {
  3831. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3832. };
  3833. /**
  3834. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3835. * Returns the current Vector4.
  3836. */
  3837. Vector4.prototype.addToRef = function (otherVector, result) {
  3838. result.x = this.x + otherVector.x;
  3839. result.y = this.y + otherVector.y;
  3840. result.z = this.z + otherVector.z;
  3841. result.w = this.w + otherVector.w;
  3842. return this;
  3843. };
  3844. /**
  3845. * Subtract in place the given vector from the current Vector4.
  3846. * Returns the updated Vector4.
  3847. */
  3848. Vector4.prototype.subtractInPlace = function (otherVector) {
  3849. this.x -= otherVector.x;
  3850. this.y -= otherVector.y;
  3851. this.z -= otherVector.z;
  3852. this.w -= otherVector.w;
  3853. return this;
  3854. };
  3855. /**
  3856. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3857. */
  3858. Vector4.prototype.subtract = function (otherVector) {
  3859. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3860. };
  3861. /**
  3862. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3863. * Returns the current Vector4.
  3864. */
  3865. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3866. result.x = this.x - otherVector.x;
  3867. result.y = this.y - otherVector.y;
  3868. result.z = this.z - otherVector.z;
  3869. result.w = this.w - otherVector.w;
  3870. return this;
  3871. };
  3872. /**
  3873. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3874. */
  3875. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3876. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3877. };
  3878. /**
  3879. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3880. * Returns the current Vector4.
  3881. */
  3882. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3883. result.x = this.x - x;
  3884. result.y = this.y - y;
  3885. result.z = this.z - z;
  3886. result.w = this.w - w;
  3887. return this;
  3888. };
  3889. /**
  3890. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3891. */
  3892. Vector4.prototype.negate = function () {
  3893. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3894. };
  3895. /**
  3896. * Multiplies the current Vector4 coordinates by scale (float).
  3897. * Returns the updated Vector4.
  3898. */
  3899. Vector4.prototype.scaleInPlace = function (scale) {
  3900. this.x *= scale;
  3901. this.y *= scale;
  3902. this.z *= scale;
  3903. this.w *= scale;
  3904. return this;
  3905. };
  3906. /**
  3907. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3908. */
  3909. Vector4.prototype.scale = function (scale) {
  3910. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3911. };
  3912. /**
  3913. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3914. * Returns the current Vector4.
  3915. */
  3916. Vector4.prototype.scaleToRef = function (scale, result) {
  3917. result.x = this.x * scale;
  3918. result.y = this.y * scale;
  3919. result.z = this.z * scale;
  3920. result.w = this.w * scale;
  3921. return this;
  3922. };
  3923. /**
  3924. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3925. * @param scale defines the scale factor
  3926. * @param result defines the Vector4 object where to store the result
  3927. * @returns the unmodified current Vector4
  3928. */
  3929. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3930. result.x += this.x * scale;
  3931. result.y += this.y * scale;
  3932. result.z += this.z * scale;
  3933. result.w += this.w * scale;
  3934. return this;
  3935. };
  3936. /**
  3937. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3938. */
  3939. Vector4.prototype.equals = function (otherVector) {
  3940. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3941. };
  3942. /**
  3943. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3944. */
  3945. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3946. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3947. return otherVector
  3948. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3949. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3950. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3951. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3952. };
  3953. /**
  3954. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3955. */
  3956. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3957. return this.x === x && this.y === y && this.z === z && this.w === w;
  3958. };
  3959. /**
  3960. * Multiplies in place the current Vector4 by the given one.
  3961. * Returns the updated Vector4.
  3962. */
  3963. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3964. this.x *= otherVector.x;
  3965. this.y *= otherVector.y;
  3966. this.z *= otherVector.z;
  3967. this.w *= otherVector.w;
  3968. return this;
  3969. };
  3970. /**
  3971. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3972. */
  3973. Vector4.prototype.multiply = function (otherVector) {
  3974. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3975. };
  3976. /**
  3977. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3978. * Returns the current Vector4.
  3979. */
  3980. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3981. result.x = this.x * otherVector.x;
  3982. result.y = this.y * otherVector.y;
  3983. result.z = this.z * otherVector.z;
  3984. result.w = this.w * otherVector.w;
  3985. return this;
  3986. };
  3987. /**
  3988. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3989. */
  3990. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3991. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3992. };
  3993. /**
  3994. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3995. */
  3996. Vector4.prototype.divide = function (otherVector) {
  3997. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3998. };
  3999. /**
  4000. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4001. * Returns the current Vector4.
  4002. */
  4003. Vector4.prototype.divideToRef = function (otherVector, result) {
  4004. result.x = this.x / otherVector.x;
  4005. result.y = this.y / otherVector.y;
  4006. result.z = this.z / otherVector.z;
  4007. result.w = this.w / otherVector.w;
  4008. return this;
  4009. };
  4010. /**
  4011. * Divides the current Vector3 coordinates by the given ones.
  4012. * @returns the updated Vector3.
  4013. */
  4014. Vector4.prototype.divideInPlace = function (otherVector) {
  4015. return this.divideToRef(otherVector, this);
  4016. };
  4017. /**
  4018. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4019. * @param other defines the second operand
  4020. * @returns the current updated Vector4
  4021. */
  4022. Vector4.prototype.minimizeInPlace = function (other) {
  4023. if (other.x < this.x)
  4024. this.x = other.x;
  4025. if (other.y < this.y)
  4026. this.y = other.y;
  4027. if (other.z < this.z)
  4028. this.z = other.z;
  4029. if (other.w < this.w)
  4030. this.w = other.w;
  4031. return this;
  4032. };
  4033. /**
  4034. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4035. * @param other defines the second operand
  4036. * @returns the current updated Vector4
  4037. */
  4038. Vector4.prototype.maximizeInPlace = function (other) {
  4039. if (other.x > this.x)
  4040. this.x = other.x;
  4041. if (other.y > this.y)
  4042. this.y = other.y;
  4043. if (other.z > this.z)
  4044. this.z = other.z;
  4045. if (other.w > this.w)
  4046. this.w = other.w;
  4047. return this;
  4048. };
  4049. // Properties
  4050. /**
  4051. * Returns the Vector4 length (float).
  4052. */
  4053. Vector4.prototype.length = function () {
  4054. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4055. };
  4056. /**
  4057. * Returns the Vector4 squared length (float).
  4058. */
  4059. Vector4.prototype.lengthSquared = function () {
  4060. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4061. };
  4062. // Methods
  4063. /**
  4064. * Normalizes in place the Vector4.
  4065. * Returns the updated Vector4.
  4066. */
  4067. Vector4.prototype.normalize = function () {
  4068. var len = this.length();
  4069. if (len === 0)
  4070. return this;
  4071. var num = 1.0 / len;
  4072. this.x *= num;
  4073. this.y *= num;
  4074. this.z *= num;
  4075. this.w *= num;
  4076. return this;
  4077. };
  4078. /**
  4079. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4080. */
  4081. Vector4.prototype.toVector3 = function () {
  4082. return new Vector3(this.x, this.y, this.z);
  4083. };
  4084. /**
  4085. * Returns a new Vector4 copied from the current one.
  4086. */
  4087. Vector4.prototype.clone = function () {
  4088. return new Vector4(this.x, this.y, this.z, this.w);
  4089. };
  4090. /**
  4091. * Updates the current Vector4 with the given one coordinates.
  4092. * Returns the updated Vector4.
  4093. */
  4094. Vector4.prototype.copyFrom = function (source) {
  4095. this.x = source.x;
  4096. this.y = source.y;
  4097. this.z = source.z;
  4098. this.w = source.w;
  4099. return this;
  4100. };
  4101. /**
  4102. * Updates the current Vector4 coordinates with the given floats.
  4103. * Returns the updated Vector4.
  4104. */
  4105. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4106. this.x = x;
  4107. this.y = y;
  4108. this.z = z;
  4109. this.w = w;
  4110. return this;
  4111. };
  4112. /**
  4113. * Updates the current Vector4 coordinates with the given floats.
  4114. * Returns the updated Vector4.
  4115. */
  4116. Vector4.prototype.set = function (x, y, z, w) {
  4117. return this.copyFromFloats(x, y, z, w);
  4118. };
  4119. // Statics
  4120. /**
  4121. * Returns a new Vector4 set from the starting index of the given array.
  4122. */
  4123. Vector4.FromArray = function (array, offset) {
  4124. if (!offset) {
  4125. offset = 0;
  4126. }
  4127. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4128. };
  4129. /**
  4130. * Updates the given vector "result" from the starting index of the given array.
  4131. */
  4132. Vector4.FromArrayToRef = function (array, offset, result) {
  4133. result.x = array[offset];
  4134. result.y = array[offset + 1];
  4135. result.z = array[offset + 2];
  4136. result.w = array[offset + 3];
  4137. };
  4138. /**
  4139. * Updates the given vector "result" from the starting index of the given Float32Array.
  4140. */
  4141. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4142. Vector4.FromArrayToRef(array, offset, result);
  4143. };
  4144. /**
  4145. * Updates the given vector "result" coordinates from the given floats.
  4146. */
  4147. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4148. result.x = x;
  4149. result.y = y;
  4150. result.z = z;
  4151. result.w = w;
  4152. };
  4153. /**
  4154. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4155. */
  4156. Vector4.Zero = function () {
  4157. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4158. };
  4159. /**
  4160. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4161. */
  4162. Vector4.One = function () {
  4163. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4164. };
  4165. /**
  4166. * Returns a new normalized Vector4 from the given one.
  4167. */
  4168. Vector4.Normalize = function (vector) {
  4169. var result = Vector4.Zero();
  4170. Vector4.NormalizeToRef(vector, result);
  4171. return result;
  4172. };
  4173. /**
  4174. * Updates the given vector "result" from the normalization of the given one.
  4175. */
  4176. Vector4.NormalizeToRef = function (vector, result) {
  4177. result.copyFrom(vector);
  4178. result.normalize();
  4179. };
  4180. Vector4.Minimize = function (left, right) {
  4181. var min = left.clone();
  4182. min.minimizeInPlace(right);
  4183. return min;
  4184. };
  4185. Vector4.Maximize = function (left, right) {
  4186. var max = left.clone();
  4187. max.maximizeInPlace(right);
  4188. return max;
  4189. };
  4190. /**
  4191. * Returns the distance (float) between the vectors "value1" and "value2".
  4192. */
  4193. Vector4.Distance = function (value1, value2) {
  4194. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4195. };
  4196. /**
  4197. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4198. */
  4199. Vector4.DistanceSquared = function (value1, value2) {
  4200. var x = value1.x - value2.x;
  4201. var y = value1.y - value2.y;
  4202. var z = value1.z - value2.z;
  4203. var w = value1.w - value2.w;
  4204. return (x * x) + (y * y) + (z * z) + (w * w);
  4205. };
  4206. /**
  4207. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4208. */
  4209. Vector4.Center = function (value1, value2) {
  4210. var center = value1.add(value2);
  4211. center.scaleInPlace(0.5);
  4212. return center;
  4213. };
  4214. /**
  4215. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4216. * This methods computes transformed normalized direction vectors only.
  4217. */
  4218. Vector4.TransformNormal = function (vector, transformation) {
  4219. var result = Vector4.Zero();
  4220. Vector4.TransformNormalToRef(vector, transformation, result);
  4221. return result;
  4222. };
  4223. /**
  4224. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4225. * This methods computes transformed normalized direction vectors only.
  4226. */
  4227. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4228. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4229. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4230. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4231. result.x = x;
  4232. result.y = y;
  4233. result.z = z;
  4234. result.w = vector.w;
  4235. };
  4236. /**
  4237. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4238. * This methods computes transformed normalized direction vectors only.
  4239. */
  4240. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4241. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4242. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4243. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4244. result.w = w;
  4245. };
  4246. return Vector4;
  4247. }());
  4248. BABYLON.Vector4 = Vector4;
  4249. var Size = /** @class */ (function () {
  4250. /**
  4251. * Creates a Size object from the given width and height (floats).
  4252. */
  4253. function Size(width, height) {
  4254. this.width = width;
  4255. this.height = height;
  4256. }
  4257. // Returns a string with the Size width and height.
  4258. Size.prototype.toString = function () {
  4259. return "{W: " + this.width + ", H: " + this.height + "}";
  4260. };
  4261. /**
  4262. * Returns the string "Size"
  4263. */
  4264. Size.prototype.getClassName = function () {
  4265. return "Size";
  4266. };
  4267. /**
  4268. * Returns the Size hash code.
  4269. */
  4270. Size.prototype.getHashCode = function () {
  4271. var hash = this.width || 0;
  4272. hash = (hash * 397) ^ (this.height || 0);
  4273. return hash;
  4274. };
  4275. /**
  4276. * Updates the current size from the given one.
  4277. * Returns the updated Size.
  4278. */
  4279. Size.prototype.copyFrom = function (src) {
  4280. this.width = src.width;
  4281. this.height = src.height;
  4282. };
  4283. /**
  4284. * Updates in place the current Size from the given floats.
  4285. * Returns the updated Size.
  4286. */
  4287. Size.prototype.copyFromFloats = function (width, height) {
  4288. this.width = width;
  4289. this.height = height;
  4290. return this;
  4291. };
  4292. /**
  4293. * Updates in place the current Size from the given floats.
  4294. * Returns the updated Size.
  4295. */
  4296. Size.prototype.set = function (width, height) {
  4297. return this.copyFromFloats(width, height);
  4298. };
  4299. /**
  4300. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4301. */
  4302. Size.prototype.multiplyByFloats = function (w, h) {
  4303. return new Size(this.width * w, this.height * h);
  4304. };
  4305. /**
  4306. * Returns a new Size copied from the given one.
  4307. */
  4308. Size.prototype.clone = function () {
  4309. return new Size(this.width, this.height);
  4310. };
  4311. /**
  4312. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4313. */
  4314. Size.prototype.equals = function (other) {
  4315. if (!other) {
  4316. return false;
  4317. }
  4318. return (this.width === other.width) && (this.height === other.height);
  4319. };
  4320. Object.defineProperty(Size.prototype, "surface", {
  4321. /**
  4322. * Returns the surface of the Size : width * height (float).
  4323. */
  4324. get: function () {
  4325. return this.width * this.height;
  4326. },
  4327. enumerable: true,
  4328. configurable: true
  4329. });
  4330. /**
  4331. * Returns a new Size set to (0.0, 0.0)
  4332. */
  4333. Size.Zero = function () {
  4334. return new Size(0.0, 0.0);
  4335. };
  4336. /**
  4337. * Returns a new Size set as the addition result of the current Size and the given one.
  4338. */
  4339. Size.prototype.add = function (otherSize) {
  4340. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4341. return r;
  4342. };
  4343. /**
  4344. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4345. */
  4346. Size.prototype.subtract = function (otherSize) {
  4347. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4348. return r;
  4349. };
  4350. /**
  4351. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4352. */
  4353. Size.Lerp = function (start, end, amount) {
  4354. var w = start.width + ((end.width - start.width) * amount);
  4355. var h = start.height + ((end.height - start.height) * amount);
  4356. return new Size(w, h);
  4357. };
  4358. return Size;
  4359. }());
  4360. BABYLON.Size = Size;
  4361. /**
  4362. * Class used to store quaternion data
  4363. * @see https://en.wikipedia.org/wiki/Quaternion
  4364. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4365. */
  4366. var Quaternion = /** @class */ (function () {
  4367. /**
  4368. * Creates a new Quaternion from the given floats
  4369. * @param x defines the first component (0 by default)
  4370. * @param y defines the second component (0 by default)
  4371. * @param z defines the third component (0 by default)
  4372. * @param w defines the fourth component (1.0 by default)
  4373. */
  4374. function Quaternion(
  4375. /** defines the first component (0 by default) */
  4376. x,
  4377. /** defines the second component (0 by default) */
  4378. y,
  4379. /** defines the third component (0 by default) */
  4380. z,
  4381. /** defines the fourth component (1.0 by default) */
  4382. w) {
  4383. if (x === void 0) { x = 0.0; }
  4384. if (y === void 0) { y = 0.0; }
  4385. if (z === void 0) { z = 0.0; }
  4386. if (w === void 0) { w = 1.0; }
  4387. this.x = x;
  4388. this.y = y;
  4389. this.z = z;
  4390. this.w = w;
  4391. }
  4392. /**
  4393. * Gets a string representation for the current quaternion
  4394. * @returns a string with the Quaternion coordinates
  4395. */
  4396. Quaternion.prototype.toString = function () {
  4397. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4398. };
  4399. /**
  4400. * Gets the class name of the quaternion
  4401. * @returns the string "Quaternion"
  4402. */
  4403. Quaternion.prototype.getClassName = function () {
  4404. return "Quaternion";
  4405. };
  4406. /**
  4407. * Gets a hash code for this quaternion
  4408. * @returns the quaternion hash code
  4409. */
  4410. Quaternion.prototype.getHashCode = function () {
  4411. var hash = this.x || 0;
  4412. hash = (hash * 397) ^ (this.y || 0);
  4413. hash = (hash * 397) ^ (this.z || 0);
  4414. hash = (hash * 397) ^ (this.w || 0);
  4415. return hash;
  4416. };
  4417. /**
  4418. * Copy the quaternion to an array
  4419. * @returns a new array populated with 4 elements from the quaternion coordinates
  4420. */
  4421. Quaternion.prototype.asArray = function () {
  4422. return [this.x, this.y, this.z, this.w];
  4423. };
  4424. /**
  4425. * Check if two quaternions are equals
  4426. * @param otherQuaternion defines the second operand
  4427. * @return true if the current quaternion and the given one coordinates are strictly equals
  4428. */
  4429. Quaternion.prototype.equals = function (otherQuaternion) {
  4430. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4431. };
  4432. /**
  4433. * Clone the current quaternion
  4434. * @returns a new quaternion copied from the current one
  4435. */
  4436. Quaternion.prototype.clone = function () {
  4437. return new Quaternion(this.x, this.y, this.z, this.w);
  4438. };
  4439. /**
  4440. * Copy a quaternion to the current one
  4441. * @param other defines the other quaternion
  4442. * @returns the updated current quaternion
  4443. */
  4444. Quaternion.prototype.copyFrom = function (other) {
  4445. this.x = other.x;
  4446. this.y = other.y;
  4447. this.z = other.z;
  4448. this.w = other.w;
  4449. return this;
  4450. };
  4451. /**
  4452. * Updates the current quaternion with the given float coordinates
  4453. * @param x defines the x coordinate
  4454. * @param y defines the y coordinate
  4455. * @param z defines the z coordinate
  4456. * @param w defines the w coordinate
  4457. * @returns the updated current quaternion
  4458. */
  4459. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4460. this.x = x;
  4461. this.y = y;
  4462. this.z = z;
  4463. this.w = w;
  4464. return this;
  4465. };
  4466. /**
  4467. * Updates the current quaternion from the given float coordinates
  4468. * @param x defines the x coordinate
  4469. * @param y defines the y coordinate
  4470. * @param z defines the z coordinate
  4471. * @param w defines the w coordinate
  4472. * @returns the updated current quaternion
  4473. */
  4474. Quaternion.prototype.set = function (x, y, z, w) {
  4475. return this.copyFromFloats(x, y, z, w);
  4476. };
  4477. /**
  4478. * Adds two quaternions
  4479. * @param other defines the second operand
  4480. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4481. */
  4482. Quaternion.prototype.add = function (other) {
  4483. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4484. };
  4485. /**
  4486. * Add a quaternion to the current one
  4487. * @param other defines the quaternion to add
  4488. * @returns the current quaternion
  4489. */
  4490. Quaternion.prototype.addInPlace = function (other) {
  4491. this.x += other.x;
  4492. this.y += other.y;
  4493. this.z += other.z;
  4494. this.w += other.w;
  4495. return this;
  4496. };
  4497. /**
  4498. * Subtract two quaternions
  4499. * @param other defines the second operand
  4500. * @returns a new quaternion as the subtraction result of the given one from the current one
  4501. */
  4502. Quaternion.prototype.subtract = function (other) {
  4503. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4504. };
  4505. /**
  4506. * Multiplies the current quaternion by a scale factor
  4507. * @param value defines the scale factor
  4508. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4509. */
  4510. Quaternion.prototype.scale = function (value) {
  4511. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4512. };
  4513. /**
  4514. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4515. * @param scale defines the scale factor
  4516. * @param result defines the Quaternion object where to store the result
  4517. * @returns the unmodified current quaternion
  4518. */
  4519. Quaternion.prototype.scaleToRef = function (scale, result) {
  4520. result.x = this.x * scale;
  4521. result.y = this.y * scale;
  4522. result.z = this.z * scale;
  4523. result.w = this.w * scale;
  4524. return this;
  4525. };
  4526. /**
  4527. * Multiplies in place the current quaternion by a scale factor
  4528. * @param value defines the scale factor
  4529. * @returns the current modified quaternion
  4530. */
  4531. Quaternion.prototype.scaleInPlace = function (value) {
  4532. this.x *= value;
  4533. this.y *= value;
  4534. this.z *= value;
  4535. this.w *= value;
  4536. return this;
  4537. };
  4538. /**
  4539. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4540. * @param scale defines the scale factor
  4541. * @param result defines the Quaternion object where to store the result
  4542. * @returns the unmodified current quaternion
  4543. */
  4544. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4545. result.x += this.x * scale;
  4546. result.y += this.y * scale;
  4547. result.z += this.z * scale;
  4548. result.w += this.w * scale;
  4549. return this;
  4550. };
  4551. /**
  4552. * Multiplies two quaternions
  4553. * @param q1 defines the second operand
  4554. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4555. */
  4556. Quaternion.prototype.multiply = function (q1) {
  4557. var result = new Quaternion(0, 0, 0, 1.0);
  4558. this.multiplyToRef(q1, result);
  4559. return result;
  4560. };
  4561. /**
  4562. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4563. * @param q1 defines the second operand
  4564. * @param result defines the target quaternion
  4565. * @returns the current quaternion
  4566. */
  4567. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4568. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4569. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4570. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4571. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4572. result.copyFromFloats(x, y, z, w);
  4573. return this;
  4574. };
  4575. /**
  4576. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4577. * @param q1 defines the second operand
  4578. * @returns the currentupdated quaternion
  4579. */
  4580. Quaternion.prototype.multiplyInPlace = function (q1) {
  4581. this.multiplyToRef(q1, this);
  4582. return this;
  4583. };
  4584. /**
  4585. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4586. * @param ref defines the target quaternion
  4587. * @returns the current quaternion
  4588. */
  4589. Quaternion.prototype.conjugateToRef = function (ref) {
  4590. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4591. return this;
  4592. };
  4593. /**
  4594. * Conjugates in place (1-q) the current quaternion
  4595. * @returns the current updated quaternion
  4596. */
  4597. Quaternion.prototype.conjugateInPlace = function () {
  4598. this.x *= -1;
  4599. this.y *= -1;
  4600. this.z *= -1;
  4601. return this;
  4602. };
  4603. /**
  4604. * Conjugates in place (1-q) the current quaternion
  4605. * @returns a new quaternion
  4606. */
  4607. Quaternion.prototype.conjugate = function () {
  4608. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4609. return result;
  4610. };
  4611. /**
  4612. * Gets length of current quaternion
  4613. * @returns the quaternion length (float)
  4614. */
  4615. Quaternion.prototype.length = function () {
  4616. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4617. };
  4618. /**
  4619. * Normalize in place the current quaternion
  4620. * @returns the current updated quaternion
  4621. */
  4622. Quaternion.prototype.normalize = function () {
  4623. var length = 1.0 / this.length();
  4624. this.x *= length;
  4625. this.y *= length;
  4626. this.z *= length;
  4627. this.w *= length;
  4628. return this;
  4629. };
  4630. /**
  4631. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4632. * @param order is a reserved parameter and is ignore for now
  4633. * @returns a new Vector3 containing the Euler angles
  4634. */
  4635. Quaternion.prototype.toEulerAngles = function (order) {
  4636. if (order === void 0) { order = "YZX"; }
  4637. var result = Vector3.Zero();
  4638. this.toEulerAnglesToRef(result, order);
  4639. return result;
  4640. };
  4641. /**
  4642. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4643. * @param result defines the vector which will be filled with the Euler angles
  4644. * @param order is a reserved parameter and is ignore for now
  4645. * @returns the current unchanged quaternion
  4646. */
  4647. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4648. if (order === void 0) { order = "YZX"; }
  4649. var qz = this.z;
  4650. var qx = this.x;
  4651. var qy = this.y;
  4652. var qw = this.w;
  4653. var sqw = qw * qw;
  4654. var sqz = qz * qz;
  4655. var sqx = qx * qx;
  4656. var sqy = qy * qy;
  4657. var zAxisY = qy * qz - qx * qw;
  4658. var limit = .4999999;
  4659. if (zAxisY < -limit) {
  4660. result.y = 2 * Math.atan2(qy, qw);
  4661. result.x = Math.PI / 2;
  4662. result.z = 0;
  4663. }
  4664. else if (zAxisY > limit) {
  4665. result.y = 2 * Math.atan2(qy, qw);
  4666. result.x = -Math.PI / 2;
  4667. result.z = 0;
  4668. }
  4669. else {
  4670. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4671. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4672. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4673. }
  4674. return this;
  4675. };
  4676. /**
  4677. * Updates the given rotation matrix with the current quaternion values
  4678. * @param result defines the target matrix
  4679. * @returns the current unchanged quaternion
  4680. */
  4681. Quaternion.prototype.toRotationMatrix = function (result) {
  4682. var xx = this.x * this.x;
  4683. var yy = this.y * this.y;
  4684. var zz = this.z * this.z;
  4685. var xy = this.x * this.y;
  4686. var zw = this.z * this.w;
  4687. var zx = this.z * this.x;
  4688. var yw = this.y * this.w;
  4689. var yz = this.y * this.z;
  4690. var xw = this.x * this.w;
  4691. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4692. result.m[1] = 2.0 * (xy + zw);
  4693. result.m[2] = 2.0 * (zx - yw);
  4694. result.m[3] = 0;
  4695. result.m[4] = 2.0 * (xy - zw);
  4696. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4697. result.m[6] = 2.0 * (yz + xw);
  4698. result.m[7] = 0;
  4699. result.m[8] = 2.0 * (zx + yw);
  4700. result.m[9] = 2.0 * (yz - xw);
  4701. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4702. result.m[11] = 0;
  4703. result.m[12] = 0;
  4704. result.m[13] = 0;
  4705. result.m[14] = 0;
  4706. result.m[15] = 1.0;
  4707. result._markAsUpdated();
  4708. return this;
  4709. };
  4710. /**
  4711. * Updates the current quaternion from the given rotation matrix values
  4712. * @param matrix defines the source matrix
  4713. * @returns the current updated quaternion
  4714. */
  4715. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4716. Quaternion.FromRotationMatrixToRef(matrix, this);
  4717. return this;
  4718. };
  4719. // Statics
  4720. /**
  4721. * Creates a new quaternion from a rotation matrix
  4722. * @param matrix defines the source matrix
  4723. * @returns a new quaternion created from the given rotation matrix values
  4724. */
  4725. Quaternion.FromRotationMatrix = function (matrix) {
  4726. var result = new Quaternion();
  4727. Quaternion.FromRotationMatrixToRef(matrix, result);
  4728. return result;
  4729. };
  4730. /**
  4731. * Updates the given quaternion with the given rotation matrix values
  4732. * @param matrix defines the source matrix
  4733. * @param result defines the target quaternion
  4734. */
  4735. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4736. var data = matrix.m;
  4737. var m11 = data[0], m12 = data[4], m13 = data[8];
  4738. var m21 = data[1], m22 = data[5], m23 = data[9];
  4739. var m31 = data[2], m32 = data[6], m33 = data[10];
  4740. var trace = m11 + m22 + m33;
  4741. var s;
  4742. if (trace > 0) {
  4743. s = 0.5 / Math.sqrt(trace + 1.0);
  4744. result.w = 0.25 / s;
  4745. result.x = (m32 - m23) * s;
  4746. result.y = (m13 - m31) * s;
  4747. result.z = (m21 - m12) * s;
  4748. }
  4749. else if (m11 > m22 && m11 > m33) {
  4750. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4751. result.w = (m32 - m23) / s;
  4752. result.x = 0.25 * s;
  4753. result.y = (m12 + m21) / s;
  4754. result.z = (m13 + m31) / s;
  4755. }
  4756. else if (m22 > m33) {
  4757. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4758. result.w = (m13 - m31) / s;
  4759. result.x = (m12 + m21) / s;
  4760. result.y = 0.25 * s;
  4761. result.z = (m23 + m32) / s;
  4762. }
  4763. else {
  4764. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4765. result.w = (m21 - m12) / s;
  4766. result.x = (m13 + m31) / s;
  4767. result.y = (m23 + m32) / s;
  4768. result.z = 0.25 * s;
  4769. }
  4770. };
  4771. /**
  4772. * Returns the dot product (float) between the quaternions "left" and "right"
  4773. * @param left defines the left operand
  4774. * @param right defines the right operand
  4775. * @returns the dot product
  4776. */
  4777. Quaternion.Dot = function (left, right) {
  4778. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4779. };
  4780. /**
  4781. * Checks if the two quaternions are close to each other
  4782. * @param quat0 defines the first quaternion to check
  4783. * @param quat1 defines the second quaternion to check
  4784. * @returns true if the two quaternions are close to each other
  4785. */
  4786. Quaternion.AreClose = function (quat0, quat1) {
  4787. var dot = Quaternion.Dot(quat0, quat1);
  4788. return dot >= 0;
  4789. };
  4790. /**
  4791. * Creates an empty quaternion
  4792. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4793. */
  4794. Quaternion.Zero = function () {
  4795. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4796. };
  4797. /**
  4798. * Inverse a given quaternion
  4799. * @param q defines the source quaternion
  4800. * @returns a new quaternion as the inverted current quaternion
  4801. */
  4802. Quaternion.Inverse = function (q) {
  4803. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4804. };
  4805. /**
  4806. * Creates an identity quaternion
  4807. * @returns the identity quaternion
  4808. */
  4809. Quaternion.Identity = function () {
  4810. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4811. };
  4812. /**
  4813. * Gets a boolean indicating if the given quaternion is identity
  4814. * @param quaternion defines the quaternion to check
  4815. * @returns true if the quaternion is identity
  4816. */
  4817. Quaternion.IsIdentity = function (quaternion) {
  4818. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4819. };
  4820. /**
  4821. * Creates a quaternion from a rotation around an axis
  4822. * @param axis defines the axis to use
  4823. * @param angle defines the angle to use
  4824. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4825. */
  4826. Quaternion.RotationAxis = function (axis, angle) {
  4827. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4828. };
  4829. /**
  4830. * Creates a rotation around an axis and stores it into the given quaternion
  4831. * @param axis defines the axis to use
  4832. * @param angle defines the angle to use
  4833. * @param result defines the target quaternion
  4834. * @returns the target quaternion
  4835. */
  4836. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4837. var sin = Math.sin(angle / 2);
  4838. axis.normalize();
  4839. result.w = Math.cos(angle / 2);
  4840. result.x = axis.x * sin;
  4841. result.y = axis.y * sin;
  4842. result.z = axis.z * sin;
  4843. return result;
  4844. };
  4845. /**
  4846. * Creates a new quaternion from data stored into an array
  4847. * @param array defines the data source
  4848. * @param offset defines the offset in the source array where the data starts
  4849. * @returns a new quaternion
  4850. */
  4851. Quaternion.FromArray = function (array, offset) {
  4852. if (!offset) {
  4853. offset = 0;
  4854. }
  4855. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4856. };
  4857. /**
  4858. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4859. * @param yaw defines the rotation around Y axis
  4860. * @param pitch defines the rotation around X axis
  4861. * @param roll defines the rotation around Z axis
  4862. * @returns the new quaternion
  4863. */
  4864. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4865. var q = new Quaternion();
  4866. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4867. return q;
  4868. };
  4869. /**
  4870. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4871. * @param yaw defines the rotation around Y axis
  4872. * @param pitch defines the rotation around X axis
  4873. * @param roll defines the rotation around Z axis
  4874. * @param result defines the target quaternion
  4875. */
  4876. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4877. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4878. var halfRoll = roll * 0.5;
  4879. var halfPitch = pitch * 0.5;
  4880. var halfYaw = yaw * 0.5;
  4881. var sinRoll = Math.sin(halfRoll);
  4882. var cosRoll = Math.cos(halfRoll);
  4883. var sinPitch = Math.sin(halfPitch);
  4884. var cosPitch = Math.cos(halfPitch);
  4885. var sinYaw = Math.sin(halfYaw);
  4886. var cosYaw = Math.cos(halfYaw);
  4887. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4888. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4889. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4890. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4891. };
  4892. /**
  4893. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4894. * @param alpha defines the rotation around first axis
  4895. * @param beta defines the rotation around second axis
  4896. * @param gamma defines the rotation around third axis
  4897. * @returns the new quaternion
  4898. */
  4899. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4900. var result = new Quaternion();
  4901. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4902. return result;
  4903. };
  4904. /**
  4905. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4906. * @param alpha defines the rotation around first axis
  4907. * @param beta defines the rotation around second axis
  4908. * @param gamma defines the rotation around third axis
  4909. * @param result defines the target quaternion
  4910. */
  4911. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4912. // Produces a quaternion from Euler angles in the z-x-z orientation
  4913. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4914. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4915. var halfBeta = beta * 0.5;
  4916. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4917. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4918. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4919. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4920. };
  4921. /**
  4922. * 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)
  4923. * @param axis1 defines the first axis
  4924. * @param axis2 defines the second axis
  4925. * @param axis3 defines the third axis
  4926. * @returns the new quaternion
  4927. */
  4928. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4929. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4930. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4931. return quat;
  4932. };
  4933. /**
  4934. * 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
  4935. * @param axis1 defines the first axis
  4936. * @param axis2 defines the second axis
  4937. * @param axis3 defines the third axis
  4938. * @param ref defines the target quaternion
  4939. */
  4940. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4941. var rotMat = MathTmp.Matrix[0];
  4942. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4943. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4944. };
  4945. /**
  4946. * Interpolates between two quaternions
  4947. * @param left defines first quaternion
  4948. * @param right defines second quaternion
  4949. * @param amount defines the gradient to use
  4950. * @returns the new interpolated quaternion
  4951. */
  4952. Quaternion.Slerp = function (left, right, amount) {
  4953. var result = Quaternion.Identity();
  4954. Quaternion.SlerpToRef(left, right, amount, result);
  4955. return result;
  4956. };
  4957. /**
  4958. * Interpolates between two quaternions and stores it into a target quaternion
  4959. * @param left defines first quaternion
  4960. * @param right defines second quaternion
  4961. * @param amount defines the gradient to use
  4962. * @param result defines the target quaternion
  4963. */
  4964. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4965. var num2;
  4966. var num3;
  4967. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4968. var flag = false;
  4969. if (num4 < 0) {
  4970. flag = true;
  4971. num4 = -num4;
  4972. }
  4973. if (num4 > 0.999999) {
  4974. num3 = 1 - amount;
  4975. num2 = flag ? -amount : amount;
  4976. }
  4977. else {
  4978. var num5 = Math.acos(num4);
  4979. var num6 = (1.0 / Math.sin(num5));
  4980. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4981. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4982. }
  4983. result.x = (num3 * left.x) + (num2 * right.x);
  4984. result.y = (num3 * left.y) + (num2 * right.y);
  4985. result.z = (num3 * left.z) + (num2 * right.z);
  4986. result.w = (num3 * left.w) + (num2 * right.w);
  4987. };
  4988. /**
  4989. * Interpolate between two quaternions using Hermite interpolation
  4990. * @param value1 defines first quaternion
  4991. * @param tangent1 defines the incoming tangent
  4992. * @param value2 defines second quaternion
  4993. * @param tangent2 defines the outgoing tangent
  4994. * @param amount defines the target quaternion
  4995. * @returns the new interpolated quaternion
  4996. */
  4997. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4998. var squared = amount * amount;
  4999. var cubed = amount * squared;
  5000. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5001. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5002. var part3 = (cubed - (2.0 * squared)) + amount;
  5003. var part4 = cubed - squared;
  5004. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5005. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5006. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5007. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5008. return new Quaternion(x, y, z, w);
  5009. };
  5010. return Quaternion;
  5011. }());
  5012. BABYLON.Quaternion = Quaternion;
  5013. /**
  5014. * Class used to store matrix data (4x4)
  5015. */
  5016. var Matrix = /** @class */ (function () {
  5017. /**
  5018. * Creates an empty matrix (filled with zeros)
  5019. */
  5020. function Matrix() {
  5021. this._isIdentity = false;
  5022. this._isIdentityDirty = true;
  5023. /**
  5024. * Gets or sets the internal data of the matrix
  5025. */
  5026. this.m = new Float32Array(16);
  5027. this._markAsUpdated();
  5028. }
  5029. /** @hidden */
  5030. Matrix.prototype._markAsUpdated = function () {
  5031. this.updateFlag = Matrix._updateFlagSeed++;
  5032. this._isIdentityDirty = true;
  5033. };
  5034. // Properties
  5035. /**
  5036. * Check if the current matrix is indentity
  5037. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5038. * @returns true is the matrix is the identity matrix
  5039. */
  5040. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5041. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5042. if (this._isIdentityDirty) {
  5043. this._isIdentityDirty = false;
  5044. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5045. this._isIdentity = false;
  5046. }
  5047. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5048. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5049. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5050. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5051. this._isIdentity = false;
  5052. }
  5053. else {
  5054. this._isIdentity = true;
  5055. }
  5056. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5057. this._isIdentity = false;
  5058. }
  5059. }
  5060. return this._isIdentity;
  5061. };
  5062. /**
  5063. * Gets the determinant of the matrix
  5064. * @returns the matrix determinant
  5065. */
  5066. Matrix.prototype.determinant = function () {
  5067. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5068. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5069. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5070. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5071. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5072. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5073. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5074. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5075. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5076. };
  5077. // Methods
  5078. /**
  5079. * Returns the matrix as a Float32Array
  5080. * @returns the matrix underlying array
  5081. */
  5082. Matrix.prototype.toArray = function () {
  5083. return this.m;
  5084. };
  5085. /**
  5086. * Returns the matrix as a Float32Array
  5087. * @returns the matrix underlying array.
  5088. */
  5089. Matrix.prototype.asArray = function () {
  5090. return this.toArray();
  5091. };
  5092. /**
  5093. * Inverts the current matrix in place
  5094. * @returns the current inverted matrix
  5095. */
  5096. Matrix.prototype.invert = function () {
  5097. this.invertToRef(this);
  5098. return this;
  5099. };
  5100. /**
  5101. * Sets all the matrix elements to zero
  5102. * @returns the current matrix
  5103. */
  5104. Matrix.prototype.reset = function () {
  5105. for (var index = 0; index < 16; index++) {
  5106. this.m[index] = 0.0;
  5107. }
  5108. this._markAsUpdated();
  5109. return this;
  5110. };
  5111. /**
  5112. * Adds the current matrix with a second one
  5113. * @param other defines the matrix to add
  5114. * @returns a new matrix as the addition of the current matrix and the given one
  5115. */
  5116. Matrix.prototype.add = function (other) {
  5117. var result = new Matrix();
  5118. this.addToRef(other, result);
  5119. return result;
  5120. };
  5121. /**
  5122. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5123. * @param other defines the matrix to add
  5124. * @param result defines the target matrix
  5125. * @returns the current matrix
  5126. */
  5127. Matrix.prototype.addToRef = function (other, result) {
  5128. for (var index = 0; index < 16; index++) {
  5129. result.m[index] = this.m[index] + other.m[index];
  5130. }
  5131. result._markAsUpdated();
  5132. return this;
  5133. };
  5134. /**
  5135. * Adds in place the given matrix to the current matrix
  5136. * @param other defines the second operand
  5137. * @returns the current updated matrix
  5138. */
  5139. Matrix.prototype.addToSelf = function (other) {
  5140. for (var index = 0; index < 16; index++) {
  5141. this.m[index] += other.m[index];
  5142. }
  5143. this._markAsUpdated();
  5144. return this;
  5145. };
  5146. /**
  5147. * Sets the given matrix to the current inverted Matrix
  5148. * @param other defines the target matrix
  5149. * @returns the unmodified current matrix
  5150. */
  5151. Matrix.prototype.invertToRef = function (other) {
  5152. var l1 = this.m[0];
  5153. var l2 = this.m[1];
  5154. var l3 = this.m[2];
  5155. var l4 = this.m[3];
  5156. var l5 = this.m[4];
  5157. var l6 = this.m[5];
  5158. var l7 = this.m[6];
  5159. var l8 = this.m[7];
  5160. var l9 = this.m[8];
  5161. var l10 = this.m[9];
  5162. var l11 = this.m[10];
  5163. var l12 = this.m[11];
  5164. var l13 = this.m[12];
  5165. var l14 = this.m[13];
  5166. var l15 = this.m[14];
  5167. var l16 = this.m[15];
  5168. var l17 = (l11 * l16) - (l12 * l15);
  5169. var l18 = (l10 * l16) - (l12 * l14);
  5170. var l19 = (l10 * l15) - (l11 * l14);
  5171. var l20 = (l9 * l16) - (l12 * l13);
  5172. var l21 = (l9 * l15) - (l11 * l13);
  5173. var l22 = (l9 * l14) - (l10 * l13);
  5174. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5175. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5176. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5177. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5178. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5179. var l28 = (l7 * l16) - (l8 * l15);
  5180. var l29 = (l6 * l16) - (l8 * l14);
  5181. var l30 = (l6 * l15) - (l7 * l14);
  5182. var l31 = (l5 * l16) - (l8 * l13);
  5183. var l32 = (l5 * l15) - (l7 * l13);
  5184. var l33 = (l5 * l14) - (l6 * l13);
  5185. var l34 = (l7 * l12) - (l8 * l11);
  5186. var l35 = (l6 * l12) - (l8 * l10);
  5187. var l36 = (l6 * l11) - (l7 * l10);
  5188. var l37 = (l5 * l12) - (l8 * l9);
  5189. var l38 = (l5 * l11) - (l7 * l9);
  5190. var l39 = (l5 * l10) - (l6 * l9);
  5191. other.m[0] = l23 * l27;
  5192. other.m[4] = l24 * l27;
  5193. other.m[8] = l25 * l27;
  5194. other.m[12] = l26 * l27;
  5195. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5196. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5197. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5198. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5199. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5200. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5201. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5202. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5203. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5204. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5205. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5206. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5207. other._markAsUpdated();
  5208. return this;
  5209. };
  5210. /**
  5211. * Inserts the translation vector (using 3 floats) in the current matrix
  5212. * @param x defines the 1st component of the translation
  5213. * @param y defines the 2nd component of the translation
  5214. * @param z defines the 3rd component of the translation
  5215. * @returns the current updated matrix
  5216. */
  5217. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5218. this.m[12] = x;
  5219. this.m[13] = y;
  5220. this.m[14] = z;
  5221. this._markAsUpdated();
  5222. return this;
  5223. };
  5224. /**
  5225. * Inserts the translation vector in the current matrix
  5226. * @param vector3 defines the translation to insert
  5227. * @returns the current updated matrix
  5228. */
  5229. Matrix.prototype.setTranslation = function (vector3) {
  5230. this.m[12] = vector3.x;
  5231. this.m[13] = vector3.y;
  5232. this.m[14] = vector3.z;
  5233. this._markAsUpdated();
  5234. return this;
  5235. };
  5236. /**
  5237. * Gets the translation value of the current matrix
  5238. * @returns a new Vector3 as the extracted translation from the matrix
  5239. */
  5240. Matrix.prototype.getTranslation = function () {
  5241. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5242. };
  5243. /**
  5244. * Fill a Vector3 with the extracted translation from the matrix
  5245. * @param result defines the Vector3 where to store the translation
  5246. * @returns the current matrix
  5247. */
  5248. Matrix.prototype.getTranslationToRef = function (result) {
  5249. result.x = this.m[12];
  5250. result.y = this.m[13];
  5251. result.z = this.m[14];
  5252. return this;
  5253. };
  5254. /**
  5255. * Remove rotation and scaling part from the matrix
  5256. * @returns the updated matrix
  5257. */
  5258. Matrix.prototype.removeRotationAndScaling = function () {
  5259. this.setRowFromFloats(0, 1, 0, 0, 0);
  5260. this.setRowFromFloats(1, 0, 1, 0, 0);
  5261. this.setRowFromFloats(2, 0, 0, 1, 0);
  5262. return this;
  5263. };
  5264. /**
  5265. * Multiply two matrices
  5266. * @param other defines the second operand
  5267. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5268. */
  5269. Matrix.prototype.multiply = function (other) {
  5270. var result = new Matrix();
  5271. this.multiplyToRef(other, result);
  5272. return result;
  5273. };
  5274. /**
  5275. * Copy the current matrix from the given one
  5276. * @param other defines the source matrix
  5277. * @returns the current updated matrix
  5278. */
  5279. Matrix.prototype.copyFrom = function (other) {
  5280. for (var index = 0; index < 16; index++) {
  5281. this.m[index] = other.m[index];
  5282. }
  5283. this._markAsUpdated();
  5284. return this;
  5285. };
  5286. /**
  5287. * Populates the given array from the starting index with the current matrix values
  5288. * @param array defines the target array
  5289. * @param offset defines the offset in the target array where to start storing values
  5290. * @returns the current matrix
  5291. */
  5292. Matrix.prototype.copyToArray = function (array, offset) {
  5293. if (offset === void 0) { offset = 0; }
  5294. for (var index = 0; index < 16; index++) {
  5295. array[offset + index] = this.m[index];
  5296. }
  5297. return this;
  5298. };
  5299. /**
  5300. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5301. * @param other defines the second operand
  5302. * @param result defines the matrix where to store the multiplication
  5303. * @returns the current matrix
  5304. */
  5305. Matrix.prototype.multiplyToRef = function (other, result) {
  5306. this.multiplyToArray(other, result.m, 0);
  5307. result._markAsUpdated();
  5308. return this;
  5309. };
  5310. /**
  5311. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5312. * @param other defines the second operand
  5313. * @param result defines the array where to store the multiplication
  5314. * @param offset defines the offset in the target array where to start storing values
  5315. * @returns the current matrix
  5316. */
  5317. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5318. var tm0 = this.m[0];
  5319. var tm1 = this.m[1];
  5320. var tm2 = this.m[2];
  5321. var tm3 = this.m[3];
  5322. var tm4 = this.m[4];
  5323. var tm5 = this.m[5];
  5324. var tm6 = this.m[6];
  5325. var tm7 = this.m[7];
  5326. var tm8 = this.m[8];
  5327. var tm9 = this.m[9];
  5328. var tm10 = this.m[10];
  5329. var tm11 = this.m[11];
  5330. var tm12 = this.m[12];
  5331. var tm13 = this.m[13];
  5332. var tm14 = this.m[14];
  5333. var tm15 = this.m[15];
  5334. var om0 = other.m[0];
  5335. var om1 = other.m[1];
  5336. var om2 = other.m[2];
  5337. var om3 = other.m[3];
  5338. var om4 = other.m[4];
  5339. var om5 = other.m[5];
  5340. var om6 = other.m[6];
  5341. var om7 = other.m[7];
  5342. var om8 = other.m[8];
  5343. var om9 = other.m[9];
  5344. var om10 = other.m[10];
  5345. var om11 = other.m[11];
  5346. var om12 = other.m[12];
  5347. var om13 = other.m[13];
  5348. var om14 = other.m[14];
  5349. var om15 = other.m[15];
  5350. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5351. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5352. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5353. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5354. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5355. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5356. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5357. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5358. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5359. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5360. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5361. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5362. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5363. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5364. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5365. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5366. return this;
  5367. };
  5368. /**
  5369. * Check equality between this matrix and a second one
  5370. * @param value defines the second matrix to compare
  5371. * @returns true is the current matrix and the given one values are strictly equal
  5372. */
  5373. Matrix.prototype.equals = function (value) {
  5374. return value &&
  5375. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5376. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5377. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5378. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5379. };
  5380. /**
  5381. * Clone the current matrix
  5382. * @returns a new matrix from the current matrix
  5383. */
  5384. Matrix.prototype.clone = function () {
  5385. 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]);
  5386. };
  5387. /**
  5388. * Returns the name of the current matrix class
  5389. * @returns the string "Matrix"
  5390. */
  5391. Matrix.prototype.getClassName = function () {
  5392. return "Matrix";
  5393. };
  5394. /**
  5395. * Gets the hash code of the current matrix
  5396. * @returns the hash code
  5397. */
  5398. Matrix.prototype.getHashCode = function () {
  5399. var hash = this.m[0] || 0;
  5400. for (var i = 1; i < 16; i++) {
  5401. hash = (hash * 397) ^ (this.m[i] || 0);
  5402. }
  5403. return hash;
  5404. };
  5405. /**
  5406. * Decomposes the current Matrix into a translation, rotation and scaling components
  5407. * @param scale defines the scale vector3 given as a reference to update
  5408. * @param rotation defines the rotation quaternion given as a reference to update
  5409. * @param translation defines the translation vector3 given as a reference to update
  5410. * @returns true if operation was successful
  5411. */
  5412. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5413. if (translation) {
  5414. translation.x = this.m[12];
  5415. translation.y = this.m[13];
  5416. translation.z = this.m[14];
  5417. }
  5418. scale = scale || MathTmp.Vector3[0];
  5419. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5420. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5421. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5422. if (this.determinant() <= 0) {
  5423. scale.y *= -1;
  5424. }
  5425. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5426. if (rotation) {
  5427. rotation.x = 0;
  5428. rotation.y = 0;
  5429. rotation.z = 0;
  5430. rotation.w = 1;
  5431. }
  5432. return false;
  5433. }
  5434. if (rotation) {
  5435. 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]);
  5436. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5437. }
  5438. return true;
  5439. };
  5440. /**
  5441. * Gets specific row of the matrix
  5442. * @param index defines the number of the row to get
  5443. * @returns the index-th row of the current matrix as a new Vector4
  5444. */
  5445. Matrix.prototype.getRow = function (index) {
  5446. if (index < 0 || index > 3) {
  5447. return null;
  5448. }
  5449. var i = index * 4;
  5450. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5451. };
  5452. /**
  5453. * Sets the index-th row of the current matrix to the vector4 values
  5454. * @param index defines the number of the row to set
  5455. * @param row defines the target vector4
  5456. * @returns the updated current matrix
  5457. */
  5458. Matrix.prototype.setRow = function (index, row) {
  5459. if (index < 0 || index > 3) {
  5460. return this;
  5461. }
  5462. var i = index * 4;
  5463. this.m[i + 0] = row.x;
  5464. this.m[i + 1] = row.y;
  5465. this.m[i + 2] = row.z;
  5466. this.m[i + 3] = row.w;
  5467. this._markAsUpdated();
  5468. return this;
  5469. };
  5470. /**
  5471. * Compute the transpose of the matrix
  5472. * @returns the new transposed matrix
  5473. */
  5474. Matrix.prototype.transpose = function () {
  5475. return Matrix.Transpose(this);
  5476. };
  5477. /**
  5478. * Compute the transpose of the matrix and store it in a given matrix
  5479. * @param result defines the target matrix
  5480. * @returns the current matrix
  5481. */
  5482. Matrix.prototype.transposeToRef = function (result) {
  5483. Matrix.TransposeToRef(this, result);
  5484. return this;
  5485. };
  5486. /**
  5487. * Sets the index-th row of the current matrix with the given 4 x float values
  5488. * @param index defines the row index
  5489. * @param x defines the x component to set
  5490. * @param y defines the y component to set
  5491. * @param z defines the z component to set
  5492. * @param w defines the w component to set
  5493. * @returns the updated current matrix
  5494. */
  5495. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5496. if (index < 0 || index > 3) {
  5497. return this;
  5498. }
  5499. var i = index * 4;
  5500. this.m[i + 0] = x;
  5501. this.m[i + 1] = y;
  5502. this.m[i + 2] = z;
  5503. this.m[i + 3] = w;
  5504. this._markAsUpdated();
  5505. return this;
  5506. };
  5507. /**
  5508. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5509. * @param scale defines the scale factor
  5510. * @returns a new matrix
  5511. */
  5512. Matrix.prototype.scale = function (scale) {
  5513. var result = new Matrix();
  5514. this.scaleToRef(scale, result);
  5515. return result;
  5516. };
  5517. /**
  5518. * Scale the current matrix values by a factor to a given result matrix
  5519. * @param scale defines the scale factor
  5520. * @param result defines the matrix to store the result
  5521. * @returns the current matrix
  5522. */
  5523. Matrix.prototype.scaleToRef = function (scale, result) {
  5524. for (var index = 0; index < 16; index++) {
  5525. result.m[index] = this.m[index] * scale;
  5526. }
  5527. result._markAsUpdated();
  5528. return this;
  5529. };
  5530. /**
  5531. * Scale the current matrix values by a factor and add the result to a given matrix
  5532. * @param scale defines the scale factor
  5533. * @param result defines the Matrix to store the result
  5534. * @returns the current matrix
  5535. */
  5536. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5537. for (var index = 0; index < 16; index++) {
  5538. result.m[index] += this.m[index] * scale;
  5539. }
  5540. result._markAsUpdated();
  5541. return this;
  5542. };
  5543. /**
  5544. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5545. * @param ref matrix to store the result
  5546. */
  5547. Matrix.prototype.toNormalMatrix = function (ref) {
  5548. this.invertToRef(ref);
  5549. ref.transpose();
  5550. var m = ref.m;
  5551. 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);
  5552. };
  5553. /**
  5554. * Gets only rotation part of the current matrix
  5555. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5556. */
  5557. Matrix.prototype.getRotationMatrix = function () {
  5558. var result = Matrix.Identity();
  5559. this.getRotationMatrixToRef(result);
  5560. return result;
  5561. };
  5562. /**
  5563. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5564. * @param result defines the target matrix to store data to
  5565. * @returns the current matrix
  5566. */
  5567. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5568. var m = this.m;
  5569. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5570. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5571. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5572. if (this.determinant() <= 0) {
  5573. sy *= -1;
  5574. }
  5575. if (sx === 0 || sy === 0 || sz === 0) {
  5576. Matrix.IdentityToRef(result);
  5577. }
  5578. else {
  5579. 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);
  5580. }
  5581. return this;
  5582. };
  5583. // Statics
  5584. /**
  5585. * Creates a matrix from an array
  5586. * @param array defines the source array
  5587. * @param offset defines an offset in the source array
  5588. * @returns a new Matrix set from the starting index of the given array
  5589. */
  5590. Matrix.FromArray = function (array, offset) {
  5591. var result = new Matrix();
  5592. if (!offset) {
  5593. offset = 0;
  5594. }
  5595. Matrix.FromArrayToRef(array, offset, result);
  5596. return result;
  5597. };
  5598. /**
  5599. * Copy the content of an array into a given matrix
  5600. * @param array defines the source array
  5601. * @param offset defines an offset in the source array
  5602. * @param result defines the target matrix
  5603. */
  5604. Matrix.FromArrayToRef = function (array, offset, result) {
  5605. for (var index = 0; index < 16; index++) {
  5606. result.m[index] = array[index + offset];
  5607. }
  5608. result._markAsUpdated();
  5609. };
  5610. /**
  5611. * Stores an array into a matrix after having multiplied each component by a given factor
  5612. * @param array defines the source array
  5613. * @param offset defines the offset in the source array
  5614. * @param scale defines the scaling factor
  5615. * @param result defines the target matrix
  5616. */
  5617. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5618. for (var index = 0; index < 16; index++) {
  5619. result.m[index] = array[index + offset] * scale;
  5620. }
  5621. result._markAsUpdated();
  5622. };
  5623. /**
  5624. * Stores a list of values (16) inside a given matrix
  5625. * @param initialM11 defines 1st value of 1st row
  5626. * @param initialM12 defines 2nd value of 1st row
  5627. * @param initialM13 defines 3rd value of 1st row
  5628. * @param initialM14 defines 4th value of 1st row
  5629. * @param initialM21 defines 1st value of 2nd row
  5630. * @param initialM22 defines 2nd value of 2nd row
  5631. * @param initialM23 defines 3rd value of 2nd row
  5632. * @param initialM24 defines 4th value of 2nd row
  5633. * @param initialM31 defines 1st value of 3rd row
  5634. * @param initialM32 defines 2nd value of 3rd row
  5635. * @param initialM33 defines 3rd value of 3rd row
  5636. * @param initialM34 defines 4th value of 3rd row
  5637. * @param initialM41 defines 1st value of 4th row
  5638. * @param initialM42 defines 2nd value of 4th row
  5639. * @param initialM43 defines 3rd value of 4th row
  5640. * @param initialM44 defines 4th value of 4th row
  5641. * @param result defines the target matrix
  5642. */
  5643. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5644. result.m[0] = initialM11;
  5645. result.m[1] = initialM12;
  5646. result.m[2] = initialM13;
  5647. result.m[3] = initialM14;
  5648. result.m[4] = initialM21;
  5649. result.m[5] = initialM22;
  5650. result.m[6] = initialM23;
  5651. result.m[7] = initialM24;
  5652. result.m[8] = initialM31;
  5653. result.m[9] = initialM32;
  5654. result.m[10] = initialM33;
  5655. result.m[11] = initialM34;
  5656. result.m[12] = initialM41;
  5657. result.m[13] = initialM42;
  5658. result.m[14] = initialM43;
  5659. result.m[15] = initialM44;
  5660. result._markAsUpdated();
  5661. };
  5662. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5663. /**
  5664. * Gets an identity matrix that must not be updated
  5665. */
  5666. get: function () {
  5667. return Matrix._identityReadOnly;
  5668. },
  5669. enumerable: true,
  5670. configurable: true
  5671. });
  5672. /**
  5673. * Creates new matrix from a list of values (16)
  5674. * @param initialM11 defines 1st value of 1st row
  5675. * @param initialM12 defines 2nd value of 1st row
  5676. * @param initialM13 defines 3rd value of 1st row
  5677. * @param initialM14 defines 4th value of 1st row
  5678. * @param initialM21 defines 1st value of 2nd row
  5679. * @param initialM22 defines 2nd value of 2nd row
  5680. * @param initialM23 defines 3rd value of 2nd row
  5681. * @param initialM24 defines 4th value of 2nd row
  5682. * @param initialM31 defines 1st value of 3rd row
  5683. * @param initialM32 defines 2nd value of 3rd row
  5684. * @param initialM33 defines 3rd value of 3rd row
  5685. * @param initialM34 defines 4th value of 3rd row
  5686. * @param initialM41 defines 1st value of 4th row
  5687. * @param initialM42 defines 2nd value of 4th row
  5688. * @param initialM43 defines 3rd value of 4th row
  5689. * @param initialM44 defines 4th value of 4th row
  5690. * @returns the new matrix
  5691. */
  5692. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5693. var result = new Matrix();
  5694. result.m[0] = initialM11;
  5695. result.m[1] = initialM12;
  5696. result.m[2] = initialM13;
  5697. result.m[3] = initialM14;
  5698. result.m[4] = initialM21;
  5699. result.m[5] = initialM22;
  5700. result.m[6] = initialM23;
  5701. result.m[7] = initialM24;
  5702. result.m[8] = initialM31;
  5703. result.m[9] = initialM32;
  5704. result.m[10] = initialM33;
  5705. result.m[11] = initialM34;
  5706. result.m[12] = initialM41;
  5707. result.m[13] = initialM42;
  5708. result.m[14] = initialM43;
  5709. result.m[15] = initialM44;
  5710. return result;
  5711. };
  5712. /**
  5713. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5714. * @param scale defines the scale vector3
  5715. * @param rotation defines the rotation quaternion
  5716. * @param translation defines the translation vector3
  5717. * @returns a new matrix
  5718. */
  5719. Matrix.Compose = function (scale, rotation, translation) {
  5720. var result = Matrix.Identity();
  5721. Matrix.ComposeToRef(scale, rotation, translation, result);
  5722. return result;
  5723. };
  5724. /**
  5725. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5726. * @param scale defines the scale vector3
  5727. * @param rotation defines the rotation quaternion
  5728. * @param translation defines the translation vector3
  5729. * @param result defines the target matrix
  5730. */
  5731. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5732. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5733. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5734. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5735. result.setTranslation(translation);
  5736. };
  5737. /**
  5738. * Creates a new identity matrix
  5739. * @returns a new identity matrix
  5740. */
  5741. Matrix.Identity = function () {
  5742. 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);
  5743. };
  5744. /**
  5745. * Creates a new identity matrix and stores the result in a given matrix
  5746. * @param result defines the target matrix
  5747. */
  5748. Matrix.IdentityToRef = function (result) {
  5749. 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);
  5750. };
  5751. /**
  5752. * Creates a new zero matrix
  5753. * @returns a new zero matrix
  5754. */
  5755. Matrix.Zero = function () {
  5756. 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);
  5757. };
  5758. /**
  5759. * Creates a new rotation matrix for "angle" radians around the X axis
  5760. * @param angle defines the angle (in radians) to use
  5761. * @return the new matrix
  5762. */
  5763. Matrix.RotationX = function (angle) {
  5764. var result = new Matrix();
  5765. Matrix.RotationXToRef(angle, result);
  5766. return result;
  5767. };
  5768. /**
  5769. * Creates a new matrix as the invert of a given matrix
  5770. * @param source defines the source matrix
  5771. * @returns the new matrix
  5772. */
  5773. Matrix.Invert = function (source) {
  5774. var result = new Matrix();
  5775. source.invertToRef(result);
  5776. return result;
  5777. };
  5778. /**
  5779. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5780. * @param angle defines the angle (in radians) to use
  5781. * @param result defines the target matrix
  5782. */
  5783. Matrix.RotationXToRef = function (angle, result) {
  5784. var s = Math.sin(angle);
  5785. var c = Math.cos(angle);
  5786. result.m[0] = 1.0;
  5787. result.m[15] = 1.0;
  5788. result.m[5] = c;
  5789. result.m[10] = c;
  5790. result.m[9] = -s;
  5791. result.m[6] = s;
  5792. result.m[1] = 0.0;
  5793. result.m[2] = 0.0;
  5794. result.m[3] = 0.0;
  5795. result.m[4] = 0.0;
  5796. result.m[7] = 0.0;
  5797. result.m[8] = 0.0;
  5798. result.m[11] = 0.0;
  5799. result.m[12] = 0.0;
  5800. result.m[13] = 0.0;
  5801. result.m[14] = 0.0;
  5802. result._markAsUpdated();
  5803. };
  5804. /**
  5805. * Creates a new rotation matrix for "angle" radians around the Y axis
  5806. * @param angle defines the angle (in radians) to use
  5807. * @return the new matrix
  5808. */
  5809. Matrix.RotationY = function (angle) {
  5810. var result = new Matrix();
  5811. Matrix.RotationYToRef(angle, result);
  5812. return result;
  5813. };
  5814. /**
  5815. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5816. * @param angle defines the angle (in radians) to use
  5817. * @param result defines the target matrix
  5818. */
  5819. Matrix.RotationYToRef = function (angle, result) {
  5820. var s = Math.sin(angle);
  5821. var c = Math.cos(angle);
  5822. result.m[5] = 1.0;
  5823. result.m[15] = 1.0;
  5824. result.m[0] = c;
  5825. result.m[2] = -s;
  5826. result.m[8] = s;
  5827. result.m[10] = c;
  5828. result.m[1] = 0.0;
  5829. result.m[3] = 0.0;
  5830. result.m[4] = 0.0;
  5831. result.m[6] = 0.0;
  5832. result.m[7] = 0.0;
  5833. result.m[9] = 0.0;
  5834. result.m[11] = 0.0;
  5835. result.m[12] = 0.0;
  5836. result.m[13] = 0.0;
  5837. result.m[14] = 0.0;
  5838. result._markAsUpdated();
  5839. };
  5840. /**
  5841. * Creates a new rotation matrix for "angle" radians around the Z axis
  5842. * @param angle defines the angle (in radians) to use
  5843. * @return the new matrix
  5844. */
  5845. Matrix.RotationZ = function (angle) {
  5846. var result = new Matrix();
  5847. Matrix.RotationZToRef(angle, result);
  5848. return result;
  5849. };
  5850. /**
  5851. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5852. * @param angle defines the angle (in radians) to use
  5853. * @param result defines the target matrix
  5854. */
  5855. Matrix.RotationZToRef = function (angle, result) {
  5856. var s = Math.sin(angle);
  5857. var c = Math.cos(angle);
  5858. result.m[10] = 1.0;
  5859. result.m[15] = 1.0;
  5860. result.m[0] = c;
  5861. result.m[1] = s;
  5862. result.m[4] = -s;
  5863. result.m[5] = c;
  5864. result.m[2] = 0.0;
  5865. result.m[3] = 0.0;
  5866. result.m[6] = 0.0;
  5867. result.m[7] = 0.0;
  5868. result.m[8] = 0.0;
  5869. result.m[9] = 0.0;
  5870. result.m[11] = 0.0;
  5871. result.m[12] = 0.0;
  5872. result.m[13] = 0.0;
  5873. result.m[14] = 0.0;
  5874. result._markAsUpdated();
  5875. };
  5876. /**
  5877. * Creates a new rotation matrix for "angle" radians around the given axis
  5878. * @param axis defines the axis to use
  5879. * @param angle defines the angle (in radians) to use
  5880. * @return the new matrix
  5881. */
  5882. Matrix.RotationAxis = function (axis, angle) {
  5883. var result = Matrix.Zero();
  5884. Matrix.RotationAxisToRef(axis, angle, result);
  5885. return result;
  5886. };
  5887. /**
  5888. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5889. * @param axis defines the axis to use
  5890. * @param angle defines the angle (in radians) to use
  5891. * @param result defines the target matrix
  5892. */
  5893. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5894. var s = Math.sin(-angle);
  5895. var c = Math.cos(-angle);
  5896. var c1 = 1 - c;
  5897. axis.normalize();
  5898. result.m[0] = (axis.x * axis.x) * c1 + c;
  5899. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5900. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5901. result.m[3] = 0.0;
  5902. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5903. result.m[5] = (axis.y * axis.y) * c1 + c;
  5904. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5905. result.m[7] = 0.0;
  5906. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5907. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5908. result.m[10] = (axis.z * axis.z) * c1 + c;
  5909. result.m[11] = 0.0;
  5910. result.m[15] = 1.0;
  5911. result._markAsUpdated();
  5912. };
  5913. /**
  5914. * Creates a rotation matrix
  5915. * @param yaw defines the yaw angle in radians (Y axis)
  5916. * @param pitch defines the pitch angle in radians (X axis)
  5917. * @param roll defines the roll angle in radians (X axis)
  5918. * @returns the new rotation matrix
  5919. */
  5920. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5921. var result = new Matrix();
  5922. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5923. return result;
  5924. };
  5925. /**
  5926. * Creates a rotation matrix and stores it in a given matrix
  5927. * @param yaw defines the yaw angle in radians (Y axis)
  5928. * @param pitch defines the pitch angle in radians (X axis)
  5929. * @param roll defines the roll angle in radians (X axis)
  5930. * @param result defines the target matrix
  5931. */
  5932. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5933. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5934. this._tempQuaternion.toRotationMatrix(result);
  5935. };
  5936. /**
  5937. * Creates a scaling matrix
  5938. * @param x defines the scale factor on X axis
  5939. * @param y defines the scale factor on Y axis
  5940. * @param z defines the scale factor on Z axis
  5941. * @returns the new matrix
  5942. */
  5943. Matrix.Scaling = function (x, y, z) {
  5944. var result = Matrix.Zero();
  5945. Matrix.ScalingToRef(x, y, z, result);
  5946. return result;
  5947. };
  5948. /**
  5949. * Creates a scaling matrix and stores it in a given matrix
  5950. * @param x defines the scale factor on X axis
  5951. * @param y defines the scale factor on Y axis
  5952. * @param z defines the scale factor on Z axis
  5953. * @param result defines the target matrix
  5954. */
  5955. Matrix.ScalingToRef = function (x, y, z, result) {
  5956. result.m[0] = x;
  5957. result.m[1] = 0.0;
  5958. result.m[2] = 0.0;
  5959. result.m[3] = 0.0;
  5960. result.m[4] = 0.0;
  5961. result.m[5] = y;
  5962. result.m[6] = 0.0;
  5963. result.m[7] = 0.0;
  5964. result.m[8] = 0.0;
  5965. result.m[9] = 0.0;
  5966. result.m[10] = z;
  5967. result.m[11] = 0.0;
  5968. result.m[12] = 0.0;
  5969. result.m[13] = 0.0;
  5970. result.m[14] = 0.0;
  5971. result.m[15] = 1.0;
  5972. result._markAsUpdated();
  5973. };
  5974. /**
  5975. * Creates a translation matrix
  5976. * @param x defines the translation on X axis
  5977. * @param y defines the translation on Y axis
  5978. * @param z defines the translationon Z axis
  5979. * @returns the new matrix
  5980. */
  5981. Matrix.Translation = function (x, y, z) {
  5982. var result = Matrix.Identity();
  5983. Matrix.TranslationToRef(x, y, z, result);
  5984. return result;
  5985. };
  5986. /**
  5987. * Creates a translation matrix and stores it in a given matrix
  5988. * @param x defines the translation on X axis
  5989. * @param y defines the translation on Y axis
  5990. * @param z defines the translationon Z axis
  5991. * @param result defines the target matrix
  5992. */
  5993. Matrix.TranslationToRef = function (x, y, z, result) {
  5994. 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);
  5995. };
  5996. /**
  5997. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5998. * @param startValue defines the start value
  5999. * @param endValue defines the end value
  6000. * @param gradient defines the gradient factor
  6001. * @returns the new matrix
  6002. */
  6003. Matrix.Lerp = function (startValue, endValue, gradient) {
  6004. var result = Matrix.Zero();
  6005. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6006. return result;
  6007. };
  6008. /**
  6009. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6010. * @param startValue defines the start value
  6011. * @param endValue defines the end value
  6012. * @param gradient defines the gradient factor
  6013. * @param result defines the Matrix object where to store data
  6014. */
  6015. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6016. for (var index = 0; index < 16; index++) {
  6017. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6018. }
  6019. result._markAsUpdated();
  6020. };
  6021. /**
  6022. * Builds a new matrix whose values are computed by:
  6023. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6024. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6025. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6026. * @param startValue defines the first matrix
  6027. * @param endValue defines the second matrix
  6028. * @param gradient defines the gradient between the two matrices
  6029. * @returns the new matrix
  6030. */
  6031. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6032. var result = Matrix.Zero();
  6033. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6034. return result;
  6035. };
  6036. /**
  6037. * Update a matrix to values which are computed by:
  6038. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6039. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6040. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6041. * @param startValue defines the first matrix
  6042. * @param endValue defines the second matrix
  6043. * @param gradient defines the gradient between the two matrices
  6044. * @param result defines the target matrix
  6045. */
  6046. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6047. var startScale = MathTmp.Vector3[0];
  6048. var startRotation = MathTmp.Quaternion[0];
  6049. var startTranslation = MathTmp.Vector3[1];
  6050. startValue.decompose(startScale, startRotation, startTranslation);
  6051. var endScale = MathTmp.Vector3[2];
  6052. var endRotation = MathTmp.Quaternion[1];
  6053. var endTranslation = MathTmp.Vector3[3];
  6054. endValue.decompose(endScale, endRotation, endTranslation);
  6055. var resultScale = MathTmp.Vector3[4];
  6056. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6057. var resultRotation = MathTmp.Quaternion[2];
  6058. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6059. var resultTranslation = MathTmp.Vector3[5];
  6060. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6061. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6062. };
  6063. /**
  6064. * 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"
  6065. * This function works in left handed mode
  6066. * @param eye defines the final position of the entity
  6067. * @param target defines where the entity should look at
  6068. * @param up defines the up vector for the entity
  6069. * @returns the new matrix
  6070. */
  6071. Matrix.LookAtLH = function (eye, target, up) {
  6072. var result = Matrix.Zero();
  6073. Matrix.LookAtLHToRef(eye, target, up, result);
  6074. return result;
  6075. };
  6076. /**
  6077. * 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".
  6078. * This function works in left handed mode
  6079. * @param eye defines the final position of the entity
  6080. * @param target defines where the entity should look at
  6081. * @param up defines the up vector for the entity
  6082. * @param result defines the target matrix
  6083. */
  6084. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6085. // Z axis
  6086. target.subtractToRef(eye, this._zAxis);
  6087. this._zAxis.normalize();
  6088. // X axis
  6089. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6090. if (this._xAxis.lengthSquared() === 0) {
  6091. this._xAxis.x = 1.0;
  6092. }
  6093. else {
  6094. this._xAxis.normalize();
  6095. }
  6096. // Y axis
  6097. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6098. this._yAxis.normalize();
  6099. // Eye angles
  6100. var ex = -Vector3.Dot(this._xAxis, eye);
  6101. var ey = -Vector3.Dot(this._yAxis, eye);
  6102. var ez = -Vector3.Dot(this._zAxis, eye);
  6103. 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);
  6104. };
  6105. /**
  6106. * 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"
  6107. * This function works in right handed mode
  6108. * @param eye defines the final position of the entity
  6109. * @param target defines where the entity should look at
  6110. * @param up defines the up vector for the entity
  6111. * @returns the new matrix
  6112. */
  6113. Matrix.LookAtRH = function (eye, target, up) {
  6114. var result = Matrix.Zero();
  6115. Matrix.LookAtRHToRef(eye, target, up, result);
  6116. return result;
  6117. };
  6118. /**
  6119. * 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".
  6120. * This function works in right handed mode
  6121. * @param eye defines the final position of the entity
  6122. * @param target defines where the entity should look at
  6123. * @param up defines the up vector for the entity
  6124. * @param result defines the target matrix
  6125. */
  6126. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6127. // Z axis
  6128. eye.subtractToRef(target, this._zAxis);
  6129. this._zAxis.normalize();
  6130. // X axis
  6131. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6132. if (this._xAxis.lengthSquared() === 0) {
  6133. this._xAxis.x = 1.0;
  6134. }
  6135. else {
  6136. this._xAxis.normalize();
  6137. }
  6138. // Y axis
  6139. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6140. this._yAxis.normalize();
  6141. // Eye angles
  6142. var ex = -Vector3.Dot(this._xAxis, eye);
  6143. var ey = -Vector3.Dot(this._yAxis, eye);
  6144. var ez = -Vector3.Dot(this._zAxis, eye);
  6145. 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);
  6146. };
  6147. /**
  6148. * Create a left-handed orthographic projection matrix
  6149. * @param width defines the viewport width
  6150. * @param height defines the viewport height
  6151. * @param znear defines the near clip plane
  6152. * @param zfar defines the far clip plane
  6153. * @returns a new matrix as a left-handed orthographic projection matrix
  6154. */
  6155. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6156. var matrix = Matrix.Zero();
  6157. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6158. return matrix;
  6159. };
  6160. /**
  6161. * Store a left-handed orthographic projection to a given matrix
  6162. * @param width defines the viewport width
  6163. * @param height defines the viewport height
  6164. * @param znear defines the near clip plane
  6165. * @param zfar defines the far clip plane
  6166. * @param result defines the target matrix
  6167. */
  6168. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6169. var n = znear;
  6170. var f = zfar;
  6171. var a = 2.0 / width;
  6172. var b = 2.0 / height;
  6173. var c = 2.0 / (f - n);
  6174. var d = -(f + n) / (f - n);
  6175. 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);
  6176. };
  6177. /**
  6178. * Create a left-handed orthographic projection matrix
  6179. * @param left defines the viewport left coordinate
  6180. * @param right defines the viewport right coordinate
  6181. * @param bottom defines the viewport bottom coordinate
  6182. * @param top defines the viewport top coordinate
  6183. * @param znear defines the near clip plane
  6184. * @param zfar defines the far clip plane
  6185. * @returns a new matrix as a left-handed orthographic projection matrix
  6186. */
  6187. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6188. var matrix = Matrix.Zero();
  6189. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6190. return matrix;
  6191. };
  6192. /**
  6193. * Stores a left-handed orthographic projection into a given matrix
  6194. * @param left defines the viewport left coordinate
  6195. * @param right defines the viewport right coordinate
  6196. * @param bottom defines the viewport bottom coordinate
  6197. * @param top defines the viewport top coordinate
  6198. * @param znear defines the near clip plane
  6199. * @param zfar defines the far clip plane
  6200. * @param result defines the target matrix
  6201. */
  6202. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6203. var n = znear;
  6204. var f = zfar;
  6205. var a = 2.0 / (right - left);
  6206. var b = 2.0 / (top - bottom);
  6207. var c = 2.0 / (f - n);
  6208. var d = -(f + n) / (f - n);
  6209. var i0 = (left + right) / (left - right);
  6210. var i1 = (top + bottom) / (bottom - top);
  6211. 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);
  6212. };
  6213. /**
  6214. * Creates a right-handed orthographic projection matrix
  6215. * @param left defines the viewport left coordinate
  6216. * @param right defines the viewport right coordinate
  6217. * @param bottom defines the viewport bottom coordinate
  6218. * @param top defines the viewport top coordinate
  6219. * @param znear defines the near clip plane
  6220. * @param zfar defines the far clip plane
  6221. * @returns a new matrix as a right-handed orthographic projection matrix
  6222. */
  6223. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6224. var matrix = Matrix.Zero();
  6225. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6226. return matrix;
  6227. };
  6228. /**
  6229. * Stores a right-handed orthographic projection into a given matrix
  6230. * @param left defines the viewport left coordinate
  6231. * @param right defines the viewport right coordinate
  6232. * @param bottom defines the viewport bottom coordinate
  6233. * @param top defines the viewport top coordinate
  6234. * @param znear defines the near clip plane
  6235. * @param zfar defines the far clip plane
  6236. * @param result defines the target matrix
  6237. */
  6238. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6239. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6240. result.m[10] *= -1.0;
  6241. };
  6242. /**
  6243. * Creates a left-handed perspective projection matrix
  6244. * @param width defines the viewport width
  6245. * @param height defines the viewport height
  6246. * @param znear defines the near clip plane
  6247. * @param zfar defines the far clip plane
  6248. * @returns a new matrix as a left-handed perspective projection matrix
  6249. */
  6250. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6251. var matrix = Matrix.Zero();
  6252. var n = znear;
  6253. var f = zfar;
  6254. var a = 2.0 * n / width;
  6255. var b = 2.0 * n / height;
  6256. var c = (f + n) / (f - n);
  6257. var d = -2.0 * f * n / (f - n);
  6258. 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);
  6259. return matrix;
  6260. };
  6261. /**
  6262. * Creates a left-handed perspective projection matrix
  6263. * @param fov defines the horizontal field of view
  6264. * @param aspect defines the aspect ratio
  6265. * @param znear defines the near clip plane
  6266. * @param zfar defines the far clip plane
  6267. * @returns a new matrix as a left-handed perspective projection matrix
  6268. */
  6269. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6270. var matrix = Matrix.Zero();
  6271. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6272. return matrix;
  6273. };
  6274. /**
  6275. * Stores a left-handed perspective projection into a given matrix
  6276. * @param fov defines the horizontal field of view
  6277. * @param aspect defines the aspect ratio
  6278. * @param znear defines the near clip plane
  6279. * @param zfar defines the far clip plane
  6280. * @param result defines the target matrix
  6281. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6282. */
  6283. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6284. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6285. var n = znear;
  6286. var f = zfar;
  6287. var t = 1.0 / (Math.tan(fov * 0.5));
  6288. var a = isVerticalFovFixed ? (t / aspect) : t;
  6289. var b = isVerticalFovFixed ? t : (t * aspect);
  6290. var c = (f + n) / (f - n);
  6291. var d = -2.0 * f * n / (f - n);
  6292. 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);
  6293. };
  6294. /**
  6295. * Creates a right-handed perspective projection matrix
  6296. * @param fov defines the horizontal field of view
  6297. * @param aspect defines the aspect ratio
  6298. * @param znear defines the near clip plane
  6299. * @param zfar defines the far clip plane
  6300. * @returns a new matrix as a right-handed perspective projection matrix
  6301. */
  6302. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6303. var matrix = Matrix.Zero();
  6304. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6305. return matrix;
  6306. };
  6307. /**
  6308. * Stores a right-handed perspective projection into a given matrix
  6309. * @param fov defines the horizontal field of view
  6310. * @param aspect defines the aspect ratio
  6311. * @param znear defines the near clip plane
  6312. * @param zfar defines the far clip plane
  6313. * @param result defines the target matrix
  6314. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6315. */
  6316. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6317. //alternatively this could be expressed as:
  6318. // m = PerspectiveFovLHToRef
  6319. // m[10] *= -1.0;
  6320. // m[11] *= -1.0;
  6321. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6322. var n = znear;
  6323. var f = zfar;
  6324. var t = 1.0 / (Math.tan(fov * 0.5));
  6325. var a = isVerticalFovFixed ? (t / aspect) : t;
  6326. var b = isVerticalFovFixed ? t : (t * aspect);
  6327. var c = -(f + n) / (f - n);
  6328. var d = -2 * f * n / (f - n);
  6329. 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);
  6330. };
  6331. /**
  6332. * Stores a perspective projection for WebVR info a given matrix
  6333. * @param fov defines the field of view
  6334. * @param znear defines the near clip plane
  6335. * @param zfar defines the far clip plane
  6336. * @param result defines the target matrix
  6337. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6338. */
  6339. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6340. if (rightHanded === void 0) { rightHanded = false; }
  6341. var rightHandedFactor = rightHanded ? -1 : 1;
  6342. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6343. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6344. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6345. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6346. var xScale = 2.0 / (leftTan + rightTan);
  6347. var yScale = 2.0 / (upTan + downTan);
  6348. result.m[0] = xScale;
  6349. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6350. result.m[5] = yScale;
  6351. result.m[6] = result.m[7] = 0.0;
  6352. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6353. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6354. result.m[10] = -zfar / (znear - zfar);
  6355. result.m[11] = 1.0 * rightHandedFactor;
  6356. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6357. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6358. result._markAsUpdated();
  6359. };
  6360. /**
  6361. * Computes a complete transformation matrix
  6362. * @param viewport defines the viewport to use
  6363. * @param world defines the world matrix
  6364. * @param view defines the view matrix
  6365. * @param projection defines the projection matrix
  6366. * @param zmin defines the near clip plane
  6367. * @param zmax defines the far clip plane
  6368. * @returns the transformation matrix
  6369. */
  6370. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6371. var cw = viewport.width;
  6372. var ch = viewport.height;
  6373. var cx = viewport.x;
  6374. var cy = viewport.y;
  6375. 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);
  6376. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6377. };
  6378. /**
  6379. * Extracts a 2x2 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 4 elements : the 2x2 matrix extracted from the given matrix
  6382. */
  6383. Matrix.GetAsMatrix2x2 = function (matrix) {
  6384. return new Float32Array([
  6385. matrix.m[0], matrix.m[1],
  6386. matrix.m[4], matrix.m[5]
  6387. ]);
  6388. };
  6389. /**
  6390. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6391. * @param matrix defines the matrix to use
  6392. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6393. */
  6394. Matrix.GetAsMatrix3x3 = function (matrix) {
  6395. return new Float32Array([
  6396. matrix.m[0], matrix.m[1], matrix.m[2],
  6397. matrix.m[4], matrix.m[5], matrix.m[6],
  6398. matrix.m[8], matrix.m[9], matrix.m[10]
  6399. ]);
  6400. };
  6401. /**
  6402. * Compute the transpose of a given matrix
  6403. * @param matrix defines the matrix to transpose
  6404. * @returns the new matrix
  6405. */
  6406. Matrix.Transpose = function (matrix) {
  6407. var result = new Matrix();
  6408. Matrix.TransposeToRef(matrix, result);
  6409. return result;
  6410. };
  6411. /**
  6412. * Compute the transpose of a matrix and store it in a target matrix
  6413. * @param matrix defines the matrix to transpose
  6414. * @param result defines the target matrix
  6415. */
  6416. Matrix.TransposeToRef = function (matrix, result) {
  6417. result.m[0] = matrix.m[0];
  6418. result.m[1] = matrix.m[4];
  6419. result.m[2] = matrix.m[8];
  6420. result.m[3] = matrix.m[12];
  6421. result.m[4] = matrix.m[1];
  6422. result.m[5] = matrix.m[5];
  6423. result.m[6] = matrix.m[9];
  6424. result.m[7] = matrix.m[13];
  6425. result.m[8] = matrix.m[2];
  6426. result.m[9] = matrix.m[6];
  6427. result.m[10] = matrix.m[10];
  6428. result.m[11] = matrix.m[14];
  6429. result.m[12] = matrix.m[3];
  6430. result.m[13] = matrix.m[7];
  6431. result.m[14] = matrix.m[11];
  6432. result.m[15] = matrix.m[15];
  6433. };
  6434. /**
  6435. * Computes a reflection matrix from a plane
  6436. * @param plane defines the reflection plane
  6437. * @returns a new matrix
  6438. */
  6439. Matrix.Reflection = function (plane) {
  6440. var matrix = new Matrix();
  6441. Matrix.ReflectionToRef(plane, matrix);
  6442. return matrix;
  6443. };
  6444. /**
  6445. * Computes a reflection matrix from a plane
  6446. * @param plane defines the reflection plane
  6447. * @param result defines the target matrix
  6448. */
  6449. Matrix.ReflectionToRef = function (plane, result) {
  6450. plane.normalize();
  6451. var x = plane.normal.x;
  6452. var y = plane.normal.y;
  6453. var z = plane.normal.z;
  6454. var temp = -2 * x;
  6455. var temp2 = -2 * y;
  6456. var temp3 = -2 * z;
  6457. result.m[0] = (temp * x) + 1;
  6458. result.m[1] = temp2 * x;
  6459. result.m[2] = temp3 * x;
  6460. result.m[3] = 0.0;
  6461. result.m[4] = temp * y;
  6462. result.m[5] = (temp2 * y) + 1;
  6463. result.m[6] = temp3 * y;
  6464. result.m[7] = 0.0;
  6465. result.m[8] = temp * z;
  6466. result.m[9] = temp2 * z;
  6467. result.m[10] = (temp3 * z) + 1;
  6468. result.m[11] = 0.0;
  6469. result.m[12] = temp * plane.d;
  6470. result.m[13] = temp2 * plane.d;
  6471. result.m[14] = temp3 * plane.d;
  6472. result.m[15] = 1.0;
  6473. result._markAsUpdated();
  6474. };
  6475. /**
  6476. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6477. * @param xaxis defines the value of the 1st axis
  6478. * @param yaxis defines the value of the 2nd axis
  6479. * @param zaxis defines the value of the 3rd axis
  6480. * @param result defines the target matrix
  6481. */
  6482. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6483. result.m[0] = xaxis.x;
  6484. result.m[1] = xaxis.y;
  6485. result.m[2] = xaxis.z;
  6486. result.m[3] = 0.0;
  6487. result.m[4] = yaxis.x;
  6488. result.m[5] = yaxis.y;
  6489. result.m[6] = yaxis.z;
  6490. result.m[7] = 0.0;
  6491. result.m[8] = zaxis.x;
  6492. result.m[9] = zaxis.y;
  6493. result.m[10] = zaxis.z;
  6494. result.m[11] = 0.0;
  6495. result.m[12] = 0.0;
  6496. result.m[13] = 0.0;
  6497. result.m[14] = 0.0;
  6498. result.m[15] = 1.0;
  6499. result._markAsUpdated();
  6500. };
  6501. /**
  6502. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6503. * @param quat defines the quaternion to use
  6504. * @param result defines the target matrix
  6505. */
  6506. Matrix.FromQuaternionToRef = function (quat, result) {
  6507. var xx = quat.x * quat.x;
  6508. var yy = quat.y * quat.y;
  6509. var zz = quat.z * quat.z;
  6510. var xy = quat.x * quat.y;
  6511. var zw = quat.z * quat.w;
  6512. var zx = quat.z * quat.x;
  6513. var yw = quat.y * quat.w;
  6514. var yz = quat.y * quat.z;
  6515. var xw = quat.x * quat.w;
  6516. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6517. result.m[1] = 2.0 * (xy + zw);
  6518. result.m[2] = 2.0 * (zx - yw);
  6519. result.m[3] = 0.0;
  6520. result.m[4] = 2.0 * (xy - zw);
  6521. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6522. result.m[6] = 2.0 * (yz + xw);
  6523. result.m[7] = 0.0;
  6524. result.m[8] = 2.0 * (zx + yw);
  6525. result.m[9] = 2.0 * (yz - xw);
  6526. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6527. result.m[11] = 0.0;
  6528. result.m[12] = 0.0;
  6529. result.m[13] = 0.0;
  6530. result.m[14] = 0.0;
  6531. result.m[15] = 1.0;
  6532. result._markAsUpdated();
  6533. };
  6534. Matrix._tempQuaternion = new Quaternion();
  6535. Matrix._xAxis = Vector3.Zero();
  6536. Matrix._yAxis = Vector3.Zero();
  6537. Matrix._zAxis = Vector3.Zero();
  6538. Matrix._updateFlagSeed = 0;
  6539. Matrix._identityReadOnly = Matrix.Identity();
  6540. return Matrix;
  6541. }());
  6542. BABYLON.Matrix = Matrix;
  6543. var Plane = /** @class */ (function () {
  6544. /**
  6545. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6546. */
  6547. function Plane(a, b, c, d) {
  6548. this.normal = new Vector3(a, b, c);
  6549. this.d = d;
  6550. }
  6551. /**
  6552. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6553. */
  6554. Plane.prototype.asArray = function () {
  6555. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6556. };
  6557. // Methods
  6558. /**
  6559. * Returns a new plane copied from the current Plane.
  6560. */
  6561. Plane.prototype.clone = function () {
  6562. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6563. };
  6564. /**
  6565. * Returns the string "Plane".
  6566. */
  6567. Plane.prototype.getClassName = function () {
  6568. return "Plane";
  6569. };
  6570. /**
  6571. * Returns the Plane hash code.
  6572. */
  6573. Plane.prototype.getHashCode = function () {
  6574. var hash = this.normal.getHashCode();
  6575. hash = (hash * 397) ^ (this.d || 0);
  6576. return hash;
  6577. };
  6578. /**
  6579. * Normalize the current Plane in place.
  6580. * Returns the updated Plane.
  6581. */
  6582. Plane.prototype.normalize = function () {
  6583. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6584. var magnitude = 0.0;
  6585. if (norm !== 0) {
  6586. magnitude = 1.0 / norm;
  6587. }
  6588. this.normal.x *= magnitude;
  6589. this.normal.y *= magnitude;
  6590. this.normal.z *= magnitude;
  6591. this.d *= magnitude;
  6592. return this;
  6593. };
  6594. /**
  6595. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6596. */
  6597. Plane.prototype.transform = function (transformation) {
  6598. var transposedMatrix = Matrix.Transpose(transformation);
  6599. var x = this.normal.x;
  6600. var y = this.normal.y;
  6601. var z = this.normal.z;
  6602. var d = this.d;
  6603. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6604. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6605. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6606. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6607. return new Plane(normalX, normalY, normalZ, finalD);
  6608. };
  6609. /**
  6610. * Returns the dot product (float) of the point coordinates and the plane normal.
  6611. */
  6612. Plane.prototype.dotCoordinate = function (point) {
  6613. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6614. };
  6615. /**
  6616. * Updates the current Plane from the plane defined by the three given points.
  6617. * Returns the updated Plane.
  6618. */
  6619. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6620. var x1 = point2.x - point1.x;
  6621. var y1 = point2.y - point1.y;
  6622. var z1 = point2.z - point1.z;
  6623. var x2 = point3.x - point1.x;
  6624. var y2 = point3.y - point1.y;
  6625. var z2 = point3.z - point1.z;
  6626. var yz = (y1 * z2) - (z1 * y2);
  6627. var xz = (z1 * x2) - (x1 * z2);
  6628. var xy = (x1 * y2) - (y1 * x2);
  6629. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6630. var invPyth;
  6631. if (pyth !== 0) {
  6632. invPyth = 1.0 / pyth;
  6633. }
  6634. else {
  6635. invPyth = 0.0;
  6636. }
  6637. this.normal.x = yz * invPyth;
  6638. this.normal.y = xz * invPyth;
  6639. this.normal.z = xy * invPyth;
  6640. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6641. return this;
  6642. };
  6643. /**
  6644. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6645. */
  6646. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6647. var dot = Vector3.Dot(this.normal, direction);
  6648. return (dot <= epsilon);
  6649. };
  6650. /**
  6651. * Returns the signed distance (float) from the given point to the Plane.
  6652. */
  6653. Plane.prototype.signedDistanceTo = function (point) {
  6654. return Vector3.Dot(point, this.normal) + this.d;
  6655. };
  6656. // Statics
  6657. /**
  6658. * Returns a new Plane from the given array.
  6659. */
  6660. Plane.FromArray = function (array) {
  6661. return new Plane(array[0], array[1], array[2], array[3]);
  6662. };
  6663. /**
  6664. * Returns a new Plane defined by the three given points.
  6665. */
  6666. Plane.FromPoints = function (point1, point2, point3) {
  6667. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6668. result.copyFromPoints(point1, point2, point3);
  6669. return result;
  6670. };
  6671. /**
  6672. * Returns a new Plane the normal vector to this plane at the given origin point.
  6673. * Note : the vector "normal" is updated because normalized.
  6674. */
  6675. Plane.FromPositionAndNormal = function (origin, normal) {
  6676. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6677. normal.normalize();
  6678. result.normal = normal;
  6679. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6680. return result;
  6681. };
  6682. /**
  6683. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6684. */
  6685. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6686. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6687. return Vector3.Dot(point, normal) + d;
  6688. };
  6689. return Plane;
  6690. }());
  6691. BABYLON.Plane = Plane;
  6692. var Viewport = /** @class */ (function () {
  6693. /**
  6694. * Creates a Viewport object located at (x, y) and sized (width, height).
  6695. */
  6696. function Viewport(x, y, width, height) {
  6697. this.x = x;
  6698. this.y = y;
  6699. this.width = width;
  6700. this.height = height;
  6701. }
  6702. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6703. if (renderWidthOrEngine.getRenderWidth) {
  6704. var engine = renderWidthOrEngine;
  6705. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6706. }
  6707. var renderWidth = renderWidthOrEngine;
  6708. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6709. };
  6710. /**
  6711. * Returns a new Viewport copied from the current one.
  6712. */
  6713. Viewport.prototype.clone = function () {
  6714. return new Viewport(this.x, this.y, this.width, this.height);
  6715. };
  6716. return Viewport;
  6717. }());
  6718. BABYLON.Viewport = Viewport;
  6719. var Frustum = /** @class */ (function () {
  6720. function Frustum() {
  6721. }
  6722. /**
  6723. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6724. */
  6725. Frustum.GetPlanes = function (transform) {
  6726. var frustumPlanes = [];
  6727. for (var index = 0; index < 6; index++) {
  6728. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6729. }
  6730. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6731. return frustumPlanes;
  6732. };
  6733. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6734. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6735. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6736. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6737. frustumPlane.d = transform.m[15] + transform.m[14];
  6738. frustumPlane.normalize();
  6739. };
  6740. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6741. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6742. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6743. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6744. frustumPlane.d = transform.m[15] - transform.m[14];
  6745. frustumPlane.normalize();
  6746. };
  6747. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6748. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6749. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6750. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6751. frustumPlane.d = transform.m[15] + transform.m[12];
  6752. frustumPlane.normalize();
  6753. };
  6754. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6755. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6756. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6757. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6758. frustumPlane.d = transform.m[15] - transform.m[12];
  6759. frustumPlane.normalize();
  6760. };
  6761. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6762. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6763. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6764. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6765. frustumPlane.d = transform.m[15] - transform.m[13];
  6766. frustumPlane.normalize();
  6767. };
  6768. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6769. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6770. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6771. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6772. frustumPlane.d = transform.m[15] + transform.m[13];
  6773. frustumPlane.normalize();
  6774. };
  6775. /**
  6776. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6777. */
  6778. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6779. // Near
  6780. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6781. // Far
  6782. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6783. // Left
  6784. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6785. // Right
  6786. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6787. // Top
  6788. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6789. // Bottom
  6790. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6791. };
  6792. return Frustum;
  6793. }());
  6794. BABYLON.Frustum = Frustum;
  6795. /** Defines supported spaces */
  6796. var Space;
  6797. (function (Space) {
  6798. /** Local (object) space */
  6799. Space[Space["LOCAL"] = 0] = "LOCAL";
  6800. /** World space */
  6801. Space[Space["WORLD"] = 1] = "WORLD";
  6802. /** Bone space */
  6803. Space[Space["BONE"] = 2] = "BONE";
  6804. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6805. /** Defines the 3 main axes */
  6806. var Axis = /** @class */ (function () {
  6807. function Axis() {
  6808. }
  6809. /** X axis */
  6810. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6811. /** Y axis */
  6812. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6813. /** Z axis */
  6814. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6815. return Axis;
  6816. }());
  6817. BABYLON.Axis = Axis;
  6818. ;
  6819. var BezierCurve = /** @class */ (function () {
  6820. function BezierCurve() {
  6821. }
  6822. /**
  6823. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6824. */
  6825. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6826. // Extract X (which is equal to time here)
  6827. var f0 = 1 - 3 * x2 + 3 * x1;
  6828. var f1 = 3 * x2 - 6 * x1;
  6829. var f2 = 3 * x1;
  6830. var refinedT = t;
  6831. for (var i = 0; i < 5; i++) {
  6832. var refinedT2 = refinedT * refinedT;
  6833. var refinedT3 = refinedT2 * refinedT;
  6834. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6835. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6836. refinedT -= (x - t) * slope;
  6837. refinedT = Math.min(1, Math.max(0, refinedT));
  6838. }
  6839. // Resolve cubic bezier for the given x
  6840. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6841. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6842. Math.pow(refinedT, 3);
  6843. };
  6844. return BezierCurve;
  6845. }());
  6846. BABYLON.BezierCurve = BezierCurve;
  6847. /**
  6848. * Defines potential orientation for back face culling
  6849. */
  6850. var Orientation;
  6851. (function (Orientation) {
  6852. /**
  6853. * Clockwise
  6854. */
  6855. Orientation[Orientation["CW"] = 0] = "CW";
  6856. /** Counter clockwise */
  6857. Orientation[Orientation["CCW"] = 1] = "CCW";
  6858. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6859. /**
  6860. * Defines angle representation
  6861. */
  6862. var Angle = /** @class */ (function () {
  6863. /**
  6864. * Creates an Angle object of "radians" radians (float).
  6865. */
  6866. function Angle(radians) {
  6867. this._radians = radians;
  6868. if (this._radians < 0.0)
  6869. this._radians += (2.0 * Math.PI);
  6870. }
  6871. /**
  6872. * Get value in degrees
  6873. * @returns the Angle value in degrees (float)
  6874. */
  6875. Angle.prototype.degrees = function () {
  6876. return this._radians * 180.0 / Math.PI;
  6877. };
  6878. /**
  6879. * Get value in radians
  6880. * @returns the Angle value in radians (float)
  6881. */
  6882. Angle.prototype.radians = function () {
  6883. return this._radians;
  6884. };
  6885. /**
  6886. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6887. * @param a defines first vector
  6888. * @param b defines second vector
  6889. * @returns a new Angle
  6890. */
  6891. Angle.BetweenTwoPoints = function (a, b) {
  6892. var delta = b.subtract(a);
  6893. var theta = Math.atan2(delta.y, delta.x);
  6894. return new Angle(theta);
  6895. };
  6896. /**
  6897. * Gets a new Angle object from the given float in radians
  6898. * @param radians defines the angle value in radians
  6899. * @returns a new Angle
  6900. */
  6901. Angle.FromRadians = function (radians) {
  6902. return new Angle(radians);
  6903. };
  6904. /**
  6905. * Gets a new Angle object from the given float in degrees
  6906. * @param degrees defines the angle value in degrees
  6907. * @returns a new Angle
  6908. */
  6909. Angle.FromDegrees = function (degrees) {
  6910. return new Angle(degrees * Math.PI / 180.0);
  6911. };
  6912. return Angle;
  6913. }());
  6914. BABYLON.Angle = Angle;
  6915. var Arc2 = /** @class */ (function () {
  6916. /**
  6917. * Creates an Arc object from the three given points : start, middle and end.
  6918. */
  6919. function Arc2(startPoint, midPoint, endPoint) {
  6920. this.startPoint = startPoint;
  6921. this.midPoint = midPoint;
  6922. this.endPoint = endPoint;
  6923. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6924. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6925. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6926. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6927. 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);
  6928. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6929. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6930. var a1 = this.startAngle.degrees();
  6931. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6932. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6933. // angles correction
  6934. if (a2 - a1 > +180.0)
  6935. a2 -= 360.0;
  6936. if (a2 - a1 < -180.0)
  6937. a2 += 360.0;
  6938. if (a3 - a2 > +180.0)
  6939. a3 -= 360.0;
  6940. if (a3 - a2 < -180.0)
  6941. a3 += 360.0;
  6942. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6943. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6944. }
  6945. return Arc2;
  6946. }());
  6947. BABYLON.Arc2 = Arc2;
  6948. var Path2 = /** @class */ (function () {
  6949. /**
  6950. * Creates a Path2 object from the starting 2D coordinates x and y.
  6951. */
  6952. function Path2(x, y) {
  6953. this._points = new Array();
  6954. this._length = 0.0;
  6955. this.closed = false;
  6956. this._points.push(new Vector2(x, y));
  6957. }
  6958. /**
  6959. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6960. * Returns the updated Path2.
  6961. */
  6962. Path2.prototype.addLineTo = function (x, y) {
  6963. if (this.closed) {
  6964. return this;
  6965. }
  6966. var newPoint = new Vector2(x, y);
  6967. var previousPoint = this._points[this._points.length - 1];
  6968. this._points.push(newPoint);
  6969. this._length += newPoint.subtract(previousPoint).length();
  6970. return this;
  6971. };
  6972. /**
  6973. * 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.
  6974. * Returns the updated Path2.
  6975. */
  6976. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6977. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6978. if (this.closed) {
  6979. return this;
  6980. }
  6981. var startPoint = this._points[this._points.length - 1];
  6982. var midPoint = new Vector2(midX, midY);
  6983. var endPoint = new Vector2(endX, endY);
  6984. var arc = new Arc2(startPoint, midPoint, endPoint);
  6985. var increment = arc.angle.radians() / numberOfSegments;
  6986. if (arc.orientation === Orientation.CW)
  6987. increment *= -1;
  6988. var currentAngle = arc.startAngle.radians() + increment;
  6989. for (var i = 0; i < numberOfSegments; i++) {
  6990. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6991. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6992. this.addLineTo(x, y);
  6993. currentAngle += increment;
  6994. }
  6995. return this;
  6996. };
  6997. /**
  6998. * Closes the Path2.
  6999. * Returns the Path2.
  7000. */
  7001. Path2.prototype.close = function () {
  7002. this.closed = true;
  7003. return this;
  7004. };
  7005. /**
  7006. * Returns the Path2 total length (float).
  7007. */
  7008. Path2.prototype.length = function () {
  7009. var result = this._length;
  7010. if (!this.closed) {
  7011. var lastPoint = this._points[this._points.length - 1];
  7012. var firstPoint = this._points[0];
  7013. result += (firstPoint.subtract(lastPoint).length());
  7014. }
  7015. return result;
  7016. };
  7017. /**
  7018. * Returns the Path2 internal array of points.
  7019. */
  7020. Path2.prototype.getPoints = function () {
  7021. return this._points;
  7022. };
  7023. /**
  7024. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7025. */
  7026. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7027. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7028. return Vector2.Zero();
  7029. }
  7030. var lengthPosition = normalizedLengthPosition * this.length();
  7031. var previousOffset = 0;
  7032. for (var i = 0; i < this._points.length; i++) {
  7033. var j = (i + 1) % this._points.length;
  7034. var a = this._points[i];
  7035. var b = this._points[j];
  7036. var bToA = b.subtract(a);
  7037. var nextOffset = (bToA.length() + previousOffset);
  7038. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7039. var dir = bToA.normalize();
  7040. var localOffset = lengthPosition - previousOffset;
  7041. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7042. }
  7043. previousOffset = nextOffset;
  7044. }
  7045. return Vector2.Zero();
  7046. };
  7047. /**
  7048. * Returns a new Path2 starting at the coordinates (x, y).
  7049. */
  7050. Path2.StartingAt = function (x, y) {
  7051. return new Path2(x, y);
  7052. };
  7053. return Path2;
  7054. }());
  7055. BABYLON.Path2 = Path2;
  7056. var Path3D = /** @class */ (function () {
  7057. /**
  7058. * new Path3D(path, normal, raw)
  7059. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7060. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7061. * path : an array of Vector3, the curve axis of the Path3D
  7062. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7063. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7064. */
  7065. function Path3D(path, firstNormal, raw) {
  7066. if (firstNormal === void 0) { firstNormal = null; }
  7067. this.path = path;
  7068. this._curve = new Array();
  7069. this._distances = new Array();
  7070. this._tangents = new Array();
  7071. this._normals = new Array();
  7072. this._binormals = new Array();
  7073. for (var p = 0; p < path.length; p++) {
  7074. this._curve[p] = path[p].clone(); // hard copy
  7075. }
  7076. this._raw = raw || false;
  7077. this._compute(firstNormal);
  7078. }
  7079. /**
  7080. * Returns the Path3D array of successive Vector3 designing its curve.
  7081. */
  7082. Path3D.prototype.getCurve = function () {
  7083. return this._curve;
  7084. };
  7085. /**
  7086. * Returns an array populated with tangent vectors on each Path3D curve point.
  7087. */
  7088. Path3D.prototype.getTangents = function () {
  7089. return this._tangents;
  7090. };
  7091. /**
  7092. * Returns an array populated with normal vectors on each Path3D curve point.
  7093. */
  7094. Path3D.prototype.getNormals = function () {
  7095. return this._normals;
  7096. };
  7097. /**
  7098. * Returns an array populated with binormal vectors on each Path3D curve point.
  7099. */
  7100. Path3D.prototype.getBinormals = function () {
  7101. return this._binormals;
  7102. };
  7103. /**
  7104. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7105. */
  7106. Path3D.prototype.getDistances = function () {
  7107. return this._distances;
  7108. };
  7109. /**
  7110. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7111. * Returns the same object updated.
  7112. */
  7113. Path3D.prototype.update = function (path, firstNormal) {
  7114. if (firstNormal === void 0) { firstNormal = null; }
  7115. for (var p = 0; p < path.length; p++) {
  7116. this._curve[p].x = path[p].x;
  7117. this._curve[p].y = path[p].y;
  7118. this._curve[p].z = path[p].z;
  7119. }
  7120. this._compute(firstNormal);
  7121. return this;
  7122. };
  7123. // private function compute() : computes tangents, normals and binormals
  7124. Path3D.prototype._compute = function (firstNormal) {
  7125. var l = this._curve.length;
  7126. // first and last tangents
  7127. this._tangents[0] = this._getFirstNonNullVector(0);
  7128. if (!this._raw) {
  7129. this._tangents[0].normalize();
  7130. }
  7131. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7132. if (!this._raw) {
  7133. this._tangents[l - 1].normalize();
  7134. }
  7135. // normals and binormals at first point : arbitrary vector with _normalVector()
  7136. var tg0 = this._tangents[0];
  7137. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7138. this._normals[0] = pp0;
  7139. if (!this._raw) {
  7140. this._normals[0].normalize();
  7141. }
  7142. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7143. if (!this._raw) {
  7144. this._binormals[0].normalize();
  7145. }
  7146. this._distances[0] = 0.0;
  7147. // normals and binormals : next points
  7148. var prev; // previous vector (segment)
  7149. var cur; // current vector (segment)
  7150. var curTang; // current tangent
  7151. // previous normal
  7152. var prevBinor; // previous binormal
  7153. for (var i = 1; i < l; i++) {
  7154. // tangents
  7155. prev = this._getLastNonNullVector(i);
  7156. if (i < l - 1) {
  7157. cur = this._getFirstNonNullVector(i);
  7158. this._tangents[i] = prev.add(cur);
  7159. this._tangents[i].normalize();
  7160. }
  7161. this._distances[i] = this._distances[i - 1] + prev.length();
  7162. // normals and binormals
  7163. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7164. curTang = this._tangents[i];
  7165. prevBinor = this._binormals[i - 1];
  7166. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7167. if (!this._raw) {
  7168. this._normals[i].normalize();
  7169. }
  7170. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7171. if (!this._raw) {
  7172. this._binormals[i].normalize();
  7173. }
  7174. }
  7175. };
  7176. // private function getFirstNonNullVector(index)
  7177. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7178. Path3D.prototype._getFirstNonNullVector = function (index) {
  7179. var i = 1;
  7180. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7181. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7182. i++;
  7183. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7184. }
  7185. return nNVector;
  7186. };
  7187. // private function getLastNonNullVector(index)
  7188. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7189. Path3D.prototype._getLastNonNullVector = function (index) {
  7190. var i = 1;
  7191. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7192. while (nLVector.length() === 0 && index > i + 1) {
  7193. i++;
  7194. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7195. }
  7196. return nLVector;
  7197. };
  7198. // private function normalVector(v0, vt, va) :
  7199. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7200. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7201. Path3D.prototype._normalVector = function (v0, vt, va) {
  7202. var normal0;
  7203. var tgl = vt.length();
  7204. if (tgl === 0.0) {
  7205. tgl = 1.0;
  7206. }
  7207. if (va === undefined || va === null) {
  7208. var point;
  7209. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7210. point = new Vector3(0.0, -1.0, 0.0);
  7211. }
  7212. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7213. point = new Vector3(1.0, 0.0, 0.0);
  7214. }
  7215. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7216. point = new Vector3(0.0, 0.0, 1.0);
  7217. }
  7218. else {
  7219. point = Vector3.Zero();
  7220. }
  7221. normal0 = Vector3.Cross(vt, point);
  7222. }
  7223. else {
  7224. normal0 = Vector3.Cross(vt, va);
  7225. Vector3.CrossToRef(normal0, vt, normal0);
  7226. }
  7227. normal0.normalize();
  7228. return normal0;
  7229. };
  7230. return Path3D;
  7231. }());
  7232. BABYLON.Path3D = Path3D;
  7233. var Curve3 = /** @class */ (function () {
  7234. /**
  7235. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7236. * A Curve3 is designed from a series of successive Vector3.
  7237. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7238. */
  7239. function Curve3(points) {
  7240. this._length = 0.0;
  7241. this._points = points;
  7242. this._length = this._computeLength(points);
  7243. }
  7244. /**
  7245. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7246. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7247. * @param v1 (Vector3) the control point
  7248. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7249. * @param nbPoints (integer) the wanted number of points in the curve
  7250. */
  7251. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7252. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7253. var bez = new Array();
  7254. var equation = function (t, val0, val1, val2) {
  7255. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7256. return res;
  7257. };
  7258. for (var i = 0; i <= nbPoints; i++) {
  7259. 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)));
  7260. }
  7261. return new Curve3(bez);
  7262. };
  7263. /**
  7264. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7265. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7266. * @param v1 (Vector3) the first control point
  7267. * @param v2 (Vector3) the second control point
  7268. * @param v3 (Vector3) the end point of the Cubic Bezier
  7269. * @param nbPoints (integer) the wanted number of points in the curve
  7270. */
  7271. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7272. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7273. var bez = new Array();
  7274. var equation = function (t, val0, val1, val2, val3) {
  7275. 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;
  7276. return res;
  7277. };
  7278. for (var i = 0; i <= nbPoints; i++) {
  7279. 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)));
  7280. }
  7281. return new Curve3(bez);
  7282. };
  7283. /**
  7284. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7285. * @param p1 (Vector3) the origin point of the Hermite Spline
  7286. * @param t1 (Vector3) the tangent vector at the origin point
  7287. * @param p2 (Vector3) the end point of the Hermite Spline
  7288. * @param t2 (Vector3) the tangent vector at the end point
  7289. * @param nbPoints (integer) the wanted number of points in the curve
  7290. */
  7291. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7292. var hermite = new Array();
  7293. var step = 1.0 / nbPoints;
  7294. for (var i = 0; i <= nbPoints; i++) {
  7295. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7296. }
  7297. return new Curve3(hermite);
  7298. };
  7299. /**
  7300. * Returns a Curve3 object along a CatmullRom Spline curve :
  7301. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7302. * @param nbPoints (integer) the wanted number of points between each curve control points
  7303. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7304. */
  7305. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7306. var catmullRom = new Array();
  7307. var step = 1.0 / nbPoints;
  7308. var amount = 0.0;
  7309. if (closed) {
  7310. var pointsCount = points.length;
  7311. for (var i = 0; i < pointsCount; i++) {
  7312. amount = 0;
  7313. for (var c = 0; c < nbPoints; c++) {
  7314. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7315. amount += step;
  7316. }
  7317. }
  7318. catmullRom.push(catmullRom[0]);
  7319. }
  7320. else {
  7321. var totalPoints = new Array();
  7322. totalPoints.push(points[0].clone());
  7323. Array.prototype.push.apply(totalPoints, points);
  7324. totalPoints.push(points[points.length - 1].clone());
  7325. for (var i = 0; i < totalPoints.length - 3; i++) {
  7326. amount = 0;
  7327. for (var c = 0; c < nbPoints; c++) {
  7328. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7329. amount += step;
  7330. }
  7331. }
  7332. i--;
  7333. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7334. }
  7335. return new Curve3(catmullRom);
  7336. };
  7337. /**
  7338. * Returns the Curve3 stored array of successive Vector3
  7339. */
  7340. Curve3.prototype.getPoints = function () {
  7341. return this._points;
  7342. };
  7343. /**
  7344. * Returns the computed length (float) of the curve.
  7345. */
  7346. Curve3.prototype.length = function () {
  7347. return this._length;
  7348. };
  7349. /**
  7350. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7351. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7352. * curveA and curveB keep unchanged.
  7353. */
  7354. Curve3.prototype.continue = function (curve) {
  7355. var lastPoint = this._points[this._points.length - 1];
  7356. var continuedPoints = this._points.slice();
  7357. var curvePoints = curve.getPoints();
  7358. for (var i = 1; i < curvePoints.length; i++) {
  7359. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7360. }
  7361. var continuedCurve = new Curve3(continuedPoints);
  7362. return continuedCurve;
  7363. };
  7364. Curve3.prototype._computeLength = function (path) {
  7365. var l = 0;
  7366. for (var i = 1; i < path.length; i++) {
  7367. l += (path[i].subtract(path[i - 1])).length();
  7368. }
  7369. return l;
  7370. };
  7371. return Curve3;
  7372. }());
  7373. BABYLON.Curve3 = Curve3;
  7374. // Vertex formats
  7375. var PositionNormalVertex = /** @class */ (function () {
  7376. function PositionNormalVertex(position, normal) {
  7377. if (position === void 0) { position = Vector3.Zero(); }
  7378. if (normal === void 0) { normal = Vector3.Up(); }
  7379. this.position = position;
  7380. this.normal = normal;
  7381. }
  7382. PositionNormalVertex.prototype.clone = function () {
  7383. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7384. };
  7385. return PositionNormalVertex;
  7386. }());
  7387. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7388. var PositionNormalTextureVertex = /** @class */ (function () {
  7389. function PositionNormalTextureVertex(position, normal, uv) {
  7390. if (position === void 0) { position = Vector3.Zero(); }
  7391. if (normal === void 0) { normal = Vector3.Up(); }
  7392. if (uv === void 0) { uv = Vector2.Zero(); }
  7393. this.position = position;
  7394. this.normal = normal;
  7395. this.uv = uv;
  7396. }
  7397. PositionNormalTextureVertex.prototype.clone = function () {
  7398. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7399. };
  7400. return PositionNormalTextureVertex;
  7401. }());
  7402. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7403. // Temporary pre-allocated objects for engine internal use
  7404. // usage in any internal function :
  7405. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7406. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7407. var Tmp = /** @class */ (function () {
  7408. function Tmp() {
  7409. }
  7410. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7411. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7412. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7413. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7414. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7415. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7416. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7417. Matrix.Zero(), Matrix.Zero(),
  7418. Matrix.Zero(), Matrix.Zero(),
  7419. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7420. return Tmp;
  7421. }());
  7422. BABYLON.Tmp = Tmp;
  7423. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7424. var MathTmp = /** @class */ (function () {
  7425. function MathTmp() {
  7426. }
  7427. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7428. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7429. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7430. return MathTmp;
  7431. }());
  7432. })(BABYLON || (BABYLON = {}));
  7433. //# sourceMappingURL=babylon.math.js.map
  7434. var BABYLON;
  7435. (function (BABYLON) {
  7436. var Scalar = /** @class */ (function () {
  7437. function Scalar() {
  7438. }
  7439. /**
  7440. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7441. */
  7442. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7443. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7444. var num = a - b;
  7445. return -epsilon <= num && num <= epsilon;
  7446. };
  7447. /**
  7448. * Returns a string : the upper case translation of the number i to hexadecimal.
  7449. */
  7450. Scalar.ToHex = function (i) {
  7451. var str = i.toString(16);
  7452. if (i <= 15) {
  7453. return ("0" + str).toUpperCase();
  7454. }
  7455. return str.toUpperCase();
  7456. };
  7457. /**
  7458. * Returns -1 if value is negative and +1 is value is positive.
  7459. * Returns the value itself if it's equal to zero.
  7460. */
  7461. Scalar.Sign = function (value) {
  7462. value = +value; // convert to a number
  7463. if (value === 0 || isNaN(value))
  7464. return value;
  7465. return value > 0 ? 1 : -1;
  7466. };
  7467. /**
  7468. * Returns the value itself if it's between min and max.
  7469. * Returns min if the value is lower than min.
  7470. * Returns max if the value is greater than max.
  7471. */
  7472. Scalar.Clamp = function (value, min, max) {
  7473. if (min === void 0) { min = 0; }
  7474. if (max === void 0) { max = 1; }
  7475. return Math.min(max, Math.max(min, value));
  7476. };
  7477. /**
  7478. * Returns the log2 of value.
  7479. */
  7480. Scalar.Log2 = function (value) {
  7481. return Math.log(value) * Math.LOG2E;
  7482. };
  7483. /**
  7484. * Loops the value, so that it is never larger than length and never smaller than 0.
  7485. *
  7486. * This is similar to the modulo operator but it works with floating point numbers.
  7487. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7488. * With t = 5 and length = 2.5, the result would be 0.0.
  7489. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7490. */
  7491. Scalar.Repeat = function (value, length) {
  7492. return value - Math.floor(value / length) * length;
  7493. };
  7494. /**
  7495. * Normalize the value between 0.0 and 1.0 using min and max values
  7496. */
  7497. Scalar.Normalize = function (value, min, max) {
  7498. return (value - min) / (max - min);
  7499. };
  7500. /**
  7501. * Denormalize the value from 0.0 and 1.0 using min and max values
  7502. */
  7503. Scalar.Denormalize = function (normalized, min, max) {
  7504. return (normalized * (max - min) + min);
  7505. };
  7506. /**
  7507. * Calculates the shortest difference between two given angles given in degrees.
  7508. */
  7509. Scalar.DeltaAngle = function (current, target) {
  7510. var num = Scalar.Repeat(target - current, 360.0);
  7511. if (num > 180.0) {
  7512. num -= 360.0;
  7513. }
  7514. return num;
  7515. };
  7516. /**
  7517. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7518. *
  7519. * The returned value will move back and forth between 0 and length
  7520. */
  7521. Scalar.PingPong = function (tx, length) {
  7522. var t = Scalar.Repeat(tx, length * 2.0);
  7523. return length - Math.abs(t - length);
  7524. };
  7525. /**
  7526. * Interpolates between min and max with smoothing at the limits.
  7527. *
  7528. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7529. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7530. */
  7531. Scalar.SmoothStep = function (from, to, tx) {
  7532. var t = Scalar.Clamp(tx);
  7533. t = -2.0 * t * t * t + 3.0 * t * t;
  7534. return to * t + from * (1.0 - t);
  7535. };
  7536. /**
  7537. * Moves a value current towards target.
  7538. *
  7539. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7540. * Negative values of maxDelta pushes the value away from target.
  7541. */
  7542. Scalar.MoveTowards = function (current, target, maxDelta) {
  7543. var result = 0;
  7544. if (Math.abs(target - current) <= maxDelta) {
  7545. result = target;
  7546. }
  7547. else {
  7548. result = current + Scalar.Sign(target - current) * maxDelta;
  7549. }
  7550. return result;
  7551. };
  7552. /**
  7553. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7554. *
  7555. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7556. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7557. */
  7558. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7559. var num = Scalar.DeltaAngle(current, target);
  7560. var result = 0;
  7561. if (-maxDelta < num && num < maxDelta) {
  7562. result = target;
  7563. }
  7564. else {
  7565. target = current + num;
  7566. result = Scalar.MoveTowards(current, target, maxDelta);
  7567. }
  7568. return result;
  7569. };
  7570. /**
  7571. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7572. */
  7573. Scalar.Lerp = function (start, end, amount) {
  7574. return start + ((end - start) * amount);
  7575. };
  7576. /**
  7577. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7578. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7579. */
  7580. Scalar.LerpAngle = function (start, end, amount) {
  7581. var num = Scalar.Repeat(end - start, 360.0);
  7582. if (num > 180.0) {
  7583. num -= 360.0;
  7584. }
  7585. return start + num * Scalar.Clamp(amount);
  7586. };
  7587. /**
  7588. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7589. */
  7590. Scalar.InverseLerp = function (a, b, value) {
  7591. var result = 0;
  7592. if (a != b) {
  7593. result = Scalar.Clamp((value - a) / (b - a));
  7594. }
  7595. else {
  7596. result = 0.0;
  7597. }
  7598. return result;
  7599. };
  7600. /**
  7601. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7602. */
  7603. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7604. var squared = amount * amount;
  7605. var cubed = amount * squared;
  7606. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7607. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7608. var part3 = (cubed - (2.0 * squared)) + amount;
  7609. var part4 = cubed - squared;
  7610. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7611. };
  7612. /**
  7613. * Returns a random float number between and min and max values
  7614. */
  7615. Scalar.RandomRange = function (min, max) {
  7616. if (min === max)
  7617. return min;
  7618. return ((Math.random() * (max - min)) + min);
  7619. };
  7620. /**
  7621. * This function returns percentage of a number in a given range.
  7622. *
  7623. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7624. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7625. */
  7626. Scalar.RangeToPercent = function (number, min, max) {
  7627. return ((number - min) / (max - min));
  7628. };
  7629. /**
  7630. * This function returns number that corresponds to the percentage in a given range.
  7631. *
  7632. * PercentToRange(0.34,0,100) will return 34.
  7633. */
  7634. Scalar.PercentToRange = function (percent, min, max) {
  7635. return ((max - min) * percent + min);
  7636. };
  7637. /**
  7638. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7639. * @param angle The angle to normalize in radian.
  7640. * @return The converted angle.
  7641. */
  7642. Scalar.NormalizeRadians = function (angle) {
  7643. // More precise but slower version kept for reference.
  7644. // angle = angle % Tools.TwoPi;
  7645. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7646. //if (angle > Math.PI) {
  7647. // angle -= Tools.TwoPi;
  7648. //}
  7649. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7650. return angle;
  7651. };
  7652. /**
  7653. * Two pi constants convenient for computation.
  7654. */
  7655. Scalar.TwoPi = Math.PI * 2;
  7656. return Scalar;
  7657. }());
  7658. BABYLON.Scalar = Scalar;
  7659. })(BABYLON || (BABYLON = {}));
  7660. //# sourceMappingURL=babylon.math.scalar.js.map
  7661. //# sourceMappingURL=babylon.mixins.js.map
  7662. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7663. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7664. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7665. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7666. //# sourceMappingURL=babylon.webgl2.js.map
  7667. var BABYLON;
  7668. (function (BABYLON) {
  7669. var __decoratorInitialStore = {};
  7670. var __mergedStore = {};
  7671. var _copySource = function (creationFunction, source, instanciate) {
  7672. var destination = creationFunction();
  7673. // Tags
  7674. if (BABYLON.Tags) {
  7675. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7676. }
  7677. var classStore = getMergedStore(destination);
  7678. // Properties
  7679. for (var property in classStore) {
  7680. var propertyDescriptor = classStore[property];
  7681. var sourceProperty = source[property];
  7682. var propertyType = propertyDescriptor.type;
  7683. if (sourceProperty !== undefined && sourceProperty !== null) {
  7684. switch (propertyType) {
  7685. case 0: // Value
  7686. case 6: // Mesh reference
  7687. case 11: // Camera reference
  7688. destination[property] = sourceProperty;
  7689. break;
  7690. case 1: // Texture
  7691. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7692. break;
  7693. case 2: // Color3
  7694. case 3: // FresnelParameters
  7695. case 4: // Vector2
  7696. case 5: // Vector3
  7697. case 7: // Color Curves
  7698. case 10: // Quaternion
  7699. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7700. break;
  7701. }
  7702. }
  7703. }
  7704. return destination;
  7705. };
  7706. function getDirectStore(target) {
  7707. var classKey = target.getClassName();
  7708. if (!__decoratorInitialStore[classKey]) {
  7709. __decoratorInitialStore[classKey] = {};
  7710. }
  7711. return __decoratorInitialStore[classKey];
  7712. }
  7713. /**
  7714. * Return the list of properties flagged as serializable
  7715. * @param target: host object
  7716. */
  7717. function getMergedStore(target) {
  7718. var classKey = target.getClassName();
  7719. if (__mergedStore[classKey]) {
  7720. return __mergedStore[classKey];
  7721. }
  7722. __mergedStore[classKey] = {};
  7723. var store = __mergedStore[classKey];
  7724. var currentTarget = target;
  7725. var currentKey = classKey;
  7726. while (currentKey) {
  7727. var initialStore = __decoratorInitialStore[currentKey];
  7728. for (var property in initialStore) {
  7729. store[property] = initialStore[property];
  7730. }
  7731. var parent_1 = void 0;
  7732. var done = false;
  7733. do {
  7734. parent_1 = Object.getPrototypeOf(currentTarget);
  7735. if (!parent_1.getClassName) {
  7736. done = true;
  7737. break;
  7738. }
  7739. if (parent_1.getClassName() !== currentKey) {
  7740. break;
  7741. }
  7742. currentTarget = parent_1;
  7743. } while (parent_1);
  7744. if (done) {
  7745. break;
  7746. }
  7747. currentKey = parent_1.getClassName();
  7748. currentTarget = parent_1;
  7749. }
  7750. return store;
  7751. }
  7752. function generateSerializableMember(type, sourceName) {
  7753. return function (target, propertyKey) {
  7754. var classStore = getDirectStore(target);
  7755. if (!classStore[propertyKey]) {
  7756. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7757. }
  7758. };
  7759. }
  7760. function generateExpandMember(setCallback, targetKey) {
  7761. if (targetKey === void 0) { targetKey = null; }
  7762. return function (target, propertyKey) {
  7763. var key = targetKey || ("_" + propertyKey);
  7764. Object.defineProperty(target, propertyKey, {
  7765. get: function () {
  7766. return this[key];
  7767. },
  7768. set: function (value) {
  7769. if (this[key] === value) {
  7770. return;
  7771. }
  7772. this[key] = value;
  7773. target[setCallback].apply(this);
  7774. },
  7775. enumerable: true,
  7776. configurable: true
  7777. });
  7778. };
  7779. }
  7780. function expandToProperty(callback, targetKey) {
  7781. if (targetKey === void 0) { targetKey = null; }
  7782. return generateExpandMember(callback, targetKey);
  7783. }
  7784. BABYLON.expandToProperty = expandToProperty;
  7785. function serialize(sourceName) {
  7786. return generateSerializableMember(0, sourceName); // value member
  7787. }
  7788. BABYLON.serialize = serialize;
  7789. function serializeAsTexture(sourceName) {
  7790. return generateSerializableMember(1, sourceName); // texture member
  7791. }
  7792. BABYLON.serializeAsTexture = serializeAsTexture;
  7793. function serializeAsColor3(sourceName) {
  7794. return generateSerializableMember(2, sourceName); // color3 member
  7795. }
  7796. BABYLON.serializeAsColor3 = serializeAsColor3;
  7797. function serializeAsFresnelParameters(sourceName) {
  7798. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7799. }
  7800. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7801. function serializeAsVector2(sourceName) {
  7802. return generateSerializableMember(4, sourceName); // vector2 member
  7803. }
  7804. BABYLON.serializeAsVector2 = serializeAsVector2;
  7805. function serializeAsVector3(sourceName) {
  7806. return generateSerializableMember(5, sourceName); // vector3 member
  7807. }
  7808. BABYLON.serializeAsVector3 = serializeAsVector3;
  7809. function serializeAsMeshReference(sourceName) {
  7810. return generateSerializableMember(6, sourceName); // mesh reference member
  7811. }
  7812. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7813. function serializeAsColorCurves(sourceName) {
  7814. return generateSerializableMember(7, sourceName); // color curves
  7815. }
  7816. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7817. function serializeAsColor4(sourceName) {
  7818. return generateSerializableMember(8, sourceName); // color 4
  7819. }
  7820. BABYLON.serializeAsColor4 = serializeAsColor4;
  7821. function serializeAsImageProcessingConfiguration(sourceName) {
  7822. return generateSerializableMember(9, sourceName); // image processing
  7823. }
  7824. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7825. function serializeAsQuaternion(sourceName) {
  7826. return generateSerializableMember(10, sourceName); // quaternion member
  7827. }
  7828. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7829. /**
  7830. * Decorator used to define property that can be serialized as reference to a camera
  7831. * @param sourceName defines the name of the property to decorate
  7832. */
  7833. function serializeAsCameraReference(sourceName) {
  7834. return generateSerializableMember(11, sourceName); // camera reference member
  7835. }
  7836. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7837. var SerializationHelper = /** @class */ (function () {
  7838. function SerializationHelper() {
  7839. }
  7840. SerializationHelper.Serialize = function (entity, serializationObject) {
  7841. if (!serializationObject) {
  7842. serializationObject = {};
  7843. }
  7844. // Tags
  7845. if (BABYLON.Tags) {
  7846. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7847. }
  7848. var serializedProperties = getMergedStore(entity);
  7849. // Properties
  7850. for (var property in serializedProperties) {
  7851. var propertyDescriptor = serializedProperties[property];
  7852. var targetPropertyName = propertyDescriptor.sourceName || property;
  7853. var propertyType = propertyDescriptor.type;
  7854. var sourceProperty = entity[property];
  7855. if (sourceProperty !== undefined && sourceProperty !== null) {
  7856. switch (propertyType) {
  7857. case 0: // Value
  7858. serializationObject[targetPropertyName] = sourceProperty;
  7859. break;
  7860. case 1: // Texture
  7861. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7862. break;
  7863. case 2: // Color3
  7864. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7865. break;
  7866. case 3: // FresnelParameters
  7867. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7868. break;
  7869. case 4: // Vector2
  7870. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7871. break;
  7872. case 5: // Vector3
  7873. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7874. break;
  7875. case 6: // Mesh reference
  7876. serializationObject[targetPropertyName] = sourceProperty.id;
  7877. break;
  7878. case 7: // Color Curves
  7879. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7880. break;
  7881. case 8: // Color 4
  7882. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7883. break;
  7884. case 9: // Image Processing
  7885. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7886. break;
  7887. case 10: // Quaternion
  7888. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7889. break;
  7890. case 11: // Camera reference
  7891. serializationObject[targetPropertyName] = sourceProperty.id;
  7892. break;
  7893. }
  7894. }
  7895. }
  7896. return serializationObject;
  7897. };
  7898. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7899. if (rootUrl === void 0) { rootUrl = null; }
  7900. var destination = creationFunction();
  7901. if (!rootUrl) {
  7902. rootUrl = "";
  7903. }
  7904. // Tags
  7905. if (BABYLON.Tags) {
  7906. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7907. }
  7908. var classStore = getMergedStore(destination);
  7909. // Properties
  7910. for (var property in classStore) {
  7911. var propertyDescriptor = classStore[property];
  7912. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7913. var propertyType = propertyDescriptor.type;
  7914. if (sourceProperty !== undefined && sourceProperty !== null) {
  7915. var dest = destination;
  7916. switch (propertyType) {
  7917. case 0: // Value
  7918. dest[property] = sourceProperty;
  7919. break;
  7920. case 1: // Texture
  7921. if (scene) {
  7922. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7923. }
  7924. break;
  7925. case 2: // Color3
  7926. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7927. break;
  7928. case 3: // FresnelParameters
  7929. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7930. break;
  7931. case 4: // Vector2
  7932. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7933. break;
  7934. case 5: // Vector3
  7935. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7936. break;
  7937. case 6: // Mesh reference
  7938. if (scene) {
  7939. dest[property] = scene.getLastMeshByID(sourceProperty);
  7940. }
  7941. break;
  7942. case 7: // Color Curves
  7943. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7944. break;
  7945. case 8: // Color 4
  7946. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7947. break;
  7948. case 9: // Image Processing
  7949. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7950. break;
  7951. case 10: // Quaternion
  7952. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7953. break;
  7954. case 11: // Camera reference
  7955. if (scene) {
  7956. dest[property] = scene.getCameraByID(sourceProperty);
  7957. }
  7958. break;
  7959. }
  7960. }
  7961. }
  7962. return destination;
  7963. };
  7964. SerializationHelper.Clone = function (creationFunction, source) {
  7965. return _copySource(creationFunction, source, false);
  7966. };
  7967. SerializationHelper.Instanciate = function (creationFunction, source) {
  7968. return _copySource(creationFunction, source, true);
  7969. };
  7970. return SerializationHelper;
  7971. }());
  7972. BABYLON.SerializationHelper = SerializationHelper;
  7973. })(BABYLON || (BABYLON = {}));
  7974. //# sourceMappingURL=babylon.decorators.js.map
  7975. var BABYLON;
  7976. (function (BABYLON) {
  7977. /**
  7978. * Wrapper class for promise with external resolve and reject.
  7979. */
  7980. var Deferred = /** @class */ (function () {
  7981. /**
  7982. * Constructor for this deferred object.
  7983. */
  7984. function Deferred() {
  7985. var _this = this;
  7986. this.promise = new Promise(function (resolve, reject) {
  7987. _this._resolve = resolve;
  7988. _this._reject = reject;
  7989. });
  7990. }
  7991. Object.defineProperty(Deferred.prototype, "resolve", {
  7992. /**
  7993. * The resolve method of the promise associated with this deferred object.
  7994. */
  7995. get: function () {
  7996. return this._resolve;
  7997. },
  7998. enumerable: true,
  7999. configurable: true
  8000. });
  8001. Object.defineProperty(Deferred.prototype, "reject", {
  8002. /**
  8003. * The reject method of the promise associated with this deferred object.
  8004. */
  8005. get: function () {
  8006. return this._reject;
  8007. },
  8008. enumerable: true,
  8009. configurable: true
  8010. });
  8011. return Deferred;
  8012. }());
  8013. BABYLON.Deferred = Deferred;
  8014. })(BABYLON || (BABYLON = {}));
  8015. //# sourceMappingURL=babylon.deferred.js.map
  8016. var BABYLON;
  8017. (function (BABYLON) {
  8018. /**
  8019. * A class serves as a medium between the observable and its observers
  8020. */
  8021. var EventState = /** @class */ (function () {
  8022. /**
  8023. * Create a new EventState
  8024. * @param mask defines the mask associated with this state
  8025. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8026. * @param target defines the original target of the state
  8027. * @param currentTarget defines the current target of the state
  8028. */
  8029. function EventState(mask, skipNextObservers, target, currentTarget) {
  8030. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8031. this.initalize(mask, skipNextObservers, target, currentTarget);
  8032. }
  8033. /**
  8034. * Initialize the current event state
  8035. * @param mask defines the mask associated with this state
  8036. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8037. * @param target defines the original target of the state
  8038. * @param currentTarget defines the current target of the state
  8039. * @returns the current event state
  8040. */
  8041. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8042. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8043. this.mask = mask;
  8044. this.skipNextObservers = skipNextObservers;
  8045. this.target = target;
  8046. this.currentTarget = currentTarget;
  8047. return this;
  8048. };
  8049. return EventState;
  8050. }());
  8051. BABYLON.EventState = EventState;
  8052. /**
  8053. * Represent an Observer registered to a given Observable object.
  8054. */
  8055. var Observer = /** @class */ (function () {
  8056. /**
  8057. * Creates a new observer
  8058. * @param callback defines the callback to call when the observer is notified
  8059. * @param mask defines the mask of the observer (used to filter notifications)
  8060. * @param scope defines the current scope used to restore the JS context
  8061. */
  8062. function Observer(
  8063. /**
  8064. * Defines the callback to call when the observer is notified
  8065. */
  8066. callback,
  8067. /**
  8068. * Defines the mask of the observer (used to filter notifications)
  8069. */
  8070. mask,
  8071. /**
  8072. * Defines the current scope used to restore the JS context
  8073. */
  8074. scope) {
  8075. if (scope === void 0) { scope = null; }
  8076. this.callback = callback;
  8077. this.mask = mask;
  8078. this.scope = scope;
  8079. /** @hidden */
  8080. this._willBeUnregistered = false;
  8081. /**
  8082. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8083. */
  8084. this.unregisterOnNextCall = false;
  8085. }
  8086. return Observer;
  8087. }());
  8088. BABYLON.Observer = Observer;
  8089. /**
  8090. * Represent a list of observers registered to multiple Observables object.
  8091. */
  8092. var MultiObserver = /** @class */ (function () {
  8093. function MultiObserver() {
  8094. }
  8095. /**
  8096. * Release associated resources
  8097. */
  8098. MultiObserver.prototype.dispose = function () {
  8099. if (this._observers && this._observables) {
  8100. for (var index = 0; index < this._observers.length; index++) {
  8101. this._observables[index].remove(this._observers[index]);
  8102. }
  8103. }
  8104. this._observers = null;
  8105. this._observables = null;
  8106. };
  8107. /**
  8108. * Raise a callback when one of the observable will notify
  8109. * @param observables defines a list of observables to watch
  8110. * @param callback defines the callback to call on notification
  8111. * @param mask defines the mask used to filter notifications
  8112. * @param scope defines the current scope used to restore the JS context
  8113. * @returns the new MultiObserver
  8114. */
  8115. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8116. if (mask === void 0) { mask = -1; }
  8117. if (scope === void 0) { scope = null; }
  8118. var result = new MultiObserver();
  8119. result._observers = new Array();
  8120. result._observables = observables;
  8121. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8122. var observable = observables_1[_i];
  8123. var observer = observable.add(callback, mask, false, scope);
  8124. if (observer) {
  8125. result._observers.push(observer);
  8126. }
  8127. }
  8128. return result;
  8129. };
  8130. return MultiObserver;
  8131. }());
  8132. BABYLON.MultiObserver = MultiObserver;
  8133. /**
  8134. * The Observable class is a simple implementation of the Observable pattern.
  8135. *
  8136. * 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.
  8137. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8138. * 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).
  8139. * 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.
  8140. */
  8141. var Observable = /** @class */ (function () {
  8142. /**
  8143. * Creates a new observable
  8144. * @param onObserverAdded defines a callback to call when a new observer is added
  8145. */
  8146. function Observable(onObserverAdded) {
  8147. this._observers = new Array();
  8148. this._eventState = new EventState(0);
  8149. if (onObserverAdded) {
  8150. this._onObserverAdded = onObserverAdded;
  8151. }
  8152. }
  8153. /**
  8154. * Create a new Observer with the specified callback
  8155. * @param callback the callback that will be executed for that Observer
  8156. * @param mask the mask used to filter observers
  8157. * @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.
  8158. * @param scope optional scope for the callback to be called from
  8159. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8160. * @returns the new observer created for the callback
  8161. */
  8162. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8163. if (mask === void 0) { mask = -1; }
  8164. if (insertFirst === void 0) { insertFirst = false; }
  8165. if (scope === void 0) { scope = null; }
  8166. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8167. if (!callback) {
  8168. return null;
  8169. }
  8170. var observer = new Observer(callback, mask, scope);
  8171. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8172. if (insertFirst) {
  8173. this._observers.unshift(observer);
  8174. }
  8175. else {
  8176. this._observers.push(observer);
  8177. }
  8178. if (this._onObserverAdded) {
  8179. this._onObserverAdded(observer);
  8180. }
  8181. return observer;
  8182. };
  8183. /**
  8184. * Remove an Observer from the Observable object
  8185. * @param observer the instance of the Observer to remove
  8186. * @returns false if it doesn't belong to this Observable
  8187. */
  8188. Observable.prototype.remove = function (observer) {
  8189. if (!observer) {
  8190. return false;
  8191. }
  8192. var index = this._observers.indexOf(observer);
  8193. if (index !== -1) {
  8194. this._observers.splice(index, 1);
  8195. return true;
  8196. }
  8197. return false;
  8198. };
  8199. /**
  8200. * Remove a callback from the Observable object
  8201. * @param callback the callback to remove
  8202. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8203. * @returns false if it doesn't belong to this Observable
  8204. */
  8205. Observable.prototype.removeCallback = function (callback, scope) {
  8206. for (var index = 0; index < this._observers.length; index++) {
  8207. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8208. this._observers.splice(index, 1);
  8209. return true;
  8210. }
  8211. }
  8212. return false;
  8213. };
  8214. Observable.prototype._deferUnregister = function (observer) {
  8215. var _this = this;
  8216. observer.unregisterOnNextCall = false;
  8217. observer._willBeUnregistered = true;
  8218. BABYLON.Tools.SetImmediate(function () {
  8219. _this.remove(observer);
  8220. });
  8221. };
  8222. /**
  8223. * Notify all Observers by calling their respective callback with the given data
  8224. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8225. * @param eventData defines the data to send to all observers
  8226. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8227. * @param target defines the original target of the state
  8228. * @param currentTarget defines the current target of the state
  8229. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8230. */
  8231. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8232. if (mask === void 0) { mask = -1; }
  8233. if (!this._observers.length) {
  8234. return true;
  8235. }
  8236. var state = this._eventState;
  8237. state.mask = mask;
  8238. state.target = target;
  8239. state.currentTarget = currentTarget;
  8240. state.skipNextObservers = false;
  8241. state.lastReturnValue = eventData;
  8242. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8243. var obs = _a[_i];
  8244. if (obs._willBeUnregistered) {
  8245. continue;
  8246. }
  8247. if (obs.mask & mask) {
  8248. if (obs.scope) {
  8249. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8250. }
  8251. else {
  8252. state.lastReturnValue = obs.callback(eventData, state);
  8253. }
  8254. if (obs.unregisterOnNextCall) {
  8255. this._deferUnregister(obs);
  8256. }
  8257. }
  8258. if (state.skipNextObservers) {
  8259. return false;
  8260. }
  8261. }
  8262. return true;
  8263. };
  8264. /**
  8265. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8266. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8267. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8268. * and it is crucial that all callbacks will be executed.
  8269. * The order of the callbacks is kept, callbacks are not executed parallel.
  8270. *
  8271. * @param eventData The data to be sent to each callback
  8272. * @param mask is used to filter observers defaults to -1
  8273. * @param target defines the callback target (see EventState)
  8274. * @param currentTarget defines he current object in the bubbling phase
  8275. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8276. */
  8277. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8278. var _this = this;
  8279. if (mask === void 0) { mask = -1; }
  8280. // create an empty promise
  8281. var p = Promise.resolve(eventData);
  8282. // no observers? return this promise.
  8283. if (!this._observers.length) {
  8284. return p;
  8285. }
  8286. var state = this._eventState;
  8287. state.mask = mask;
  8288. state.target = target;
  8289. state.currentTarget = currentTarget;
  8290. state.skipNextObservers = false;
  8291. // execute one callback after another (not using Promise.all, the order is important)
  8292. this._observers.forEach(function (obs) {
  8293. if (state.skipNextObservers) {
  8294. return;
  8295. }
  8296. if (obs._willBeUnregistered) {
  8297. return;
  8298. }
  8299. if (obs.mask & mask) {
  8300. if (obs.scope) {
  8301. p = p.then(function (lastReturnedValue) {
  8302. state.lastReturnValue = lastReturnedValue;
  8303. return obs.callback.apply(obs.scope, [eventData, state]);
  8304. });
  8305. }
  8306. else {
  8307. p = p.then(function (lastReturnedValue) {
  8308. state.lastReturnValue = lastReturnedValue;
  8309. return obs.callback(eventData, state);
  8310. });
  8311. }
  8312. if (obs.unregisterOnNextCall) {
  8313. _this._deferUnregister(obs);
  8314. }
  8315. }
  8316. });
  8317. // return the eventData
  8318. return p.then(function () { return eventData; });
  8319. };
  8320. /**
  8321. * Notify a specific observer
  8322. * @param observer defines the observer to notify
  8323. * @param eventData defines the data to be sent to each callback
  8324. * @param mask is used to filter observers defaults to -1
  8325. */
  8326. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8327. if (mask === void 0) { mask = -1; }
  8328. var state = this._eventState;
  8329. state.mask = mask;
  8330. state.skipNextObservers = false;
  8331. observer.callback(eventData, state);
  8332. };
  8333. /**
  8334. * Gets a boolean indicating if the observable has at least one observer
  8335. * @returns true is the Observable has at least one Observer registered
  8336. */
  8337. Observable.prototype.hasObservers = function () {
  8338. return this._observers.length > 0;
  8339. };
  8340. /**
  8341. * Clear the list of observers
  8342. */
  8343. Observable.prototype.clear = function () {
  8344. this._observers = new Array();
  8345. this._onObserverAdded = null;
  8346. };
  8347. /**
  8348. * Clone the current observable
  8349. * @returns a new observable
  8350. */
  8351. Observable.prototype.clone = function () {
  8352. var result = new Observable();
  8353. result._observers = this._observers.slice(0);
  8354. return result;
  8355. };
  8356. /**
  8357. * Does this observable handles observer registered with a given mask
  8358. * @param mask defines the mask to be tested
  8359. * @return whether or not one observer registered with the given mask is handeled
  8360. **/
  8361. Observable.prototype.hasSpecificMask = function (mask) {
  8362. if (mask === void 0) { mask = -1; }
  8363. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8364. var obs = _a[_i];
  8365. if (obs.mask & mask || obs.mask === mask) {
  8366. return true;
  8367. }
  8368. }
  8369. return false;
  8370. };
  8371. return Observable;
  8372. }());
  8373. BABYLON.Observable = Observable;
  8374. })(BABYLON || (BABYLON = {}));
  8375. //# sourceMappingURL=babylon.observable.js.map
  8376. var BABYLON;
  8377. (function (BABYLON) {
  8378. var SmartArray = /** @class */ (function () {
  8379. function SmartArray(capacity) {
  8380. this.length = 0;
  8381. this.data = new Array(capacity);
  8382. this._id = SmartArray._GlobalId++;
  8383. }
  8384. SmartArray.prototype.push = function (value) {
  8385. this.data[this.length++] = value;
  8386. if (this.length > this.data.length) {
  8387. this.data.length *= 2;
  8388. }
  8389. };
  8390. SmartArray.prototype.forEach = function (func) {
  8391. for (var index = 0; index < this.length; index++) {
  8392. func(this.data[index]);
  8393. }
  8394. };
  8395. SmartArray.prototype.sort = function (compareFn) {
  8396. this.data.sort(compareFn);
  8397. };
  8398. SmartArray.prototype.reset = function () {
  8399. this.length = 0;
  8400. };
  8401. SmartArray.prototype.dispose = function () {
  8402. this.reset();
  8403. if (this.data) {
  8404. this.data.length = 0;
  8405. this.data = [];
  8406. }
  8407. };
  8408. SmartArray.prototype.concat = function (array) {
  8409. if (array.length === 0) {
  8410. return;
  8411. }
  8412. if (this.length + array.length > this.data.length) {
  8413. this.data.length = (this.length + array.length) * 2;
  8414. }
  8415. for (var index = 0; index < array.length; index++) {
  8416. this.data[this.length++] = (array.data || array)[index];
  8417. }
  8418. };
  8419. SmartArray.prototype.indexOf = function (value) {
  8420. var position = this.data.indexOf(value);
  8421. if (position >= this.length) {
  8422. return -1;
  8423. }
  8424. return position;
  8425. };
  8426. SmartArray.prototype.contains = function (value) {
  8427. return this.data.indexOf(value) !== -1;
  8428. };
  8429. // Statics
  8430. SmartArray._GlobalId = 0;
  8431. return SmartArray;
  8432. }());
  8433. BABYLON.SmartArray = SmartArray;
  8434. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8435. __extends(SmartArrayNoDuplicate, _super);
  8436. function SmartArrayNoDuplicate() {
  8437. var _this = _super !== null && _super.apply(this, arguments) || this;
  8438. _this._duplicateId = 0;
  8439. return _this;
  8440. }
  8441. SmartArrayNoDuplicate.prototype.push = function (value) {
  8442. _super.prototype.push.call(this, value);
  8443. if (!value.__smartArrayFlags) {
  8444. value.__smartArrayFlags = {};
  8445. }
  8446. value.__smartArrayFlags[this._id] = this._duplicateId;
  8447. };
  8448. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8449. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8450. return false;
  8451. }
  8452. this.push(value);
  8453. return true;
  8454. };
  8455. SmartArrayNoDuplicate.prototype.reset = function () {
  8456. _super.prototype.reset.call(this);
  8457. this._duplicateId++;
  8458. };
  8459. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8460. if (array.length === 0) {
  8461. return;
  8462. }
  8463. if (this.length + array.length > this.data.length) {
  8464. this.data.length = (this.length + array.length) * 2;
  8465. }
  8466. for (var index = 0; index < array.length; index++) {
  8467. var item = (array.data || array)[index];
  8468. this.pushNoDuplicate(item);
  8469. }
  8470. };
  8471. return SmartArrayNoDuplicate;
  8472. }(SmartArray));
  8473. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8474. })(BABYLON || (BABYLON = {}));
  8475. //# sourceMappingURL=babylon.smartArray.js.map
  8476. var BABYLON;
  8477. (function (BABYLON) {
  8478. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8479. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8480. var LoadFileError = /** @class */ (function (_super) {
  8481. __extends(LoadFileError, _super);
  8482. function LoadFileError(message, request) {
  8483. var _this = _super.call(this, message) || this;
  8484. _this.request = request;
  8485. _this.name = "LoadFileError";
  8486. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8487. return _this;
  8488. }
  8489. // Polyfill for Object.setPrototypeOf if necessary.
  8490. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8491. return LoadFileError;
  8492. }(Error));
  8493. BABYLON.LoadFileError = LoadFileError;
  8494. var RetryStrategy = /** @class */ (function () {
  8495. function RetryStrategy() {
  8496. }
  8497. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8498. if (maxRetries === void 0) { maxRetries = 3; }
  8499. if (baseInterval === void 0) { baseInterval = 500; }
  8500. return function (url, request, retryIndex) {
  8501. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8502. return -1;
  8503. }
  8504. return Math.pow(2, retryIndex) * baseInterval;
  8505. };
  8506. };
  8507. return RetryStrategy;
  8508. }());
  8509. BABYLON.RetryStrategy = RetryStrategy;
  8510. // Screenshots
  8511. var screenshotCanvas;
  8512. var cloneValue = function (source, destinationObject) {
  8513. if (!source)
  8514. return null;
  8515. if (source instanceof BABYLON.Mesh) {
  8516. return null;
  8517. }
  8518. if (source instanceof BABYLON.SubMesh) {
  8519. return source.clone(destinationObject);
  8520. }
  8521. else if (source.clone) {
  8522. return source.clone();
  8523. }
  8524. return null;
  8525. };
  8526. var Tools = /** @class */ (function () {
  8527. function Tools() {
  8528. }
  8529. /**
  8530. * Interpolates between a and b via alpha
  8531. * @param a The lower value (returned when alpha = 0)
  8532. * @param b The upper value (returned when alpha = 1)
  8533. * @param alpha The interpolation-factor
  8534. * @return The mixed value
  8535. */
  8536. Tools.Mix = function (a, b, alpha) {
  8537. return a * (1 - alpha) + b * alpha;
  8538. };
  8539. Tools.Instantiate = function (className) {
  8540. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8541. return Tools.RegisteredExternalClasses[className];
  8542. }
  8543. var arr = className.split(".");
  8544. var fn = (window || this);
  8545. for (var i = 0, len = arr.length; i < len; i++) {
  8546. fn = fn[arr[i]];
  8547. }
  8548. if (typeof fn !== "function") {
  8549. return null;
  8550. }
  8551. return fn;
  8552. };
  8553. /**
  8554. * Provides a slice function that will work even on IE
  8555. * @param data defines the array to slice
  8556. * @param start defines the start of the data (optional)
  8557. * @param end defines the end of the data (optional)
  8558. * @returns the new sliced array
  8559. */
  8560. Tools.Slice = function (data, start, end) {
  8561. if (data.slice) {
  8562. return data.slice(start, end);
  8563. }
  8564. return Array.prototype.slice.call(data, start, end);
  8565. };
  8566. Tools.SetImmediate = function (action) {
  8567. if (window.setImmediate) {
  8568. window.setImmediate(action);
  8569. }
  8570. else {
  8571. setTimeout(action, 1);
  8572. }
  8573. };
  8574. Tools.IsExponentOfTwo = function (value) {
  8575. var count = 1;
  8576. do {
  8577. count *= 2;
  8578. } while (count < value);
  8579. return count === value;
  8580. };
  8581. /**
  8582. * Returns the nearest 32-bit single precision float representation of a Number
  8583. * @param value A Number. If the parameter is of a different type, it will get converted
  8584. * to a number or to NaN if it cannot be converted
  8585. * @returns number
  8586. */
  8587. Tools.FloatRound = function (value) {
  8588. if (Math.fround) {
  8589. return Math.fround(value);
  8590. }
  8591. return (Tools._tmpFloatArray[0] = value);
  8592. };
  8593. /**
  8594. * Find the next highest power of two.
  8595. * @param x Number to start search from.
  8596. * @return Next highest power of two.
  8597. */
  8598. Tools.CeilingPOT = function (x) {
  8599. x--;
  8600. x |= x >> 1;
  8601. x |= x >> 2;
  8602. x |= x >> 4;
  8603. x |= x >> 8;
  8604. x |= x >> 16;
  8605. x++;
  8606. return x;
  8607. };
  8608. /**
  8609. * Find the next lowest power of two.
  8610. * @param x Number to start search from.
  8611. * @return Next lowest power of two.
  8612. */
  8613. Tools.FloorPOT = function (x) {
  8614. x = x | (x >> 1);
  8615. x = x | (x >> 2);
  8616. x = x | (x >> 4);
  8617. x = x | (x >> 8);
  8618. x = x | (x >> 16);
  8619. return x - (x >> 1);
  8620. };
  8621. /**
  8622. * Find the nearest power of two.
  8623. * @param x Number to start search from.
  8624. * @return Next nearest power of two.
  8625. */
  8626. Tools.NearestPOT = function (x) {
  8627. var c = Tools.CeilingPOT(x);
  8628. var f = Tools.FloorPOT(x);
  8629. return (c - x) > (x - f) ? f : c;
  8630. };
  8631. Tools.GetExponentOfTwo = function (value, max, mode) {
  8632. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8633. var pot;
  8634. switch (mode) {
  8635. case BABYLON.Engine.SCALEMODE_FLOOR:
  8636. pot = Tools.FloorPOT(value);
  8637. break;
  8638. case BABYLON.Engine.SCALEMODE_NEAREST:
  8639. pot = Tools.NearestPOT(value);
  8640. break;
  8641. case BABYLON.Engine.SCALEMODE_CEILING:
  8642. default:
  8643. pot = Tools.CeilingPOT(value);
  8644. break;
  8645. }
  8646. return Math.min(pot, max);
  8647. };
  8648. Tools.GetFilename = function (path) {
  8649. var index = path.lastIndexOf("/");
  8650. if (index < 0)
  8651. return path;
  8652. return path.substring(index + 1);
  8653. };
  8654. /**
  8655. * Extracts the "folder" part of a path (everything before the filename).
  8656. * @param uri The URI to extract the info from
  8657. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8658. * @returns The "folder" part of the path
  8659. */
  8660. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8661. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8662. var index = uri.lastIndexOf("/");
  8663. if (index < 0) {
  8664. if (returnUnchangedIfNoSlash) {
  8665. return uri;
  8666. }
  8667. return "";
  8668. }
  8669. return uri.substring(0, index + 1);
  8670. };
  8671. Tools.GetDOMTextContent = function (element) {
  8672. var result = "";
  8673. var child = element.firstChild;
  8674. while (child) {
  8675. if (child.nodeType === 3) {
  8676. result += child.textContent;
  8677. }
  8678. child = child.nextSibling;
  8679. }
  8680. return result;
  8681. };
  8682. Tools.ToDegrees = function (angle) {
  8683. return angle * 180 / Math.PI;
  8684. };
  8685. Tools.ToRadians = function (angle) {
  8686. return angle * Math.PI / 180;
  8687. };
  8688. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8689. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8690. var output = "";
  8691. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8692. var i = 0;
  8693. var bytes = new Uint8Array(buffer);
  8694. while (i < bytes.length) {
  8695. chr1 = bytes[i++];
  8696. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8697. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8698. enc1 = chr1 >> 2;
  8699. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8700. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8701. enc4 = chr3 & 63;
  8702. if (isNaN(chr2)) {
  8703. enc3 = enc4 = 64;
  8704. }
  8705. else if (isNaN(chr3)) {
  8706. enc4 = 64;
  8707. }
  8708. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8709. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8710. }
  8711. return "data:image/png;base64," + output;
  8712. };
  8713. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8714. if (bias === void 0) { bias = null; }
  8715. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8716. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8717. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8718. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 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.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8736. if (bias === void 0) { bias = null; }
  8737. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8738. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8739. if (!stride) {
  8740. stride = 3;
  8741. }
  8742. for (var index = start; index < start + count; index++) {
  8743. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8744. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8745. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8746. }
  8747. if (bias) {
  8748. minimum.x -= minimum.x * bias.x + bias.y;
  8749. minimum.y -= minimum.y * bias.x + bias.y;
  8750. minimum.z -= minimum.z * bias.x + bias.y;
  8751. maximum.x += maximum.x * bias.x + bias.y;
  8752. maximum.y += maximum.y * bias.x + bias.y;
  8753. maximum.z += maximum.z * bias.x + bias.y;
  8754. }
  8755. return {
  8756. minimum: minimum,
  8757. maximum: maximum
  8758. };
  8759. };
  8760. Tools.Vector2ArrayFeeder = function (array) {
  8761. return function (index) {
  8762. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8763. var length = isFloatArray ? array.length / 2 : array.length;
  8764. if (index >= length) {
  8765. return null;
  8766. }
  8767. if (isFloatArray) {
  8768. var fa = array;
  8769. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8770. }
  8771. var a = array;
  8772. return a[index];
  8773. };
  8774. };
  8775. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8776. if (bias === void 0) { bias = null; }
  8777. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8778. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8779. var i = 0;
  8780. var cur = feeder(i++);
  8781. while (cur) {
  8782. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8783. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8784. cur = feeder(i++);
  8785. }
  8786. if (bias) {
  8787. minimum.x -= minimum.x * bias.x + bias.y;
  8788. minimum.y -= minimum.y * bias.x + bias.y;
  8789. maximum.x += maximum.x * bias.x + bias.y;
  8790. maximum.y += maximum.y * bias.x + bias.y;
  8791. }
  8792. return {
  8793. minimum: minimum,
  8794. maximum: maximum
  8795. };
  8796. };
  8797. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8798. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8799. return null;
  8800. return Array.isArray(obj) ? obj : [obj];
  8801. };
  8802. // Misc.
  8803. Tools.GetPointerPrefix = function () {
  8804. var eventPrefix = "pointer";
  8805. // Check if pointer events are supported
  8806. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8807. eventPrefix = "mouse";
  8808. }
  8809. return eventPrefix;
  8810. };
  8811. /**
  8812. * @param func - the function to be called
  8813. * @param requester - the object that will request the next frame. Falls back to window.
  8814. */
  8815. Tools.QueueNewFrame = function (func, requester) {
  8816. if (!Tools.IsWindowObjectExist()) {
  8817. return setTimeout(func, 16);
  8818. }
  8819. if (!requester) {
  8820. requester = window;
  8821. }
  8822. if (requester.requestAnimationFrame) {
  8823. return requester.requestAnimationFrame(func);
  8824. }
  8825. else if (requester.msRequestAnimationFrame) {
  8826. return requester.msRequestAnimationFrame(func);
  8827. }
  8828. else if (requester.webkitRequestAnimationFrame) {
  8829. return requester.webkitRequestAnimationFrame(func);
  8830. }
  8831. else if (requester.mozRequestAnimationFrame) {
  8832. return requester.mozRequestAnimationFrame(func);
  8833. }
  8834. else if (requester.oRequestAnimationFrame) {
  8835. return requester.oRequestAnimationFrame(func);
  8836. }
  8837. else {
  8838. return window.setTimeout(func, 16);
  8839. }
  8840. };
  8841. Tools.RequestFullscreen = function (element) {
  8842. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8843. if (!requestFunction)
  8844. return;
  8845. requestFunction.call(element);
  8846. };
  8847. Tools.ExitFullscreen = function () {
  8848. if (document.exitFullscreen) {
  8849. document.exitFullscreen();
  8850. }
  8851. else if (document.mozCancelFullScreen) {
  8852. document.mozCancelFullScreen();
  8853. }
  8854. else if (document.webkitCancelFullScreen) {
  8855. document.webkitCancelFullScreen();
  8856. }
  8857. else if (document.msCancelFullScreen) {
  8858. document.msCancelFullScreen();
  8859. }
  8860. };
  8861. Tools.SetCorsBehavior = function (url, element) {
  8862. if (url && url.indexOf("data:") === 0) {
  8863. return;
  8864. }
  8865. if (Tools.CorsBehavior) {
  8866. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8867. element.crossOrigin = Tools.CorsBehavior;
  8868. }
  8869. else {
  8870. var result = Tools.CorsBehavior(url);
  8871. if (result) {
  8872. element.crossOrigin = result;
  8873. }
  8874. }
  8875. }
  8876. };
  8877. // External files
  8878. Tools.CleanUrl = function (url) {
  8879. url = url.replace(/#/mg, "%23");
  8880. return url;
  8881. };
  8882. /**
  8883. * Loads an image as an HTMLImageElement.
  8884. * @param input url string, ArrayBuffer, or Blob to load
  8885. * @param onLoad callback called when the image successfully loads
  8886. * @param onError callback called when the image fails to load
  8887. * @param database database for caching
  8888. * @returns the HTMLImageElement of the loaded image
  8889. */
  8890. Tools.LoadImage = function (input, onLoad, onError, database) {
  8891. var url;
  8892. var usingObjectURL = false;
  8893. if (input instanceof ArrayBuffer) {
  8894. url = URL.createObjectURL(new Blob([input]));
  8895. usingObjectURL = true;
  8896. }
  8897. else if (input instanceof Blob) {
  8898. url = URL.createObjectURL(input);
  8899. usingObjectURL = true;
  8900. }
  8901. else {
  8902. url = Tools.CleanUrl(input);
  8903. url = Tools.PreprocessUrl(input);
  8904. }
  8905. var img = new Image();
  8906. Tools.SetCorsBehavior(url, img);
  8907. var loadHandler = function () {
  8908. if (usingObjectURL && img.src) {
  8909. URL.revokeObjectURL(img.src);
  8910. }
  8911. img.removeEventListener("load", loadHandler);
  8912. img.removeEventListener("error", errorHandler);
  8913. onLoad(img);
  8914. };
  8915. var errorHandler = function (err) {
  8916. if (usingObjectURL && img.src) {
  8917. URL.revokeObjectURL(img.src);
  8918. }
  8919. img.removeEventListener("load", loadHandler);
  8920. img.removeEventListener("error", errorHandler);
  8921. Tools.Error("Error while trying to load image: " + input);
  8922. if (onError) {
  8923. onError("Error while trying to load image: " + input, err);
  8924. }
  8925. };
  8926. img.addEventListener("load", loadHandler);
  8927. img.addEventListener("error", errorHandler);
  8928. var noIndexedDB = function () {
  8929. img.src = url;
  8930. };
  8931. var loadFromIndexedDB = function () {
  8932. if (database) {
  8933. database.loadImageFromDB(url, img);
  8934. }
  8935. };
  8936. //ANY database to do!
  8937. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8938. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8939. }
  8940. else {
  8941. if (url.indexOf("file:") !== -1) {
  8942. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8943. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8944. try {
  8945. var blobURL;
  8946. try {
  8947. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8948. }
  8949. catch (ex) {
  8950. // Chrome doesn't support oneTimeOnly parameter
  8951. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8952. }
  8953. img.src = blobURL;
  8954. usingObjectURL = true;
  8955. }
  8956. catch (e) {
  8957. img.src = "";
  8958. }
  8959. return img;
  8960. }
  8961. }
  8962. noIndexedDB();
  8963. }
  8964. return img;
  8965. };
  8966. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8967. url = Tools.CleanUrl(url);
  8968. url = Tools.PreprocessUrl(url);
  8969. // If file and file input are set
  8970. if (url.indexOf("file:") !== -1) {
  8971. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8972. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8973. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8974. }
  8975. }
  8976. var loadUrl = Tools.BaseUrl + url;
  8977. var aborted = false;
  8978. var fileRequest = {
  8979. onCompleteObservable: new BABYLON.Observable(),
  8980. abort: function () { return aborted = true; },
  8981. };
  8982. var requestFile = function () {
  8983. var request = new XMLHttpRequest();
  8984. var retryHandle = null;
  8985. fileRequest.abort = function () {
  8986. aborted = true;
  8987. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8988. request.abort();
  8989. }
  8990. if (retryHandle !== null) {
  8991. clearTimeout(retryHandle);
  8992. retryHandle = null;
  8993. }
  8994. };
  8995. var retryLoop = function (retryIndex) {
  8996. request.open('GET', loadUrl, true);
  8997. if (useArrayBuffer) {
  8998. request.responseType = "arraybuffer";
  8999. }
  9000. if (onProgress) {
  9001. request.addEventListener("progress", onProgress);
  9002. }
  9003. var onLoadEnd = function () {
  9004. request.removeEventListener("loadend", onLoadEnd);
  9005. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9006. fileRequest.onCompleteObservable.clear();
  9007. };
  9008. request.addEventListener("loadend", onLoadEnd);
  9009. var onReadyStateChange = function () {
  9010. if (aborted) {
  9011. return;
  9012. }
  9013. // In case of undefined state in some browsers.
  9014. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9015. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9016. request.removeEventListener("readystatechange", onReadyStateChange);
  9017. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9018. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9019. return;
  9020. }
  9021. var retryStrategy = Tools.DefaultRetryStrategy;
  9022. if (retryStrategy) {
  9023. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9024. if (waitTime !== -1) {
  9025. // Prevent the request from completing for retry.
  9026. request.removeEventListener("loadend", onLoadEnd);
  9027. request = new XMLHttpRequest();
  9028. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9029. return;
  9030. }
  9031. }
  9032. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9033. if (onError) {
  9034. onError(request, e);
  9035. }
  9036. else {
  9037. throw e;
  9038. }
  9039. }
  9040. };
  9041. request.addEventListener("readystatechange", onReadyStateChange);
  9042. request.send();
  9043. };
  9044. retryLoop(0);
  9045. };
  9046. // Caching all files
  9047. if (database && database.enableSceneOffline) {
  9048. var noIndexedDB_1 = function () {
  9049. if (!aborted) {
  9050. requestFile();
  9051. }
  9052. };
  9053. var loadFromIndexedDB = function () {
  9054. // TODO: database needs to support aborting and should return a IFileRequest
  9055. if (aborted) {
  9056. return;
  9057. }
  9058. if (database) {
  9059. database.loadFileFromDB(url, function (data) {
  9060. if (!aborted) {
  9061. onSuccess(data);
  9062. }
  9063. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9064. }, onProgress ? function (event) {
  9065. if (!aborted) {
  9066. onProgress(event);
  9067. }
  9068. } : undefined, noIndexedDB_1, useArrayBuffer);
  9069. }
  9070. };
  9071. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9072. }
  9073. else {
  9074. requestFile();
  9075. }
  9076. return fileRequest;
  9077. };
  9078. /**
  9079. * Load a script (identified by an url). When the url returns, the
  9080. * content of this file is added into a new script element, attached to the DOM (body element)
  9081. */
  9082. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9083. var head = document.getElementsByTagName('head')[0];
  9084. var script = document.createElement('script');
  9085. script.type = 'text/javascript';
  9086. script.src = scriptUrl;
  9087. script.onload = function () {
  9088. if (onSuccess) {
  9089. onSuccess();
  9090. }
  9091. };
  9092. script.onerror = function (e) {
  9093. if (onError) {
  9094. onError("Unable to load script '" + scriptUrl + "'", e);
  9095. }
  9096. };
  9097. head.appendChild(script);
  9098. };
  9099. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9100. var reader = new FileReader();
  9101. var request = {
  9102. onCompleteObservable: new BABYLON.Observable(),
  9103. abort: function () { return reader.abort(); },
  9104. };
  9105. reader.onloadend = function (e) {
  9106. request.onCompleteObservable.notifyObservers(request);
  9107. };
  9108. reader.onload = function (e) {
  9109. //target doesn't have result from ts 1.3
  9110. callback(e.target['result']);
  9111. };
  9112. reader.onprogress = progressCallback;
  9113. reader.readAsDataURL(fileToLoad);
  9114. return request;
  9115. };
  9116. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9117. var reader = new FileReader();
  9118. var request = {
  9119. onCompleteObservable: new BABYLON.Observable(),
  9120. abort: function () { return reader.abort(); },
  9121. };
  9122. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9123. reader.onerror = function (e) {
  9124. Tools.Log("Error while reading file: " + fileToLoad.name);
  9125. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9126. };
  9127. reader.onload = function (e) {
  9128. //target doesn't have result from ts 1.3
  9129. callback(e.target['result']);
  9130. };
  9131. if (progressCallBack) {
  9132. reader.onprogress = progressCallBack;
  9133. }
  9134. if (!useArrayBuffer) {
  9135. // Asynchronous read
  9136. reader.readAsText(fileToLoad);
  9137. }
  9138. else {
  9139. reader.readAsArrayBuffer(fileToLoad);
  9140. }
  9141. return request;
  9142. };
  9143. //returns a downloadable url to a file content.
  9144. Tools.FileAsURL = function (content) {
  9145. var fileBlob = new Blob([content]);
  9146. var url = window.URL || window.webkitURL;
  9147. var link = url.createObjectURL(fileBlob);
  9148. return link;
  9149. };
  9150. // Misc.
  9151. Tools.Format = function (value, decimals) {
  9152. if (decimals === void 0) { decimals = 2; }
  9153. return value.toFixed(decimals);
  9154. };
  9155. Tools.CheckExtends = function (v, min, max) {
  9156. if (v.x < min.x)
  9157. min.x = v.x;
  9158. if (v.y < min.y)
  9159. min.y = v.y;
  9160. if (v.z < min.z)
  9161. min.z = v.z;
  9162. if (v.x > max.x)
  9163. max.x = v.x;
  9164. if (v.y > max.y)
  9165. max.y = v.y;
  9166. if (v.z > max.z)
  9167. max.z = v.z;
  9168. };
  9169. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9170. for (var prop in source) {
  9171. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9172. continue;
  9173. }
  9174. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9175. continue;
  9176. }
  9177. var sourceValue = source[prop];
  9178. var typeOfSourceValue = typeof sourceValue;
  9179. if (typeOfSourceValue === "function") {
  9180. continue;
  9181. }
  9182. try {
  9183. if (typeOfSourceValue === "object") {
  9184. if (sourceValue instanceof Array) {
  9185. destination[prop] = [];
  9186. if (sourceValue.length > 0) {
  9187. if (typeof sourceValue[0] == "object") {
  9188. for (var index = 0; index < sourceValue.length; index++) {
  9189. var clonedValue = cloneValue(sourceValue[index], destination);
  9190. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9191. destination[prop].push(clonedValue);
  9192. }
  9193. }
  9194. }
  9195. else {
  9196. destination[prop] = sourceValue.slice(0);
  9197. }
  9198. }
  9199. }
  9200. else {
  9201. destination[prop] = cloneValue(sourceValue, destination);
  9202. }
  9203. }
  9204. else {
  9205. destination[prop] = sourceValue;
  9206. }
  9207. }
  9208. catch (e) {
  9209. // Just ignore error (it could be because of a read-only property)
  9210. }
  9211. }
  9212. };
  9213. Tools.IsEmpty = function (obj) {
  9214. for (var i in obj) {
  9215. if (obj.hasOwnProperty(i)) {
  9216. return false;
  9217. }
  9218. }
  9219. return true;
  9220. };
  9221. Tools.RegisterTopRootEvents = function (events) {
  9222. for (var index = 0; index < events.length; index++) {
  9223. var event = events[index];
  9224. window.addEventListener(event.name, event.handler, false);
  9225. try {
  9226. if (window.parent) {
  9227. window.parent.addEventListener(event.name, event.handler, false);
  9228. }
  9229. }
  9230. catch (e) {
  9231. // Silently fails...
  9232. }
  9233. }
  9234. };
  9235. Tools.UnregisterTopRootEvents = function (events) {
  9236. for (var index = 0; index < events.length; index++) {
  9237. var event = events[index];
  9238. window.removeEventListener(event.name, event.handler);
  9239. try {
  9240. if (window.parent) {
  9241. window.parent.removeEventListener(event.name, event.handler);
  9242. }
  9243. }
  9244. catch (e) {
  9245. // Silently fails...
  9246. }
  9247. }
  9248. };
  9249. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9250. if (mimeType === void 0) { mimeType = "image/png"; }
  9251. // Read the contents of the framebuffer
  9252. var numberOfChannelsByLine = width * 4;
  9253. var halfHeight = height / 2;
  9254. //Reading datas from WebGL
  9255. var data = engine.readPixels(0, 0, width, height);
  9256. //To flip image on Y axis.
  9257. for (var i = 0; i < halfHeight; i++) {
  9258. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9259. var currentCell = j + i * numberOfChannelsByLine;
  9260. var targetLine = height - i - 1;
  9261. var targetCell = j + targetLine * numberOfChannelsByLine;
  9262. var temp = data[currentCell];
  9263. data[currentCell] = data[targetCell];
  9264. data[targetCell] = temp;
  9265. }
  9266. }
  9267. // Create a 2D canvas to store the result
  9268. if (!screenshotCanvas) {
  9269. screenshotCanvas = document.createElement('canvas');
  9270. }
  9271. screenshotCanvas.width = width;
  9272. screenshotCanvas.height = height;
  9273. var context = screenshotCanvas.getContext('2d');
  9274. if (context) {
  9275. // Copy the pixels to a 2D canvas
  9276. var imageData = context.createImageData(width, height);
  9277. var castData = (imageData.data);
  9278. castData.set(data);
  9279. context.putImageData(imageData, 0, 0);
  9280. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9281. }
  9282. };
  9283. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9284. if (mimeType === void 0) { mimeType = "image/png"; }
  9285. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9286. if (successCallback) {
  9287. successCallback(base64Image);
  9288. }
  9289. else {
  9290. // We need HTMLCanvasElement.toBlob for HD screenshots
  9291. if (!screenshotCanvas.toBlob) {
  9292. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9293. screenshotCanvas.toBlob = function (callback, type, quality) {
  9294. var _this = this;
  9295. setTimeout(function () {
  9296. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9297. for (var i = 0; i < len; i++) {
  9298. arr[i] = binStr.charCodeAt(i);
  9299. }
  9300. callback(new Blob([arr], { type: type || 'image/png' }));
  9301. });
  9302. };
  9303. }
  9304. screenshotCanvas.toBlob(function (blob) {
  9305. var url = URL.createObjectURL(blob);
  9306. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9307. if (("download" in document.createElement("a"))) {
  9308. var a = window.document.createElement("a");
  9309. a.href = url;
  9310. if (fileName) {
  9311. a.setAttribute("download", fileName);
  9312. }
  9313. else {
  9314. var date = new Date();
  9315. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9316. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9317. }
  9318. window.document.body.appendChild(a);
  9319. a.addEventListener("click", function () {
  9320. if (a.parentElement) {
  9321. a.parentElement.removeChild(a);
  9322. }
  9323. });
  9324. a.click();
  9325. }
  9326. else {
  9327. var newWindow = window.open("");
  9328. if (!newWindow)
  9329. return;
  9330. var img = newWindow.document.createElement("img");
  9331. img.onload = function () {
  9332. // no longer need to read the blob so it's revoked
  9333. URL.revokeObjectURL(url);
  9334. };
  9335. img.src = url;
  9336. newWindow.document.body.appendChild(img);
  9337. }
  9338. });
  9339. }
  9340. };
  9341. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9342. if (mimeType === void 0) { mimeType = "image/png"; }
  9343. var width;
  9344. var height;
  9345. // If a precision value is specified
  9346. if (size.precision) {
  9347. width = Math.round(engine.getRenderWidth() * size.precision);
  9348. height = Math.round(width / engine.getAspectRatio(camera));
  9349. }
  9350. else if (size.width && size.height) {
  9351. width = size.width;
  9352. height = size.height;
  9353. }
  9354. //If passing only width, computing height to keep display canvas ratio.
  9355. else if (size.width && !size.height) {
  9356. width = size.width;
  9357. height = Math.round(width / engine.getAspectRatio(camera));
  9358. }
  9359. //If passing only height, computing width to keep display canvas ratio.
  9360. else if (size.height && !size.width) {
  9361. height = size.height;
  9362. width = Math.round(height * engine.getAspectRatio(camera));
  9363. }
  9364. //Assuming here that "size" parameter is a number
  9365. else if (!isNaN(size)) {
  9366. height = size;
  9367. width = size;
  9368. }
  9369. else {
  9370. Tools.Error("Invalid 'size' parameter !");
  9371. return;
  9372. }
  9373. if (!screenshotCanvas) {
  9374. screenshotCanvas = document.createElement('canvas');
  9375. }
  9376. screenshotCanvas.width = width;
  9377. screenshotCanvas.height = height;
  9378. var renderContext = screenshotCanvas.getContext("2d");
  9379. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9380. var newWidth = width;
  9381. var newHeight = newWidth / ratio;
  9382. if (newHeight > height) {
  9383. newHeight = height;
  9384. newWidth = newHeight * ratio;
  9385. }
  9386. var offsetX = Math.max(0, width - newWidth) / 2;
  9387. var offsetY = Math.max(0, height - newHeight) / 2;
  9388. var renderingCanvas = engine.getRenderingCanvas();
  9389. if (renderContext && renderingCanvas) {
  9390. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9391. }
  9392. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9393. };
  9394. /**
  9395. * Generates an image screenshot from the specified camera.
  9396. *
  9397. * @param engine The engine to use for rendering
  9398. * @param camera The camera to use for rendering
  9399. * @param size This parameter can be set to a single number or to an object with the
  9400. * following (optional) properties: precision, width, height. If a single number is passed,
  9401. * it will be used for both width and height. If an object is passed, the screenshot size
  9402. * will be derived from the parameters. The precision property is a multiplier allowing
  9403. * rendering at a higher or lower resolution.
  9404. * @param successCallback The callback receives a single parameter which contains the
  9405. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9406. * src parameter of an <img> to display it.
  9407. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9408. * Check your browser for supported MIME types.
  9409. * @param samples Texture samples (default: 1)
  9410. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9411. * @param fileName A name for for the downloaded file.
  9412. * @constructor
  9413. */
  9414. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9415. if (mimeType === void 0) { mimeType = "image/png"; }
  9416. if (samples === void 0) { samples = 1; }
  9417. if (antialiasing === void 0) { antialiasing = false; }
  9418. var width;
  9419. var height;
  9420. //If a precision value is specified
  9421. if (size.precision) {
  9422. width = Math.round(engine.getRenderWidth() * size.precision);
  9423. height = Math.round(width / engine.getAspectRatio(camera));
  9424. size = { width: width, height: height };
  9425. }
  9426. else if (size.width && size.height) {
  9427. width = size.width;
  9428. height = size.height;
  9429. }
  9430. //If passing only width, computing height to keep display canvas ratio.
  9431. else if (size.width && !size.height) {
  9432. width = size.width;
  9433. height = Math.round(width / engine.getAspectRatio(camera));
  9434. size = { width: width, height: height };
  9435. }
  9436. //If passing only height, computing width to keep display canvas ratio.
  9437. else if (size.height && !size.width) {
  9438. height = size.height;
  9439. width = Math.round(height * engine.getAspectRatio(camera));
  9440. size = { width: width, height: height };
  9441. }
  9442. //Assuming here that "size" parameter is a number
  9443. else if (!isNaN(size)) {
  9444. height = size;
  9445. width = size;
  9446. }
  9447. else {
  9448. Tools.Error("Invalid 'size' parameter !");
  9449. return;
  9450. }
  9451. var scene = camera.getScene();
  9452. var previousCamera = null;
  9453. if (scene.activeCamera !== camera) {
  9454. previousCamera = scene.activeCamera;
  9455. scene.activeCamera = camera;
  9456. }
  9457. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9458. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9459. texture.renderList = null;
  9460. texture.samples = samples;
  9461. if (antialiasing) {
  9462. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9463. }
  9464. texture.onAfterRenderObservable.add(function () {
  9465. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9466. });
  9467. scene.incrementRenderId();
  9468. scene.resetCachedMaterial();
  9469. texture.render(true);
  9470. texture.dispose();
  9471. if (previousCamera) {
  9472. scene.activeCamera = previousCamera;
  9473. }
  9474. camera.getProjectionMatrix(true); // Force cache refresh;
  9475. };
  9476. // XHR response validator for local file scenario
  9477. Tools.ValidateXHRData = function (xhr, dataType) {
  9478. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9479. if (dataType === void 0) { dataType = 7; }
  9480. try {
  9481. if (dataType & 1) {
  9482. if (xhr.responseText && xhr.responseText.length > 0) {
  9483. return true;
  9484. }
  9485. else if (dataType === 1) {
  9486. return false;
  9487. }
  9488. }
  9489. if (dataType & 2) {
  9490. // Check header width and height since there is no "TGA" magic number
  9491. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9492. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9493. return true;
  9494. }
  9495. else if (dataType === 2) {
  9496. return false;
  9497. }
  9498. }
  9499. if (dataType & 4) {
  9500. // Check for the "DDS" magic number
  9501. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9502. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9503. return true;
  9504. }
  9505. else {
  9506. return false;
  9507. }
  9508. }
  9509. }
  9510. catch (e) {
  9511. // Global protection
  9512. }
  9513. return false;
  9514. };
  9515. /**
  9516. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9517. * Be aware Math.random() could cause collisions, but:
  9518. * "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"
  9519. */
  9520. Tools.RandomId = function () {
  9521. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9522. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9523. return v.toString(16);
  9524. });
  9525. };
  9526. /**
  9527. * Test if the given uri is a base64 string.
  9528. * @param uri The uri to test
  9529. * @return True if the uri is a base64 string or false otherwise.
  9530. */
  9531. Tools.IsBase64 = function (uri) {
  9532. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9533. };
  9534. /**
  9535. * Decode the given base64 uri.
  9536. * @param uri The uri to decode
  9537. * @return The decoded base64 data.
  9538. */
  9539. Tools.DecodeBase64 = function (uri) {
  9540. var decodedString = atob(uri.split(",")[1]);
  9541. var bufferLength = decodedString.length;
  9542. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9543. for (var i = 0; i < bufferLength; i++) {
  9544. bufferView[i] = decodedString.charCodeAt(i);
  9545. }
  9546. return bufferView.buffer;
  9547. };
  9548. Object.defineProperty(Tools, "NoneLogLevel", {
  9549. get: function () {
  9550. return Tools._NoneLogLevel;
  9551. },
  9552. enumerable: true,
  9553. configurable: true
  9554. });
  9555. Object.defineProperty(Tools, "MessageLogLevel", {
  9556. get: function () {
  9557. return Tools._MessageLogLevel;
  9558. },
  9559. enumerable: true,
  9560. configurable: true
  9561. });
  9562. Object.defineProperty(Tools, "WarningLogLevel", {
  9563. get: function () {
  9564. return Tools._WarningLogLevel;
  9565. },
  9566. enumerable: true,
  9567. configurable: true
  9568. });
  9569. Object.defineProperty(Tools, "ErrorLogLevel", {
  9570. get: function () {
  9571. return Tools._ErrorLogLevel;
  9572. },
  9573. enumerable: true,
  9574. configurable: true
  9575. });
  9576. Object.defineProperty(Tools, "AllLogLevel", {
  9577. get: function () {
  9578. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9579. },
  9580. enumerable: true,
  9581. configurable: true
  9582. });
  9583. Tools._AddLogEntry = function (entry) {
  9584. Tools._LogCache = entry + Tools._LogCache;
  9585. if (Tools.OnNewCacheEntry) {
  9586. Tools.OnNewCacheEntry(entry);
  9587. }
  9588. };
  9589. Tools._FormatMessage = function (message) {
  9590. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9591. var date = new Date();
  9592. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9593. };
  9594. Tools._LogDisabled = function (message) {
  9595. // nothing to do
  9596. };
  9597. Tools._LogEnabled = function (message) {
  9598. var formattedMessage = Tools._FormatMessage(message);
  9599. console.log("BJS - " + formattedMessage);
  9600. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9601. Tools._AddLogEntry(entry);
  9602. };
  9603. Tools._WarnDisabled = function (message) {
  9604. // nothing to do
  9605. };
  9606. Tools._WarnEnabled = function (message) {
  9607. var formattedMessage = Tools._FormatMessage(message);
  9608. console.warn("BJS - " + formattedMessage);
  9609. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9610. Tools._AddLogEntry(entry);
  9611. };
  9612. Tools._ErrorDisabled = function (message) {
  9613. // nothing to do
  9614. };
  9615. Tools._ErrorEnabled = function (message) {
  9616. Tools.errorsCount++;
  9617. var formattedMessage = Tools._FormatMessage(message);
  9618. console.error("BJS - " + formattedMessage);
  9619. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9620. Tools._AddLogEntry(entry);
  9621. };
  9622. Object.defineProperty(Tools, "LogCache", {
  9623. get: function () {
  9624. return Tools._LogCache;
  9625. },
  9626. enumerable: true,
  9627. configurable: true
  9628. });
  9629. Tools.ClearLogCache = function () {
  9630. Tools._LogCache = "";
  9631. Tools.errorsCount = 0;
  9632. };
  9633. Object.defineProperty(Tools, "LogLevels", {
  9634. set: function (level) {
  9635. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9636. Tools.Log = Tools._LogEnabled;
  9637. }
  9638. else {
  9639. Tools.Log = Tools._LogDisabled;
  9640. }
  9641. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9642. Tools.Warn = Tools._WarnEnabled;
  9643. }
  9644. else {
  9645. Tools.Warn = Tools._WarnDisabled;
  9646. }
  9647. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9648. Tools.Error = Tools._ErrorEnabled;
  9649. }
  9650. else {
  9651. Tools.Error = Tools._ErrorDisabled;
  9652. }
  9653. },
  9654. enumerable: true,
  9655. configurable: true
  9656. });
  9657. Tools.IsWindowObjectExist = function () {
  9658. return (typeof window) !== "undefined";
  9659. };
  9660. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9661. get: function () {
  9662. return Tools._PerformanceNoneLogLevel;
  9663. },
  9664. enumerable: true,
  9665. configurable: true
  9666. });
  9667. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9668. get: function () {
  9669. return Tools._PerformanceUserMarkLogLevel;
  9670. },
  9671. enumerable: true,
  9672. configurable: true
  9673. });
  9674. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9675. get: function () {
  9676. return Tools._PerformanceConsoleLogLevel;
  9677. },
  9678. enumerable: true,
  9679. configurable: true
  9680. });
  9681. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9682. set: function (level) {
  9683. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9684. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9685. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9686. return;
  9687. }
  9688. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9689. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9690. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9691. return;
  9692. }
  9693. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9694. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9695. },
  9696. enumerable: true,
  9697. configurable: true
  9698. });
  9699. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9700. };
  9701. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9702. };
  9703. Tools._StartUserMark = function (counterName, condition) {
  9704. if (condition === void 0) { condition = true; }
  9705. if (!Tools._performance) {
  9706. if (!Tools.IsWindowObjectExist()) {
  9707. return;
  9708. }
  9709. Tools._performance = window.performance;
  9710. }
  9711. if (!condition || !Tools._performance.mark) {
  9712. return;
  9713. }
  9714. Tools._performance.mark(counterName + "-Begin");
  9715. };
  9716. Tools._EndUserMark = function (counterName, condition) {
  9717. if (condition === void 0) { condition = true; }
  9718. if (!condition || !Tools._performance.mark) {
  9719. return;
  9720. }
  9721. Tools._performance.mark(counterName + "-End");
  9722. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9723. };
  9724. Tools._StartPerformanceConsole = function (counterName, condition) {
  9725. if (condition === void 0) { condition = true; }
  9726. if (!condition) {
  9727. return;
  9728. }
  9729. Tools._StartUserMark(counterName, condition);
  9730. if (console.time) {
  9731. console.time(counterName);
  9732. }
  9733. };
  9734. Tools._EndPerformanceConsole = function (counterName, condition) {
  9735. if (condition === void 0) { condition = true; }
  9736. if (!condition) {
  9737. return;
  9738. }
  9739. Tools._EndUserMark(counterName, condition);
  9740. if (console.time) {
  9741. console.timeEnd(counterName);
  9742. }
  9743. };
  9744. Object.defineProperty(Tools, "Now", {
  9745. get: function () {
  9746. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9747. return window.performance.now();
  9748. }
  9749. return Date.now();
  9750. },
  9751. enumerable: true,
  9752. configurable: true
  9753. });
  9754. /**
  9755. * This method will return the name of the class used to create the instance of the given object.
  9756. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9757. * @param object the object to get the class name from
  9758. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9759. */
  9760. Tools.GetClassName = function (object, isType) {
  9761. if (isType === void 0) { isType = false; }
  9762. var name = null;
  9763. if (!isType && object.getClassName) {
  9764. name = object.getClassName();
  9765. }
  9766. else {
  9767. if (object instanceof Object) {
  9768. var classObj = isType ? object : Object.getPrototypeOf(object);
  9769. name = classObj.constructor["__bjsclassName__"];
  9770. }
  9771. if (!name) {
  9772. name = typeof object;
  9773. }
  9774. }
  9775. return name;
  9776. };
  9777. Tools.First = function (array, predicate) {
  9778. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9779. var el = array_1[_i];
  9780. if (predicate(el)) {
  9781. return el;
  9782. }
  9783. }
  9784. return null;
  9785. };
  9786. /**
  9787. * This method will return the name of the full name of the class, including its owning module (if any).
  9788. * 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).
  9789. * @param object the object to get the class name from
  9790. * @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.
  9791. */
  9792. Tools.getFullClassName = function (object, isType) {
  9793. if (isType === void 0) { isType = false; }
  9794. var className = null;
  9795. var moduleName = null;
  9796. if (!isType && object.getClassName) {
  9797. className = object.getClassName();
  9798. }
  9799. else {
  9800. if (object instanceof Object) {
  9801. var classObj = isType ? object : Object.getPrototypeOf(object);
  9802. className = classObj.constructor["__bjsclassName__"];
  9803. moduleName = classObj.constructor["__bjsmoduleName__"];
  9804. }
  9805. if (!className) {
  9806. className = typeof object;
  9807. }
  9808. }
  9809. if (!className) {
  9810. return null;
  9811. }
  9812. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9813. };
  9814. /**
  9815. * 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.
  9816. * @param array
  9817. */
  9818. Tools.arrayOrStringFeeder = function (array) {
  9819. return function (index) {
  9820. if (index >= array.length) {
  9821. return null;
  9822. }
  9823. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9824. if (val && val.getHashCode) {
  9825. val = val.getHashCode();
  9826. }
  9827. if (typeof val === "string") {
  9828. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9829. }
  9830. return val;
  9831. };
  9832. };
  9833. /**
  9834. * Compute the hashCode of a stream of number
  9835. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9836. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9837. * @return the hash code computed
  9838. */
  9839. Tools.hashCodeFromStream = function (feeder) {
  9840. // Based from here: http://stackoverflow.com/a/7616484/802124
  9841. var hash = 0;
  9842. var index = 0;
  9843. var chr = feeder(index++);
  9844. while (chr != null) {
  9845. hash = ((hash << 5) - hash) + chr;
  9846. hash |= 0; // Convert to 32bit integer
  9847. chr = feeder(index++);
  9848. }
  9849. return hash;
  9850. };
  9851. /**
  9852. * Returns a promise that resolves after the given amount of time.
  9853. * @param delay Number of milliseconds to delay
  9854. * @returns Promise that resolves after the given amount of time
  9855. */
  9856. Tools.DelayAsync = function (delay) {
  9857. return new Promise(function (resolve) {
  9858. setTimeout(function () {
  9859. resolve();
  9860. }, delay);
  9861. });
  9862. };
  9863. Tools.BaseUrl = "";
  9864. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9865. /**
  9866. * Default behaviour for cors in the application.
  9867. * It can be a string if the expected behavior is identical in the entire app.
  9868. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9869. */
  9870. Tools.CorsBehavior = "anonymous";
  9871. Tools.UseFallbackTexture = true;
  9872. /**
  9873. * Use this object to register external classes like custom textures or material
  9874. * to allow the laoders to instantiate them
  9875. */
  9876. Tools.RegisteredExternalClasses = {};
  9877. // Used in case of a texture loading problem
  9878. 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";
  9879. Tools._tmpFloatArray = new Float32Array(1);
  9880. Tools.PreprocessUrl = function (url) {
  9881. return url;
  9882. };
  9883. // Logs
  9884. Tools._NoneLogLevel = 0;
  9885. Tools._MessageLogLevel = 1;
  9886. Tools._WarningLogLevel = 2;
  9887. Tools._ErrorLogLevel = 4;
  9888. Tools._LogCache = "";
  9889. Tools.errorsCount = 0;
  9890. Tools.Log = Tools._LogEnabled;
  9891. Tools.Warn = Tools._WarnEnabled;
  9892. Tools.Error = Tools._ErrorEnabled;
  9893. // Performances
  9894. Tools._PerformanceNoneLogLevel = 0;
  9895. Tools._PerformanceUserMarkLogLevel = 1;
  9896. Tools._PerformanceConsoleLogLevel = 2;
  9897. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9898. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9899. return Tools;
  9900. }());
  9901. BABYLON.Tools = Tools;
  9902. /**
  9903. * This class is used to track a performance counter which is number based.
  9904. * The user has access to many properties which give statistics of different nature
  9905. *
  9906. * The implementer can track two kinds of Performance Counter: time and count
  9907. * 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.
  9908. * 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.
  9909. */
  9910. var PerfCounter = /** @class */ (function () {
  9911. function PerfCounter() {
  9912. this._startMonitoringTime = 0;
  9913. this._min = 0;
  9914. this._max = 0;
  9915. this._average = 0;
  9916. this._lastSecAverage = 0;
  9917. this._current = 0;
  9918. this._totalValueCount = 0;
  9919. this._totalAccumulated = 0;
  9920. this._lastSecAccumulated = 0;
  9921. this._lastSecTime = 0;
  9922. this._lastSecValueCount = 0;
  9923. }
  9924. Object.defineProperty(PerfCounter.prototype, "min", {
  9925. /**
  9926. * Returns the smallest value ever
  9927. */
  9928. get: function () {
  9929. return this._min;
  9930. },
  9931. enumerable: true,
  9932. configurable: true
  9933. });
  9934. Object.defineProperty(PerfCounter.prototype, "max", {
  9935. /**
  9936. * Returns the biggest value ever
  9937. */
  9938. get: function () {
  9939. return this._max;
  9940. },
  9941. enumerable: true,
  9942. configurable: true
  9943. });
  9944. Object.defineProperty(PerfCounter.prototype, "average", {
  9945. /**
  9946. * Returns the average value since the performance counter is running
  9947. */
  9948. get: function () {
  9949. return this._average;
  9950. },
  9951. enumerable: true,
  9952. configurable: true
  9953. });
  9954. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9955. /**
  9956. * Returns the average value of the last second the counter was monitored
  9957. */
  9958. get: function () {
  9959. return this._lastSecAverage;
  9960. },
  9961. enumerable: true,
  9962. configurable: true
  9963. });
  9964. Object.defineProperty(PerfCounter.prototype, "current", {
  9965. /**
  9966. * Returns the current value
  9967. */
  9968. get: function () {
  9969. return this._current;
  9970. },
  9971. enumerable: true,
  9972. configurable: true
  9973. });
  9974. Object.defineProperty(PerfCounter.prototype, "total", {
  9975. get: function () {
  9976. return this._totalAccumulated;
  9977. },
  9978. enumerable: true,
  9979. configurable: true
  9980. });
  9981. Object.defineProperty(PerfCounter.prototype, "count", {
  9982. get: function () {
  9983. return this._totalValueCount;
  9984. },
  9985. enumerable: true,
  9986. configurable: true
  9987. });
  9988. /**
  9989. * Call this method to start monitoring a new frame.
  9990. * 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.
  9991. */
  9992. PerfCounter.prototype.fetchNewFrame = function () {
  9993. this._totalValueCount++;
  9994. this._current = 0;
  9995. this._lastSecValueCount++;
  9996. };
  9997. /**
  9998. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9999. * @param newCount the count value to add to the monitored count
  10000. * @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.
  10001. */
  10002. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10003. if (!PerfCounter.Enabled) {
  10004. return;
  10005. }
  10006. this._current += newCount;
  10007. if (fetchResult) {
  10008. this._fetchResult();
  10009. }
  10010. };
  10011. /**
  10012. * Start monitoring this performance counter
  10013. */
  10014. PerfCounter.prototype.beginMonitoring = function () {
  10015. if (!PerfCounter.Enabled) {
  10016. return;
  10017. }
  10018. this._startMonitoringTime = Tools.Now;
  10019. };
  10020. /**
  10021. * Compute the time lapsed since the previous beginMonitoring() call.
  10022. * @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
  10023. */
  10024. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10025. if (newFrame === void 0) { newFrame = true; }
  10026. if (!PerfCounter.Enabled) {
  10027. return;
  10028. }
  10029. if (newFrame) {
  10030. this.fetchNewFrame();
  10031. }
  10032. var currentTime = Tools.Now;
  10033. this._current = currentTime - this._startMonitoringTime;
  10034. if (newFrame) {
  10035. this._fetchResult();
  10036. }
  10037. };
  10038. PerfCounter.prototype._fetchResult = function () {
  10039. this._totalAccumulated += this._current;
  10040. this._lastSecAccumulated += this._current;
  10041. // Min/Max update
  10042. this._min = Math.min(this._min, this._current);
  10043. this._max = Math.max(this._max, this._current);
  10044. this._average = this._totalAccumulated / this._totalValueCount;
  10045. // Reset last sec?
  10046. var now = Tools.Now;
  10047. if ((now - this._lastSecTime) > 1000) {
  10048. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10049. this._lastSecTime = now;
  10050. this._lastSecAccumulated = 0;
  10051. this._lastSecValueCount = 0;
  10052. }
  10053. };
  10054. PerfCounter.Enabled = true;
  10055. return PerfCounter;
  10056. }());
  10057. BABYLON.PerfCounter = PerfCounter;
  10058. /**
  10059. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10060. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10061. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10062. * @param name The name of the class, case should be preserved
  10063. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10064. */
  10065. function className(name, module) {
  10066. return function (target) {
  10067. target["__bjsclassName__"] = name;
  10068. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10069. };
  10070. }
  10071. BABYLON.className = className;
  10072. /**
  10073. * An implementation of a loop for asynchronous functions.
  10074. */
  10075. var AsyncLoop = /** @class */ (function () {
  10076. /**
  10077. * Constroctor.
  10078. * @param iterations the number of iterations.
  10079. * @param _fn the function to run each iteration
  10080. * @param _successCallback the callback that will be called upon succesful execution
  10081. * @param offset starting offset.
  10082. */
  10083. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10084. if (offset === void 0) { offset = 0; }
  10085. this.iterations = iterations;
  10086. this._fn = _fn;
  10087. this._successCallback = _successCallback;
  10088. this.index = offset - 1;
  10089. this._done = false;
  10090. }
  10091. /**
  10092. * Execute the next iteration. Must be called after the last iteration was finished.
  10093. */
  10094. AsyncLoop.prototype.executeNext = function () {
  10095. if (!this._done) {
  10096. if (this.index + 1 < this.iterations) {
  10097. ++this.index;
  10098. this._fn(this);
  10099. }
  10100. else {
  10101. this.breakLoop();
  10102. }
  10103. }
  10104. };
  10105. /**
  10106. * Break the loop and run the success callback.
  10107. */
  10108. AsyncLoop.prototype.breakLoop = function () {
  10109. this._done = true;
  10110. this._successCallback();
  10111. };
  10112. /**
  10113. * Helper function
  10114. */
  10115. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10116. if (offset === void 0) { offset = 0; }
  10117. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10118. loop.executeNext();
  10119. return loop;
  10120. };
  10121. /**
  10122. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10123. * @param iterations total number of iterations
  10124. * @param syncedIterations number of synchronous iterations in each async iteration.
  10125. * @param fn the function to call each iteration.
  10126. * @param callback a success call back that will be called when iterating stops.
  10127. * @param breakFunction a break condition (optional)
  10128. * @param timeout timeout settings for the setTimeout function. default - 0.
  10129. * @constructor
  10130. */
  10131. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10132. if (timeout === void 0) { timeout = 0; }
  10133. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10134. if (breakFunction && breakFunction())
  10135. loop.breakLoop();
  10136. else {
  10137. setTimeout(function () {
  10138. for (var i = 0; i < syncedIterations; ++i) {
  10139. var iteration = (loop.index * syncedIterations) + i;
  10140. if (iteration >= iterations)
  10141. break;
  10142. fn(iteration);
  10143. if (breakFunction && breakFunction()) {
  10144. loop.breakLoop();
  10145. break;
  10146. }
  10147. }
  10148. loop.executeNext();
  10149. }, timeout);
  10150. }
  10151. }, callback);
  10152. };
  10153. return AsyncLoop;
  10154. }());
  10155. BABYLON.AsyncLoop = AsyncLoop;
  10156. })(BABYLON || (BABYLON = {}));
  10157. //# sourceMappingURL=babylon.tools.js.map
  10158. var BABYLON;
  10159. (function (BABYLON) {
  10160. var PromiseStates;
  10161. (function (PromiseStates) {
  10162. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10163. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10164. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10165. })(PromiseStates || (PromiseStates = {}));
  10166. var FulFillmentAgregator = /** @class */ (function () {
  10167. function FulFillmentAgregator() {
  10168. this.count = 0;
  10169. this.target = 0;
  10170. this.results = [];
  10171. }
  10172. return FulFillmentAgregator;
  10173. }());
  10174. var InternalPromise = /** @class */ (function () {
  10175. function InternalPromise(resolver) {
  10176. var _this = this;
  10177. this._state = PromiseStates.Pending;
  10178. this._children = new Array();
  10179. this._rejectWasConsumed = false;
  10180. if (!resolver) {
  10181. return;
  10182. }
  10183. try {
  10184. resolver(function (value) {
  10185. _this._resolve(value);
  10186. }, function (reason) {
  10187. _this._reject(reason);
  10188. });
  10189. }
  10190. catch (e) {
  10191. this._reject(e);
  10192. }
  10193. }
  10194. Object.defineProperty(InternalPromise.prototype, "_result", {
  10195. get: function () {
  10196. return this._resultValue;
  10197. },
  10198. set: function (value) {
  10199. this._resultValue = value;
  10200. if (this._parent && this._parent._result === undefined) {
  10201. this._parent._result = value;
  10202. }
  10203. },
  10204. enumerable: true,
  10205. configurable: true
  10206. });
  10207. InternalPromise.prototype.catch = function (onRejected) {
  10208. return this.then(undefined, onRejected);
  10209. };
  10210. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10211. var _this = this;
  10212. var newPromise = new InternalPromise();
  10213. newPromise._onFulfilled = onFulfilled;
  10214. newPromise._onRejected = onRejected;
  10215. // Composition
  10216. this._children.push(newPromise);
  10217. newPromise._parent = this;
  10218. if (this._state !== PromiseStates.Pending) {
  10219. BABYLON.Tools.SetImmediate(function () {
  10220. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10221. var returnedValue = newPromise._resolve(_this._result);
  10222. if (returnedValue !== undefined && returnedValue !== null) {
  10223. if (returnedValue._state !== undefined) {
  10224. var returnedPromise = returnedValue;
  10225. newPromise._children.push(returnedPromise);
  10226. returnedPromise._parent = newPromise;
  10227. newPromise = returnedPromise;
  10228. }
  10229. else {
  10230. newPromise._result = returnedValue;
  10231. }
  10232. }
  10233. }
  10234. else {
  10235. newPromise._reject(_this._reason);
  10236. }
  10237. });
  10238. }
  10239. return newPromise;
  10240. };
  10241. InternalPromise.prototype._moveChildren = function (children) {
  10242. var _this = this;
  10243. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10244. this._children.forEach(function (child) {
  10245. child._parent = _this;
  10246. });
  10247. if (this._state === PromiseStates.Fulfilled) {
  10248. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10249. var child = _b[_i];
  10250. child._resolve(this._result);
  10251. }
  10252. }
  10253. else if (this._state === PromiseStates.Rejected) {
  10254. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10255. var child = _d[_c];
  10256. child._reject(this._reason);
  10257. }
  10258. }
  10259. var _a;
  10260. };
  10261. InternalPromise.prototype._resolve = function (value) {
  10262. try {
  10263. this._state = PromiseStates.Fulfilled;
  10264. var returnedValue = null;
  10265. if (this._onFulfilled) {
  10266. returnedValue = this._onFulfilled(value);
  10267. }
  10268. if (returnedValue !== undefined && returnedValue !== null) {
  10269. if (returnedValue._state !== undefined) {
  10270. // Transmit children
  10271. var returnedPromise = returnedValue;
  10272. returnedPromise._parent = this;
  10273. returnedPromise._moveChildren(this._children);
  10274. value = returnedPromise._result;
  10275. }
  10276. else {
  10277. value = returnedValue;
  10278. }
  10279. }
  10280. this._result = value;
  10281. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10282. var child = _a[_i];
  10283. child._resolve(value);
  10284. }
  10285. this._children.length = 0;
  10286. delete this._onFulfilled;
  10287. delete this._onRejected;
  10288. }
  10289. catch (e) {
  10290. this._reject(e, true);
  10291. }
  10292. };
  10293. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10294. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10295. this._state = PromiseStates.Rejected;
  10296. this._reason = reason;
  10297. if (this._onRejected && !onLocalThrow) {
  10298. try {
  10299. this._onRejected(reason);
  10300. this._rejectWasConsumed = true;
  10301. }
  10302. catch (e) {
  10303. reason = e;
  10304. }
  10305. }
  10306. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10307. var child = _a[_i];
  10308. if (this._rejectWasConsumed) {
  10309. child._resolve(null);
  10310. }
  10311. else {
  10312. child._reject(reason);
  10313. }
  10314. }
  10315. this._children.length = 0;
  10316. delete this._onFulfilled;
  10317. delete this._onRejected;
  10318. };
  10319. InternalPromise.resolve = function (value) {
  10320. var newPromise = new InternalPromise();
  10321. newPromise._resolve(value);
  10322. return newPromise;
  10323. };
  10324. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10325. promise.then(function (value) {
  10326. agregator.results[index] = value;
  10327. agregator.count++;
  10328. if (agregator.count === agregator.target) {
  10329. agregator.rootPromise._resolve(agregator.results);
  10330. }
  10331. return null;
  10332. }, function (reason) {
  10333. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10334. agregator.rootPromise._reject(reason);
  10335. }
  10336. });
  10337. };
  10338. InternalPromise.all = function (promises) {
  10339. var newPromise = new InternalPromise();
  10340. var agregator = new FulFillmentAgregator();
  10341. agregator.target = promises.length;
  10342. agregator.rootPromise = newPromise;
  10343. if (promises.length) {
  10344. for (var index = 0; index < promises.length; index++) {
  10345. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10346. }
  10347. }
  10348. else {
  10349. newPromise._resolve([]);
  10350. }
  10351. return newPromise;
  10352. };
  10353. InternalPromise.race = function (promises) {
  10354. var newPromise = new InternalPromise();
  10355. if (promises.length) {
  10356. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10357. var promise = promises_1[_i];
  10358. promise.then(function (value) {
  10359. if (newPromise) {
  10360. newPromise._resolve(value);
  10361. newPromise = null;
  10362. }
  10363. return null;
  10364. }, function (reason) {
  10365. if (newPromise) {
  10366. newPromise._reject(reason);
  10367. newPromise = null;
  10368. }
  10369. });
  10370. }
  10371. }
  10372. return newPromise;
  10373. };
  10374. return InternalPromise;
  10375. }());
  10376. /**
  10377. * Helper class that provides a small promise polyfill
  10378. */
  10379. var PromisePolyfill = /** @class */ (function () {
  10380. function PromisePolyfill() {
  10381. }
  10382. /**
  10383. * Static function used to check if the polyfill is required
  10384. * If this is the case then the function will inject the polyfill to window.Promise
  10385. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10386. */
  10387. PromisePolyfill.Apply = function (force) {
  10388. if (force === void 0) { force = false; }
  10389. if (force || typeof Promise === 'undefined') {
  10390. var root = window;
  10391. root.Promise = InternalPromise;
  10392. }
  10393. };
  10394. return PromisePolyfill;
  10395. }());
  10396. BABYLON.PromisePolyfill = PromisePolyfill;
  10397. })(BABYLON || (BABYLON = {}));
  10398. //# sourceMappingURL=babylon.promise.js.map
  10399. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10400. var BABYLON;
  10401. (function (BABYLON) {
  10402. /**
  10403. * Helper class to push actions to a pool of workers.
  10404. */
  10405. var WorkerPool = /** @class */ (function () {
  10406. /**
  10407. * Constructor
  10408. * @param workers Array of workers to use for actions
  10409. */
  10410. function WorkerPool(workers) {
  10411. this._pendingActions = new Array();
  10412. this._workerInfos = workers.map(function (worker) { return ({
  10413. worker: worker,
  10414. active: false
  10415. }); });
  10416. }
  10417. /**
  10418. * Terminates all workers and clears any pending actions.
  10419. */
  10420. WorkerPool.prototype.dispose = function () {
  10421. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10422. var workerInfo = _a[_i];
  10423. workerInfo.worker.terminate();
  10424. }
  10425. delete this._workerInfos;
  10426. delete this._pendingActions;
  10427. };
  10428. /**
  10429. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10430. * pended until a worker has completed its action.
  10431. * @param action The action to perform. Call onComplete when the action is complete.
  10432. */
  10433. WorkerPool.prototype.push = function (action) {
  10434. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10435. var workerInfo = _a[_i];
  10436. if (!workerInfo.active) {
  10437. this._execute(workerInfo, action);
  10438. return;
  10439. }
  10440. }
  10441. this._pendingActions.push(action);
  10442. };
  10443. WorkerPool.prototype._execute = function (workerInfo, action) {
  10444. var _this = this;
  10445. workerInfo.active = true;
  10446. action(workerInfo.worker, function () {
  10447. workerInfo.active = false;
  10448. var nextAction = _this._pendingActions.shift();
  10449. if (nextAction) {
  10450. _this._execute(workerInfo, nextAction);
  10451. }
  10452. });
  10453. };
  10454. return WorkerPool;
  10455. }());
  10456. BABYLON.WorkerPool = WorkerPool;
  10457. })(BABYLON || (BABYLON = {}));
  10458. //# sourceMappingURL=babylon.workerPool.js.map
  10459. var BABYLON;
  10460. (function (BABYLON) {
  10461. /**
  10462. * @hidden
  10463. **/
  10464. var _AlphaState = /** @class */ (function () {
  10465. /**
  10466. * Initializes the state.
  10467. */
  10468. function _AlphaState() {
  10469. this._isAlphaBlendDirty = false;
  10470. this._isBlendFunctionParametersDirty = false;
  10471. this._isBlendEquationParametersDirty = false;
  10472. this._isBlendConstantsDirty = false;
  10473. this._alphaBlend = false;
  10474. this._blendFunctionParameters = new Array(4);
  10475. this._blendEquationParameters = new Array(2);
  10476. this._blendConstants = new Array(4);
  10477. this.reset();
  10478. }
  10479. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10480. get: function () {
  10481. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10482. },
  10483. enumerable: true,
  10484. configurable: true
  10485. });
  10486. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10487. get: function () {
  10488. return this._alphaBlend;
  10489. },
  10490. set: function (value) {
  10491. if (this._alphaBlend === value) {
  10492. return;
  10493. }
  10494. this._alphaBlend = value;
  10495. this._isAlphaBlendDirty = true;
  10496. },
  10497. enumerable: true,
  10498. configurable: true
  10499. });
  10500. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10501. if (this._blendConstants[0] === r &&
  10502. this._blendConstants[1] === g &&
  10503. this._blendConstants[2] === b &&
  10504. this._blendConstants[3] === a) {
  10505. return;
  10506. }
  10507. this._blendConstants[0] = r;
  10508. this._blendConstants[1] = g;
  10509. this._blendConstants[2] = b;
  10510. this._blendConstants[3] = a;
  10511. this._isBlendConstantsDirty = true;
  10512. };
  10513. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10514. if (this._blendFunctionParameters[0] === value0 &&
  10515. this._blendFunctionParameters[1] === value1 &&
  10516. this._blendFunctionParameters[2] === value2 &&
  10517. this._blendFunctionParameters[3] === value3) {
  10518. return;
  10519. }
  10520. this._blendFunctionParameters[0] = value0;
  10521. this._blendFunctionParameters[1] = value1;
  10522. this._blendFunctionParameters[2] = value2;
  10523. this._blendFunctionParameters[3] = value3;
  10524. this._isBlendFunctionParametersDirty = true;
  10525. };
  10526. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10527. if (this._blendEquationParameters[0] === rgb &&
  10528. this._blendEquationParameters[1] === alpha) {
  10529. return;
  10530. }
  10531. this._blendEquationParameters[0] = rgb;
  10532. this._blendEquationParameters[1] = alpha;
  10533. this._isBlendEquationParametersDirty = true;
  10534. };
  10535. _AlphaState.prototype.reset = function () {
  10536. this._alphaBlend = false;
  10537. this._blendFunctionParameters[0] = null;
  10538. this._blendFunctionParameters[1] = null;
  10539. this._blendFunctionParameters[2] = null;
  10540. this._blendFunctionParameters[3] = null;
  10541. this._blendEquationParameters[0] = null;
  10542. this._blendEquationParameters[1] = null;
  10543. this._blendConstants[0] = null;
  10544. this._blendConstants[1] = null;
  10545. this._blendConstants[2] = null;
  10546. this._blendConstants[3] = null;
  10547. this._isAlphaBlendDirty = true;
  10548. this._isBlendFunctionParametersDirty = false;
  10549. this._isBlendEquationParametersDirty = false;
  10550. this._isBlendConstantsDirty = false;
  10551. };
  10552. _AlphaState.prototype.apply = function (gl) {
  10553. if (!this.isDirty) {
  10554. return;
  10555. }
  10556. // Alpha blend
  10557. if (this._isAlphaBlendDirty) {
  10558. if (this._alphaBlend) {
  10559. gl.enable(gl.BLEND);
  10560. }
  10561. else {
  10562. gl.disable(gl.BLEND);
  10563. }
  10564. this._isAlphaBlendDirty = false;
  10565. }
  10566. // Alpha function
  10567. if (this._isBlendFunctionParametersDirty) {
  10568. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10569. this._isBlendFunctionParametersDirty = false;
  10570. }
  10571. // Alpha equation
  10572. if (this._isBlendEquationParametersDirty) {
  10573. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10574. this._isBlendEquationParametersDirty = false;
  10575. }
  10576. // Constants
  10577. if (this._isBlendConstantsDirty) {
  10578. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10579. this._isBlendConstantsDirty = false;
  10580. }
  10581. };
  10582. return _AlphaState;
  10583. }());
  10584. BABYLON._AlphaState = _AlphaState;
  10585. })(BABYLON || (BABYLON = {}));
  10586. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10587. var BABYLON;
  10588. (function (BABYLON) {
  10589. /**
  10590. * @hidden
  10591. **/
  10592. var _DepthCullingState = /** @class */ (function () {
  10593. /**
  10594. * Initializes the state.
  10595. */
  10596. function _DepthCullingState() {
  10597. this._isDepthTestDirty = false;
  10598. this._isDepthMaskDirty = false;
  10599. this._isDepthFuncDirty = false;
  10600. this._isCullFaceDirty = false;
  10601. this._isCullDirty = false;
  10602. this._isZOffsetDirty = false;
  10603. this._isFrontFaceDirty = false;
  10604. this.reset();
  10605. }
  10606. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10607. get: function () {
  10608. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10609. },
  10610. enumerable: true,
  10611. configurable: true
  10612. });
  10613. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10614. get: function () {
  10615. return this._zOffset;
  10616. },
  10617. set: function (value) {
  10618. if (this._zOffset === value) {
  10619. return;
  10620. }
  10621. this._zOffset = value;
  10622. this._isZOffsetDirty = true;
  10623. },
  10624. enumerable: true,
  10625. configurable: true
  10626. });
  10627. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10628. get: function () {
  10629. return this._cullFace;
  10630. },
  10631. set: function (value) {
  10632. if (this._cullFace === value) {
  10633. return;
  10634. }
  10635. this._cullFace = value;
  10636. this._isCullFaceDirty = true;
  10637. },
  10638. enumerable: true,
  10639. configurable: true
  10640. });
  10641. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10642. get: function () {
  10643. return this._cull;
  10644. },
  10645. set: function (value) {
  10646. if (this._cull === value) {
  10647. return;
  10648. }
  10649. this._cull = value;
  10650. this._isCullDirty = true;
  10651. },
  10652. enumerable: true,
  10653. configurable: true
  10654. });
  10655. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10656. get: function () {
  10657. return this._depthFunc;
  10658. },
  10659. set: function (value) {
  10660. if (this._depthFunc === value) {
  10661. return;
  10662. }
  10663. this._depthFunc = value;
  10664. this._isDepthFuncDirty = true;
  10665. },
  10666. enumerable: true,
  10667. configurable: true
  10668. });
  10669. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10670. get: function () {
  10671. return this._depthMask;
  10672. },
  10673. set: function (value) {
  10674. if (this._depthMask === value) {
  10675. return;
  10676. }
  10677. this._depthMask = value;
  10678. this._isDepthMaskDirty = true;
  10679. },
  10680. enumerable: true,
  10681. configurable: true
  10682. });
  10683. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10684. get: function () {
  10685. return this._depthTest;
  10686. },
  10687. set: function (value) {
  10688. if (this._depthTest === value) {
  10689. return;
  10690. }
  10691. this._depthTest = value;
  10692. this._isDepthTestDirty = true;
  10693. },
  10694. enumerable: true,
  10695. configurable: true
  10696. });
  10697. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10698. get: function () {
  10699. return this._frontFace;
  10700. },
  10701. set: function (value) {
  10702. if (this._frontFace === value) {
  10703. return;
  10704. }
  10705. this._frontFace = value;
  10706. this._isFrontFaceDirty = true;
  10707. },
  10708. enumerable: true,
  10709. configurable: true
  10710. });
  10711. _DepthCullingState.prototype.reset = function () {
  10712. this._depthMask = true;
  10713. this._depthTest = true;
  10714. this._depthFunc = null;
  10715. this._cullFace = null;
  10716. this._cull = null;
  10717. this._zOffset = 0;
  10718. this._frontFace = null;
  10719. this._isDepthTestDirty = true;
  10720. this._isDepthMaskDirty = true;
  10721. this._isDepthFuncDirty = false;
  10722. this._isCullFaceDirty = false;
  10723. this._isCullDirty = false;
  10724. this._isZOffsetDirty = false;
  10725. this._isFrontFaceDirty = false;
  10726. };
  10727. _DepthCullingState.prototype.apply = function (gl) {
  10728. if (!this.isDirty) {
  10729. return;
  10730. }
  10731. // Cull
  10732. if (this._isCullDirty) {
  10733. if (this.cull) {
  10734. gl.enable(gl.CULL_FACE);
  10735. }
  10736. else {
  10737. gl.disable(gl.CULL_FACE);
  10738. }
  10739. this._isCullDirty = false;
  10740. }
  10741. // Cull face
  10742. if (this._isCullFaceDirty) {
  10743. gl.cullFace(this.cullFace);
  10744. this._isCullFaceDirty = false;
  10745. }
  10746. // Depth mask
  10747. if (this._isDepthMaskDirty) {
  10748. gl.depthMask(this.depthMask);
  10749. this._isDepthMaskDirty = false;
  10750. }
  10751. // Depth test
  10752. if (this._isDepthTestDirty) {
  10753. if (this.depthTest) {
  10754. gl.enable(gl.DEPTH_TEST);
  10755. }
  10756. else {
  10757. gl.disable(gl.DEPTH_TEST);
  10758. }
  10759. this._isDepthTestDirty = false;
  10760. }
  10761. // Depth func
  10762. if (this._isDepthFuncDirty) {
  10763. gl.depthFunc(this.depthFunc);
  10764. this._isDepthFuncDirty = false;
  10765. }
  10766. // zOffset
  10767. if (this._isZOffsetDirty) {
  10768. if (this.zOffset) {
  10769. gl.enable(gl.POLYGON_OFFSET_FILL);
  10770. gl.polygonOffset(this.zOffset, 0);
  10771. }
  10772. else {
  10773. gl.disable(gl.POLYGON_OFFSET_FILL);
  10774. }
  10775. this._isZOffsetDirty = false;
  10776. }
  10777. // Front face
  10778. if (this._isFrontFaceDirty) {
  10779. gl.frontFace(this.frontFace);
  10780. this._isFrontFaceDirty = false;
  10781. }
  10782. };
  10783. return _DepthCullingState;
  10784. }());
  10785. BABYLON._DepthCullingState = _DepthCullingState;
  10786. })(BABYLON || (BABYLON = {}));
  10787. //# sourceMappingURL=babylon.depthCullingState.js.map
  10788. var BABYLON;
  10789. (function (BABYLON) {
  10790. /**
  10791. * @hidden
  10792. **/
  10793. var _StencilState = /** @class */ (function () {
  10794. function _StencilState() {
  10795. this._isStencilTestDirty = false;
  10796. this._isStencilMaskDirty = false;
  10797. this._isStencilFuncDirty = false;
  10798. this._isStencilOpDirty = false;
  10799. this.reset();
  10800. }
  10801. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10802. get: function () {
  10803. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10804. },
  10805. enumerable: true,
  10806. configurable: true
  10807. });
  10808. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10809. get: function () {
  10810. return this._stencilFunc;
  10811. },
  10812. set: function (value) {
  10813. if (this._stencilFunc === value) {
  10814. return;
  10815. }
  10816. this._stencilFunc = value;
  10817. this._isStencilFuncDirty = true;
  10818. },
  10819. enumerable: true,
  10820. configurable: true
  10821. });
  10822. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10823. get: function () {
  10824. return this._stencilFuncRef;
  10825. },
  10826. set: function (value) {
  10827. if (this._stencilFuncRef === value) {
  10828. return;
  10829. }
  10830. this._stencilFuncRef = value;
  10831. this._isStencilFuncDirty = true;
  10832. },
  10833. enumerable: true,
  10834. configurable: true
  10835. });
  10836. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10837. get: function () {
  10838. return this._stencilFuncMask;
  10839. },
  10840. set: function (value) {
  10841. if (this._stencilFuncMask === value) {
  10842. return;
  10843. }
  10844. this._stencilFuncMask = value;
  10845. this._isStencilFuncDirty = true;
  10846. },
  10847. enumerable: true,
  10848. configurable: true
  10849. });
  10850. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10851. get: function () {
  10852. return this._stencilOpStencilFail;
  10853. },
  10854. set: function (value) {
  10855. if (this._stencilOpStencilFail === value) {
  10856. return;
  10857. }
  10858. this._stencilOpStencilFail = value;
  10859. this._isStencilOpDirty = true;
  10860. },
  10861. enumerable: true,
  10862. configurable: true
  10863. });
  10864. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10865. get: function () {
  10866. return this._stencilOpDepthFail;
  10867. },
  10868. set: function (value) {
  10869. if (this._stencilOpDepthFail === value) {
  10870. return;
  10871. }
  10872. this._stencilOpDepthFail = value;
  10873. this._isStencilOpDirty = true;
  10874. },
  10875. enumerable: true,
  10876. configurable: true
  10877. });
  10878. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10879. get: function () {
  10880. return this._stencilOpStencilDepthPass;
  10881. },
  10882. set: function (value) {
  10883. if (this._stencilOpStencilDepthPass === value) {
  10884. return;
  10885. }
  10886. this._stencilOpStencilDepthPass = value;
  10887. this._isStencilOpDirty = true;
  10888. },
  10889. enumerable: true,
  10890. configurable: true
  10891. });
  10892. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10893. get: function () {
  10894. return this._stencilMask;
  10895. },
  10896. set: function (value) {
  10897. if (this._stencilMask === value) {
  10898. return;
  10899. }
  10900. this._stencilMask = value;
  10901. this._isStencilMaskDirty = true;
  10902. },
  10903. enumerable: true,
  10904. configurable: true
  10905. });
  10906. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10907. get: function () {
  10908. return this._stencilTest;
  10909. },
  10910. set: function (value) {
  10911. if (this._stencilTest === value) {
  10912. return;
  10913. }
  10914. this._stencilTest = value;
  10915. this._isStencilTestDirty = true;
  10916. },
  10917. enumerable: true,
  10918. configurable: true
  10919. });
  10920. _StencilState.prototype.reset = function () {
  10921. this._stencilTest = false;
  10922. this._stencilMask = 0xFF;
  10923. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10924. this._stencilFuncRef = 1;
  10925. this._stencilFuncMask = 0xFF;
  10926. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10927. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10928. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10929. this._isStencilTestDirty = true;
  10930. this._isStencilMaskDirty = true;
  10931. this._isStencilFuncDirty = true;
  10932. this._isStencilOpDirty = true;
  10933. };
  10934. _StencilState.prototype.apply = function (gl) {
  10935. if (!this.isDirty) {
  10936. return;
  10937. }
  10938. // Stencil test
  10939. if (this._isStencilTestDirty) {
  10940. if (this.stencilTest) {
  10941. gl.enable(gl.STENCIL_TEST);
  10942. }
  10943. else {
  10944. gl.disable(gl.STENCIL_TEST);
  10945. }
  10946. this._isStencilTestDirty = false;
  10947. }
  10948. // Stencil mask
  10949. if (this._isStencilMaskDirty) {
  10950. gl.stencilMask(this.stencilMask);
  10951. this._isStencilMaskDirty = false;
  10952. }
  10953. // Stencil func
  10954. if (this._isStencilFuncDirty) {
  10955. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10956. this._isStencilFuncDirty = false;
  10957. }
  10958. // Stencil op
  10959. if (this._isStencilOpDirty) {
  10960. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10961. this._isStencilOpDirty = false;
  10962. }
  10963. };
  10964. return _StencilState;
  10965. }());
  10966. BABYLON._StencilState = _StencilState;
  10967. })(BABYLON || (BABYLON = {}));
  10968. //# sourceMappingURL=babylon.stencilState.js.map
  10969. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10970. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10971. s = arguments[i];
  10972. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10973. t[p] = s[p];
  10974. }
  10975. return t;
  10976. };
  10977. var BABYLON;
  10978. (function (BABYLON) {
  10979. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10980. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10981. };
  10982. var compileRawShader = function (gl, source, type) {
  10983. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10984. gl.shaderSource(shader, source);
  10985. gl.compileShader(shader);
  10986. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10987. var log = gl.getShaderInfoLog(shader);
  10988. if (log) {
  10989. throw new Error(log);
  10990. }
  10991. }
  10992. if (!shader) {
  10993. throw new Error("Something went wrong while compile the shader.");
  10994. }
  10995. return shader;
  10996. };
  10997. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10998. var magFilter = gl.NEAREST;
  10999. var minFilter = gl.NEAREST;
  11000. switch (samplingMode) {
  11001. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11002. magFilter = gl.LINEAR;
  11003. if (generateMipMaps) {
  11004. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11005. }
  11006. else {
  11007. minFilter = gl.LINEAR;
  11008. }
  11009. break;
  11010. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11011. magFilter = gl.LINEAR;
  11012. if (generateMipMaps) {
  11013. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11014. }
  11015. else {
  11016. minFilter = gl.LINEAR;
  11017. }
  11018. break;
  11019. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11020. magFilter = gl.NEAREST;
  11021. if (generateMipMaps) {
  11022. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11023. }
  11024. else {
  11025. minFilter = gl.NEAREST;
  11026. }
  11027. break;
  11028. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11029. magFilter = gl.NEAREST;
  11030. if (generateMipMaps) {
  11031. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11032. }
  11033. else {
  11034. minFilter = gl.NEAREST;
  11035. }
  11036. break;
  11037. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11038. magFilter = gl.NEAREST;
  11039. if (generateMipMaps) {
  11040. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11041. }
  11042. else {
  11043. minFilter = gl.LINEAR;
  11044. }
  11045. break;
  11046. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11047. magFilter = gl.NEAREST;
  11048. if (generateMipMaps) {
  11049. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11050. }
  11051. else {
  11052. minFilter = gl.LINEAR;
  11053. }
  11054. break;
  11055. case BABYLON.Texture.NEAREST_LINEAR:
  11056. magFilter = gl.NEAREST;
  11057. minFilter = gl.LINEAR;
  11058. break;
  11059. case BABYLON.Texture.NEAREST_NEAREST:
  11060. magFilter = gl.NEAREST;
  11061. minFilter = gl.NEAREST;
  11062. break;
  11063. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11064. magFilter = gl.LINEAR;
  11065. if (generateMipMaps) {
  11066. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11067. }
  11068. else {
  11069. minFilter = gl.NEAREST;
  11070. }
  11071. break;
  11072. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11073. magFilter = gl.LINEAR;
  11074. if (generateMipMaps) {
  11075. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11076. }
  11077. else {
  11078. minFilter = gl.NEAREST;
  11079. }
  11080. break;
  11081. case BABYLON.Texture.LINEAR_LINEAR:
  11082. magFilter = gl.LINEAR;
  11083. minFilter = gl.LINEAR;
  11084. break;
  11085. case BABYLON.Texture.LINEAR_NEAREST:
  11086. magFilter = gl.LINEAR;
  11087. minFilter = gl.NEAREST;
  11088. break;
  11089. }
  11090. return {
  11091. min: minFilter,
  11092. mag: magFilter
  11093. };
  11094. };
  11095. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11096. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11097. var img;
  11098. var onload = function () {
  11099. loadedImages[index] = img;
  11100. loadedImages._internalCount++;
  11101. if (scene) {
  11102. scene._removePendingData(img);
  11103. }
  11104. if (loadedImages._internalCount === 6) {
  11105. onfinish(loadedImages);
  11106. }
  11107. };
  11108. var onerror = function (message, exception) {
  11109. if (scene) {
  11110. scene._removePendingData(img);
  11111. }
  11112. if (onErrorCallBack) {
  11113. onErrorCallBack(message, exception);
  11114. }
  11115. };
  11116. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11117. if (scene) {
  11118. scene._addPendingData(img);
  11119. }
  11120. };
  11121. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11122. if (onError === void 0) { onError = null; }
  11123. var loadedImages = [];
  11124. loadedImages._internalCount = 0;
  11125. for (var index = 0; index < 6; index++) {
  11126. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11127. }
  11128. };
  11129. var BufferPointer = /** @class */ (function () {
  11130. function BufferPointer() {
  11131. }
  11132. return BufferPointer;
  11133. }());
  11134. /**
  11135. * Interface for attribute information associated with buffer instanciation
  11136. */
  11137. var InstancingAttributeInfo = /** @class */ (function () {
  11138. function InstancingAttributeInfo() {
  11139. }
  11140. return InstancingAttributeInfo;
  11141. }());
  11142. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11143. /**
  11144. * Define options used to create a render target texture
  11145. */
  11146. var RenderTargetCreationOptions = /** @class */ (function () {
  11147. function RenderTargetCreationOptions() {
  11148. }
  11149. return RenderTargetCreationOptions;
  11150. }());
  11151. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11152. /**
  11153. * Define options used to create a depth texture
  11154. */
  11155. var DepthTextureCreationOptions = /** @class */ (function () {
  11156. function DepthTextureCreationOptions() {
  11157. }
  11158. return DepthTextureCreationOptions;
  11159. }());
  11160. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11161. /**
  11162. * Class used to describe the capabilities of the engine relatively to the current browser
  11163. */
  11164. var EngineCapabilities = /** @class */ (function () {
  11165. function EngineCapabilities() {
  11166. }
  11167. return EngineCapabilities;
  11168. }());
  11169. BABYLON.EngineCapabilities = EngineCapabilities;
  11170. /**
  11171. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11172. */
  11173. var Engine = /** @class */ (function () {
  11174. /**
  11175. * Creates a new engine
  11176. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11177. * @param antialias defines enable antialiasing (default: false)
  11178. * @param options defines further options to be sent to the getContext() function
  11179. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11180. */
  11181. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11182. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11183. var _this = this;
  11184. // Public members
  11185. /**
  11186. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11187. */
  11188. this.forcePOTTextures = false;
  11189. /**
  11190. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11191. */
  11192. this.isFullscreen = false;
  11193. /**
  11194. * Gets a boolean indicating if the pointer is currently locked
  11195. */
  11196. this.isPointerLock = false;
  11197. /**
  11198. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11199. */
  11200. this.cullBackFaces = true;
  11201. /**
  11202. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11203. */
  11204. this.renderEvenInBackground = true;
  11205. /**
  11206. * Gets or sets a boolean indicating that cache can be kept between frames
  11207. */
  11208. this.preventCacheWipeBetweenFrames = false;
  11209. /**
  11210. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11211. **/
  11212. this.enableOfflineSupport = false;
  11213. /**
  11214. * 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)
  11215. **/
  11216. this.disableManifestCheck = false;
  11217. /**
  11218. * Gets the list of created scenes
  11219. */
  11220. this.scenes = new Array();
  11221. /**
  11222. * Gets the list of created postprocesses
  11223. */
  11224. this.postProcesses = new Array();
  11225. // Observables
  11226. /**
  11227. * Observable event triggered each time the rendering canvas is resized
  11228. */
  11229. this.onResizeObservable = new BABYLON.Observable();
  11230. /**
  11231. * Observable event triggered each time the canvas loses focus
  11232. */
  11233. this.onCanvasBlurObservable = new BABYLON.Observable();
  11234. /**
  11235. * Observable event triggered each time the canvas gains focus
  11236. */
  11237. this.onCanvasFocusObservable = new BABYLON.Observable();
  11238. /**
  11239. * Observable event triggered each time the canvas receives pointerout event
  11240. */
  11241. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11242. /**
  11243. * Observable event triggered before each texture is initialized
  11244. */
  11245. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11246. //WebVR
  11247. this._vrDisplay = undefined;
  11248. this._vrSupported = false;
  11249. this._vrExclusivePointerMode = false;
  11250. // Uniform buffers list
  11251. /**
  11252. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11253. */
  11254. this.disableUniformBuffers = false;
  11255. /** @hidden */
  11256. this._uniformBuffers = new Array();
  11257. // Observables
  11258. /**
  11259. * Observable raised when the engine begins a new frame
  11260. */
  11261. this.onBeginFrameObservable = new BABYLON.Observable();
  11262. /**
  11263. * Observable raised when the engine ends the current frame
  11264. */
  11265. this.onEndFrameObservable = new BABYLON.Observable();
  11266. /**
  11267. * Observable raised when the engine is about to compile a shader
  11268. */
  11269. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11270. /**
  11271. * Observable raised when the engine has jsut compiled a shader
  11272. */
  11273. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11274. this._windowIsBackground = false;
  11275. this._webGLVersion = 1.0;
  11276. /** @hidden */
  11277. this._badOS = false;
  11278. /** @hidden */
  11279. this._badDesktopOS = false;
  11280. /**
  11281. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11282. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11283. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11284. */
  11285. this.disableTextureBindingOptimization = false;
  11286. /**
  11287. * Observable signaled when VR display mode changes
  11288. */
  11289. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11290. /**
  11291. * Observable signaled when VR request present is complete
  11292. */
  11293. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11294. /**
  11295. * Observable signaled when VR request present starts
  11296. */
  11297. this.onVRRequestPresentStart = new BABYLON.Observable();
  11298. this._colorWrite = true;
  11299. /** @hidden */
  11300. this._drawCalls = new BABYLON.PerfCounter();
  11301. /** @hidden */
  11302. this._textureCollisions = new BABYLON.PerfCounter();
  11303. this._renderingQueueLaunched = false;
  11304. this._activeRenderLoops = new Array();
  11305. // Deterministic lockstepMaxSteps
  11306. this._deterministicLockstep = false;
  11307. this._lockstepMaxSteps = 4;
  11308. // Lost context
  11309. /**
  11310. * Observable signaled when a context lost event is raised
  11311. */
  11312. this.onContextLostObservable = new BABYLON.Observable();
  11313. /**
  11314. * Observable signaled when a context restored event is raised
  11315. */
  11316. this.onContextRestoredObservable = new BABYLON.Observable();
  11317. this._contextWasLost = false;
  11318. this._doNotHandleContextLost = false;
  11319. // FPS
  11320. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11321. this._fps = 60;
  11322. this._deltaTime = 0;
  11323. /**
  11324. * Turn this value on if you want to pause FPS computation when in background
  11325. */
  11326. this.disablePerformanceMonitorInBackground = false;
  11327. // States
  11328. /** @hidden */
  11329. this._depthCullingState = new BABYLON._DepthCullingState();
  11330. /** @hidden */
  11331. this._stencilState = new BABYLON._StencilState();
  11332. /** @hidden */
  11333. this._alphaState = new BABYLON._AlphaState();
  11334. /** @hidden */
  11335. this._alphaMode = Engine.ALPHA_DISABLE;
  11336. // Cache
  11337. this._internalTexturesCache = new Array();
  11338. /** @hidden */
  11339. this._activeChannel = 0;
  11340. this._currentTextureChannel = -1;
  11341. /** @hidden */
  11342. this._boundTexturesCache = {};
  11343. this._compiledEffects = {};
  11344. this._vertexAttribArraysEnabled = [];
  11345. this._uintIndicesCurrentlySet = false;
  11346. this._currentBoundBuffer = new Array();
  11347. this._currentBufferPointers = new Array();
  11348. this._currentInstanceLocations = new Array();
  11349. this._currentInstanceBuffers = new Array();
  11350. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11351. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11352. this._vaoRecordInProgress = false;
  11353. this._mustWipeVertexAttributes = false;
  11354. this._nextFreeTextureSlots = new Array();
  11355. this._maxSimultaneousTextures = 0;
  11356. this._activeRequests = new Array();
  11357. // Hardware supported Compressed Textures
  11358. this._texturesSupported = new Array();
  11359. this._onVRFullScreenTriggered = function () {
  11360. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11361. //get the old size before we change
  11362. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11363. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11364. //get the width and height, change the render size
  11365. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11366. _this.setHardwareScalingLevel(1);
  11367. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11368. }
  11369. else {
  11370. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11371. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11372. }
  11373. };
  11374. this._boundUniforms = {};
  11375. // Register promises
  11376. BABYLON.PromisePolyfill.Apply();
  11377. var canvas = null;
  11378. Engine.Instances.push(this);
  11379. if (!canvasOrContext) {
  11380. return;
  11381. }
  11382. options = options || {};
  11383. if (canvasOrContext.getContext) {
  11384. canvas = canvasOrContext;
  11385. this._renderingCanvas = canvas;
  11386. if (antialias != null) {
  11387. options.antialias = antialias;
  11388. }
  11389. if (options.deterministicLockstep === undefined) {
  11390. options.deterministicLockstep = false;
  11391. }
  11392. if (options.lockstepMaxSteps === undefined) {
  11393. options.lockstepMaxSteps = 4;
  11394. }
  11395. if (options.preserveDrawingBuffer === undefined) {
  11396. options.preserveDrawingBuffer = false;
  11397. }
  11398. if (options.audioEngine === undefined) {
  11399. options.audioEngine = true;
  11400. }
  11401. if (options.stencil === undefined) {
  11402. options.stencil = true;
  11403. }
  11404. this._deterministicLockstep = options.deterministicLockstep;
  11405. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11406. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11407. // Exceptions
  11408. if (navigator && navigator.userAgent) {
  11409. var ua = navigator.userAgent;
  11410. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11411. var exception = _a[_i];
  11412. var key = exception.key;
  11413. var targets = exception.targets;
  11414. if (ua.indexOf(key) > -1) {
  11415. if (exception.capture && exception.captureConstraint) {
  11416. var capture = exception.capture;
  11417. var constraint = exception.captureConstraint;
  11418. var regex = new RegExp(capture);
  11419. var matches = regex.exec(ua);
  11420. if (matches && matches.length > 0) {
  11421. var capturedValue = parseInt(matches[matches.length - 1]);
  11422. if (capturedValue >= constraint) {
  11423. continue;
  11424. }
  11425. }
  11426. }
  11427. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11428. var target = targets_1[_b];
  11429. switch (target) {
  11430. case "uniformBuffer":
  11431. this.disableUniformBuffers = true;
  11432. break;
  11433. case "textureBindingOptimization":
  11434. this.disableTextureBindingOptimization = true;
  11435. break;
  11436. }
  11437. }
  11438. }
  11439. }
  11440. }
  11441. // GL
  11442. if (!options.disableWebGL2Support) {
  11443. try {
  11444. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11445. if (this._gl) {
  11446. this._webGLVersion = 2.0;
  11447. }
  11448. }
  11449. catch (e) {
  11450. // Do nothing
  11451. }
  11452. }
  11453. if (!this._gl) {
  11454. if (!canvas) {
  11455. throw new Error("The provided canvas is null or undefined.");
  11456. }
  11457. try {
  11458. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11459. }
  11460. catch (e) {
  11461. throw new Error("WebGL not supported");
  11462. }
  11463. }
  11464. if (!this._gl) {
  11465. throw new Error("WebGL not supported");
  11466. }
  11467. this._onCanvasFocus = function () {
  11468. _this.onCanvasFocusObservable.notifyObservers(_this);
  11469. };
  11470. this._onCanvasBlur = function () {
  11471. _this.onCanvasBlurObservable.notifyObservers(_this);
  11472. };
  11473. canvas.addEventListener("focus", this._onCanvasFocus);
  11474. canvas.addEventListener("blur", this._onCanvasBlur);
  11475. this._onBlur = function () {
  11476. if (_this.disablePerformanceMonitorInBackground) {
  11477. _this._performanceMonitor.disable();
  11478. }
  11479. _this._windowIsBackground = true;
  11480. };
  11481. this._onFocus = function () {
  11482. if (_this.disablePerformanceMonitorInBackground) {
  11483. _this._performanceMonitor.enable();
  11484. }
  11485. _this._windowIsBackground = false;
  11486. };
  11487. this._onCanvasPointerOut = function (ev) {
  11488. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11489. };
  11490. window.addEventListener("blur", this._onBlur);
  11491. window.addEventListener("focus", this._onFocus);
  11492. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11493. // Context lost
  11494. if (!this._doNotHandleContextLost) {
  11495. this._onContextLost = function (evt) {
  11496. evt.preventDefault();
  11497. _this._contextWasLost = true;
  11498. BABYLON.Tools.Warn("WebGL context lost.");
  11499. _this.onContextLostObservable.notifyObservers(_this);
  11500. };
  11501. this._onContextRestored = function (evt) {
  11502. // Adding a timeout to avoid race condition at browser level
  11503. setTimeout(function () {
  11504. // Rebuild gl context
  11505. _this._initGLContext();
  11506. // Rebuild effects
  11507. _this._rebuildEffects();
  11508. // Rebuild textures
  11509. _this._rebuildInternalTextures();
  11510. // Rebuild buffers
  11511. _this._rebuildBuffers();
  11512. // Cache
  11513. _this.wipeCaches(true);
  11514. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11515. _this.onContextRestoredObservable.notifyObservers(_this);
  11516. _this._contextWasLost = false;
  11517. }, 0);
  11518. };
  11519. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11520. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11521. }
  11522. }
  11523. else {
  11524. this._gl = canvasOrContext;
  11525. this._renderingCanvas = this._gl.canvas;
  11526. if (this._gl.renderbufferStorageMultisample) {
  11527. this._webGLVersion = 2.0;
  11528. }
  11529. options.stencil = this._gl.getContextAttributes().stencil;
  11530. }
  11531. // Viewport
  11532. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11533. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11534. this.resize();
  11535. this._isStencilEnable = options.stencil ? true : false;
  11536. this._initGLContext();
  11537. if (canvas) {
  11538. // Fullscreen
  11539. this._onFullscreenChange = function () {
  11540. if (document.fullscreen !== undefined) {
  11541. _this.isFullscreen = document.fullscreen;
  11542. }
  11543. else if (document.mozFullScreen !== undefined) {
  11544. _this.isFullscreen = document.mozFullScreen;
  11545. }
  11546. else if (document.webkitIsFullScreen !== undefined) {
  11547. _this.isFullscreen = document.webkitIsFullScreen;
  11548. }
  11549. else if (document.msIsFullScreen !== undefined) {
  11550. _this.isFullscreen = document.msIsFullScreen;
  11551. }
  11552. // Pointer lock
  11553. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11554. canvas.requestPointerLock = canvas.requestPointerLock ||
  11555. canvas.msRequestPointerLock ||
  11556. canvas.mozRequestPointerLock ||
  11557. canvas.webkitRequestPointerLock;
  11558. if (canvas.requestPointerLock) {
  11559. canvas.requestPointerLock();
  11560. }
  11561. }
  11562. };
  11563. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11564. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11565. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11566. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11567. // Pointer lock
  11568. this._onPointerLockChange = function () {
  11569. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11570. document.webkitPointerLockElement === canvas ||
  11571. document.msPointerLockElement === canvas ||
  11572. document.pointerLockElement === canvas);
  11573. };
  11574. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11575. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11576. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11577. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11578. this._onVRDisplayPointerRestricted = function () {
  11579. if (canvas) {
  11580. canvas.requestPointerLock();
  11581. }
  11582. };
  11583. this._onVRDisplayPointerUnrestricted = function () {
  11584. document.exitPointerLock();
  11585. };
  11586. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11587. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11588. }
  11589. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11590. Engine.audioEngine = new BABYLON.AudioEngine();
  11591. }
  11592. // Prepare buffer pointers
  11593. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11594. this._currentBufferPointers[i] = new BufferPointer();
  11595. }
  11596. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11597. // Load WebVR Devices
  11598. if (options.autoEnableWebVR) {
  11599. this.initWebVR();
  11600. }
  11601. // Detect if we are running on a faulty buggy OS.
  11602. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11603. // Detect if we are running on a faulty buggy desktop OS.
  11604. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11605. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11606. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11607. }
  11608. Object.defineProperty(Engine, "LastCreatedEngine", {
  11609. /**
  11610. * Gets the latest created engine
  11611. */
  11612. get: function () {
  11613. if (Engine.Instances.length === 0) {
  11614. return null;
  11615. }
  11616. return Engine.Instances[Engine.Instances.length - 1];
  11617. },
  11618. enumerable: true,
  11619. configurable: true
  11620. });
  11621. Object.defineProperty(Engine, "LastCreatedScene", {
  11622. /**
  11623. * Gets the latest created scene
  11624. */
  11625. get: function () {
  11626. var lastCreatedEngine = Engine.LastCreatedEngine;
  11627. if (!lastCreatedEngine) {
  11628. return null;
  11629. }
  11630. if (lastCreatedEngine.scenes.length === 0) {
  11631. return null;
  11632. }
  11633. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11634. },
  11635. enumerable: true,
  11636. configurable: true
  11637. });
  11638. /**
  11639. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11640. * @param flag defines which part of the materials must be marked as dirty
  11641. * @param predicate defines a predicate used to filter which materials should be affected
  11642. */
  11643. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11644. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11645. var engine = Engine.Instances[engineIndex];
  11646. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11647. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11648. }
  11649. }
  11650. };
  11651. Object.defineProperty(Engine, "NEVER", {
  11652. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11653. get: function () {
  11654. return Engine._NEVER;
  11655. },
  11656. enumerable: true,
  11657. configurable: true
  11658. });
  11659. Object.defineProperty(Engine, "ALWAYS", {
  11660. /** 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 */
  11661. get: function () {
  11662. return Engine._ALWAYS;
  11663. },
  11664. enumerable: true,
  11665. configurable: true
  11666. });
  11667. Object.defineProperty(Engine, "LESS", {
  11668. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11669. get: function () {
  11670. return Engine._LESS;
  11671. },
  11672. enumerable: true,
  11673. configurable: true
  11674. });
  11675. Object.defineProperty(Engine, "EQUAL", {
  11676. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11677. get: function () {
  11678. return Engine._EQUAL;
  11679. },
  11680. enumerable: true,
  11681. configurable: true
  11682. });
  11683. Object.defineProperty(Engine, "LEQUAL", {
  11684. /** 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 */
  11685. get: function () {
  11686. return Engine._LEQUAL;
  11687. },
  11688. enumerable: true,
  11689. configurable: true
  11690. });
  11691. Object.defineProperty(Engine, "GREATER", {
  11692. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11693. get: function () {
  11694. return Engine._GREATER;
  11695. },
  11696. enumerable: true,
  11697. configurable: true
  11698. });
  11699. Object.defineProperty(Engine, "GEQUAL", {
  11700. /** 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 */
  11701. get: function () {
  11702. return Engine._GEQUAL;
  11703. },
  11704. enumerable: true,
  11705. configurable: true
  11706. });
  11707. Object.defineProperty(Engine, "NOTEQUAL", {
  11708. /** 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 */
  11709. get: function () {
  11710. return Engine._NOTEQUAL;
  11711. },
  11712. enumerable: true,
  11713. configurable: true
  11714. });
  11715. Object.defineProperty(Engine, "KEEP", {
  11716. /** Passed to stencilOperation to specify that stencil value must be kept */
  11717. get: function () {
  11718. return Engine._KEEP;
  11719. },
  11720. enumerable: true,
  11721. configurable: true
  11722. });
  11723. Object.defineProperty(Engine, "REPLACE", {
  11724. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11725. get: function () {
  11726. return Engine._REPLACE;
  11727. },
  11728. enumerable: true,
  11729. configurable: true
  11730. });
  11731. Object.defineProperty(Engine, "INCR", {
  11732. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11733. get: function () {
  11734. return Engine._INCR;
  11735. },
  11736. enumerable: true,
  11737. configurable: true
  11738. });
  11739. Object.defineProperty(Engine, "DECR", {
  11740. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11741. get: function () {
  11742. return Engine._DECR;
  11743. },
  11744. enumerable: true,
  11745. configurable: true
  11746. });
  11747. Object.defineProperty(Engine, "INVERT", {
  11748. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11749. get: function () {
  11750. return Engine._INVERT;
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. Object.defineProperty(Engine, "INCR_WRAP", {
  11756. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11757. get: function () {
  11758. return Engine._INCR_WRAP;
  11759. },
  11760. enumerable: true,
  11761. configurable: true
  11762. });
  11763. Object.defineProperty(Engine, "DECR_WRAP", {
  11764. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11765. get: function () {
  11766. return Engine._DECR_WRAP;
  11767. },
  11768. enumerable: true,
  11769. configurable: true
  11770. });
  11771. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11772. // Alpha
  11773. /** Defines that alpha blending is disabled */
  11774. get: function () {
  11775. return Engine._ALPHA_DISABLE;
  11776. },
  11777. enumerable: true,
  11778. configurable: true
  11779. });
  11780. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11781. /** Defines that alpha blending to SRC + DEST */
  11782. get: function () {
  11783. return Engine._ALPHA_ONEONE;
  11784. },
  11785. enumerable: true,
  11786. configurable: true
  11787. });
  11788. Object.defineProperty(Engine, "ALPHA_ADD", {
  11789. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11790. get: function () {
  11791. return Engine._ALPHA_ADD;
  11792. },
  11793. enumerable: true,
  11794. configurable: true
  11795. });
  11796. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11797. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11798. get: function () {
  11799. return Engine._ALPHA_COMBINE;
  11800. },
  11801. enumerable: true,
  11802. configurable: true
  11803. });
  11804. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11805. /** Defines that alpha blending to DEST - SRC * DEST */
  11806. get: function () {
  11807. return Engine._ALPHA_SUBTRACT;
  11808. },
  11809. enumerable: true,
  11810. configurable: true
  11811. });
  11812. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11813. /** Defines that alpha blending to SRC * DEST */
  11814. get: function () {
  11815. return Engine._ALPHA_MULTIPLY;
  11816. },
  11817. enumerable: true,
  11818. configurable: true
  11819. });
  11820. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11821. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11822. get: function () {
  11823. return Engine._ALPHA_MAXIMIZED;
  11824. },
  11825. enumerable: true,
  11826. configurable: true
  11827. });
  11828. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11829. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11830. get: function () {
  11831. return Engine._ALPHA_PREMULTIPLIED;
  11832. },
  11833. enumerable: true,
  11834. configurable: true
  11835. });
  11836. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11837. /**
  11838. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11839. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11840. */
  11841. get: function () {
  11842. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11843. },
  11844. enumerable: true,
  11845. configurable: true
  11846. });
  11847. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11848. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11849. get: function () {
  11850. return Engine._ALPHA_INTERPOLATE;
  11851. },
  11852. enumerable: true,
  11853. configurable: true
  11854. });
  11855. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11856. /**
  11857. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11858. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11859. */
  11860. get: function () {
  11861. return Engine._ALPHA_SCREENMODE;
  11862. },
  11863. enumerable: true,
  11864. configurable: true
  11865. });
  11866. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11867. // Delays
  11868. /** Defines that the ressource is not delayed*/
  11869. get: function () {
  11870. return Engine._DELAYLOADSTATE_NONE;
  11871. },
  11872. enumerable: true,
  11873. configurable: true
  11874. });
  11875. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11876. /** Defines that the ressource was successfully delay loaded */
  11877. get: function () {
  11878. return Engine._DELAYLOADSTATE_LOADED;
  11879. },
  11880. enumerable: true,
  11881. configurable: true
  11882. });
  11883. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11884. /** Defines that the ressource is currently delay loading */
  11885. get: function () {
  11886. return Engine._DELAYLOADSTATE_LOADING;
  11887. },
  11888. enumerable: true,
  11889. configurable: true
  11890. });
  11891. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11892. /** Defines that the ressource is delayed and has not started loading */
  11893. get: function () {
  11894. return Engine._DELAYLOADSTATE_NOTLOADED;
  11895. },
  11896. enumerable: true,
  11897. configurable: true
  11898. });
  11899. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11900. /** ALPHA */
  11901. get: function () {
  11902. return Engine._TEXTUREFORMAT_ALPHA;
  11903. },
  11904. enumerable: true,
  11905. configurable: true
  11906. });
  11907. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11908. /** LUMINANCE */
  11909. get: function () {
  11910. return Engine._TEXTUREFORMAT_LUMINANCE;
  11911. },
  11912. enumerable: true,
  11913. configurable: true
  11914. });
  11915. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11916. /**
  11917. * R32F
  11918. */
  11919. get: function () {
  11920. return Engine._TEXTUREFORMAT_R32F;
  11921. },
  11922. enumerable: true,
  11923. configurable: true
  11924. });
  11925. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11926. /**
  11927. * RG32F
  11928. */
  11929. get: function () {
  11930. return Engine._TEXTUREFORMAT_RG32F;
  11931. },
  11932. enumerable: true,
  11933. configurable: true
  11934. });
  11935. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11936. /**
  11937. * RGB32F
  11938. */
  11939. get: function () {
  11940. return Engine._TEXTUREFORMAT_RGB32F;
  11941. },
  11942. enumerable: true,
  11943. configurable: true
  11944. });
  11945. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11946. /**
  11947. * RGBA32F
  11948. */
  11949. get: function () {
  11950. return Engine._TEXTUREFORMAT_RGBA32F;
  11951. },
  11952. enumerable: true,
  11953. configurable: true
  11954. });
  11955. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11956. /** LUMINANCE_ALPHA */
  11957. get: function () {
  11958. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11959. },
  11960. enumerable: true,
  11961. configurable: true
  11962. });
  11963. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11964. /** RGB */
  11965. get: function () {
  11966. return Engine._TEXTUREFORMAT_RGB;
  11967. },
  11968. enumerable: true,
  11969. configurable: true
  11970. });
  11971. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11972. /** RGBA */
  11973. get: function () {
  11974. return Engine._TEXTUREFORMAT_RGBA;
  11975. },
  11976. enumerable: true,
  11977. configurable: true
  11978. });
  11979. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11980. /** UNSIGNED_INT */
  11981. get: function () {
  11982. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11983. },
  11984. enumerable: true,
  11985. configurable: true
  11986. });
  11987. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11988. /** FLOAT */
  11989. get: function () {
  11990. return Engine._TEXTURETYPE_FLOAT;
  11991. },
  11992. enumerable: true,
  11993. configurable: true
  11994. });
  11995. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11996. /** HALF_FLOAT */
  11997. get: function () {
  11998. return Engine._TEXTURETYPE_HALF_FLOAT;
  11999. },
  12000. enumerable: true,
  12001. configurable: true
  12002. });
  12003. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12004. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12005. get: function () {
  12006. return Engine._SCALEMODE_FLOOR;
  12007. },
  12008. enumerable: true,
  12009. configurable: true
  12010. });
  12011. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12012. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12013. get: function () {
  12014. return Engine._SCALEMODE_NEAREST;
  12015. },
  12016. enumerable: true,
  12017. configurable: true
  12018. });
  12019. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12020. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12021. get: function () {
  12022. return Engine._SCALEMODE_CEILING;
  12023. },
  12024. enumerable: true,
  12025. configurable: true
  12026. });
  12027. Object.defineProperty(Engine, "Version", {
  12028. /**
  12029. * Returns the current version of the framework
  12030. */
  12031. get: function () {
  12032. return "3.3.0-alpha.1";
  12033. },
  12034. enumerable: true,
  12035. configurable: true
  12036. });
  12037. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12038. /**
  12039. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12040. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12041. */
  12042. get: function () {
  12043. return this._vrExclusivePointerMode;
  12044. },
  12045. enumerable: true,
  12046. configurable: true
  12047. });
  12048. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12049. /**
  12050. * Gets a boolean indicating that the engine supports uniform buffers
  12051. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12052. */
  12053. get: function () {
  12054. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12055. },
  12056. enumerable: true,
  12057. configurable: true
  12058. });
  12059. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12060. /**
  12061. * Gets a boolean indicating that only power of 2 textures are supported
  12062. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12063. */
  12064. get: function () {
  12065. return this._webGLVersion < 2 || this.forcePOTTextures;
  12066. },
  12067. enumerable: true,
  12068. configurable: true
  12069. });
  12070. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12071. /**
  12072. * Gets the performance monitor attached to this engine
  12073. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12074. */
  12075. get: function () {
  12076. return this._performanceMonitor;
  12077. },
  12078. enumerable: true,
  12079. configurable: true
  12080. });
  12081. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12082. /**
  12083. * Gets the list of texture formats supported
  12084. */
  12085. get: function () {
  12086. return this._texturesSupported;
  12087. },
  12088. enumerable: true,
  12089. configurable: true
  12090. });
  12091. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12092. /**
  12093. * Gets the list of texture formats in use
  12094. */
  12095. get: function () {
  12096. return this._textureFormatInUse;
  12097. },
  12098. enumerable: true,
  12099. configurable: true
  12100. });
  12101. Object.defineProperty(Engine.prototype, "currentViewport", {
  12102. /**
  12103. * Gets the current viewport
  12104. */
  12105. get: function () {
  12106. return this._cachedViewport;
  12107. },
  12108. enumerable: true,
  12109. configurable: true
  12110. });
  12111. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12112. /**
  12113. * Gets the default empty texture
  12114. */
  12115. get: function () {
  12116. if (!this._emptyTexture) {
  12117. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12118. }
  12119. return this._emptyTexture;
  12120. },
  12121. enumerable: true,
  12122. configurable: true
  12123. });
  12124. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12125. /**
  12126. * Gets the default empty 3D texture
  12127. */
  12128. get: function () {
  12129. if (!this._emptyTexture3D) {
  12130. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12131. }
  12132. return this._emptyTexture3D;
  12133. },
  12134. enumerable: true,
  12135. configurable: true
  12136. });
  12137. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12138. /**
  12139. * Gets the default empty cube texture
  12140. */
  12141. get: function () {
  12142. if (!this._emptyCubeTexture) {
  12143. var faceData = new Uint8Array(4);
  12144. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12145. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12146. }
  12147. return this._emptyCubeTexture;
  12148. },
  12149. enumerable: true,
  12150. configurable: true
  12151. });
  12152. Engine.prototype._rebuildInternalTextures = function () {
  12153. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12154. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12155. var internalTexture = currentState_1[_i];
  12156. internalTexture._rebuild();
  12157. }
  12158. };
  12159. Engine.prototype._rebuildEffects = function () {
  12160. for (var key in this._compiledEffects) {
  12161. var effect = this._compiledEffects[key];
  12162. effect._prepareEffect();
  12163. }
  12164. BABYLON.Effect.ResetCache();
  12165. };
  12166. Engine.prototype._rebuildBuffers = function () {
  12167. // Index / Vertex
  12168. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12169. var scene = _a[_i];
  12170. scene.resetCachedMaterial();
  12171. scene._rebuildGeometries();
  12172. scene._rebuildTextures();
  12173. }
  12174. // Uniforms
  12175. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12176. var uniformBuffer = _c[_b];
  12177. uniformBuffer._rebuild();
  12178. }
  12179. };
  12180. Engine.prototype._initGLContext = function () {
  12181. // Caps
  12182. this._caps = new EngineCapabilities();
  12183. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12184. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12185. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12186. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12187. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12188. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12189. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12190. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12191. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12192. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12193. // Infos
  12194. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12195. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12196. if (rendererInfo != null) {
  12197. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12198. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12199. }
  12200. if (!this._glVendor) {
  12201. this._glVendor = "Unknown vendor";
  12202. }
  12203. if (!this._glRenderer) {
  12204. this._glRenderer = "Unknown renderer";
  12205. }
  12206. // Constants
  12207. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12208. if (this._gl.RGBA16F !== 0x881A) {
  12209. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12210. }
  12211. if (this._gl.RGBA32F !== 0x8814) {
  12212. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12213. }
  12214. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12215. this._gl.DEPTH24_STENCIL8 = 35056;
  12216. }
  12217. // Extensions
  12218. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12219. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12220. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12221. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12222. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12223. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12224. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12225. 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');
  12226. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12227. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12228. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12229. this._caps.highPrecisionShaderSupported = true;
  12230. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12231. if (this._caps.timerQuery) {
  12232. if (this._webGLVersion === 1) {
  12233. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12234. }
  12235. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12236. }
  12237. // Checks if some of the format renders first to allow the use of webgl inspector.
  12238. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12239. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12240. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12241. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12242. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12243. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12244. if (this._webGLVersion > 1) {
  12245. this._gl.HALF_FLOAT_OES = 0x140B;
  12246. }
  12247. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12248. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12249. // Draw buffers
  12250. if (this._webGLVersion > 1) {
  12251. this._caps.drawBuffersExtension = true;
  12252. }
  12253. else {
  12254. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12255. if (drawBuffersExtension !== null) {
  12256. this._caps.drawBuffersExtension = true;
  12257. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12258. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12259. for (var i = 0; i < 16; i++) {
  12260. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12261. }
  12262. }
  12263. else {
  12264. this._caps.drawBuffersExtension = false;
  12265. }
  12266. }
  12267. // Depth Texture
  12268. if (this._webGLVersion > 1) {
  12269. this._caps.depthTextureExtension = true;
  12270. }
  12271. else {
  12272. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12273. if (depthTextureExtension != null) {
  12274. this._caps.depthTextureExtension = true;
  12275. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12276. }
  12277. }
  12278. // Vertex array object
  12279. if (this._webGLVersion > 1) {
  12280. this._caps.vertexArrayObject = true;
  12281. }
  12282. else {
  12283. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12284. if (vertexArrayObjectExtension != null) {
  12285. this._caps.vertexArrayObject = true;
  12286. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12287. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12288. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12289. }
  12290. else {
  12291. this._caps.vertexArrayObject = false;
  12292. }
  12293. }
  12294. // Instances count
  12295. if (this._webGLVersion > 1) {
  12296. this._caps.instancedArrays = true;
  12297. }
  12298. else {
  12299. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12300. if (instanceExtension != null) {
  12301. this._caps.instancedArrays = true;
  12302. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12303. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12304. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12305. }
  12306. else {
  12307. this._caps.instancedArrays = false;
  12308. }
  12309. }
  12310. // Intelligently add supported compressed formats in order to check for.
  12311. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12312. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12313. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12314. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12315. if (this._caps.astc)
  12316. this.texturesSupported.push('-astc.ktx');
  12317. if (this._caps.s3tc)
  12318. this.texturesSupported.push('-dxt.ktx');
  12319. if (this._caps.pvrtc)
  12320. this.texturesSupported.push('-pvrtc.ktx');
  12321. if (this._caps.etc2)
  12322. this.texturesSupported.push('-etc2.ktx');
  12323. if (this._caps.etc1)
  12324. this.texturesSupported.push('-etc1.ktx');
  12325. if (this._gl.getShaderPrecisionFormat) {
  12326. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12327. if (highp) {
  12328. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12329. }
  12330. }
  12331. // Depth buffer
  12332. this.setDepthBuffer(true);
  12333. this.setDepthFunctionToLessOrEqual();
  12334. this.setDepthWrite(true);
  12335. // Texture maps
  12336. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12337. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12338. this._nextFreeTextureSlots.push(slot);
  12339. }
  12340. };
  12341. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12342. /**
  12343. * Gets version of the current webGL context
  12344. */
  12345. get: function () {
  12346. return this._webGLVersion;
  12347. },
  12348. enumerable: true,
  12349. configurable: true
  12350. });
  12351. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12352. /**
  12353. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12354. */
  12355. get: function () {
  12356. return this._isStencilEnable;
  12357. },
  12358. enumerable: true,
  12359. configurable: true
  12360. });
  12361. Engine.prototype._prepareWorkingCanvas = function () {
  12362. if (this._workingCanvas) {
  12363. return;
  12364. }
  12365. this._workingCanvas = document.createElement("canvas");
  12366. var context = this._workingCanvas.getContext("2d");
  12367. if (context) {
  12368. this._workingContext = context;
  12369. }
  12370. };
  12371. /**
  12372. * Reset the texture cache to empty state
  12373. */
  12374. Engine.prototype.resetTextureCache = function () {
  12375. for (var key in this._boundTexturesCache) {
  12376. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12377. continue;
  12378. }
  12379. var boundTexture = this._boundTexturesCache[key];
  12380. if (boundTexture) {
  12381. this._removeDesignatedSlot(boundTexture);
  12382. }
  12383. this._boundTexturesCache[key] = null;
  12384. }
  12385. if (!this.disableTextureBindingOptimization) {
  12386. this._nextFreeTextureSlots = [];
  12387. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12388. this._nextFreeTextureSlots.push(slot);
  12389. }
  12390. }
  12391. this._currentTextureChannel = -1;
  12392. };
  12393. /**
  12394. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12395. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12396. * @returns true if engine is in deterministic lock step mode
  12397. */
  12398. Engine.prototype.isDeterministicLockStep = function () {
  12399. return this._deterministicLockstep;
  12400. };
  12401. /**
  12402. * Gets the max steps when engine is running in deterministic lock step
  12403. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12404. * @returns the max steps
  12405. */
  12406. Engine.prototype.getLockstepMaxSteps = function () {
  12407. return this._lockstepMaxSteps;
  12408. };
  12409. /**
  12410. * Gets an object containing information about the current webGL context
  12411. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12412. */
  12413. Engine.prototype.getGlInfo = function () {
  12414. return {
  12415. vendor: this._glVendor,
  12416. renderer: this._glRenderer,
  12417. version: this._glVersion
  12418. };
  12419. };
  12420. /**
  12421. * Gets current aspect ratio
  12422. * @param camera defines the camera to use to get the aspect ratio
  12423. * @param useScreen defines if screen size must be used (or the current render target if any)
  12424. * @returns a number defining the aspect ratio
  12425. */
  12426. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12427. if (useScreen === void 0) { useScreen = false; }
  12428. var viewport = camera.viewport;
  12429. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12430. };
  12431. /**
  12432. * Gets current screen aspect ratio
  12433. * @returns a number defining the aspect ratio
  12434. */
  12435. Engine.prototype.getScreenAspectRatio = function () {
  12436. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12437. };
  12438. /**
  12439. * Gets the current render width
  12440. * @param useScreen defines if screen size must be used (or the current render target if any)
  12441. * @returns a number defining the current render width
  12442. */
  12443. Engine.prototype.getRenderWidth = function (useScreen) {
  12444. if (useScreen === void 0) { useScreen = false; }
  12445. if (!useScreen && this._currentRenderTarget) {
  12446. return this._currentRenderTarget.width;
  12447. }
  12448. return this._gl.drawingBufferWidth;
  12449. };
  12450. /**
  12451. * Gets the current render height
  12452. * @param useScreen defines if screen size must be used (or the current render target if any)
  12453. * @returns a number defining the current render height
  12454. */
  12455. Engine.prototype.getRenderHeight = function (useScreen) {
  12456. if (useScreen === void 0) { useScreen = false; }
  12457. if (!useScreen && this._currentRenderTarget) {
  12458. return this._currentRenderTarget.height;
  12459. }
  12460. return this._gl.drawingBufferHeight;
  12461. };
  12462. /**
  12463. * Gets the HTML canvas attached with the current webGL context
  12464. * @returns a HTML canvas
  12465. */
  12466. Engine.prototype.getRenderingCanvas = function () {
  12467. return this._renderingCanvas;
  12468. };
  12469. /**
  12470. * Gets the client rect of the HTML canvas attached with the current webGL context
  12471. * @returns a client rectanglee
  12472. */
  12473. Engine.prototype.getRenderingCanvasClientRect = function () {
  12474. if (!this._renderingCanvas) {
  12475. return null;
  12476. }
  12477. return this._renderingCanvas.getBoundingClientRect();
  12478. };
  12479. /**
  12480. * Defines the hardware scaling level.
  12481. * By default the hardware scaling level is computed from the window device ratio.
  12482. * 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.
  12483. * @param level defines the level to use
  12484. */
  12485. Engine.prototype.setHardwareScalingLevel = function (level) {
  12486. this._hardwareScalingLevel = level;
  12487. this.resize();
  12488. };
  12489. /**
  12490. * Gets the current hardware scaling level.
  12491. * By default the hardware scaling level is computed from the window device ratio.
  12492. * 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.
  12493. * @returns a number indicating the current hardware scaling level
  12494. */
  12495. Engine.prototype.getHardwareScalingLevel = function () {
  12496. return this._hardwareScalingLevel;
  12497. };
  12498. /**
  12499. * Gets the list of loaded textures
  12500. * @returns an array containing all loaded textures
  12501. */
  12502. Engine.prototype.getLoadedTexturesCache = function () {
  12503. return this._internalTexturesCache;
  12504. };
  12505. /**
  12506. * Gets the object containing all engine capabilities
  12507. * @returns the EngineCapabilities object
  12508. */
  12509. Engine.prototype.getCaps = function () {
  12510. return this._caps;
  12511. };
  12512. Object.defineProperty(Engine.prototype, "drawCalls", {
  12513. /** @hidden */
  12514. get: function () {
  12515. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12516. return 0;
  12517. },
  12518. enumerable: true,
  12519. configurable: true
  12520. });
  12521. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12522. /** @hidden */
  12523. get: function () {
  12524. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12525. return null;
  12526. },
  12527. enumerable: true,
  12528. configurable: true
  12529. });
  12530. /**
  12531. * Gets the current depth function
  12532. * @returns a number defining the depth function
  12533. */
  12534. Engine.prototype.getDepthFunction = function () {
  12535. return this._depthCullingState.depthFunc;
  12536. };
  12537. /**
  12538. * Sets the current depth function
  12539. * @param depthFunc defines the function to use
  12540. */
  12541. Engine.prototype.setDepthFunction = function (depthFunc) {
  12542. this._depthCullingState.depthFunc = depthFunc;
  12543. };
  12544. /**
  12545. * Sets the current depth function to GREATER
  12546. */
  12547. Engine.prototype.setDepthFunctionToGreater = function () {
  12548. this._depthCullingState.depthFunc = this._gl.GREATER;
  12549. };
  12550. /**
  12551. * Sets the current depth function to GEQUAL
  12552. */
  12553. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12554. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12555. };
  12556. /**
  12557. * Sets the current depth function to LESS
  12558. */
  12559. Engine.prototype.setDepthFunctionToLess = function () {
  12560. this._depthCullingState.depthFunc = this._gl.LESS;
  12561. };
  12562. /**
  12563. * Sets the current depth function to LEQUAL
  12564. */
  12565. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12566. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12567. };
  12568. /**
  12569. * Gets a boolean indicating if stencil buffer is enabled
  12570. * @returns the current stencil buffer state
  12571. */
  12572. Engine.prototype.getStencilBuffer = function () {
  12573. return this._stencilState.stencilTest;
  12574. };
  12575. /**
  12576. * Enable or disable the stencil buffer
  12577. * @param enable defines if the stencil buffer must be enabled or disabled
  12578. */
  12579. Engine.prototype.setStencilBuffer = function (enable) {
  12580. this._stencilState.stencilTest = enable;
  12581. };
  12582. /**
  12583. * Gets the current stencil mask
  12584. * @returns a number defining the new stencil mask to use
  12585. */
  12586. Engine.prototype.getStencilMask = function () {
  12587. return this._stencilState.stencilMask;
  12588. };
  12589. /**
  12590. * Sets the current stencil mask
  12591. * @param mask defines the new stencil mask to use
  12592. */
  12593. Engine.prototype.setStencilMask = function (mask) {
  12594. this._stencilState.stencilMask = mask;
  12595. };
  12596. /**
  12597. * Gets the current stencil function
  12598. * @returns a number defining the stencil function to use
  12599. */
  12600. Engine.prototype.getStencilFunction = function () {
  12601. return this._stencilState.stencilFunc;
  12602. };
  12603. /**
  12604. * Gets the current stencil reference value
  12605. * @returns a number defining the stencil reference value to use
  12606. */
  12607. Engine.prototype.getStencilFunctionReference = function () {
  12608. return this._stencilState.stencilFuncRef;
  12609. };
  12610. /**
  12611. * Gets the current stencil mask
  12612. * @returns a number defining the stencil mask to use
  12613. */
  12614. Engine.prototype.getStencilFunctionMask = function () {
  12615. return this._stencilState.stencilFuncMask;
  12616. };
  12617. /**
  12618. * Sets the current stencil function
  12619. * @param stencilFunc defines the new stencil function to use
  12620. */
  12621. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12622. this._stencilState.stencilFunc = stencilFunc;
  12623. };
  12624. /**
  12625. * Sets the current stencil reference
  12626. * @param reference defines the new stencil reference to use
  12627. */
  12628. Engine.prototype.setStencilFunctionReference = function (reference) {
  12629. this._stencilState.stencilFuncRef = reference;
  12630. };
  12631. /**
  12632. * Sets the current stencil mask
  12633. * @param mask defines the new stencil mask to use
  12634. */
  12635. Engine.prototype.setStencilFunctionMask = function (mask) {
  12636. this._stencilState.stencilFuncMask = mask;
  12637. };
  12638. /**
  12639. * Gets the current stencil operation when stencil fails
  12640. * @returns a number defining stencil operation to use when stencil fails
  12641. */
  12642. Engine.prototype.getStencilOperationFail = function () {
  12643. return this._stencilState.stencilOpStencilFail;
  12644. };
  12645. /**
  12646. * Gets the current stencil operation when depth fails
  12647. * @returns a number defining stencil operation to use when depth fails
  12648. */
  12649. Engine.prototype.getStencilOperationDepthFail = function () {
  12650. return this._stencilState.stencilOpDepthFail;
  12651. };
  12652. /**
  12653. * Gets the current stencil operation when stencil passes
  12654. * @returns a number defining stencil operation to use when stencil passes
  12655. */
  12656. Engine.prototype.getStencilOperationPass = function () {
  12657. return this._stencilState.stencilOpStencilDepthPass;
  12658. };
  12659. /**
  12660. * Sets the stencil operation to use when stencil fails
  12661. * @param operation defines the stencil operation to use when stencil fails
  12662. */
  12663. Engine.prototype.setStencilOperationFail = function (operation) {
  12664. this._stencilState.stencilOpStencilFail = operation;
  12665. };
  12666. /**
  12667. * Sets the stencil operation to use when depth fails
  12668. * @param operation defines the stencil operation to use when depth fails
  12669. */
  12670. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12671. this._stencilState.stencilOpDepthFail = operation;
  12672. };
  12673. /**
  12674. * Sets the stencil operation to use when stencil passes
  12675. * @param operation defines the stencil operation to use when stencil passes
  12676. */
  12677. Engine.prototype.setStencilOperationPass = function (operation) {
  12678. this._stencilState.stencilOpStencilDepthPass = operation;
  12679. };
  12680. /**
  12681. * Sets a boolean indicating if the dithering state is enabled or disabled
  12682. * @param value defines the dithering state
  12683. */
  12684. Engine.prototype.setDitheringState = function (value) {
  12685. if (value) {
  12686. this._gl.enable(this._gl.DITHER);
  12687. }
  12688. else {
  12689. this._gl.disable(this._gl.DITHER);
  12690. }
  12691. };
  12692. /**
  12693. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12694. * @param value defines the rasterizer state
  12695. */
  12696. Engine.prototype.setRasterizerState = function (value) {
  12697. if (value) {
  12698. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12699. }
  12700. else {
  12701. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12702. }
  12703. };
  12704. /**
  12705. * stop executing a render loop function and remove it from the execution array
  12706. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12707. */
  12708. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12709. if (!renderFunction) {
  12710. this._activeRenderLoops = [];
  12711. return;
  12712. }
  12713. var index = this._activeRenderLoops.indexOf(renderFunction);
  12714. if (index >= 0) {
  12715. this._activeRenderLoops.splice(index, 1);
  12716. }
  12717. };
  12718. /** @hidden */
  12719. Engine.prototype._renderLoop = function () {
  12720. if (!this._contextWasLost) {
  12721. var shouldRender = true;
  12722. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12723. shouldRender = false;
  12724. }
  12725. if (shouldRender) {
  12726. // Start new frame
  12727. this.beginFrame();
  12728. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12729. var renderFunction = this._activeRenderLoops[index];
  12730. renderFunction();
  12731. }
  12732. // Present
  12733. this.endFrame();
  12734. }
  12735. }
  12736. if (this._activeRenderLoops.length > 0) {
  12737. // Register new frame
  12738. var requester = null;
  12739. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12740. requester = this._vrDisplay;
  12741. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12742. }
  12743. else {
  12744. this._renderingQueueLaunched = false;
  12745. }
  12746. };
  12747. /**
  12748. * Register and execute a render loop. The engine can have more than one render function
  12749. * @param renderFunction defines the function to continuously execute
  12750. */
  12751. Engine.prototype.runRenderLoop = function (renderFunction) {
  12752. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12753. return;
  12754. }
  12755. this._activeRenderLoops.push(renderFunction);
  12756. if (!this._renderingQueueLaunched) {
  12757. this._renderingQueueLaunched = true;
  12758. this._bindedRenderFunction = this._renderLoop.bind(this);
  12759. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12760. }
  12761. };
  12762. /**
  12763. * Toggle full screen mode
  12764. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12765. * @param options defines an option object to be sent to the requestFullscreen function
  12766. */
  12767. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12768. if (this.isFullscreen) {
  12769. BABYLON.Tools.ExitFullscreen();
  12770. }
  12771. else {
  12772. this._pointerLockRequested = requestPointerLock;
  12773. if (this._renderingCanvas) {
  12774. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12775. }
  12776. }
  12777. };
  12778. /**
  12779. * Clear the current render buffer or the current render target (if any is set up)
  12780. * @param color defines the color to use
  12781. * @param backBuffer defines if the back buffer must be cleared
  12782. * @param depth defines if the depth buffer must be cleared
  12783. * @param stencil defines if the stencil buffer must be cleared
  12784. */
  12785. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12786. if (stencil === void 0) { stencil = false; }
  12787. this.applyStates();
  12788. var mode = 0;
  12789. if (backBuffer && color) {
  12790. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12791. mode |= this._gl.COLOR_BUFFER_BIT;
  12792. }
  12793. if (depth) {
  12794. this._gl.clearDepth(1.0);
  12795. mode |= this._gl.DEPTH_BUFFER_BIT;
  12796. }
  12797. if (stencil) {
  12798. this._gl.clearStencil(0);
  12799. mode |= this._gl.STENCIL_BUFFER_BIT;
  12800. }
  12801. this._gl.clear(mode);
  12802. };
  12803. /**
  12804. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12805. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12806. * @param y defines the y-coordinate of the corner of the clear rectangle
  12807. * @param width defines the width of the clear rectangle
  12808. * @param height defines the height of the clear rectangle
  12809. * @param clearColor defines the clear color
  12810. */
  12811. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12812. var gl = this._gl;
  12813. // Save state
  12814. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12815. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12816. // Change state
  12817. gl.enable(gl.SCISSOR_TEST);
  12818. gl.scissor(x, y, width, height);
  12819. // Clear
  12820. this.clear(clearColor, true, true, true);
  12821. // Restore state
  12822. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12823. if (curScissor === true) {
  12824. gl.enable(gl.SCISSOR_TEST);
  12825. }
  12826. else {
  12827. gl.disable(gl.SCISSOR_TEST);
  12828. }
  12829. };
  12830. /**
  12831. * Set the WebGL's viewport
  12832. * @param viewport defines the viewport element to be used
  12833. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12834. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12835. */
  12836. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12837. var width = requiredWidth || this.getRenderWidth();
  12838. var height = requiredHeight || this.getRenderHeight();
  12839. var x = viewport.x || 0;
  12840. var y = viewport.y || 0;
  12841. this._cachedViewport = viewport;
  12842. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12843. };
  12844. /**
  12845. * Directly set the WebGL Viewport
  12846. * @param x defines the x coordinate of the viewport (in screen space)
  12847. * @param y defines the y coordinate of the viewport (in screen space)
  12848. * @param width defines the width of the viewport (in screen space)
  12849. * @param height defines the height of the viewport (in screen space)
  12850. * @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
  12851. */
  12852. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12853. var currentViewport = this._cachedViewport;
  12854. this._cachedViewport = null;
  12855. this._gl.viewport(x, y, width, height);
  12856. return currentViewport;
  12857. };
  12858. /**
  12859. * Begin a new frame
  12860. */
  12861. Engine.prototype.beginFrame = function () {
  12862. this.onBeginFrameObservable.notifyObservers(this);
  12863. this._measureFps();
  12864. };
  12865. /**
  12866. * Enf the current frame
  12867. */
  12868. Engine.prototype.endFrame = function () {
  12869. // Force a flush in case we are using a bad OS.
  12870. if (this._badOS) {
  12871. this.flushFramebuffer();
  12872. }
  12873. // Submit frame to the vr device, if enabled
  12874. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12875. // TODO: We should only submit the frame if we read frameData successfully.
  12876. this._vrDisplay.submitFrame();
  12877. }
  12878. this.onEndFrameObservable.notifyObservers(this);
  12879. };
  12880. /**
  12881. * Resize the view according to the canvas' size
  12882. */
  12883. Engine.prototype.resize = function () {
  12884. // We're not resizing the size of the canvas while in VR mode & presenting
  12885. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12886. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12887. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12888. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12889. }
  12890. };
  12891. /**
  12892. * Force a specific size of the canvas
  12893. * @param width defines the new canvas' width
  12894. * @param height defines the new canvas' height
  12895. */
  12896. Engine.prototype.setSize = function (width, height) {
  12897. if (!this._renderingCanvas) {
  12898. return;
  12899. }
  12900. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12901. return;
  12902. }
  12903. this._renderingCanvas.width = width;
  12904. this._renderingCanvas.height = height;
  12905. for (var index = 0; index < this.scenes.length; index++) {
  12906. var scene = this.scenes[index];
  12907. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12908. var cam = scene.cameras[camIndex];
  12909. cam._currentRenderId = 0;
  12910. }
  12911. }
  12912. if (this.onResizeObservable.hasObservers) {
  12913. this.onResizeObservable.notifyObservers(this);
  12914. }
  12915. };
  12916. // WebVR functions
  12917. /**
  12918. * Gets a boolean indicating if a webVR device was detected
  12919. * @returns true if a webVR device was detected
  12920. */
  12921. Engine.prototype.isVRDevicePresent = function () {
  12922. return !!this._vrDisplay;
  12923. };
  12924. /**
  12925. * Gets the current webVR device
  12926. * @returns the current webVR device (or null)
  12927. */
  12928. Engine.prototype.getVRDevice = function () {
  12929. return this._vrDisplay;
  12930. };
  12931. /**
  12932. * Initializes a webVR display and starts listening to display change events
  12933. * The onVRDisplayChangedObservable will be notified upon these changes
  12934. * @returns The onVRDisplayChangedObservable
  12935. */
  12936. Engine.prototype.initWebVR = function () {
  12937. this.initWebVRAsync();
  12938. return this.onVRDisplayChangedObservable;
  12939. };
  12940. /**
  12941. * Initializes a webVR display and starts listening to display change events
  12942. * The onVRDisplayChangedObservable will be notified upon these changes
  12943. * @returns A promise containing a VRDisplay and if vr is supported
  12944. */
  12945. Engine.prototype.initWebVRAsync = function () {
  12946. var _this = this;
  12947. var notifyObservers = function () {
  12948. var eventArgs = {
  12949. vrDisplay: _this._vrDisplay,
  12950. vrSupported: _this._vrSupported
  12951. };
  12952. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12953. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12954. };
  12955. if (!this._onVrDisplayConnect) {
  12956. this._onVrDisplayConnect = function (event) {
  12957. _this._vrDisplay = event.display;
  12958. notifyObservers();
  12959. };
  12960. this._onVrDisplayDisconnect = function () {
  12961. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12962. _this._vrDisplay = undefined;
  12963. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12964. notifyObservers();
  12965. };
  12966. this._onVrDisplayPresentChange = function () {
  12967. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12968. };
  12969. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12970. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12971. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12972. }
  12973. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12974. this._webVRInitPromise.then(notifyObservers);
  12975. return this._webVRInitPromise;
  12976. };
  12977. /**
  12978. * Call this function to switch to webVR mode
  12979. * Will do nothing if webVR is not supported or if there is no webVR device
  12980. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12981. */
  12982. Engine.prototype.enableVR = function () {
  12983. var _this = this;
  12984. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12985. var onResolved = function () {
  12986. _this.onVRRequestPresentComplete.notifyObservers(true);
  12987. _this._onVRFullScreenTriggered();
  12988. };
  12989. var onRejected = function () {
  12990. _this.onVRRequestPresentComplete.notifyObservers(false);
  12991. };
  12992. this.onVRRequestPresentStart.notifyObservers(this);
  12993. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12994. }
  12995. };
  12996. /**
  12997. * Call this function to leave webVR mode
  12998. * Will do nothing if webVR is not supported or if there is no webVR device
  12999. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13000. */
  13001. Engine.prototype.disableVR = function () {
  13002. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13003. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13004. }
  13005. };
  13006. Engine.prototype._getVRDisplaysAsync = function () {
  13007. var _this = this;
  13008. return new Promise(function (res, rej) {
  13009. if (navigator.getVRDisplays) {
  13010. navigator.getVRDisplays().then(function (devices) {
  13011. _this._vrSupported = true;
  13012. // note that devices may actually be an empty array. This is fine;
  13013. // we expect this._vrDisplay to be undefined in this case.
  13014. _this._vrDisplay = devices[0];
  13015. res({
  13016. vrDisplay: _this._vrDisplay,
  13017. vrSupported: _this._vrSupported
  13018. });
  13019. });
  13020. }
  13021. else {
  13022. _this._vrDisplay = undefined;
  13023. _this._vrSupported = false;
  13024. res({
  13025. vrDisplay: _this._vrDisplay,
  13026. vrSupported: _this._vrSupported
  13027. });
  13028. }
  13029. });
  13030. };
  13031. /**
  13032. * Binds the frame buffer to the specified texture.
  13033. * @param texture The texture to render to or null for the default canvas
  13034. * @param faceIndex The face of the texture to render to in case of cube texture
  13035. * @param requiredWidth The width of the target to render to
  13036. * @param requiredHeight The height of the target to render to
  13037. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13038. * @param depthStencilTexture The depth stencil texture to use to render
  13039. */
  13040. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  13041. if (this._currentRenderTarget) {
  13042. this.unBindFramebuffer(this._currentRenderTarget);
  13043. }
  13044. this._currentRenderTarget = texture;
  13045. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13046. var gl = this._gl;
  13047. if (texture.isCube) {
  13048. if (faceIndex === undefined) {
  13049. faceIndex = 0;
  13050. }
  13051. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13052. if (depthStencilTexture) {
  13053. if (depthStencilTexture._generateStencilBuffer) {
  13054. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13055. }
  13056. else {
  13057. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13058. }
  13059. }
  13060. }
  13061. if (this._cachedViewport && !forceFullscreenViewport) {
  13062. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13063. }
  13064. else {
  13065. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  13066. }
  13067. this.wipeCaches();
  13068. };
  13069. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13070. if (this._currentFramebuffer !== framebuffer) {
  13071. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13072. this._currentFramebuffer = framebuffer;
  13073. }
  13074. };
  13075. /**
  13076. * Unbind the current render target texture from the webGL context
  13077. * @param texture defines the render target texture to unbind
  13078. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13079. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13080. */
  13081. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13082. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13083. this._currentRenderTarget = null;
  13084. // If MSAA, we need to bitblt back to main texture
  13085. var gl = this._gl;
  13086. if (texture._MSAAFramebuffer) {
  13087. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13088. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13089. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13090. }
  13091. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13092. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13093. gl.generateMipmap(gl.TEXTURE_2D);
  13094. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13095. }
  13096. if (onBeforeUnbind) {
  13097. if (texture._MSAAFramebuffer) {
  13098. // Bind the correct framebuffer
  13099. this.bindUnboundFramebuffer(texture._framebuffer);
  13100. }
  13101. onBeforeUnbind();
  13102. }
  13103. this.bindUnboundFramebuffer(null);
  13104. };
  13105. /**
  13106. * Unbind a list of render target textures from the webGL context
  13107. * This is used only when drawBuffer extension or webGL2 are active
  13108. * @param textures defines the render target textures to unbind
  13109. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13110. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13111. */
  13112. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13113. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13114. this._currentRenderTarget = null;
  13115. // If MSAA, we need to bitblt back to main texture
  13116. var gl = this._gl;
  13117. if (textures[0]._MSAAFramebuffer) {
  13118. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13119. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13120. var attachments = textures[0]._attachments;
  13121. if (!attachments) {
  13122. attachments = new Array(textures.length);
  13123. textures[0]._attachments = attachments;
  13124. }
  13125. for (var i = 0; i < textures.length; i++) {
  13126. var texture = textures[i];
  13127. for (var j = 0; j < attachments.length; j++) {
  13128. attachments[j] = gl.NONE;
  13129. }
  13130. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13131. gl.readBuffer(attachments[i]);
  13132. gl.drawBuffers(attachments);
  13133. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13134. }
  13135. for (var i = 0; i < attachments.length; i++) {
  13136. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13137. }
  13138. gl.drawBuffers(attachments);
  13139. }
  13140. for (var i = 0; i < textures.length; i++) {
  13141. var texture = textures[i];
  13142. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13143. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13144. gl.generateMipmap(gl.TEXTURE_2D);
  13145. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13146. }
  13147. }
  13148. if (onBeforeUnbind) {
  13149. if (textures[0]._MSAAFramebuffer) {
  13150. // Bind the correct framebuffer
  13151. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13152. }
  13153. onBeforeUnbind();
  13154. }
  13155. this.bindUnboundFramebuffer(null);
  13156. };
  13157. /**
  13158. * Force the mipmap generation for the given render target texture
  13159. * @param texture defines the render target texture to use
  13160. */
  13161. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13162. if (texture.generateMipMaps) {
  13163. var gl = this._gl;
  13164. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13165. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13166. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13167. }
  13168. };
  13169. /**
  13170. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13171. */
  13172. Engine.prototype.flushFramebuffer = function () {
  13173. this._gl.flush();
  13174. };
  13175. /**
  13176. * Unbind the current render target and bind the default framebuffer
  13177. */
  13178. Engine.prototype.restoreDefaultFramebuffer = function () {
  13179. if (this._currentRenderTarget) {
  13180. this.unBindFramebuffer(this._currentRenderTarget);
  13181. }
  13182. else {
  13183. this.bindUnboundFramebuffer(null);
  13184. }
  13185. if (this._cachedViewport) {
  13186. this.setViewport(this._cachedViewport);
  13187. }
  13188. this.wipeCaches();
  13189. };
  13190. // UBOs
  13191. /**
  13192. * Create an uniform buffer
  13193. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13194. * @param elements defines the content of the uniform buffer
  13195. * @returns the webGL uniform buffer
  13196. */
  13197. Engine.prototype.createUniformBuffer = function (elements) {
  13198. var ubo = this._gl.createBuffer();
  13199. if (!ubo) {
  13200. throw new Error("Unable to create uniform buffer");
  13201. }
  13202. this.bindUniformBuffer(ubo);
  13203. if (elements instanceof Float32Array) {
  13204. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13205. }
  13206. else {
  13207. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13208. }
  13209. this.bindUniformBuffer(null);
  13210. ubo.references = 1;
  13211. return ubo;
  13212. };
  13213. /**
  13214. * Create a dynamic uniform buffer
  13215. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13216. * @param elements defines the content of the uniform buffer
  13217. * @returns the webGL uniform buffer
  13218. */
  13219. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13220. var ubo = this._gl.createBuffer();
  13221. if (!ubo) {
  13222. throw new Error("Unable to create dynamic uniform buffer");
  13223. }
  13224. this.bindUniformBuffer(ubo);
  13225. if (elements instanceof Float32Array) {
  13226. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13227. }
  13228. else {
  13229. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13230. }
  13231. this.bindUniformBuffer(null);
  13232. ubo.references = 1;
  13233. return ubo;
  13234. };
  13235. /**
  13236. * Update an existing uniform buffer
  13237. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13238. * @param uniformBuffer defines the target uniform buffer
  13239. * @param elements defines the content to update
  13240. * @param offset defines the offset in the uniform buffer where update should start
  13241. * @param count defines the size of the data to update
  13242. */
  13243. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13244. this.bindUniformBuffer(uniformBuffer);
  13245. if (offset === undefined) {
  13246. offset = 0;
  13247. }
  13248. if (count === undefined) {
  13249. if (elements instanceof Float32Array) {
  13250. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13251. }
  13252. else {
  13253. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13254. }
  13255. }
  13256. else {
  13257. if (elements instanceof Float32Array) {
  13258. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13259. }
  13260. else {
  13261. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13262. }
  13263. }
  13264. this.bindUniformBuffer(null);
  13265. };
  13266. // VBOs
  13267. Engine.prototype._resetVertexBufferBinding = function () {
  13268. this.bindArrayBuffer(null);
  13269. this._cachedVertexBuffers = null;
  13270. };
  13271. /**
  13272. * Creates a vertex buffer
  13273. * @param data the data for the vertex buffer
  13274. * @returns the new WebGL static buffer
  13275. */
  13276. Engine.prototype.createVertexBuffer = function (data) {
  13277. var vbo = this._gl.createBuffer();
  13278. if (!vbo) {
  13279. throw new Error("Unable to create vertex buffer");
  13280. }
  13281. this.bindArrayBuffer(vbo);
  13282. if (data instanceof Array) {
  13283. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13284. }
  13285. else {
  13286. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13287. }
  13288. this._resetVertexBufferBinding();
  13289. vbo.references = 1;
  13290. return vbo;
  13291. };
  13292. /**
  13293. * Creates a dynamic vertex buffer
  13294. * @param data the data for the dynamic vertex buffer
  13295. * @returns the new WebGL dynamic buffer
  13296. */
  13297. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13298. var vbo = this._gl.createBuffer();
  13299. if (!vbo) {
  13300. throw new Error("Unable to create dynamic vertex buffer");
  13301. }
  13302. this.bindArrayBuffer(vbo);
  13303. if (data instanceof Array) {
  13304. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13305. }
  13306. else {
  13307. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13308. }
  13309. this._resetVertexBufferBinding();
  13310. vbo.references = 1;
  13311. return vbo;
  13312. };
  13313. /**
  13314. * Update a dynamic index buffer
  13315. * @param indexBuffer defines the target index buffer
  13316. * @param indices defines the data to update
  13317. * @param offset defines the offset in the target index buffer where update should start
  13318. */
  13319. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13320. if (offset === void 0) { offset = 0; }
  13321. // Force cache update
  13322. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13323. this.bindIndexBuffer(indexBuffer);
  13324. var arrayBuffer;
  13325. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13326. arrayBuffer = indices;
  13327. }
  13328. else {
  13329. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13330. }
  13331. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13332. this._resetIndexBufferBinding();
  13333. };
  13334. /**
  13335. * Updates a dynamic vertex buffer.
  13336. * @param vertexBuffer the vertex buffer to update
  13337. * @param data the data used to update the vertex buffer
  13338. * @param byteOffset the byte offset of the data
  13339. * @param byteLength the byte length of the data
  13340. */
  13341. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13342. this.bindArrayBuffer(vertexBuffer);
  13343. if (byteOffset === undefined) {
  13344. byteOffset = 0;
  13345. }
  13346. if (byteLength === undefined) {
  13347. if (data instanceof Array) {
  13348. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13349. }
  13350. else {
  13351. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13352. }
  13353. }
  13354. else {
  13355. if (data instanceof Array) {
  13356. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13357. }
  13358. else {
  13359. if (data instanceof ArrayBuffer) {
  13360. data = new Uint8Array(data, byteOffset, byteLength);
  13361. }
  13362. else {
  13363. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13364. }
  13365. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13366. }
  13367. }
  13368. this._resetVertexBufferBinding();
  13369. };
  13370. Engine.prototype._resetIndexBufferBinding = function () {
  13371. this.bindIndexBuffer(null);
  13372. this._cachedIndexBuffer = null;
  13373. };
  13374. /**
  13375. * Creates a new index buffer
  13376. * @param indices defines the content of the index buffer
  13377. * @param updatable defines if the index buffer must be updatable
  13378. * @returns a new webGL buffer
  13379. */
  13380. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13381. var vbo = this._gl.createBuffer();
  13382. if (!vbo) {
  13383. throw new Error("Unable to create index buffer");
  13384. }
  13385. this.bindIndexBuffer(vbo);
  13386. // Check for 32 bits indices
  13387. var arrayBuffer;
  13388. var need32Bits = false;
  13389. if (indices instanceof Uint16Array) {
  13390. arrayBuffer = indices;
  13391. }
  13392. else {
  13393. //check 32 bit support
  13394. if (this._caps.uintIndices) {
  13395. if (indices instanceof Uint32Array) {
  13396. arrayBuffer = indices;
  13397. need32Bits = true;
  13398. }
  13399. else {
  13400. //number[] or Int32Array, check if 32 bit is necessary
  13401. for (var index = 0; index < indices.length; index++) {
  13402. if (indices[index] > 65535) {
  13403. need32Bits = true;
  13404. break;
  13405. }
  13406. }
  13407. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13408. }
  13409. }
  13410. else {
  13411. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13412. arrayBuffer = new Uint16Array(indices);
  13413. }
  13414. }
  13415. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13416. this._resetIndexBufferBinding();
  13417. vbo.references = 1;
  13418. vbo.is32Bits = need32Bits;
  13419. return vbo;
  13420. };
  13421. /**
  13422. * Bind a webGL buffer to the webGL context
  13423. * @param buffer defines the buffer to bind
  13424. */
  13425. Engine.prototype.bindArrayBuffer = function (buffer) {
  13426. if (!this._vaoRecordInProgress) {
  13427. this._unbindVertexArrayObject();
  13428. }
  13429. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13430. };
  13431. /**
  13432. * Bind an uniform buffer to the current webGL context
  13433. * @param buffer defines the buffer to bind
  13434. */
  13435. Engine.prototype.bindUniformBuffer = function (buffer) {
  13436. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13437. };
  13438. /**
  13439. * Bind a buffer to the current webGL context at a given location
  13440. * @param buffer defines the buffer to bind
  13441. * @param location defines the index where to bind the buffer
  13442. */
  13443. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13444. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13445. };
  13446. /**
  13447. * Bind a specific block at a given index in a specific shader program
  13448. * @param shaderProgram defines the shader program
  13449. * @param blockName defines the block name
  13450. * @param index defines the index where to bind the block
  13451. */
  13452. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13453. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13454. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13455. };
  13456. ;
  13457. Engine.prototype.bindIndexBuffer = function (buffer) {
  13458. if (!this._vaoRecordInProgress) {
  13459. this._unbindVertexArrayObject();
  13460. }
  13461. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13462. };
  13463. Engine.prototype.bindBuffer = function (buffer, target) {
  13464. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13465. this._gl.bindBuffer(target, buffer);
  13466. this._currentBoundBuffer[target] = buffer;
  13467. }
  13468. };
  13469. /**
  13470. * update the bound buffer with the given data
  13471. * @param data defines the data to update
  13472. */
  13473. Engine.prototype.updateArrayBuffer = function (data) {
  13474. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13475. };
  13476. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13477. var pointer = this._currentBufferPointers[indx];
  13478. var changed = false;
  13479. if (!pointer.active) {
  13480. changed = true;
  13481. pointer.active = true;
  13482. pointer.index = indx;
  13483. pointer.size = size;
  13484. pointer.type = type;
  13485. pointer.normalized = normalized;
  13486. pointer.stride = stride;
  13487. pointer.offset = offset;
  13488. pointer.buffer = buffer;
  13489. }
  13490. else {
  13491. if (pointer.buffer !== buffer) {
  13492. pointer.buffer = buffer;
  13493. changed = true;
  13494. }
  13495. if (pointer.size !== size) {
  13496. pointer.size = size;
  13497. changed = true;
  13498. }
  13499. if (pointer.type !== type) {
  13500. pointer.type = type;
  13501. changed = true;
  13502. }
  13503. if (pointer.normalized !== normalized) {
  13504. pointer.normalized = normalized;
  13505. changed = true;
  13506. }
  13507. if (pointer.stride !== stride) {
  13508. pointer.stride = stride;
  13509. changed = true;
  13510. }
  13511. if (pointer.offset !== offset) {
  13512. pointer.offset = offset;
  13513. changed = true;
  13514. }
  13515. }
  13516. if (changed || this._vaoRecordInProgress) {
  13517. this.bindArrayBuffer(buffer);
  13518. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13519. }
  13520. };
  13521. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13522. if (indexBuffer == null) {
  13523. return;
  13524. }
  13525. if (this._cachedIndexBuffer !== indexBuffer) {
  13526. this._cachedIndexBuffer = indexBuffer;
  13527. this.bindIndexBuffer(indexBuffer);
  13528. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13529. }
  13530. };
  13531. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13532. var attributes = effect.getAttributesNames();
  13533. if (!this._vaoRecordInProgress) {
  13534. this._unbindVertexArrayObject();
  13535. }
  13536. this.unbindAllAttributes();
  13537. for (var index = 0; index < attributes.length; index++) {
  13538. var order = effect.getAttributeLocation(index);
  13539. if (order >= 0) {
  13540. var vertexBuffer = vertexBuffers[attributes[index]];
  13541. if (!vertexBuffer) {
  13542. continue;
  13543. }
  13544. this._gl.enableVertexAttribArray(order);
  13545. if (!this._vaoRecordInProgress) {
  13546. this._vertexAttribArraysEnabled[order] = true;
  13547. }
  13548. var buffer = vertexBuffer.getBuffer();
  13549. if (buffer) {
  13550. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13551. if (vertexBuffer.getIsInstanced()) {
  13552. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13553. if (!this._vaoRecordInProgress) {
  13554. this._currentInstanceLocations.push(order);
  13555. this._currentInstanceBuffers.push(buffer);
  13556. }
  13557. }
  13558. }
  13559. }
  13560. }
  13561. };
  13562. /**
  13563. * Records a vertex array object
  13564. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13565. * @param vertexBuffers defines the list of vertex buffers to store
  13566. * @param indexBuffer defines the index buffer to store
  13567. * @param effect defines the effect to store
  13568. * @returns the new vertex array object
  13569. */
  13570. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13571. var vao = this._gl.createVertexArray();
  13572. this._vaoRecordInProgress = true;
  13573. this._gl.bindVertexArray(vao);
  13574. this._mustWipeVertexAttributes = true;
  13575. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13576. this.bindIndexBuffer(indexBuffer);
  13577. this._vaoRecordInProgress = false;
  13578. this._gl.bindVertexArray(null);
  13579. return vao;
  13580. };
  13581. /**
  13582. * Bind a specific vertex array object
  13583. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13584. * @param vertexArrayObject defines the vertex array object to bind
  13585. * @param indexBuffer defines the index buffer to bind
  13586. */
  13587. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13588. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13589. this._cachedVertexArrayObject = vertexArrayObject;
  13590. this._gl.bindVertexArray(vertexArrayObject);
  13591. this._cachedVertexBuffers = null;
  13592. this._cachedIndexBuffer = null;
  13593. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13594. this._mustWipeVertexAttributes = true;
  13595. }
  13596. };
  13597. /**
  13598. * Bind webGl buffers directly to the webGL context
  13599. * @param vertexBuffer defines the vertex buffer to bind
  13600. * @param indexBuffer defines the index buffer to bind
  13601. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13602. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13603. * @param effect defines the effect associated with the vertex buffer
  13604. */
  13605. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13606. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13607. this._cachedVertexBuffers = vertexBuffer;
  13608. this._cachedEffectForVertexBuffers = effect;
  13609. var attributesCount = effect.getAttributesCount();
  13610. this._unbindVertexArrayObject();
  13611. this.unbindAllAttributes();
  13612. var offset = 0;
  13613. for (var index = 0; index < attributesCount; index++) {
  13614. if (index < vertexDeclaration.length) {
  13615. var order = effect.getAttributeLocation(index);
  13616. if (order >= 0) {
  13617. this._gl.enableVertexAttribArray(order);
  13618. this._vertexAttribArraysEnabled[order] = true;
  13619. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13620. }
  13621. offset += vertexDeclaration[index] * 4;
  13622. }
  13623. }
  13624. }
  13625. this._bindIndexBufferWithCache(indexBuffer);
  13626. };
  13627. Engine.prototype._unbindVertexArrayObject = function () {
  13628. if (!this._cachedVertexArrayObject) {
  13629. return;
  13630. }
  13631. this._cachedVertexArrayObject = null;
  13632. this._gl.bindVertexArray(null);
  13633. };
  13634. /**
  13635. * Bind a list of vertex buffers to the webGL context
  13636. * @param vertexBuffers defines the list of vertex buffers to bind
  13637. * @param indexBuffer defines the index buffer to bind
  13638. * @param effect defines the effect associated with the vertex buffers
  13639. */
  13640. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13641. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13642. this._cachedVertexBuffers = vertexBuffers;
  13643. this._cachedEffectForVertexBuffers = effect;
  13644. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13645. }
  13646. this._bindIndexBufferWithCache(indexBuffer);
  13647. };
  13648. /**
  13649. * Unbind all instance attributes
  13650. */
  13651. Engine.prototype.unbindInstanceAttributes = function () {
  13652. var boundBuffer;
  13653. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13654. var instancesBuffer = this._currentInstanceBuffers[i];
  13655. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13656. boundBuffer = instancesBuffer;
  13657. this.bindArrayBuffer(instancesBuffer);
  13658. }
  13659. var offsetLocation = this._currentInstanceLocations[i];
  13660. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13661. }
  13662. this._currentInstanceBuffers.length = 0;
  13663. this._currentInstanceLocations.length = 0;
  13664. };
  13665. /**
  13666. * Release and free the memory of a vertex array object
  13667. * @param vao defines the vertex array object to delete
  13668. */
  13669. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13670. this._gl.deleteVertexArray(vao);
  13671. };
  13672. /** @hidden */
  13673. Engine.prototype._releaseBuffer = function (buffer) {
  13674. buffer.references--;
  13675. if (buffer.references === 0) {
  13676. this._gl.deleteBuffer(buffer);
  13677. return true;
  13678. }
  13679. return false;
  13680. };
  13681. /**
  13682. * Creates a webGL buffer to use with instanciation
  13683. * @param capacity defines the size of the buffer
  13684. * @returns the webGL buffer
  13685. */
  13686. Engine.prototype.createInstancesBuffer = function (capacity) {
  13687. var buffer = this._gl.createBuffer();
  13688. if (!buffer) {
  13689. throw new Error("Unable to create instance buffer");
  13690. }
  13691. buffer.capacity = capacity;
  13692. this.bindArrayBuffer(buffer);
  13693. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13694. return buffer;
  13695. };
  13696. /**
  13697. * Delete a webGL buffer used with instanciation
  13698. * @param buffer defines the webGL buffer to delete
  13699. */
  13700. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13701. this._gl.deleteBuffer(buffer);
  13702. };
  13703. /**
  13704. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13705. * @param instancesBuffer defines the webGL buffer to update and bind
  13706. * @param data defines the data to store in the buffer
  13707. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13708. */
  13709. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13710. this.bindArrayBuffer(instancesBuffer);
  13711. if (data) {
  13712. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13713. }
  13714. if (offsetLocations[0].index !== undefined) {
  13715. var stride = 0;
  13716. for (var i = 0; i < offsetLocations.length; i++) {
  13717. var ai = offsetLocations[i];
  13718. stride += ai.attributeSize * 4;
  13719. }
  13720. for (var i = 0; i < offsetLocations.length; i++) {
  13721. var ai = offsetLocations[i];
  13722. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13723. this._gl.enableVertexAttribArray(ai.index);
  13724. this._vertexAttribArraysEnabled[ai.index] = true;
  13725. }
  13726. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13727. this._gl.vertexAttribDivisor(ai.index, 1);
  13728. this._currentInstanceLocations.push(ai.index);
  13729. this._currentInstanceBuffers.push(instancesBuffer);
  13730. }
  13731. }
  13732. else {
  13733. for (var index = 0; index < 4; index++) {
  13734. var offsetLocation = offsetLocations[index];
  13735. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13736. this._gl.enableVertexAttribArray(offsetLocation);
  13737. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13738. }
  13739. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13740. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13741. this._currentInstanceLocations.push(offsetLocation);
  13742. this._currentInstanceBuffers.push(instancesBuffer);
  13743. }
  13744. }
  13745. };
  13746. /**
  13747. * Apply all cached states (depth, culling, stencil and alpha)
  13748. */
  13749. Engine.prototype.applyStates = function () {
  13750. this._depthCullingState.apply(this._gl);
  13751. this._stencilState.apply(this._gl);
  13752. this._alphaState.apply(this._gl);
  13753. };
  13754. /**
  13755. * Send a draw order
  13756. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13757. * @param indexStart defines the starting index
  13758. * @param indexCount defines the number of index to draw
  13759. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13760. */
  13761. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13762. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13763. };
  13764. /**
  13765. * Draw a list of points
  13766. * @param verticesStart defines the index of first vertex to draw
  13767. * @param verticesCount defines the count of vertices to draw
  13768. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13769. */
  13770. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13771. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13772. };
  13773. /**
  13774. * Draw a list of unindexed primitives
  13775. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13776. * @param verticesStart defines the index of first vertex to draw
  13777. * @param verticesCount defines the count of vertices to draw
  13778. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13779. */
  13780. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13781. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13782. };
  13783. /**
  13784. * Draw a list of indexed primitives
  13785. * @param fillMode defines the primitive to use
  13786. * @param indexStart defines the starting index
  13787. * @param indexCount defines the number of index to draw
  13788. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13789. */
  13790. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13791. // Apply states
  13792. this.applyStates();
  13793. this._drawCalls.addCount(1, false);
  13794. // Render
  13795. var drawMode = this._drawMode(fillMode);
  13796. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13797. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13798. if (instancesCount) {
  13799. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13800. }
  13801. else {
  13802. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13803. }
  13804. };
  13805. /**
  13806. * Draw a list of unindexed primitives
  13807. * @param fillMode defines the primitive to use
  13808. * @param verticesStart defines the index of first vertex to draw
  13809. * @param verticesCount defines the count of vertices to draw
  13810. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13811. */
  13812. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13813. // Apply states
  13814. this.applyStates();
  13815. this._drawCalls.addCount(1, false);
  13816. var drawMode = this._drawMode(fillMode);
  13817. if (instancesCount) {
  13818. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13819. }
  13820. else {
  13821. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13822. }
  13823. };
  13824. Engine.prototype._drawMode = function (fillMode) {
  13825. switch (fillMode) {
  13826. // Triangle views
  13827. case BABYLON.Material.TriangleFillMode:
  13828. return this._gl.TRIANGLES;
  13829. case BABYLON.Material.PointFillMode:
  13830. return this._gl.POINTS;
  13831. case BABYLON.Material.WireFrameFillMode:
  13832. return this._gl.LINES;
  13833. // Draw modes
  13834. case BABYLON.Material.PointListDrawMode:
  13835. return this._gl.POINTS;
  13836. case BABYLON.Material.LineListDrawMode:
  13837. return this._gl.LINES;
  13838. case BABYLON.Material.LineLoopDrawMode:
  13839. return this._gl.LINE_LOOP;
  13840. case BABYLON.Material.LineStripDrawMode:
  13841. return this._gl.LINE_STRIP;
  13842. case BABYLON.Material.TriangleStripDrawMode:
  13843. return this._gl.TRIANGLE_STRIP;
  13844. case BABYLON.Material.TriangleFanDrawMode:
  13845. return this._gl.TRIANGLE_FAN;
  13846. default:
  13847. return this._gl.TRIANGLES;
  13848. }
  13849. };
  13850. // Shaders
  13851. /** @hidden */
  13852. Engine.prototype._releaseEffect = function (effect) {
  13853. if (this._compiledEffects[effect._key]) {
  13854. delete this._compiledEffects[effect._key];
  13855. this._deleteProgram(effect.getProgram());
  13856. }
  13857. };
  13858. /** @hidden */
  13859. Engine.prototype._deleteProgram = function (program) {
  13860. if (program) {
  13861. program.__SPECTOR_rebuildProgram = null;
  13862. if (program.transformFeedback) {
  13863. this.deleteTransformFeedback(program.transformFeedback);
  13864. program.transformFeedback = null;
  13865. }
  13866. this._gl.deleteProgram(program);
  13867. }
  13868. };
  13869. /**
  13870. * Create a new effect (used to store vertex/fragment shaders)
  13871. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13872. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13873. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13874. * @param samplers defines an array of string used to represent textures
  13875. * @param defines defines the string containing the defines to use to compile the shaders
  13876. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13877. * @param onCompiled defines a function to call when the effect creation is successful
  13878. * @param onError defines a function to call when the effect creation has failed
  13879. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13880. * @returns the new Effect
  13881. */
  13882. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13883. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13884. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13885. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13886. if (this._compiledEffects[name]) {
  13887. var compiledEffect = this._compiledEffects[name];
  13888. if (onCompiled && compiledEffect.isReady()) {
  13889. onCompiled(compiledEffect);
  13890. }
  13891. return compiledEffect;
  13892. }
  13893. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13894. effect._key = name;
  13895. this._compiledEffects[name] = effect;
  13896. return effect;
  13897. };
  13898. /**
  13899. * Create an effect to use with particle systems
  13900. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13901. * @param uniformsNames defines a list of attribute names
  13902. * @param samplers defines an array of string used to represent textures
  13903. * @param defines defines the string containing the defines to use to compile the shaders
  13904. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13905. * @param onCompiled defines a function to call when the effect creation is successful
  13906. * @param onError defines a function to call when the effect creation has failed
  13907. * @returns the new Effect
  13908. */
  13909. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13910. if (uniformsNames === void 0) { uniformsNames = []; }
  13911. if (samplers === void 0) { samplers = []; }
  13912. if (defines === void 0) { defines = ""; }
  13913. return this.createEffect({
  13914. vertex: "particles",
  13915. fragmentElement: fragmentName
  13916. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13917. };
  13918. /**
  13919. * Directly creates a webGL program
  13920. * @param vertexCode defines the vertex shader code to use
  13921. * @param fragmentCode defines the fragment shader code to use
  13922. * @param context defines the webGL context to use (if not set, the current one will be used)
  13923. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13924. * @returns the new webGL program
  13925. */
  13926. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13927. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13928. context = context || this._gl;
  13929. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13930. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13931. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13932. };
  13933. /**
  13934. * Creates a webGL program
  13935. * @param vertexCode defines the vertex shader code to use
  13936. * @param fragmentCode defines the fragment shader code to use
  13937. * @param defines defines the string containing the defines to use to compile the shaders
  13938. * @param context defines the webGL context to use (if not set, the current one will be used)
  13939. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13940. * @returns the new webGL program
  13941. */
  13942. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13943. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13944. context = context || this._gl;
  13945. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13946. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13947. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13948. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13949. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13950. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13951. return program;
  13952. };
  13953. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13954. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13955. var shaderProgram = context.createProgram();
  13956. if (!shaderProgram) {
  13957. throw new Error("Unable to create program");
  13958. }
  13959. context.attachShader(shaderProgram, vertexShader);
  13960. context.attachShader(shaderProgram, fragmentShader);
  13961. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13962. var transformFeedback = this.createTransformFeedback();
  13963. this.bindTransformFeedback(transformFeedback);
  13964. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13965. shaderProgram.transformFeedback = transformFeedback;
  13966. }
  13967. context.linkProgram(shaderProgram);
  13968. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13969. this.bindTransformFeedback(null);
  13970. }
  13971. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13972. if (!linked) {
  13973. context.validateProgram(shaderProgram);
  13974. var error = context.getProgramInfoLog(shaderProgram);
  13975. if (error) {
  13976. throw new Error(error);
  13977. }
  13978. }
  13979. context.deleteShader(vertexShader);
  13980. context.deleteShader(fragmentShader);
  13981. return shaderProgram;
  13982. };
  13983. /**
  13984. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13985. * @param shaderProgram defines the webGL program to use
  13986. * @param uniformsNames defines the list of uniform names
  13987. * @returns an array of webGL uniform locations
  13988. */
  13989. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13990. var results = new Array();
  13991. for (var index = 0; index < uniformsNames.length; index++) {
  13992. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13993. }
  13994. return results;
  13995. };
  13996. /**
  13997. * Gets the lsit of active attributes for a given webGL program
  13998. * @param shaderProgram defines the webGL program to use
  13999. * @param attributesNames defines the list of attribute names to get
  14000. * @returns an array of indices indicating the offset of each attribute
  14001. */
  14002. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14003. var results = [];
  14004. for (var index = 0; index < attributesNames.length; index++) {
  14005. try {
  14006. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14007. }
  14008. catch (e) {
  14009. results.push(-1);
  14010. }
  14011. }
  14012. return results;
  14013. };
  14014. /**
  14015. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14016. * @param effect defines the effect to activate
  14017. */
  14018. Engine.prototype.enableEffect = function (effect) {
  14019. if (!effect) {
  14020. return;
  14021. }
  14022. // Use program
  14023. this.bindSamplers(effect);
  14024. this._currentEffect = effect;
  14025. if (effect.onBind) {
  14026. effect.onBind(effect);
  14027. }
  14028. effect.onBindObservable.notifyObservers(effect);
  14029. };
  14030. /**
  14031. * Set the value of an uniform to an array of int32
  14032. * @param uniform defines the webGL uniform location where to store the value
  14033. * @param array defines the array of int32 to store
  14034. */
  14035. Engine.prototype.setIntArray = function (uniform, array) {
  14036. if (!uniform)
  14037. return;
  14038. this._gl.uniform1iv(uniform, array);
  14039. };
  14040. /**
  14041. * Set the value of an uniform to an array of int32 (stored as vec2)
  14042. * @param uniform defines the webGL uniform location where to store the value
  14043. * @param array defines the array of int32 to store
  14044. */
  14045. Engine.prototype.setIntArray2 = function (uniform, array) {
  14046. if (!uniform || array.length % 2 !== 0)
  14047. return;
  14048. this._gl.uniform2iv(uniform, array);
  14049. };
  14050. /**
  14051. * Set the value of an uniform to an array of int32 (stored as vec3)
  14052. * @param uniform defines the webGL uniform location where to store the value
  14053. * @param array defines the array of int32 to store
  14054. */
  14055. Engine.prototype.setIntArray3 = function (uniform, array) {
  14056. if (!uniform || array.length % 3 !== 0)
  14057. return;
  14058. this._gl.uniform3iv(uniform, array);
  14059. };
  14060. /**
  14061. * Set the value of an uniform to an array of int32 (stored as vec4)
  14062. * @param uniform defines the webGL uniform location where to store the value
  14063. * @param array defines the array of int32 to store
  14064. */
  14065. Engine.prototype.setIntArray4 = function (uniform, array) {
  14066. if (!uniform || array.length % 4 !== 0)
  14067. return;
  14068. this._gl.uniform4iv(uniform, array);
  14069. };
  14070. /**
  14071. * Set the value of an uniform to an array of float32
  14072. * @param uniform defines the webGL uniform location where to store the value
  14073. * @param array defines the array of float32 to store
  14074. */
  14075. Engine.prototype.setFloatArray = function (uniform, array) {
  14076. if (!uniform)
  14077. return;
  14078. this._gl.uniform1fv(uniform, array);
  14079. };
  14080. /**
  14081. * Set the value of an uniform to an array of float32 (stored as vec2)
  14082. * @param uniform defines the webGL uniform location where to store the value
  14083. * @param array defines the array of float32 to store
  14084. */
  14085. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14086. if (!uniform || array.length % 2 !== 0)
  14087. return;
  14088. this._gl.uniform2fv(uniform, array);
  14089. };
  14090. /**
  14091. * Set the value of an uniform to an array of float32 (stored as vec3)
  14092. * @param uniform defines the webGL uniform location where to store the value
  14093. * @param array defines the array of float32 to store
  14094. */
  14095. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14096. if (!uniform || array.length % 3 !== 0)
  14097. return;
  14098. this._gl.uniform3fv(uniform, array);
  14099. };
  14100. /**
  14101. * Set the value of an uniform to an array of float32 (stored as vec4)
  14102. * @param uniform defines the webGL uniform location where to store the value
  14103. * @param array defines the array of float32 to store
  14104. */
  14105. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14106. if (!uniform || array.length % 4 !== 0)
  14107. return;
  14108. this._gl.uniform4fv(uniform, array);
  14109. };
  14110. /**
  14111. * Set the value of an uniform to an array of number
  14112. * @param uniform defines the webGL uniform location where to store the value
  14113. * @param array defines the array of number to store
  14114. */
  14115. Engine.prototype.setArray = function (uniform, array) {
  14116. if (!uniform)
  14117. return;
  14118. this._gl.uniform1fv(uniform, array);
  14119. };
  14120. /**
  14121. * Set the value of an uniform to an array of number (stored as vec2)
  14122. * @param uniform defines the webGL uniform location where to store the value
  14123. * @param array defines the array of number to store
  14124. */
  14125. Engine.prototype.setArray2 = function (uniform, array) {
  14126. if (!uniform || array.length % 2 !== 0)
  14127. return;
  14128. this._gl.uniform2fv(uniform, array);
  14129. };
  14130. /**
  14131. * Set the value of an uniform to an array of number (stored as vec3)
  14132. * @param uniform defines the webGL uniform location where to store the value
  14133. * @param array defines the array of number to store
  14134. */
  14135. Engine.prototype.setArray3 = function (uniform, array) {
  14136. if (!uniform || array.length % 3 !== 0)
  14137. return;
  14138. this._gl.uniform3fv(uniform, array);
  14139. };
  14140. /**
  14141. * Set the value of an uniform to an array of number (stored as vec4)
  14142. * @param uniform defines the webGL uniform location where to store the value
  14143. * @param array defines the array of number to store
  14144. */
  14145. Engine.prototype.setArray4 = function (uniform, array) {
  14146. if (!uniform || array.length % 4 !== 0)
  14147. return;
  14148. this._gl.uniform4fv(uniform, array);
  14149. };
  14150. /**
  14151. * Set the value of an uniform to an array of float32 (stored as matrices)
  14152. * @param uniform defines the webGL uniform location where to store the value
  14153. * @param matrices defines the array of float32 to store
  14154. */
  14155. Engine.prototype.setMatrices = function (uniform, matrices) {
  14156. if (!uniform)
  14157. return;
  14158. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14159. };
  14160. /**
  14161. * Set the value of an uniform to a matrix
  14162. * @param uniform defines the webGL uniform location where to store the value
  14163. * @param matrix defines the matrix to store
  14164. */
  14165. Engine.prototype.setMatrix = function (uniform, matrix) {
  14166. if (!uniform)
  14167. return;
  14168. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14169. };
  14170. /**
  14171. * Set the value of an uniform to a matrix (3x3)
  14172. * @param uniform defines the webGL uniform location where to store the value
  14173. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14174. */
  14175. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14176. if (!uniform)
  14177. return;
  14178. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14179. };
  14180. /**
  14181. * Set the value of an uniform to a matrix (2x2)
  14182. * @param uniform defines the webGL uniform location where to store the value
  14183. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14184. */
  14185. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14186. if (!uniform)
  14187. return;
  14188. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14189. };
  14190. /**
  14191. * Set the value of an uniform to a number (int)
  14192. * @param uniform defines the webGL uniform location where to store the value
  14193. * @param value defines the int number to store
  14194. */
  14195. Engine.prototype.setInt = function (uniform, value) {
  14196. if (!uniform)
  14197. return;
  14198. this._gl.uniform1i(uniform, value);
  14199. };
  14200. /**
  14201. * Set the value of an uniform to a number (float)
  14202. * @param uniform defines the webGL uniform location where to store the value
  14203. * @param value defines the float number to store
  14204. */
  14205. Engine.prototype.setFloat = function (uniform, value) {
  14206. if (!uniform)
  14207. return;
  14208. this._gl.uniform1f(uniform, value);
  14209. };
  14210. /**
  14211. * Set the value of an uniform to a vec2
  14212. * @param uniform defines the webGL uniform location where to store the value
  14213. * @param x defines the 1st component of the value
  14214. * @param y defines the 2nd component of the value
  14215. */
  14216. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14217. if (!uniform)
  14218. return;
  14219. this._gl.uniform2f(uniform, x, y);
  14220. };
  14221. /**
  14222. * Set the value of an uniform to a vec3
  14223. * @param uniform defines the webGL uniform location where to store the value
  14224. * @param x defines the 1st component of the value
  14225. * @param y defines the 2nd component of the value
  14226. * @param z defines the 3rd component of the value
  14227. */
  14228. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14229. if (!uniform)
  14230. return;
  14231. this._gl.uniform3f(uniform, x, y, z);
  14232. };
  14233. /**
  14234. * Set the value of an uniform to a boolean
  14235. * @param uniform defines the webGL uniform location where to store the value
  14236. * @param bool defines the boolean to store
  14237. */
  14238. Engine.prototype.setBool = function (uniform, bool) {
  14239. if (!uniform)
  14240. return;
  14241. this._gl.uniform1i(uniform, bool);
  14242. };
  14243. /**
  14244. * Set the value of an uniform to a vec4
  14245. * @param uniform defines the webGL uniform location where to store the value
  14246. * @param x defines the 1st component of the value
  14247. * @param y defines the 2nd component of the value
  14248. * @param z defines the 3rd component of the value
  14249. * @param w defines the 4th component of the value
  14250. */
  14251. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14252. if (!uniform)
  14253. return;
  14254. this._gl.uniform4f(uniform, x, y, z, w);
  14255. };
  14256. /**
  14257. * Set the value of an uniform to a Color3
  14258. * @param uniform defines the webGL uniform location where to store the value
  14259. * @param color3 defines the color to store
  14260. */
  14261. Engine.prototype.setColor3 = function (uniform, color3) {
  14262. if (!uniform)
  14263. return;
  14264. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14265. };
  14266. /**
  14267. * Set the value of an uniform to a Color3 and an alpha value
  14268. * @param uniform defines the webGL uniform location where to store the value
  14269. * @param color3 defines the color to store
  14270. * @param alpha defines the alpha component to store
  14271. */
  14272. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14273. if (!uniform)
  14274. return;
  14275. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14276. };
  14277. /**
  14278. * Sets a Color4 on a uniform variable
  14279. * @param uniform defines the uniform location
  14280. * @param color4 defines the value to be set
  14281. */
  14282. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14283. if (!uniform)
  14284. return;
  14285. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14286. };
  14287. // States
  14288. /**
  14289. * Set various states to the webGL context
  14290. * @param culling defines backface culling state
  14291. * @param zOffset defines the value to apply to zOffset (0 by default)
  14292. * @param force defines if states must be applied even if cache is up to date
  14293. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14294. */
  14295. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14296. if (zOffset === void 0) { zOffset = 0; }
  14297. if (reverseSide === void 0) { reverseSide = false; }
  14298. // Culling
  14299. if (this._depthCullingState.cull !== culling || force) {
  14300. this._depthCullingState.cull = culling;
  14301. }
  14302. // Cull face
  14303. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14304. if (this._depthCullingState.cullFace !== cullFace || force) {
  14305. this._depthCullingState.cullFace = cullFace;
  14306. }
  14307. // Z offset
  14308. this.setZOffset(zOffset);
  14309. // Front face
  14310. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14311. if (this._depthCullingState.frontFace !== frontFace || force) {
  14312. this._depthCullingState.frontFace = frontFace;
  14313. }
  14314. };
  14315. /**
  14316. * Set the z offset to apply to current rendering
  14317. * @param value defines the offset to apply
  14318. */
  14319. Engine.prototype.setZOffset = function (value) {
  14320. this._depthCullingState.zOffset = value;
  14321. };
  14322. /**
  14323. * Gets the current value of the zOffset
  14324. * @returns the current zOffset state
  14325. */
  14326. Engine.prototype.getZOffset = function () {
  14327. return this._depthCullingState.zOffset;
  14328. };
  14329. /**
  14330. * Enable or disable depth buffering
  14331. * @param enable defines the state to set
  14332. */
  14333. Engine.prototype.setDepthBuffer = function (enable) {
  14334. this._depthCullingState.depthTest = enable;
  14335. };
  14336. /**
  14337. * Gets a boolean indicating if depth writing is enabled
  14338. * @returns the current depth writing state
  14339. */
  14340. Engine.prototype.getDepthWrite = function () {
  14341. return this._depthCullingState.depthMask;
  14342. };
  14343. /**
  14344. * Enable or disable depth writing
  14345. * @param enable defines the state to set
  14346. */
  14347. Engine.prototype.setDepthWrite = function (enable) {
  14348. this._depthCullingState.depthMask = enable;
  14349. };
  14350. /**
  14351. * Enable or disable color writing
  14352. * @param enable defines the state to set
  14353. */
  14354. Engine.prototype.setColorWrite = function (enable) {
  14355. this._gl.colorMask(enable, enable, enable, enable);
  14356. this._colorWrite = enable;
  14357. };
  14358. /**
  14359. * Gets a boolean indicating if color writing is enabled
  14360. * @returns the current color writing state
  14361. */
  14362. Engine.prototype.getColorWrite = function () {
  14363. return this._colorWrite;
  14364. };
  14365. /**
  14366. * Sets alpha constants used by some alpha blending modes
  14367. * @param r defines the red component
  14368. * @param g defines the green component
  14369. * @param b defines the blue component
  14370. * @param a defines the alpha component
  14371. */
  14372. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14373. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14374. };
  14375. /**
  14376. * Sets the current alpha mode
  14377. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14378. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14379. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14380. */
  14381. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14382. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14383. if (this._alphaMode === mode) {
  14384. return;
  14385. }
  14386. switch (mode) {
  14387. case Engine.ALPHA_DISABLE:
  14388. this._alphaState.alphaBlend = false;
  14389. break;
  14390. case Engine.ALPHA_PREMULTIPLIED:
  14391. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14392. this._alphaState.alphaBlend = true;
  14393. break;
  14394. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14395. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14396. this._alphaState.alphaBlend = true;
  14397. break;
  14398. case Engine.ALPHA_COMBINE:
  14399. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14400. this._alphaState.alphaBlend = true;
  14401. break;
  14402. case Engine.ALPHA_ONEONE:
  14403. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14404. this._alphaState.alphaBlend = true;
  14405. break;
  14406. case Engine.ALPHA_ADD:
  14407. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14408. this._alphaState.alphaBlend = true;
  14409. break;
  14410. case Engine.ALPHA_SUBTRACT:
  14411. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14412. this._alphaState.alphaBlend = true;
  14413. break;
  14414. case Engine.ALPHA_MULTIPLY:
  14415. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14416. this._alphaState.alphaBlend = true;
  14417. break;
  14418. case Engine.ALPHA_MAXIMIZED:
  14419. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14420. this._alphaState.alphaBlend = true;
  14421. break;
  14422. case Engine.ALPHA_INTERPOLATE:
  14423. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14424. this._alphaState.alphaBlend = true;
  14425. break;
  14426. case Engine.ALPHA_SCREENMODE:
  14427. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14428. this._alphaState.alphaBlend = true;
  14429. break;
  14430. }
  14431. if (!noDepthWriteChange) {
  14432. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14433. }
  14434. this._alphaMode = mode;
  14435. };
  14436. /**
  14437. * Gets the current alpha mode
  14438. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14439. * @returns the current alpha mode
  14440. */
  14441. Engine.prototype.getAlphaMode = function () {
  14442. return this._alphaMode;
  14443. };
  14444. // Textures
  14445. /**
  14446. * Force the entire cache to be cleared
  14447. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14448. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14449. */
  14450. Engine.prototype.wipeCaches = function (bruteForce) {
  14451. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14452. return;
  14453. }
  14454. this._currentEffect = null;
  14455. if (bruteForce) {
  14456. this.resetTextureCache();
  14457. this._currentProgram = null;
  14458. this._stencilState.reset();
  14459. this._depthCullingState.reset();
  14460. this.setDepthFunctionToLessOrEqual();
  14461. this._alphaState.reset();
  14462. }
  14463. this._resetVertexBufferBinding();
  14464. this._cachedIndexBuffer = null;
  14465. this._cachedEffectForVertexBuffers = null;
  14466. this._unbindVertexArrayObject();
  14467. this.bindIndexBuffer(null);
  14468. };
  14469. /**
  14470. * Set the compressed texture format to use, based on the formats you have, and the formats
  14471. * supported by the hardware / browser.
  14472. *
  14473. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14474. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14475. * to API arguments needed to compressed textures. This puts the burden on the container
  14476. * generator to house the arcane code for determining these for current & future formats.
  14477. *
  14478. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14479. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14480. *
  14481. * Note: The result of this call is not taken into account when a texture is base64.
  14482. *
  14483. * @param formatsAvailable defines the list of those format families you have created
  14484. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14485. *
  14486. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14487. * @returns The extension selected.
  14488. */
  14489. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14490. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14491. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14492. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14493. return this._textureFormatInUse = this._texturesSupported[i];
  14494. }
  14495. }
  14496. }
  14497. // actively set format to nothing, to allow this to be called more than once
  14498. // and possibly fail the 2nd time
  14499. this._textureFormatInUse = null;
  14500. return null;
  14501. };
  14502. /** @hidden */
  14503. Engine.prototype._createTexture = function () {
  14504. var texture = this._gl.createTexture();
  14505. if (!texture) {
  14506. throw new Error("Unable to create texture");
  14507. }
  14508. return texture;
  14509. };
  14510. /**
  14511. * Usually called from BABYLON.Texture.ts.
  14512. * Passed information to create a WebGLTexture
  14513. * @param urlArg defines a value which contains one of the following:
  14514. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14515. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14516. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14517. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14518. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14519. * @param scene needed for loading to the correct scene
  14520. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14521. * @param onLoad optional callback to be called upon successful completion
  14522. * @param onError optional callback to be called upon failure
  14523. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14524. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14525. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14526. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14527. */
  14528. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14529. var _this = this;
  14530. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14531. if (onLoad === void 0) { onLoad = null; }
  14532. if (onError === void 0) { onError = null; }
  14533. if (buffer === void 0) { buffer = null; }
  14534. if (fallback === void 0) { fallback = null; }
  14535. if (format === void 0) { format = null; }
  14536. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14537. var fromData = url.substr(0, 5) === "data:";
  14538. var fromBlob = url.substr(0, 5) === "blob:";
  14539. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14540. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14541. // establish the file extension, if possible
  14542. var lastDot = url.lastIndexOf('.');
  14543. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14544. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14545. var isTGA = (extension.indexOf(".tga") === 0);
  14546. // determine if a ktx file should be substituted
  14547. var isKTX = false;
  14548. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14549. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14550. isKTX = true;
  14551. }
  14552. if (scene) {
  14553. scene._addPendingData(texture);
  14554. }
  14555. texture.url = url;
  14556. texture.generateMipMaps = !noMipmap;
  14557. texture.samplingMode = samplingMode;
  14558. texture.invertY = invertY;
  14559. if (!this._doNotHandleContextLost) {
  14560. // Keep a link to the buffer only if we plan to handle context lost
  14561. texture._buffer = buffer;
  14562. }
  14563. var onLoadObserver = null;
  14564. if (onLoad && !fallback) {
  14565. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14566. }
  14567. if (!fallback)
  14568. this._internalTexturesCache.push(texture);
  14569. var onerror = function (message, exception) {
  14570. if (scene) {
  14571. scene._removePendingData(texture);
  14572. }
  14573. if (onLoadObserver) {
  14574. texture.onLoadedObservable.remove(onLoadObserver);
  14575. }
  14576. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14577. if (isKTX) {
  14578. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14579. }
  14580. else if (BABYLON.Tools.UseFallbackTexture) {
  14581. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14582. }
  14583. if (onError) {
  14584. onError(message || "Unknown error", exception);
  14585. }
  14586. };
  14587. var callback = null;
  14588. // processing for non-image formats
  14589. if (isKTX || isTGA || isDDS) {
  14590. if (isKTX) {
  14591. callback = function (data) {
  14592. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14593. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14594. ktx.uploadLevels(_this._gl, !noMipmap);
  14595. return false;
  14596. }, samplingMode);
  14597. };
  14598. }
  14599. else if (isTGA) {
  14600. callback = function (arrayBuffer) {
  14601. var data = new Uint8Array(arrayBuffer);
  14602. var header = BABYLON.TGATools.GetTGAHeader(data);
  14603. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14604. BABYLON.TGATools.UploadContent(_this._gl, data);
  14605. return false;
  14606. }, samplingMode);
  14607. };
  14608. }
  14609. else if (isDDS) {
  14610. callback = function (data) {
  14611. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14612. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14613. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14614. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14615. return false;
  14616. }, samplingMode);
  14617. };
  14618. }
  14619. if (!buffer) {
  14620. this._loadFile(url, function (data) {
  14621. if (callback) {
  14622. callback(data);
  14623. }
  14624. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14625. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14626. });
  14627. }
  14628. else {
  14629. if (callback) {
  14630. callback(buffer);
  14631. }
  14632. }
  14633. // image format processing
  14634. }
  14635. else {
  14636. var onload = function (img) {
  14637. if (fromBlob && !_this._doNotHandleContextLost) {
  14638. // We need to store the image if we need to rebuild the texture
  14639. // in case of a webgl context lost
  14640. texture._buffer = img;
  14641. }
  14642. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14643. var gl = _this._gl;
  14644. var isPot = (img.width === potWidth && img.height === potHeight);
  14645. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14646. if (isPot) {
  14647. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14648. return false;
  14649. }
  14650. // Using shaders to rescale because canvas.drawImage is lossy
  14651. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14652. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14653. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14654. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14655. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14656. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14657. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14658. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14659. _this._releaseTexture(source);
  14660. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14661. continuationCallback();
  14662. });
  14663. return true;
  14664. }, samplingMode);
  14665. };
  14666. if (!fromData || isBase64) {
  14667. if (buffer instanceof HTMLImageElement) {
  14668. onload(buffer);
  14669. }
  14670. else {
  14671. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14672. }
  14673. }
  14674. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14675. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14676. }
  14677. else {
  14678. onload(buffer);
  14679. }
  14680. }
  14681. return texture;
  14682. };
  14683. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14684. var _this = this;
  14685. var rtt = this.createRenderTargetTexture({
  14686. width: destination.width,
  14687. height: destination.height,
  14688. }, {
  14689. generateMipMaps: false,
  14690. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14691. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14692. generateDepthBuffer: false,
  14693. generateStencilBuffer: false
  14694. });
  14695. if (!this._rescalePostProcess) {
  14696. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14697. }
  14698. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14699. _this._rescalePostProcess.onApply = function (effect) {
  14700. effect._bindTexture("textureSampler", source);
  14701. };
  14702. var hostingScene = scene;
  14703. if (!hostingScene) {
  14704. hostingScene = _this.scenes[_this.scenes.length - 1];
  14705. }
  14706. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14707. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14708. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14709. _this.unBindFramebuffer(rtt);
  14710. _this._releaseTexture(rtt);
  14711. if (onComplete) {
  14712. onComplete();
  14713. }
  14714. });
  14715. };
  14716. /**
  14717. * Update a raw texture
  14718. * @param texture defines the texture to update
  14719. * @param data defines the data to store in the texture
  14720. * @param format defines the format of the data
  14721. * @param invertY defines if data must be stored with Y axis inverted
  14722. * @param compression defines the compression used (null by default)
  14723. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14724. */
  14725. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14726. if (compression === void 0) { compression = null; }
  14727. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14728. if (!texture) {
  14729. return;
  14730. }
  14731. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14732. var internalFormat = this._getInternalFormat(format);
  14733. var textureType = this._getWebGLTextureType(type);
  14734. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14735. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14736. if (!this._doNotHandleContextLost) {
  14737. texture._bufferView = data;
  14738. texture.format = format;
  14739. texture.type = type;
  14740. texture.invertY = invertY;
  14741. texture._compression = compression;
  14742. }
  14743. if (texture.width % 4 !== 0) {
  14744. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14745. }
  14746. if (compression && data) {
  14747. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14748. }
  14749. else {
  14750. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14751. }
  14752. if (texture.generateMipMaps) {
  14753. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14754. }
  14755. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14756. // this.resetTextureCache();
  14757. texture.isReady = true;
  14758. };
  14759. /**
  14760. * Creates a raw texture
  14761. * @param data defines the data to store in the texture
  14762. * @param width defines the width of the texture
  14763. * @param height defines the height of the texture
  14764. * @param format defines the format of the data
  14765. * @param generateMipMaps defines if the engine should generate the mip levels
  14766. * @param invertY defines if data must be stored with Y axis inverted
  14767. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14768. * @param compression defines the compression used (null by default)
  14769. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14770. * @returns the raw texture inside an InternalTexture
  14771. */
  14772. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14773. if (compression === void 0) { compression = null; }
  14774. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14775. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14776. texture.baseWidth = width;
  14777. texture.baseHeight = height;
  14778. texture.width = width;
  14779. texture.height = height;
  14780. texture.format = format;
  14781. texture.generateMipMaps = generateMipMaps;
  14782. texture.samplingMode = samplingMode;
  14783. texture.invertY = invertY;
  14784. texture._compression = compression;
  14785. texture.type = type;
  14786. if (!this._doNotHandleContextLost) {
  14787. texture._bufferView = data;
  14788. }
  14789. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14790. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14791. // Filters
  14792. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14793. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14794. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14795. if (generateMipMaps) {
  14796. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14797. }
  14798. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14799. this._internalTexturesCache.push(texture);
  14800. return texture;
  14801. };
  14802. /**
  14803. * Creates a dynamic texture
  14804. * @param width defines the width of the texture
  14805. * @param height defines the height of the texture
  14806. * @param generateMipMaps defines if the engine should generate the mip levels
  14807. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14808. * @returns the dynamic texture inside an InternalTexture
  14809. */
  14810. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14811. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14812. texture.baseWidth = width;
  14813. texture.baseHeight = height;
  14814. if (generateMipMaps) {
  14815. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14816. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14817. }
  14818. // this.resetTextureCache();
  14819. texture.width = width;
  14820. texture.height = height;
  14821. texture.isReady = false;
  14822. texture.generateMipMaps = generateMipMaps;
  14823. texture.samplingMode = samplingMode;
  14824. this.updateTextureSamplingMode(samplingMode, texture);
  14825. this._internalTexturesCache.push(texture);
  14826. return texture;
  14827. };
  14828. /**
  14829. * Update the sampling mode of a given texture
  14830. * @param samplingMode defines the required sampling mode
  14831. * @param texture defines the texture to update
  14832. */
  14833. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14834. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14835. if (texture.isCube) {
  14836. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14837. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14838. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14839. }
  14840. else if (texture.is3D) {
  14841. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14842. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14843. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14844. }
  14845. else {
  14846. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14847. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14848. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14849. }
  14850. texture.samplingMode = samplingMode;
  14851. };
  14852. /**
  14853. * Update the content of a dynamic texture
  14854. * @param texture defines the texture to update
  14855. * @param canvas defines the canvas containing the source
  14856. * @param invertY defines if data must be stored with Y axis inverted
  14857. * @param premulAlpha defines if alpha is stored as premultiplied
  14858. * @param format defines the format of the data
  14859. */
  14860. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14861. if (premulAlpha === void 0) { premulAlpha = false; }
  14862. if (!texture) {
  14863. return;
  14864. }
  14865. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14866. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14867. if (premulAlpha) {
  14868. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14869. }
  14870. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14871. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14872. if (texture.generateMipMaps) {
  14873. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14874. }
  14875. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14876. if (premulAlpha) {
  14877. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14878. }
  14879. texture.isReady = true;
  14880. };
  14881. /**
  14882. * Update a video texture
  14883. * @param texture defines the texture to update
  14884. * @param video defines the video element to use
  14885. * @param invertY defines if data must be stored with Y axis inverted
  14886. */
  14887. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14888. if (!texture || texture._isDisabled) {
  14889. return;
  14890. }
  14891. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14892. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14893. try {
  14894. // Testing video texture support
  14895. if (this._videoTextureSupported === undefined) {
  14896. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14897. if (this._gl.getError() !== 0) {
  14898. this._videoTextureSupported = false;
  14899. }
  14900. else {
  14901. this._videoTextureSupported = true;
  14902. }
  14903. }
  14904. // Copy video through the current working canvas if video texture is not supported
  14905. if (!this._videoTextureSupported) {
  14906. if (!texture._workingCanvas) {
  14907. texture._workingCanvas = document.createElement("canvas");
  14908. var context = texture._workingCanvas.getContext("2d");
  14909. if (!context) {
  14910. throw new Error("Unable to get 2d context");
  14911. }
  14912. texture._workingContext = context;
  14913. texture._workingCanvas.width = texture.width;
  14914. texture._workingCanvas.height = texture.height;
  14915. }
  14916. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14917. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14918. }
  14919. else {
  14920. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14921. }
  14922. if (texture.generateMipMaps) {
  14923. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14924. }
  14925. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14926. // this.resetTextureCache();
  14927. texture.isReady = true;
  14928. }
  14929. catch (ex) {
  14930. // Something unexpected
  14931. // Let's disable the texture
  14932. texture._isDisabled = true;
  14933. }
  14934. };
  14935. /**
  14936. * Updates a depth texture Comparison Mode and Function.
  14937. * If the comparison Function is equal to 0, the mode will be set to none.
  14938. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14939. * @param texture The texture to set the comparison function for
  14940. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14941. */
  14942. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14943. if (this.webGLVersion === 1) {
  14944. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14945. return;
  14946. }
  14947. var gl = this._gl;
  14948. if (texture.isCube) {
  14949. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14950. if (comparisonFunction === 0) {
  14951. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14952. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14953. }
  14954. else {
  14955. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14956. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14957. }
  14958. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14959. }
  14960. else {
  14961. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14962. if (comparisonFunction === 0) {
  14963. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14964. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14965. }
  14966. else {
  14967. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14968. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14969. }
  14970. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14971. }
  14972. texture._comparisonFunction = comparisonFunction;
  14973. };
  14974. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14975. var width = size.width || size;
  14976. var height = size.height || size;
  14977. internalTexture.baseWidth = width;
  14978. internalTexture.baseHeight = height;
  14979. internalTexture.width = width;
  14980. internalTexture.height = height;
  14981. internalTexture.isReady = true;
  14982. internalTexture.samples = 1;
  14983. internalTexture.generateMipMaps = false;
  14984. internalTexture._generateDepthBuffer = true;
  14985. internalTexture._generateStencilBuffer = generateStencil;
  14986. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14987. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14988. internalTexture._comparisonFunction = comparisonFunction;
  14989. var gl = this._gl;
  14990. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14991. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14992. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14993. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14994. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14995. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14996. if (comparisonFunction === 0) {
  14997. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14998. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14999. }
  15000. else {
  15001. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15002. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15003. }
  15004. };
  15005. /**
  15006. * Creates a depth stencil texture.
  15007. * This is only available in WebGL 2 or with the depth texture extension available.
  15008. * @param size The size of face edge in the texture.
  15009. * @param options The options defining the texture.
  15010. * @returns The texture
  15011. */
  15012. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15013. if (options.isCube) {
  15014. var width = size.width || size;
  15015. return this._createDepthStencilCubeTexture(width, options);
  15016. }
  15017. else {
  15018. return this._createDepthStencilTexture(size, options);
  15019. }
  15020. };
  15021. /**
  15022. * Creates a depth stencil texture.
  15023. * This is only available in WebGL 2 or with the depth texture extension available.
  15024. * @param size The size of face edge in the texture.
  15025. * @param options The options defining the texture.
  15026. * @returns The texture
  15027. */
  15028. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15029. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15030. if (!this._caps.depthTextureExtension) {
  15031. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15032. return internalTexture;
  15033. }
  15034. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15035. var gl = this._gl;
  15036. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15037. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15038. if (this.webGLVersion > 1) {
  15039. if (internalOptions.generateStencil) {
  15040. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15041. }
  15042. else {
  15043. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15044. }
  15045. }
  15046. else {
  15047. if (internalOptions.generateStencil) {
  15048. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15049. }
  15050. else {
  15051. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15052. }
  15053. }
  15054. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15055. return internalTexture;
  15056. };
  15057. /**
  15058. * Creates a depth stencil cube texture.
  15059. * This is only available in WebGL 2.
  15060. * @param size The size of face edge in the cube texture.
  15061. * @param options The options defining the cube texture.
  15062. * @returns The cube texture
  15063. */
  15064. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15065. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15066. internalTexture.isCube = true;
  15067. if (this.webGLVersion === 1) {
  15068. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15069. return internalTexture;
  15070. }
  15071. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15072. var gl = this._gl;
  15073. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15074. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15075. // Create the depth/stencil buffer
  15076. for (var face = 0; face < 6; face++) {
  15077. if (internalOptions.generateStencil) {
  15078. 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);
  15079. }
  15080. else {
  15081. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15082. }
  15083. }
  15084. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15085. return internalTexture;
  15086. };
  15087. /**
  15088. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15089. * @param renderTarget The render target to set the frame buffer for
  15090. */
  15091. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15092. // Create the framebuffer
  15093. var internalTexture = renderTarget.getInternalTexture();
  15094. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15095. return;
  15096. }
  15097. var gl = this._gl;
  15098. var depthStencilTexture = renderTarget.depthStencilTexture;
  15099. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15100. if (depthStencilTexture.isCube) {
  15101. if (depthStencilTexture._generateStencilBuffer) {
  15102. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15103. }
  15104. else {
  15105. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15106. }
  15107. }
  15108. else {
  15109. if (depthStencilTexture._generateStencilBuffer) {
  15110. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15111. }
  15112. else {
  15113. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15114. }
  15115. }
  15116. this.bindUnboundFramebuffer(null);
  15117. };
  15118. /**
  15119. * Creates a new render target texture
  15120. * @param size defines the size of the texture
  15121. * @param options defines the options used to create the texture
  15122. * @returns a new render target texture stored in an InternalTexture
  15123. */
  15124. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15125. var fullOptions = new RenderTargetCreationOptions();
  15126. if (options !== undefined && typeof options === "object") {
  15127. fullOptions.generateMipMaps = options.generateMipMaps;
  15128. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15129. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15130. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15131. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15132. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15133. }
  15134. else {
  15135. fullOptions.generateMipMaps = options;
  15136. fullOptions.generateDepthBuffer = true;
  15137. fullOptions.generateStencilBuffer = false;
  15138. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15139. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15140. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15141. }
  15142. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15143. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15144. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15145. }
  15146. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15147. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15148. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15149. }
  15150. var gl = this._gl;
  15151. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15152. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15153. var width = size.width || size;
  15154. var height = size.height || size;
  15155. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15156. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15157. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15158. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15159. }
  15160. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15161. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15162. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15163. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15164. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15165. // Create the framebuffer
  15166. var currentFrameBuffer = this._currentFramebuffer;
  15167. var framebuffer = gl.createFramebuffer();
  15168. this.bindUnboundFramebuffer(framebuffer);
  15169. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15170. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15171. if (fullOptions.generateMipMaps) {
  15172. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15173. }
  15174. // Unbind
  15175. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15176. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15177. this.bindUnboundFramebuffer(currentFrameBuffer);
  15178. texture._framebuffer = framebuffer;
  15179. texture.baseWidth = width;
  15180. texture.baseHeight = height;
  15181. texture.width = width;
  15182. texture.height = height;
  15183. texture.isReady = true;
  15184. texture.samples = 1;
  15185. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15186. texture.samplingMode = fullOptions.samplingMode;
  15187. texture.type = fullOptions.type;
  15188. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15189. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15190. // this.resetTextureCache();
  15191. this._internalTexturesCache.push(texture);
  15192. return texture;
  15193. };
  15194. /**
  15195. * Create a multi render target texture
  15196. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15197. * @param size defines the size of the texture
  15198. * @param options defines the creation options
  15199. * @returns the cube texture as an InternalTexture
  15200. */
  15201. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15202. var generateMipMaps = false;
  15203. var generateDepthBuffer = true;
  15204. var generateStencilBuffer = false;
  15205. var generateDepthTexture = false;
  15206. var textureCount = 1;
  15207. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15208. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15209. var types = new Array();
  15210. var samplingModes = new Array();
  15211. if (options !== undefined) {
  15212. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15213. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15214. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15215. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15216. textureCount = options.textureCount || 1;
  15217. if (options.types) {
  15218. types = options.types;
  15219. }
  15220. if (options.samplingModes) {
  15221. samplingModes = options.samplingModes;
  15222. }
  15223. }
  15224. var gl = this._gl;
  15225. // Create the framebuffer
  15226. var framebuffer = gl.createFramebuffer();
  15227. this.bindUnboundFramebuffer(framebuffer);
  15228. var width = size.width || size;
  15229. var height = size.height || size;
  15230. var textures = [];
  15231. var attachments = [];
  15232. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15233. for (var i = 0; i < textureCount; i++) {
  15234. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15235. var type = types[i] || defaultType;
  15236. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15237. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15238. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15239. }
  15240. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15241. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15242. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15243. }
  15244. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15245. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15246. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15247. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15248. }
  15249. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15250. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15251. textures.push(texture);
  15252. attachments.push(attachment);
  15253. gl.activeTexture(gl["TEXTURE" + i]);
  15254. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15255. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15256. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15257. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15258. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15259. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15260. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15261. if (generateMipMaps) {
  15262. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15263. }
  15264. // Unbind
  15265. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15266. texture._framebuffer = framebuffer;
  15267. texture._depthStencilBuffer = depthStencilBuffer;
  15268. texture.baseWidth = width;
  15269. texture.baseHeight = height;
  15270. texture.width = width;
  15271. texture.height = height;
  15272. texture.isReady = true;
  15273. texture.samples = 1;
  15274. texture.generateMipMaps = generateMipMaps;
  15275. texture.samplingMode = samplingMode;
  15276. texture.type = type;
  15277. texture._generateDepthBuffer = generateDepthBuffer;
  15278. texture._generateStencilBuffer = generateStencilBuffer;
  15279. texture._attachments = attachments;
  15280. this._internalTexturesCache.push(texture);
  15281. }
  15282. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15283. // Depth texture
  15284. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15285. gl.activeTexture(gl.TEXTURE0);
  15286. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15287. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15288. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15289. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15290. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15291. 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);
  15292. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15293. depthTexture._framebuffer = framebuffer;
  15294. depthTexture.baseWidth = width;
  15295. depthTexture.baseHeight = height;
  15296. depthTexture.width = width;
  15297. depthTexture.height = height;
  15298. depthTexture.isReady = true;
  15299. depthTexture.samples = 1;
  15300. depthTexture.generateMipMaps = generateMipMaps;
  15301. depthTexture.samplingMode = gl.NEAREST;
  15302. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15303. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15304. textures.push(depthTexture);
  15305. this._internalTexturesCache.push(depthTexture);
  15306. }
  15307. gl.drawBuffers(attachments);
  15308. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15309. this.bindUnboundFramebuffer(null);
  15310. this.resetTextureCache();
  15311. return textures;
  15312. };
  15313. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15314. if (samples === void 0) { samples = 1; }
  15315. var depthStencilBuffer = null;
  15316. var gl = this._gl;
  15317. // Create the depth/stencil buffer
  15318. if (generateStencilBuffer) {
  15319. depthStencilBuffer = gl.createRenderbuffer();
  15320. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15321. if (samples > 1) {
  15322. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15323. }
  15324. else {
  15325. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15326. }
  15327. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15328. }
  15329. else if (generateDepthBuffer) {
  15330. depthStencilBuffer = gl.createRenderbuffer();
  15331. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15332. if (samples > 1) {
  15333. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15334. }
  15335. else {
  15336. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15337. }
  15338. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15339. }
  15340. return depthStencilBuffer;
  15341. };
  15342. /**
  15343. * Updates the sample count of a render target texture
  15344. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15345. * @param texture defines the texture to update
  15346. * @param samples defines the sample count to set
  15347. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15348. */
  15349. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15350. if (this.webGLVersion < 2 || !texture) {
  15351. return 1;
  15352. }
  15353. if (texture.samples === samples) {
  15354. return samples;
  15355. }
  15356. var gl = this._gl;
  15357. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15358. // Dispose previous render buffers
  15359. if (texture._depthStencilBuffer) {
  15360. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15361. texture._depthStencilBuffer = null;
  15362. }
  15363. if (texture._MSAAFramebuffer) {
  15364. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15365. texture._MSAAFramebuffer = null;
  15366. }
  15367. if (texture._MSAARenderBuffer) {
  15368. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15369. texture._MSAARenderBuffer = null;
  15370. }
  15371. if (samples > 1) {
  15372. var framebuffer = gl.createFramebuffer();
  15373. if (!framebuffer) {
  15374. throw new Error("Unable to create multi sampled framebuffer");
  15375. }
  15376. texture._MSAAFramebuffer = framebuffer;
  15377. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  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, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15385. texture._MSAARenderBuffer = colorRenderbuffer;
  15386. }
  15387. else {
  15388. this.bindUnboundFramebuffer(texture._framebuffer);
  15389. }
  15390. texture.samples = samples;
  15391. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15392. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15393. this.bindUnboundFramebuffer(null);
  15394. return samples;
  15395. };
  15396. /**
  15397. * Update the sample count for a given multiple render target texture
  15398. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15399. * @param textures defines the textures to update
  15400. * @param samples defines the sample count to set
  15401. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15402. */
  15403. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15404. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15405. return 1;
  15406. }
  15407. if (textures[0].samples === samples) {
  15408. return samples;
  15409. }
  15410. var gl = this._gl;
  15411. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15412. // Dispose previous render buffers
  15413. if (textures[0]._depthStencilBuffer) {
  15414. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15415. textures[0]._depthStencilBuffer = null;
  15416. }
  15417. if (textures[0]._MSAAFramebuffer) {
  15418. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15419. textures[0]._MSAAFramebuffer = null;
  15420. }
  15421. for (var i = 0; i < textures.length; i++) {
  15422. if (textures[i]._MSAARenderBuffer) {
  15423. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15424. textures[i]._MSAARenderBuffer = null;
  15425. }
  15426. }
  15427. if (samples > 1) {
  15428. var framebuffer = gl.createFramebuffer();
  15429. if (!framebuffer) {
  15430. throw new Error("Unable to create multi sampled framebuffer");
  15431. }
  15432. this.bindUnboundFramebuffer(framebuffer);
  15433. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15434. var attachments = [];
  15435. for (var i = 0; i < textures.length; i++) {
  15436. var texture = textures[i];
  15437. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15438. var colorRenderbuffer = gl.createRenderbuffer();
  15439. if (!colorRenderbuffer) {
  15440. throw new Error("Unable to create multi sampled framebuffer");
  15441. }
  15442. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15443. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15444. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15445. texture._MSAAFramebuffer = framebuffer;
  15446. texture._MSAARenderBuffer = colorRenderbuffer;
  15447. texture.samples = samples;
  15448. texture._depthStencilBuffer = depthStencilBuffer;
  15449. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15450. attachments.push(attachment);
  15451. }
  15452. gl.drawBuffers(attachments);
  15453. }
  15454. else {
  15455. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15456. }
  15457. this.bindUnboundFramebuffer(null);
  15458. return samples;
  15459. };
  15460. /** @hidden */
  15461. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15462. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15463. };
  15464. /** @hidden */
  15465. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15466. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15467. };
  15468. /**
  15469. * Creates a new render target cube texture
  15470. * @param size defines the size of the texture
  15471. * @param options defines the options used to create the texture
  15472. * @returns a new render target cube texture stored in an InternalTexture
  15473. */
  15474. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15475. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15476. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15477. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15478. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15479. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15480. }
  15481. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15482. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15483. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15484. }
  15485. var gl = this._gl;
  15486. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15487. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15488. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15489. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15490. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15491. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15492. }
  15493. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15494. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15495. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15496. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15497. for (var face = 0; face < 6; face++) {
  15498. 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);
  15499. }
  15500. // Create the framebuffer
  15501. var framebuffer = gl.createFramebuffer();
  15502. this.bindUnboundFramebuffer(framebuffer);
  15503. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15504. // MipMaps
  15505. if (fullOptions.generateMipMaps) {
  15506. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15507. }
  15508. // Unbind
  15509. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15510. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15511. this.bindUnboundFramebuffer(null);
  15512. texture._framebuffer = framebuffer;
  15513. texture.width = size;
  15514. texture.height = size;
  15515. texture.isReady = true;
  15516. texture.isCube = true;
  15517. texture.samples = 1;
  15518. texture.generateMipMaps = fullOptions.generateMipMaps;
  15519. texture.samplingMode = fullOptions.samplingMode;
  15520. texture.type = fullOptions.type;
  15521. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15522. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15523. this._internalTexturesCache.push(texture);
  15524. return texture;
  15525. };
  15526. /**
  15527. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15528. * @param rootUrl defines the url where the file to load is located
  15529. * @param scene defines the current scene
  15530. * @param scale defines scale to apply to the mip map selection
  15531. * @param offset defines offset to apply to the mip map selection
  15532. * @param onLoad defines an optional callback raised when the texture is loaded
  15533. * @param onError defines an optional callback raised if there is an issue to load the texture
  15534. * @param format defines the format of the data
  15535. * @param forcedExtension defines the extension to use to pick the right loader
  15536. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15537. * @returns the cube texture as an InternalTexture
  15538. */
  15539. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15540. var _this = this;
  15541. if (onLoad === void 0) { onLoad = null; }
  15542. if (onError === void 0) { onError = null; }
  15543. if (forcedExtension === void 0) { forcedExtension = null; }
  15544. if (createPolynomials === void 0) { createPolynomials = true; }
  15545. var callback = function (loadData) {
  15546. if (!loadData) {
  15547. if (onLoad) {
  15548. onLoad(null);
  15549. }
  15550. return;
  15551. }
  15552. var texture = loadData.texture;
  15553. if (!createPolynomials) {
  15554. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15555. }
  15556. else if (loadData.info.sphericalPolynomial) {
  15557. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15558. }
  15559. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15560. texture._lodGenerationScale = scale;
  15561. texture._lodGenerationOffset = offset;
  15562. if (_this._caps.textureLOD) {
  15563. // Do not add extra process if texture lod is supported.
  15564. if (onLoad) {
  15565. onLoad(texture);
  15566. }
  15567. return;
  15568. }
  15569. var mipSlices = 3;
  15570. var gl = _this._gl;
  15571. var width = loadData.width;
  15572. if (!width) {
  15573. return;
  15574. }
  15575. var textures = [];
  15576. for (var i = 0; i < mipSlices; i++) {
  15577. //compute LOD from even spacing in smoothness (matching shader calculation)
  15578. var smoothness = i / (mipSlices - 1);
  15579. var roughness = 1 - smoothness;
  15580. var minLODIndex = offset; // roughness = 0
  15581. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15582. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15583. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15584. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15585. glTextureFromLod.isCube = true;
  15586. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15587. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15588. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15589. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15590. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15591. if (loadData.isDDS) {
  15592. var info = loadData.info;
  15593. var data = loadData.data;
  15594. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15595. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15596. }
  15597. else {
  15598. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15599. }
  15600. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15601. // Wrap in a base texture for easy binding.
  15602. var lodTexture = new BABYLON.BaseTexture(scene);
  15603. lodTexture.isCube = true;
  15604. lodTexture._texture = glTextureFromLod;
  15605. glTextureFromLod.isReady = true;
  15606. textures.push(lodTexture);
  15607. }
  15608. texture._lodTextureHigh = textures[2];
  15609. texture._lodTextureMid = textures[1];
  15610. texture._lodTextureLow = textures[0];
  15611. if (onLoad) {
  15612. onLoad(texture);
  15613. }
  15614. };
  15615. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials);
  15616. };
  15617. /**
  15618. * Creates a cube texture
  15619. * @param rootUrl defines the url where the files to load is located
  15620. * @param scene defines the current scene
  15621. * @param files defines the list of files to load (1 per face)
  15622. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15623. * @param onLoad defines an optional callback raised when the texture is loaded
  15624. * @param onError defines an optional callback raised if there is an issue to load the texture
  15625. * @param format defines the format of the data
  15626. * @param forcedExtension defines the extension to use to pick the right loader
  15627. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15628. * @returns the cube texture as an InternalTexture
  15629. */
  15630. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15631. var _this = this;
  15632. if (onLoad === void 0) { onLoad = null; }
  15633. if (onError === void 0) { onError = null; }
  15634. if (forcedExtension === void 0) { forcedExtension = null; }
  15635. if (createPolynomials === void 0) { createPolynomials = false; }
  15636. var gl = this._gl;
  15637. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15638. texture.isCube = true;
  15639. texture.url = rootUrl;
  15640. texture.generateMipMaps = !noMipmap;
  15641. if (!this._doNotHandleContextLost) {
  15642. texture._extension = forcedExtension;
  15643. texture._files = files;
  15644. }
  15645. var isKTX = false;
  15646. var isDDS = false;
  15647. var lastDot = rootUrl.lastIndexOf('.');
  15648. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15649. if (this._textureFormatInUse) {
  15650. extension = this._textureFormatInUse;
  15651. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15652. isKTX = true;
  15653. }
  15654. else {
  15655. isDDS = (extension === ".dds");
  15656. }
  15657. var onerror = function (request, exception) {
  15658. if (onError && request) {
  15659. onError(request.status + " " + request.statusText, exception);
  15660. }
  15661. };
  15662. if (isKTX) {
  15663. this._loadFile(rootUrl, function (data) {
  15664. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15665. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15666. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15667. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15668. ktx.uploadLevels(_this._gl, !noMipmap);
  15669. _this.setCubeMapTextureParams(gl, loadMipmap);
  15670. texture.width = ktx.pixelWidth;
  15671. texture.height = ktx.pixelHeight;
  15672. texture.isReady = true;
  15673. }, undefined, undefined, true, onerror);
  15674. }
  15675. else if (isDDS) {
  15676. if (files && files.length === 6) {
  15677. this._cascadeLoadFiles(scene, function (imgs) {
  15678. var info;
  15679. var loadMipmap = false;
  15680. var width = 0;
  15681. for (var index = 0; index < imgs.length; index++) {
  15682. var data = imgs[index];
  15683. info = BABYLON.DDSTools.GetDDSInfo(data);
  15684. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15685. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15686. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15687. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15688. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15689. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15690. }
  15691. texture.width = info.width;
  15692. texture.height = info.height;
  15693. texture.type = info.textureType;
  15694. width = info.width;
  15695. }
  15696. _this.setCubeMapTextureParams(gl, loadMipmap);
  15697. texture.isReady = true;
  15698. if (onLoad) {
  15699. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15700. }
  15701. }, files, onError);
  15702. }
  15703. else {
  15704. this._loadFile(rootUrl, function (data) {
  15705. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15706. if (createPolynomials) {
  15707. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15708. }
  15709. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15710. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15711. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15712. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15713. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15714. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15715. }
  15716. _this.setCubeMapTextureParams(gl, loadMipmap);
  15717. texture.width = info.width;
  15718. texture.height = info.height;
  15719. texture.isReady = true;
  15720. texture.type = info.textureType;
  15721. if (onLoad) {
  15722. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15723. }
  15724. }, undefined, undefined, true, onerror);
  15725. }
  15726. }
  15727. else {
  15728. if (!files) {
  15729. throw new Error("Cannot load cubemap because files were not defined");
  15730. }
  15731. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15732. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15733. var height = width;
  15734. _this._prepareWorkingCanvas();
  15735. if (!_this._workingCanvas || !_this._workingContext) {
  15736. return;
  15737. }
  15738. _this._workingCanvas.width = width;
  15739. _this._workingCanvas.height = height;
  15740. var faces = [
  15741. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15742. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15743. ];
  15744. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15745. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15746. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15747. for (var index = 0; index < faces.length; index++) {
  15748. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15749. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15750. }
  15751. if (!noMipmap) {
  15752. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15753. }
  15754. _this.setCubeMapTextureParams(gl, !noMipmap);
  15755. texture.width = width;
  15756. texture.height = height;
  15757. texture.isReady = true;
  15758. if (format) {
  15759. texture.format = format;
  15760. }
  15761. texture.onLoadedObservable.notifyObservers(texture);
  15762. texture.onLoadedObservable.clear();
  15763. if (onLoad) {
  15764. onLoad();
  15765. }
  15766. }, files, onError);
  15767. }
  15768. this._internalTexturesCache.push(texture);
  15769. return texture;
  15770. };
  15771. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15772. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15773. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15774. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15775. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15776. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15777. // this.resetTextureCache();
  15778. };
  15779. /**
  15780. * Update a raw cube texture
  15781. * @param texture defines the texture to udpdate
  15782. * @param data defines the data to store
  15783. * @param format defines the data format
  15784. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15785. * @param invertY defines if data must be stored with Y axis inverted
  15786. * @param compression defines the compression used (null by default)
  15787. * @param level defines which level of the texture to update
  15788. */
  15789. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15790. if (compression === void 0) { compression = null; }
  15791. if (level === void 0) { level = 0; }
  15792. texture._bufferViewArray = data;
  15793. texture.format = format;
  15794. texture.type = type;
  15795. texture.invertY = invertY;
  15796. texture._compression = compression;
  15797. var gl = this._gl;
  15798. var textureType = this._getWebGLTextureType(type);
  15799. var internalFormat = this._getInternalFormat(format);
  15800. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15801. var needConversion = false;
  15802. if (internalFormat === gl.RGB) {
  15803. internalFormat = gl.RGBA;
  15804. needConversion = true;
  15805. }
  15806. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15807. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15808. if (texture.width % 4 !== 0) {
  15809. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15810. }
  15811. // Data are known to be in +X +Y +Z -X -Y -Z
  15812. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15813. var faceData = data[faceIndex];
  15814. if (compression) {
  15815. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15816. }
  15817. else {
  15818. if (needConversion) {
  15819. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15820. }
  15821. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15822. }
  15823. }
  15824. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15825. if (isPot && texture.generateMipMaps && level === 0) {
  15826. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15827. }
  15828. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15829. // this.resetTextureCache();
  15830. texture.isReady = true;
  15831. };
  15832. /**
  15833. * Creates a new raw cube texture
  15834. * @param data defines the array of data to use to create each face
  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 generateMipMaps defines if the engine should generate the mip levels
  15839. * @param invertY defines if data must be stored with Y axis inverted
  15840. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15841. * @param compression defines the compression used (null by default)
  15842. * @returns the cube texture as an InternalTexture
  15843. */
  15844. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15845. if (compression === void 0) { compression = null; }
  15846. var gl = this._gl;
  15847. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15848. texture.isCube = true;
  15849. texture.generateMipMaps = generateMipMaps;
  15850. texture.format = format;
  15851. texture.type = type;
  15852. if (!this._doNotHandleContextLost) {
  15853. texture._bufferViewArray = data;
  15854. }
  15855. var textureType = this._getWebGLTextureType(type);
  15856. var internalFormat = this._getInternalFormat(format);
  15857. if (internalFormat === gl.RGB) {
  15858. internalFormat = gl.RGBA;
  15859. }
  15860. var width = size;
  15861. var height = width;
  15862. texture.width = width;
  15863. texture.height = height;
  15864. // Double check on POT to generate Mips.
  15865. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15866. if (!isPot) {
  15867. generateMipMaps = false;
  15868. }
  15869. // Upload data if needed. The texture won't be ready until then.
  15870. if (data) {
  15871. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15872. }
  15873. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15874. // Filters
  15875. if (data && generateMipMaps) {
  15876. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15877. }
  15878. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15879. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15880. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15881. }
  15882. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15883. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15884. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15885. }
  15886. else {
  15887. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15888. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15889. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15890. }
  15891. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15892. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15893. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15894. return texture;
  15895. };
  15896. /**
  15897. * Creates a new raw cube texture from a specified url
  15898. * @param url defines the url where the data is located
  15899. * @param scene defines the current scene
  15900. * @param size defines the size of the textures
  15901. * @param format defines the format of the data
  15902. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15903. * @param noMipmap defines if the engine should avoid generating the mip levels
  15904. * @param callback defines a callback used to extract texture data from loaded data
  15905. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15906. * @param onLoad defines a callback called when texture is loaded
  15907. * @param onError defines a callback called if there is an error
  15908. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15909. * @param invertY defines if data must be stored with Y axis inverted
  15910. * @returns the cube texture as an InternalTexture
  15911. */
  15912. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15913. var _this = this;
  15914. if (onLoad === void 0) { onLoad = null; }
  15915. if (onError === void 0) { onError = null; }
  15916. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15917. if (invertY === void 0) { invertY = false; }
  15918. var gl = this._gl;
  15919. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15920. scene._addPendingData(texture);
  15921. texture.url = url;
  15922. this._internalTexturesCache.push(texture);
  15923. var onerror = function (request, exception) {
  15924. scene._removePendingData(texture);
  15925. if (onError && request) {
  15926. onError(request.status + " " + request.statusText, exception);
  15927. }
  15928. };
  15929. var internalCallback = function (data) {
  15930. var width = texture.width;
  15931. var faceDataArrays = callback(data);
  15932. if (!faceDataArrays) {
  15933. return;
  15934. }
  15935. if (mipmapGenerator) {
  15936. var textureType = _this._getWebGLTextureType(type);
  15937. var internalFormat = _this._getInternalFormat(format);
  15938. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15939. var needConversion = false;
  15940. if (internalFormat === gl.RGB) {
  15941. internalFormat = gl.RGBA;
  15942. needConversion = true;
  15943. }
  15944. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15945. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15946. var mipData = mipmapGenerator(faceDataArrays);
  15947. for (var level = 0; level < mipData.length; level++) {
  15948. var mipSize = width >> level;
  15949. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15950. var mipFaceData = mipData[level][faceIndex];
  15951. if (needConversion) {
  15952. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15953. }
  15954. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15955. }
  15956. }
  15957. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15958. }
  15959. else {
  15960. texture.generateMipMaps = !noMipmap;
  15961. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15962. }
  15963. texture.isReady = true;
  15964. // this.resetTextureCache();
  15965. scene._removePendingData(texture);
  15966. if (onLoad) {
  15967. onLoad();
  15968. }
  15969. };
  15970. this._loadFile(url, function (data) {
  15971. internalCallback(data);
  15972. }, undefined, scene.database, true, onerror);
  15973. return texture;
  15974. };
  15975. ;
  15976. /**
  15977. * Update a raw 3D texture
  15978. * @param texture defines the texture to update
  15979. * @param data defines the data to store
  15980. * @param format defines the data format
  15981. * @param invertY defines if data must be stored with Y axis inverted
  15982. * @param compression defines the used compression (can be null)
  15983. */
  15984. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15985. if (compression === void 0) { compression = null; }
  15986. var internalFormat = this._getInternalFormat(format);
  15987. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15988. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15989. if (!this._doNotHandleContextLost) {
  15990. texture._bufferView = data;
  15991. texture.format = format;
  15992. texture.invertY = invertY;
  15993. texture._compression = compression;
  15994. }
  15995. if (texture.width % 4 !== 0) {
  15996. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15997. }
  15998. if (compression && data) {
  15999. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16000. }
  16001. else {
  16002. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  16003. }
  16004. if (texture.generateMipMaps) {
  16005. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16006. }
  16007. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16008. // this.resetTextureCache();
  16009. texture.isReady = true;
  16010. };
  16011. /**
  16012. * Creates a new raw 3D texture
  16013. * @param data defines the data used to create the texture
  16014. * @param width defines the width of the texture
  16015. * @param height defines the height of the texture
  16016. * @param depth defines the depth of the texture
  16017. * @param format defines the format of the texture
  16018. * @param generateMipMaps defines if the engine must generate mip levels
  16019. * @param invertY defines if data must be stored with Y axis inverted
  16020. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16021. * @param compression defines the compressed used (can be null)
  16022. * @returns a new raw 3D texture (stored in an InternalTexture)
  16023. */
  16024. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  16025. if (compression === void 0) { compression = null; }
  16026. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16027. texture.baseWidth = width;
  16028. texture.baseHeight = height;
  16029. texture.baseDepth = depth;
  16030. texture.width = width;
  16031. texture.height = height;
  16032. texture.depth = depth;
  16033. texture.format = format;
  16034. texture.generateMipMaps = generateMipMaps;
  16035. texture.samplingMode = samplingMode;
  16036. texture.is3D = true;
  16037. if (!this._doNotHandleContextLost) {
  16038. texture._bufferView = data;
  16039. }
  16040. this.updateRawTexture3D(texture, data, format, invertY, compression);
  16041. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16042. // Filters
  16043. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16044. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16045. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16046. if (generateMipMaps) {
  16047. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16048. }
  16049. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16050. this._internalTexturesCache.push(texture);
  16051. return texture;
  16052. };
  16053. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16054. var gl = this._gl;
  16055. if (!gl) {
  16056. return;
  16057. }
  16058. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16059. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16060. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16061. if (!noMipmap && !isCompressed) {
  16062. gl.generateMipmap(gl.TEXTURE_2D);
  16063. }
  16064. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16065. // this.resetTextureCache();
  16066. if (scene) {
  16067. scene._removePendingData(texture);
  16068. }
  16069. texture.onLoadedObservable.notifyObservers(texture);
  16070. texture.onLoadedObservable.clear();
  16071. };
  16072. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16073. var _this = this;
  16074. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16075. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16076. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16077. var gl = this._gl;
  16078. if (!gl) {
  16079. return;
  16080. }
  16081. if (!texture._webGLTexture) {
  16082. // this.resetTextureCache();
  16083. if (scene) {
  16084. scene._removePendingData(texture);
  16085. }
  16086. return;
  16087. }
  16088. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16089. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16090. texture.baseWidth = width;
  16091. texture.baseHeight = height;
  16092. texture.width = potWidth;
  16093. texture.height = potHeight;
  16094. texture.isReady = true;
  16095. if (processFunction(potWidth, potHeight, function () {
  16096. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16097. })) {
  16098. // Returning as texture needs extra async steps
  16099. return;
  16100. }
  16101. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16102. };
  16103. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16104. // Create new RGBA data container.
  16105. var rgbaData;
  16106. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16107. rgbaData = new Float32Array(width * height * 4);
  16108. }
  16109. else {
  16110. rgbaData = new Uint32Array(width * height * 4);
  16111. }
  16112. // Convert each pixel.
  16113. for (var x = 0; x < width; x++) {
  16114. for (var y = 0; y < height; y++) {
  16115. var index = (y * width + x) * 3;
  16116. var newIndex = (y * width + x) * 4;
  16117. // Map Old Value to new value.
  16118. rgbaData[newIndex + 0] = rgbData[index + 0];
  16119. rgbaData[newIndex + 1] = rgbData[index + 1];
  16120. rgbaData[newIndex + 2] = rgbData[index + 2];
  16121. // Add fully opaque alpha channel.
  16122. rgbaData[newIndex + 3] = 1;
  16123. }
  16124. }
  16125. return rgbaData;
  16126. };
  16127. /** @hidden */
  16128. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16129. var gl = this._gl;
  16130. if (texture._framebuffer) {
  16131. gl.deleteFramebuffer(texture._framebuffer);
  16132. texture._framebuffer = null;
  16133. }
  16134. if (texture._depthStencilBuffer) {
  16135. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16136. texture._depthStencilBuffer = null;
  16137. }
  16138. if (texture._MSAAFramebuffer) {
  16139. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16140. texture._MSAAFramebuffer = null;
  16141. }
  16142. if (texture._MSAARenderBuffer) {
  16143. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16144. texture._MSAARenderBuffer = null;
  16145. }
  16146. };
  16147. /** @hidden */
  16148. Engine.prototype._releaseTexture = function (texture) {
  16149. var gl = this._gl;
  16150. this._releaseFramebufferObjects(texture);
  16151. gl.deleteTexture(texture._webGLTexture);
  16152. // Unbind channels
  16153. this.unbindAllTextures();
  16154. var index = this._internalTexturesCache.indexOf(texture);
  16155. if (index !== -1) {
  16156. this._internalTexturesCache.splice(index, 1);
  16157. }
  16158. // Integrated fixed lod samplers.
  16159. if (texture._lodTextureHigh) {
  16160. texture._lodTextureHigh.dispose();
  16161. }
  16162. if (texture._lodTextureMid) {
  16163. texture._lodTextureMid.dispose();
  16164. }
  16165. if (texture._lodTextureLow) {
  16166. texture._lodTextureLow.dispose();
  16167. }
  16168. // Set output texture of post process to null if the texture has been released/disposed
  16169. this.scenes.forEach(function (scene) {
  16170. scene.postProcesses.forEach(function (postProcess) {
  16171. if (postProcess._outputTexture == texture) {
  16172. postProcess._outputTexture = null;
  16173. }
  16174. });
  16175. scene.cameras.forEach(function (camera) {
  16176. camera._postProcesses.forEach(function (postProcess) {
  16177. if (postProcess) {
  16178. if (postProcess._outputTexture == texture) {
  16179. postProcess._outputTexture = null;
  16180. }
  16181. }
  16182. });
  16183. });
  16184. });
  16185. };
  16186. Engine.prototype.setProgram = function (program) {
  16187. if (this._currentProgram !== program) {
  16188. this._gl.useProgram(program);
  16189. this._currentProgram = program;
  16190. }
  16191. };
  16192. /**
  16193. * Binds an effect to the webGL context
  16194. * @param effect defines the effect to bind
  16195. */
  16196. Engine.prototype.bindSamplers = function (effect) {
  16197. this.setProgram(effect.getProgram());
  16198. var samplers = effect.getSamplers();
  16199. for (var index = 0; index < samplers.length; index++) {
  16200. var uniform = effect.getUniform(samplers[index]);
  16201. if (uniform) {
  16202. this._boundUniforms[index] = uniform;
  16203. }
  16204. }
  16205. this._currentEffect = null;
  16206. };
  16207. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16208. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16209. return;
  16210. }
  16211. // Remove
  16212. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16213. // Bind last to it
  16214. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16215. // Bind to dummy
  16216. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16217. };
  16218. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16219. if (!internalTexture) {
  16220. return -1;
  16221. }
  16222. internalTexture._initialSlot = channel;
  16223. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16224. if (channel !== internalTexture._designatedSlot) {
  16225. this._textureCollisions.addCount(1, false);
  16226. }
  16227. }
  16228. else {
  16229. if (channel !== internalTexture._designatedSlot) {
  16230. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16231. return internalTexture._designatedSlot;
  16232. }
  16233. else {
  16234. // No slot for this texture, let's pick a new one (if we find a free slot)
  16235. if (this._nextFreeTextureSlots.length) {
  16236. return this._nextFreeTextureSlots[0];
  16237. }
  16238. // We need to recycle the oldest bound texture, sorry.
  16239. this._textureCollisions.addCount(1, false);
  16240. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16241. }
  16242. }
  16243. }
  16244. return channel;
  16245. };
  16246. Engine.prototype._linkTrackers = function (previous, next) {
  16247. previous.next = next;
  16248. next.previous = previous;
  16249. };
  16250. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16251. var currentSlot = internalTexture._designatedSlot;
  16252. if (currentSlot === -1) {
  16253. return -1;
  16254. }
  16255. internalTexture._designatedSlot = -1;
  16256. if (this.disableTextureBindingOptimization) {
  16257. return -1;
  16258. }
  16259. // Remove from bound list
  16260. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16261. // Free the slot
  16262. this._boundTexturesCache[currentSlot] = null;
  16263. this._nextFreeTextureSlots.push(currentSlot);
  16264. return currentSlot;
  16265. };
  16266. Engine.prototype._activateCurrentTexture = function () {
  16267. if (this._currentTextureChannel !== this._activeChannel) {
  16268. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16269. this._currentTextureChannel = this._activeChannel;
  16270. }
  16271. };
  16272. /** @hidden */
  16273. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16274. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16275. if (force === void 0) { force = false; }
  16276. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16277. this._activeChannel = texture._designatedSlot;
  16278. }
  16279. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16280. var isTextureForRendering = texture && texture._initialSlot > -1;
  16281. if (currentTextureBound !== texture || force) {
  16282. if (currentTextureBound) {
  16283. this._removeDesignatedSlot(currentTextureBound);
  16284. }
  16285. this._activateCurrentTexture();
  16286. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16287. this._boundTexturesCache[this._activeChannel] = texture;
  16288. if (texture) {
  16289. if (!this.disableTextureBindingOptimization) {
  16290. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16291. if (slotIndex > -1) {
  16292. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16293. }
  16294. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16295. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16296. }
  16297. texture._designatedSlot = this._activeChannel;
  16298. }
  16299. }
  16300. else if (forTextureDataUpdate) {
  16301. this._activateCurrentTexture();
  16302. }
  16303. if (isTextureForRendering && !forTextureDataUpdate) {
  16304. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16305. }
  16306. };
  16307. /** @hidden */
  16308. Engine.prototype._bindTexture = function (channel, texture) {
  16309. if (channel < 0) {
  16310. return;
  16311. }
  16312. if (texture) {
  16313. channel = this._getCorrectTextureChannel(channel, texture);
  16314. }
  16315. this._activeChannel = channel;
  16316. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16317. };
  16318. /**
  16319. * Sets a texture to the webGL context from a postprocess
  16320. * @param channel defines the channel to use
  16321. * @param postProcess defines the source postprocess
  16322. */
  16323. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16324. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16325. };
  16326. /**
  16327. * Binds the output of the passed in post process to the texture channel specified
  16328. * @param channel The channel the texture should be bound to
  16329. * @param postProcess The post process which's output should be bound
  16330. */
  16331. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16332. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16333. };
  16334. /**
  16335. * Unbind all textures from the webGL context
  16336. */
  16337. Engine.prototype.unbindAllTextures = function () {
  16338. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16339. this._activeChannel = channel;
  16340. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16341. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16342. if (this.webGLVersion > 1) {
  16343. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16344. }
  16345. }
  16346. };
  16347. /**
  16348. * Sets a texture to the according uniform.
  16349. * @param channel The texture channel
  16350. * @param uniform The uniform to set
  16351. * @param texture The texture to apply
  16352. */
  16353. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16354. if (channel < 0) {
  16355. return;
  16356. }
  16357. if (uniform) {
  16358. this._boundUniforms[channel] = uniform;
  16359. }
  16360. this._setTexture(channel, texture);
  16361. };
  16362. /**
  16363. * Sets a depth stencil texture from a render target to the according uniform.
  16364. * @param channel The texture channel
  16365. * @param uniform The uniform to set
  16366. * @param texture The render target texture containing the depth stencil texture to apply
  16367. */
  16368. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16369. if (channel < 0) {
  16370. return;
  16371. }
  16372. if (uniform) {
  16373. this._boundUniforms[channel] = uniform;
  16374. }
  16375. if (!texture || !texture.depthStencilTexture) {
  16376. this._setTexture(channel, null);
  16377. }
  16378. else {
  16379. this._setTexture(channel, texture, false, true);
  16380. }
  16381. };
  16382. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16383. var uniform = this._boundUniforms[sourceSlot];
  16384. if (uniform._currentState === destination) {
  16385. return;
  16386. }
  16387. this._gl.uniform1i(uniform, destination);
  16388. uniform._currentState = destination;
  16389. };
  16390. Engine.prototype._getTextureWrapMode = function (mode) {
  16391. switch (mode) {
  16392. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16393. return this._gl.REPEAT;
  16394. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16395. return this._gl.CLAMP_TO_EDGE;
  16396. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16397. return this._gl.MIRRORED_REPEAT;
  16398. }
  16399. return this._gl.REPEAT;
  16400. };
  16401. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16402. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16403. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16404. // Not ready?
  16405. if (!texture) {
  16406. if (this._boundTexturesCache[channel] != null) {
  16407. this._activeChannel = channel;
  16408. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16409. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16410. if (this.webGLVersion > 1) {
  16411. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16412. }
  16413. }
  16414. return false;
  16415. }
  16416. // Video
  16417. if (texture.video) {
  16418. this._activeChannel = channel;
  16419. texture.update();
  16420. }
  16421. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16422. texture.delayLoad();
  16423. return false;
  16424. }
  16425. var internalTexture;
  16426. if (depthStencilTexture) {
  16427. internalTexture = texture.depthStencilTexture;
  16428. }
  16429. else if (texture.isReady()) {
  16430. internalTexture = texture.getInternalTexture();
  16431. }
  16432. else if (texture.isCube) {
  16433. internalTexture = this.emptyCubeTexture;
  16434. }
  16435. else if (texture.is3D) {
  16436. internalTexture = this.emptyTexture3D;
  16437. }
  16438. else {
  16439. internalTexture = this.emptyTexture;
  16440. }
  16441. if (!isPartOfTextureArray) {
  16442. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16443. }
  16444. var needToBind = true;
  16445. if (this._boundTexturesCache[channel] === internalTexture) {
  16446. this._moveBoundTextureOnTop(internalTexture);
  16447. if (!isPartOfTextureArray) {
  16448. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16449. }
  16450. needToBind = false;
  16451. }
  16452. this._activeChannel = channel;
  16453. if (internalTexture && internalTexture.is3D) {
  16454. if (needToBind) {
  16455. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16456. }
  16457. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16458. internalTexture._cachedWrapU = texture.wrapU;
  16459. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16460. }
  16461. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16462. internalTexture._cachedWrapV = texture.wrapV;
  16463. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16464. }
  16465. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16466. internalTexture._cachedWrapR = texture.wrapR;
  16467. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16468. }
  16469. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16470. }
  16471. else if (internalTexture && internalTexture.isCube) {
  16472. if (needToBind) {
  16473. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16474. }
  16475. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16476. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16477. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16478. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16479. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16480. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16481. }
  16482. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16483. }
  16484. else {
  16485. if (needToBind) {
  16486. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16487. }
  16488. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16489. internalTexture._cachedWrapU = texture.wrapU;
  16490. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16491. }
  16492. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16493. internalTexture._cachedWrapV = texture.wrapV;
  16494. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16495. }
  16496. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16497. }
  16498. return true;
  16499. };
  16500. /**
  16501. * Sets an array of texture to the webGL context
  16502. * @param channel defines the channel where the texture array must be set
  16503. * @param uniform defines the associated uniform location
  16504. * @param textures defines the array of textures to bind
  16505. */
  16506. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16507. if (channel < 0 || !uniform) {
  16508. return;
  16509. }
  16510. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16511. this._textureUnits = new Int32Array(textures.length);
  16512. }
  16513. for (var i = 0; i < textures.length; i++) {
  16514. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16515. }
  16516. this._gl.uniform1iv(uniform, this._textureUnits);
  16517. for (var index = 0; index < textures.length; index++) {
  16518. this._setTexture(this._textureUnits[index], textures[index], true);
  16519. }
  16520. };
  16521. /** @hidden */
  16522. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16523. var internalTexture = texture.getInternalTexture();
  16524. if (!internalTexture) {
  16525. return;
  16526. }
  16527. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16528. var value = texture.anisotropicFilteringLevel;
  16529. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16530. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16531. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16532. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16533. }
  16534. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16535. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16536. internalTexture._cachedAnisotropicFilteringLevel = value;
  16537. }
  16538. };
  16539. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16540. this._bindTextureDirectly(target, texture, true, true);
  16541. this._gl.texParameterf(target, parameter, value);
  16542. };
  16543. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16544. if (texture) {
  16545. this._bindTextureDirectly(target, texture, true, true);
  16546. }
  16547. this._gl.texParameteri(target, parameter, value);
  16548. };
  16549. /**
  16550. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16551. * @param x defines the x coordinate of the rectangle where pixels must be read
  16552. * @param y defines the y coordinate of the rectangle where pixels must be read
  16553. * @param width defines the width of the rectangle where pixels must be read
  16554. * @param height defines the height of the rectangle where pixels must be read
  16555. * @returns a Uint8Array containing RGBA colors
  16556. */
  16557. Engine.prototype.readPixels = function (x, y, width, height) {
  16558. var data = new Uint8Array(height * width * 4);
  16559. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16560. return data;
  16561. };
  16562. /**
  16563. * Add an externaly attached data from its key.
  16564. * This method call will fail and return false, if such key already exists.
  16565. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16566. * @param key the unique key that identifies the data
  16567. * @param data the data object to associate to the key for this Engine instance
  16568. * @return true if no such key were already present and the data was added successfully, false otherwise
  16569. */
  16570. Engine.prototype.addExternalData = function (key, data) {
  16571. if (!this._externalData) {
  16572. this._externalData = new BABYLON.StringDictionary();
  16573. }
  16574. return this._externalData.add(key, data);
  16575. };
  16576. /**
  16577. * Get an externaly attached data from its key
  16578. * @param key the unique key that identifies the data
  16579. * @return the associated data, if present (can be null), or undefined if not present
  16580. */
  16581. Engine.prototype.getExternalData = function (key) {
  16582. if (!this._externalData) {
  16583. this._externalData = new BABYLON.StringDictionary();
  16584. }
  16585. return this._externalData.get(key);
  16586. };
  16587. /**
  16588. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16589. * @param key the unique key that identifies the data
  16590. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16591. * @return the associated data, can be null if the factory returned null.
  16592. */
  16593. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16594. if (!this._externalData) {
  16595. this._externalData = new BABYLON.StringDictionary();
  16596. }
  16597. return this._externalData.getOrAddWithFactory(key, factory);
  16598. };
  16599. /**
  16600. * Remove an externaly attached data from the Engine instance
  16601. * @param key the unique key that identifies the data
  16602. * @return true if the data was successfully removed, false if it doesn't exist
  16603. */
  16604. Engine.prototype.removeExternalData = function (key) {
  16605. if (!this._externalData) {
  16606. this._externalData = new BABYLON.StringDictionary();
  16607. }
  16608. return this._externalData.remove(key);
  16609. };
  16610. /**
  16611. * Unbind all vertex attributes from the webGL context
  16612. */
  16613. Engine.prototype.unbindAllAttributes = function () {
  16614. if (this._mustWipeVertexAttributes) {
  16615. this._mustWipeVertexAttributes = false;
  16616. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16617. this._gl.disableVertexAttribArray(i);
  16618. this._vertexAttribArraysEnabled[i] = false;
  16619. this._currentBufferPointers[i].active = false;
  16620. }
  16621. return;
  16622. }
  16623. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16624. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16625. continue;
  16626. }
  16627. this._gl.disableVertexAttribArray(i);
  16628. this._vertexAttribArraysEnabled[i] = false;
  16629. this._currentBufferPointers[i].active = false;
  16630. }
  16631. };
  16632. /**
  16633. * 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
  16634. */
  16635. Engine.prototype.releaseEffects = function () {
  16636. for (var name in this._compiledEffects) {
  16637. this._deleteProgram(this._compiledEffects[name]._program);
  16638. }
  16639. this._compiledEffects = {};
  16640. };
  16641. /**
  16642. * Dispose and release all associated resources
  16643. */
  16644. Engine.prototype.dispose = function () {
  16645. this.hideLoadingUI();
  16646. this.stopRenderLoop();
  16647. // Release postProcesses
  16648. while (this.postProcesses.length) {
  16649. this.postProcesses[0].dispose();
  16650. }
  16651. // Empty texture
  16652. if (this._emptyTexture) {
  16653. this._releaseTexture(this._emptyTexture);
  16654. this._emptyTexture = null;
  16655. }
  16656. if (this._emptyCubeTexture) {
  16657. this._releaseTexture(this._emptyCubeTexture);
  16658. this._emptyCubeTexture = null;
  16659. }
  16660. // Rescale PP
  16661. if (this._rescalePostProcess) {
  16662. this._rescalePostProcess.dispose();
  16663. }
  16664. // Release scenes
  16665. while (this.scenes.length) {
  16666. this.scenes[0].dispose();
  16667. }
  16668. // Release audio engine
  16669. if (Engine.audioEngine) {
  16670. Engine.audioEngine.dispose();
  16671. }
  16672. // Release effects
  16673. this.releaseEffects();
  16674. // Unbind
  16675. this.unbindAllAttributes();
  16676. this._boundUniforms = [];
  16677. if (this._dummyFramebuffer) {
  16678. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16679. }
  16680. //WebVR
  16681. this.disableVR();
  16682. // Events
  16683. if (BABYLON.Tools.IsWindowObjectExist()) {
  16684. window.removeEventListener("blur", this._onBlur);
  16685. window.removeEventListener("focus", this._onFocus);
  16686. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16687. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16688. if (this._renderingCanvas) {
  16689. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16690. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16691. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16692. if (!this._doNotHandleContextLost) {
  16693. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16694. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16695. }
  16696. }
  16697. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16698. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16699. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16700. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16701. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16702. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16703. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16704. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16705. if (this._onVrDisplayConnect) {
  16706. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16707. if (this._onVrDisplayDisconnect) {
  16708. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16709. }
  16710. if (this._onVrDisplayPresentChange) {
  16711. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16712. }
  16713. this._onVrDisplayConnect = null;
  16714. this._onVrDisplayDisconnect = null;
  16715. }
  16716. }
  16717. // Remove from Instances
  16718. var index = Engine.Instances.indexOf(this);
  16719. if (index >= 0) {
  16720. Engine.Instances.splice(index, 1);
  16721. }
  16722. this._workingCanvas = null;
  16723. this._workingContext = null;
  16724. this._currentBufferPointers = [];
  16725. this._renderingCanvas = null;
  16726. this._currentProgram = null;
  16727. this._bindedRenderFunction = null;
  16728. this.onResizeObservable.clear();
  16729. this.onCanvasBlurObservable.clear();
  16730. this.onCanvasFocusObservable.clear();
  16731. this.onCanvasPointerOutObservable.clear();
  16732. this.onBeginFrameObservable.clear();
  16733. this.onEndFrameObservable.clear();
  16734. BABYLON.Effect.ResetCache();
  16735. // Abort active requests
  16736. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16737. var request = _a[_i];
  16738. request.abort();
  16739. }
  16740. };
  16741. // Loading screen
  16742. /**
  16743. * Display the loading screen
  16744. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16745. */
  16746. Engine.prototype.displayLoadingUI = function () {
  16747. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16748. return;
  16749. }
  16750. var loadingScreen = this.loadingScreen;
  16751. if (loadingScreen) {
  16752. loadingScreen.displayLoadingUI();
  16753. }
  16754. };
  16755. /**
  16756. * Hide the loading screen
  16757. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16758. */
  16759. Engine.prototype.hideLoadingUI = function () {
  16760. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16761. return;
  16762. }
  16763. var loadingScreen = this.loadingScreen;
  16764. if (loadingScreen) {
  16765. loadingScreen.hideLoadingUI();
  16766. }
  16767. };
  16768. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16769. /**
  16770. * Gets the current loading screen object
  16771. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16772. */
  16773. get: function () {
  16774. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16775. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16776. return this._loadingScreen;
  16777. },
  16778. /**
  16779. * Sets the current loading screen object
  16780. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16781. */
  16782. set: function (loadingScreen) {
  16783. this._loadingScreen = loadingScreen;
  16784. },
  16785. enumerable: true,
  16786. configurable: true
  16787. });
  16788. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16789. /**
  16790. * Sets the current loading screen text
  16791. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16792. */
  16793. set: function (text) {
  16794. this.loadingScreen.loadingUIText = text;
  16795. },
  16796. enumerable: true,
  16797. configurable: true
  16798. });
  16799. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16800. /**
  16801. * Sets the current loading screen background color
  16802. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16803. */
  16804. set: function (color) {
  16805. this.loadingScreen.loadingUIBackgroundColor = color;
  16806. },
  16807. enumerable: true,
  16808. configurable: true
  16809. });
  16810. /**
  16811. * Attach a new callback raised when context lost event is fired
  16812. * @param callback defines the callback to call
  16813. */
  16814. Engine.prototype.attachContextLostEvent = function (callback) {
  16815. if (this._renderingCanvas) {
  16816. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16817. }
  16818. };
  16819. /**
  16820. * Attach a new callback raised when context restored event is fired
  16821. * @param callback defines the callback to call
  16822. */
  16823. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16824. if (this._renderingCanvas) {
  16825. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16826. }
  16827. };
  16828. /**
  16829. * Gets the source code of the vertex shader associated with a specific webGL program
  16830. * @param program defines the program to use
  16831. * @returns a string containing the source code of the vertex shader associated with the program
  16832. */
  16833. Engine.prototype.getVertexShaderSource = function (program) {
  16834. var shaders = this._gl.getAttachedShaders(program);
  16835. if (!shaders) {
  16836. return null;
  16837. }
  16838. return this._gl.getShaderSource(shaders[0]);
  16839. };
  16840. /**
  16841. * Gets the source code of the fragment shader associated with a specific webGL program
  16842. * @param program defines the program to use
  16843. * @returns a string containing the source code of the fragment shader associated with the program
  16844. */
  16845. Engine.prototype.getFragmentShaderSource = function (program) {
  16846. var shaders = this._gl.getAttachedShaders(program);
  16847. if (!shaders) {
  16848. return null;
  16849. }
  16850. return this._gl.getShaderSource(shaders[1]);
  16851. };
  16852. /**
  16853. * Get the current error code of the webGL context
  16854. * @returns the error code
  16855. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16856. */
  16857. Engine.prototype.getError = function () {
  16858. return this._gl.getError();
  16859. };
  16860. // FPS
  16861. /**
  16862. * Gets the current framerate
  16863. * @returns a number representing the framerate
  16864. */
  16865. Engine.prototype.getFps = function () {
  16866. return this._fps;
  16867. };
  16868. /**
  16869. * Gets the time spent between current and previous frame
  16870. * @returns a number representing the delta time in ms
  16871. */
  16872. Engine.prototype.getDeltaTime = function () {
  16873. return this._deltaTime;
  16874. };
  16875. Engine.prototype._measureFps = function () {
  16876. this._performanceMonitor.sampleFrame();
  16877. this._fps = this._performanceMonitor.averageFPS;
  16878. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16879. };
  16880. /** @hidden */
  16881. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16882. if (faceIndex === void 0) { faceIndex = -1; }
  16883. var gl = this._gl;
  16884. if (!this._dummyFramebuffer) {
  16885. var dummy = gl.createFramebuffer();
  16886. if (!dummy) {
  16887. throw new Error("Unable to create dummy framebuffer");
  16888. }
  16889. this._dummyFramebuffer = dummy;
  16890. }
  16891. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16892. if (faceIndex > -1) {
  16893. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16894. }
  16895. else {
  16896. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16897. }
  16898. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16899. var buffer;
  16900. switch (readType) {
  16901. case gl.UNSIGNED_BYTE:
  16902. buffer = new Uint8Array(4 * width * height);
  16903. readType = gl.UNSIGNED_BYTE;
  16904. break;
  16905. default:
  16906. buffer = new Float32Array(4 * width * height);
  16907. readType = gl.FLOAT;
  16908. break;
  16909. }
  16910. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16911. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16912. return buffer;
  16913. };
  16914. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16915. if (this._webGLVersion > 1) {
  16916. return this._caps.colorBufferFloat;
  16917. }
  16918. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16919. };
  16920. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16921. if (this._webGLVersion > 1) {
  16922. return this._caps.colorBufferFloat;
  16923. }
  16924. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16925. };
  16926. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16927. Engine.prototype._canRenderToFramebuffer = function (type) {
  16928. var gl = this._gl;
  16929. //clear existing errors
  16930. while (gl.getError() !== gl.NO_ERROR) { }
  16931. var successful = true;
  16932. var texture = gl.createTexture();
  16933. gl.bindTexture(gl.TEXTURE_2D, texture);
  16934. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16935. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16936. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16937. var fb = gl.createFramebuffer();
  16938. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16939. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16940. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16941. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16942. successful = successful && (gl.getError() === gl.NO_ERROR);
  16943. //try render by clearing frame buffer's color buffer
  16944. if (successful) {
  16945. gl.clear(gl.COLOR_BUFFER_BIT);
  16946. successful = successful && (gl.getError() === gl.NO_ERROR);
  16947. }
  16948. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16949. if (successful) {
  16950. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16951. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16952. var readFormat = gl.RGBA;
  16953. var readType = gl.UNSIGNED_BYTE;
  16954. var buffer = new Uint8Array(4);
  16955. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16956. successful = successful && (gl.getError() === gl.NO_ERROR);
  16957. }
  16958. //clean up
  16959. gl.deleteTexture(texture);
  16960. gl.deleteFramebuffer(fb);
  16961. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16962. //clear accumulated errors
  16963. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16964. return successful;
  16965. };
  16966. /** @hidden */
  16967. Engine.prototype._getWebGLTextureType = function (type) {
  16968. if (type === Engine.TEXTURETYPE_FLOAT) {
  16969. return this._gl.FLOAT;
  16970. }
  16971. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16972. // Add Half Float Constant.
  16973. return this._gl.HALF_FLOAT_OES;
  16974. }
  16975. return this._gl.UNSIGNED_BYTE;
  16976. };
  16977. ;
  16978. Engine.prototype._getInternalFormat = function (format) {
  16979. var internalFormat = this._gl.RGBA;
  16980. switch (format) {
  16981. case Engine.TEXTUREFORMAT_ALPHA:
  16982. internalFormat = this._gl.ALPHA;
  16983. break;
  16984. case Engine.TEXTUREFORMAT_LUMINANCE:
  16985. internalFormat = this._gl.LUMINANCE;
  16986. break;
  16987. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16988. internalFormat = this._gl.LUMINANCE_ALPHA;
  16989. break;
  16990. case Engine.TEXTUREFORMAT_RGB:
  16991. case Engine.TEXTUREFORMAT_RGB32F:
  16992. internalFormat = this._gl.RGB;
  16993. break;
  16994. case Engine.TEXTUREFORMAT_RGBA:
  16995. case Engine.TEXTUREFORMAT_RGBA32F:
  16996. internalFormat = this._gl.RGBA;
  16997. break;
  16998. case Engine.TEXTUREFORMAT_R32F:
  16999. internalFormat = this._gl.RED;
  17000. break;
  17001. case Engine.TEXTUREFORMAT_RG32F:
  17002. internalFormat = this._gl.RG;
  17003. break;
  17004. }
  17005. return internalFormat;
  17006. };
  17007. /** @hidden */
  17008. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17009. if (this._webGLVersion === 1) {
  17010. if (format) {
  17011. switch (format) {
  17012. case Engine.TEXTUREFORMAT_LUMINANCE:
  17013. return this._gl.LUMINANCE;
  17014. }
  17015. }
  17016. return this._gl.RGBA;
  17017. }
  17018. if (type === Engine.TEXTURETYPE_FLOAT) {
  17019. if (format) {
  17020. switch (format) {
  17021. case Engine.TEXTUREFORMAT_R32F:
  17022. return this._gl.R32F;
  17023. case Engine.TEXTUREFORMAT_RG32F:
  17024. return this._gl.RG32F;
  17025. case Engine.TEXTUREFORMAT_RGB32F:
  17026. return this._gl.RGB32F;
  17027. }
  17028. }
  17029. return this._gl.RGBA32F;
  17030. }
  17031. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17032. return this._gl.RGBA16F;
  17033. }
  17034. if (format) {
  17035. switch (format) {
  17036. case Engine.TEXTUREFORMAT_LUMINANCE:
  17037. return this._gl.LUMINANCE;
  17038. case Engine.TEXTUREFORMAT_RGB:
  17039. return this._gl.RGB;
  17040. }
  17041. }
  17042. return this._gl.RGBA;
  17043. };
  17044. ;
  17045. /** @hidden */
  17046. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17047. if (type === Engine.TEXTURETYPE_FLOAT) {
  17048. return this._gl.RGBA32F;
  17049. }
  17050. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17051. return this._gl.RGBA16F;
  17052. }
  17053. return this._gl.RGBA8;
  17054. };
  17055. ;
  17056. /**
  17057. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17058. * @return the new query
  17059. */
  17060. Engine.prototype.createQuery = function () {
  17061. return this._gl.createQuery();
  17062. };
  17063. /**
  17064. * Delete and release a webGL query
  17065. * @param query defines the query to delete
  17066. * @return the current engine
  17067. */
  17068. Engine.prototype.deleteQuery = function (query) {
  17069. this._gl.deleteQuery(query);
  17070. return this;
  17071. };
  17072. /**
  17073. * Check if a given query has resolved and got its value
  17074. * @param query defines the query to check
  17075. * @returns true if the query got its value
  17076. */
  17077. Engine.prototype.isQueryResultAvailable = function (query) {
  17078. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17079. };
  17080. /**
  17081. * Gets the value of a given query
  17082. * @param query defines the query to check
  17083. * @returns the value of the query
  17084. */
  17085. Engine.prototype.getQueryResult = function (query) {
  17086. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17087. };
  17088. /**
  17089. * Initiates an occlusion query
  17090. * @param algorithmType defines the algorithm to use
  17091. * @param query defines the query to use
  17092. * @returns the current engine
  17093. * @see http://doc.babylonjs.com/features/occlusionquery
  17094. */
  17095. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17096. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17097. this._gl.beginQuery(glAlgorithm, query);
  17098. return this;
  17099. };
  17100. /**
  17101. * Ends an occlusion query
  17102. * @see http://doc.babylonjs.com/features/occlusionquery
  17103. * @param algorithmType defines the algorithm to use
  17104. * @returns the current engine
  17105. */
  17106. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17107. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17108. this._gl.endQuery(glAlgorithm);
  17109. return this;
  17110. };
  17111. /* Time queries */
  17112. Engine.prototype._createTimeQuery = function () {
  17113. var timerQuery = this._caps.timerQuery;
  17114. if (timerQuery.createQueryEXT) {
  17115. return timerQuery.createQueryEXT();
  17116. }
  17117. return this.createQuery();
  17118. };
  17119. Engine.prototype._deleteTimeQuery = function (query) {
  17120. var timerQuery = this._caps.timerQuery;
  17121. if (timerQuery.deleteQueryEXT) {
  17122. timerQuery.deleteQueryEXT(query);
  17123. return;
  17124. }
  17125. this.deleteQuery(query);
  17126. };
  17127. Engine.prototype._getTimeQueryResult = function (query) {
  17128. var timerQuery = this._caps.timerQuery;
  17129. if (timerQuery.getQueryObjectEXT) {
  17130. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17131. }
  17132. return this.getQueryResult(query);
  17133. };
  17134. Engine.prototype._getTimeQueryAvailability = function (query) {
  17135. var timerQuery = this._caps.timerQuery;
  17136. if (timerQuery.getQueryObjectEXT) {
  17137. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17138. }
  17139. return this.isQueryResultAvailable(query);
  17140. };
  17141. /**
  17142. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17143. * Please note that only one query can be issued at a time
  17144. * @returns a time token used to track the time span
  17145. */
  17146. Engine.prototype.startTimeQuery = function () {
  17147. var timerQuery = this._caps.timerQuery;
  17148. if (!timerQuery) {
  17149. return null;
  17150. }
  17151. var token = new BABYLON._TimeToken();
  17152. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17153. if (this._caps.canUseTimestampForTimerQuery) {
  17154. token._startTimeQuery = this._createTimeQuery();
  17155. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17156. }
  17157. else {
  17158. if (this._currentNonTimestampToken) {
  17159. return this._currentNonTimestampToken;
  17160. }
  17161. token._timeElapsedQuery = this._createTimeQuery();
  17162. if (timerQuery.beginQueryEXT) {
  17163. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17164. }
  17165. else {
  17166. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17167. }
  17168. this._currentNonTimestampToken = token;
  17169. }
  17170. return token;
  17171. };
  17172. /**
  17173. * Ends a time query
  17174. * @param token defines the token used to measure the time span
  17175. * @returns the time spent (in ns)
  17176. */
  17177. Engine.prototype.endTimeQuery = function (token) {
  17178. var timerQuery = this._caps.timerQuery;
  17179. if (!timerQuery || !token) {
  17180. return -1;
  17181. }
  17182. if (this._caps.canUseTimestampForTimerQuery) {
  17183. if (!token._startTimeQuery) {
  17184. return -1;
  17185. }
  17186. if (!token._endTimeQuery) {
  17187. token._endTimeQuery = this._createTimeQuery();
  17188. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17189. }
  17190. }
  17191. else if (!token._timeElapsedQueryEnded) {
  17192. if (!token._timeElapsedQuery) {
  17193. return -1;
  17194. }
  17195. if (timerQuery.endQueryEXT) {
  17196. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17197. }
  17198. else {
  17199. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17200. }
  17201. token._timeElapsedQueryEnded = true;
  17202. }
  17203. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17204. var available = false;
  17205. if (token._endTimeQuery) {
  17206. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17207. }
  17208. else if (token._timeElapsedQuery) {
  17209. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17210. }
  17211. if (available && !disjoint) {
  17212. var result = 0;
  17213. if (this._caps.canUseTimestampForTimerQuery) {
  17214. if (!token._startTimeQuery || !token._endTimeQuery) {
  17215. return -1;
  17216. }
  17217. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17218. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17219. result = timeEnd - timeStart;
  17220. this._deleteTimeQuery(token._startTimeQuery);
  17221. this._deleteTimeQuery(token._endTimeQuery);
  17222. token._startTimeQuery = null;
  17223. token._endTimeQuery = null;
  17224. }
  17225. else {
  17226. if (!token._timeElapsedQuery) {
  17227. return -1;
  17228. }
  17229. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17230. this._deleteTimeQuery(token._timeElapsedQuery);
  17231. token._timeElapsedQuery = null;
  17232. token._timeElapsedQueryEnded = false;
  17233. this._currentNonTimestampToken = null;
  17234. }
  17235. return result;
  17236. }
  17237. return -1;
  17238. };
  17239. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17240. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17241. };
  17242. // Transform feedback
  17243. /**
  17244. * Creates a webGL transform feedback object
  17245. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17246. * @returns the webGL transform feedback object
  17247. */
  17248. Engine.prototype.createTransformFeedback = function () {
  17249. return this._gl.createTransformFeedback();
  17250. };
  17251. /**
  17252. * Delete a webGL transform feedback object
  17253. * @param value defines the webGL transform feedback object to delete
  17254. */
  17255. Engine.prototype.deleteTransformFeedback = function (value) {
  17256. this._gl.deleteTransformFeedback(value);
  17257. };
  17258. /**
  17259. * Bind a webGL transform feedback object to the webgl context
  17260. * @param value defines the webGL transform feedback object to bind
  17261. */
  17262. Engine.prototype.bindTransformFeedback = function (value) {
  17263. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17264. };
  17265. /**
  17266. * Begins a transform feedback operation
  17267. * @param usePoints defines if points or triangles must be used
  17268. */
  17269. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17270. if (usePoints === void 0) { usePoints = true; }
  17271. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17272. };
  17273. /**
  17274. * Ends a transform feedback operation
  17275. */
  17276. Engine.prototype.endTransformFeedback = function () {
  17277. this._gl.endTransformFeedback();
  17278. };
  17279. /**
  17280. * Specify the varyings to use with transform feedback
  17281. * @param program defines the associated webGL program
  17282. * @param value defines the list of strings representing the varying names
  17283. */
  17284. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17285. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17286. };
  17287. /**
  17288. * Bind a webGL buffer for a transform feedback operation
  17289. * @param value defines the webGL buffer to bind
  17290. */
  17291. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17292. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17293. };
  17294. /** @hidden */
  17295. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17296. var _this = this;
  17297. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17298. this._activeRequests.push(request);
  17299. request.onCompleteObservable.add(function (request) {
  17300. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17301. });
  17302. return request;
  17303. };
  17304. /** @hidden */
  17305. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17306. var _this = this;
  17307. return new Promise(function (resolve, reject) {
  17308. _this._loadFile(url, function (data) {
  17309. resolve(data);
  17310. }, undefined, database, useArrayBuffer, function (request, exception) {
  17311. reject(exception);
  17312. });
  17313. });
  17314. };
  17315. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17316. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17317. var onload = function (data) {
  17318. loadedFiles[index] = data;
  17319. loadedFiles._internalCount++;
  17320. if (loadedFiles._internalCount === 6) {
  17321. onfinish(loadedFiles);
  17322. }
  17323. };
  17324. var onerror = function (request, exception) {
  17325. if (onErrorCallBack && request) {
  17326. onErrorCallBack(request.status + " " + request.statusText, exception);
  17327. }
  17328. };
  17329. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17330. };
  17331. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17332. if (onError === void 0) { onError = null; }
  17333. var loadedFiles = [];
  17334. loadedFiles._internalCount = 0;
  17335. for (var index = 0; index < 6; index++) {
  17336. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17337. }
  17338. };
  17339. // Statics
  17340. /**
  17341. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17342. * @returns true if the engine can be created
  17343. * @ignorenaming
  17344. */
  17345. Engine.isSupported = function () {
  17346. try {
  17347. var tempcanvas = document.createElement("canvas");
  17348. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17349. return gl != null && !!window.WebGLRenderingContext;
  17350. }
  17351. catch (e) {
  17352. return false;
  17353. }
  17354. };
  17355. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17356. Engine.ExceptionList = [
  17357. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17358. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17359. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17360. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17361. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17362. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17363. ];
  17364. /** Gets the list of created engines */
  17365. Engine.Instances = new Array();
  17366. // Const statics
  17367. Engine._ALPHA_DISABLE = 0;
  17368. Engine._ALPHA_ADD = 1;
  17369. Engine._ALPHA_COMBINE = 2;
  17370. Engine._ALPHA_SUBTRACT = 3;
  17371. Engine._ALPHA_MULTIPLY = 4;
  17372. Engine._ALPHA_MAXIMIZED = 5;
  17373. Engine._ALPHA_ONEONE = 6;
  17374. Engine._ALPHA_PREMULTIPLIED = 7;
  17375. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17376. Engine._ALPHA_INTERPOLATE = 9;
  17377. Engine._ALPHA_SCREENMODE = 10;
  17378. Engine._DELAYLOADSTATE_NONE = 0;
  17379. Engine._DELAYLOADSTATE_LOADED = 1;
  17380. Engine._DELAYLOADSTATE_LOADING = 2;
  17381. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17382. Engine._TEXTUREFORMAT_ALPHA = 0;
  17383. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17384. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17385. Engine._TEXTUREFORMAT_RGB = 4;
  17386. Engine._TEXTUREFORMAT_RGBA = 5;
  17387. Engine._TEXTUREFORMAT_R32F = 6;
  17388. Engine._TEXTUREFORMAT_RG32F = 7;
  17389. Engine._TEXTUREFORMAT_RGB32F = 8;
  17390. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17391. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17392. Engine._TEXTURETYPE_FLOAT = 1;
  17393. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17394. // Depht or Stencil test Constants.
  17395. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17396. 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.
  17397. 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.
  17398. 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.
  17399. 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.
  17400. 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.
  17401. 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.
  17402. 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.
  17403. // Stencil Actions Constants.
  17404. Engine._KEEP = 0x1E00;
  17405. Engine._REPLACE = 0x1E01;
  17406. Engine._INCR = 0x1E02;
  17407. Engine._DECR = 0x1E03;
  17408. Engine._INVERT = 0x150A;
  17409. Engine._INCR_WRAP = 0x8507;
  17410. Engine._DECR_WRAP = 0x8508;
  17411. // Texture rescaling mode
  17412. Engine._SCALEMODE_FLOOR = 1;
  17413. Engine._SCALEMODE_NEAREST = 2;
  17414. Engine._SCALEMODE_CEILING = 3;
  17415. // Updatable statics so stick with vars here
  17416. /**
  17417. * Gets or sets the epsilon value used by collision engine
  17418. */
  17419. Engine.CollisionsEpsilon = 0.001;
  17420. /**
  17421. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17422. */
  17423. Engine.CodeRepository = "src/";
  17424. /**
  17425. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17426. */
  17427. Engine.ShadersRepository = "src/Shaders/";
  17428. return Engine;
  17429. }());
  17430. BABYLON.Engine = Engine;
  17431. })(BABYLON || (BABYLON = {}));
  17432. //# sourceMappingURL=babylon.engine.js.map
  17433. var BABYLON;
  17434. (function (BABYLON) {
  17435. /**
  17436. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17437. */
  17438. var Node = /** @class */ (function () {
  17439. /**
  17440. * Creates a new Node
  17441. * @param {string} name - the name and id to be given to this node
  17442. * @param {BABYLON.Scene} the scene this node will be added to
  17443. */
  17444. function Node(name, scene) {
  17445. if (scene === void 0) { scene = null; }
  17446. /**
  17447. * Gets or sets a string used to store user defined state for the node
  17448. */
  17449. this.state = "";
  17450. /**
  17451. * Gets or sets an object used to store user defined information for the node
  17452. */
  17453. this.metadata = null;
  17454. /**
  17455. * Gets or sets a boolean used to define if the node must be serialized
  17456. */
  17457. this.doNotSerialize = false;
  17458. /** @hidden */
  17459. this._isDisposed = false;
  17460. /**
  17461. * Gets a list of Animations associated with the node
  17462. */
  17463. this.animations = new Array();
  17464. this._ranges = {};
  17465. this._isEnabled = true;
  17466. this._isReady = true;
  17467. /** @hidden */
  17468. this._currentRenderId = -1;
  17469. this._parentRenderId = -1;
  17470. this._childRenderId = -1;
  17471. this._animationPropertiesOverride = null;
  17472. /**
  17473. * An event triggered when the mesh is disposed
  17474. */
  17475. this.onDisposeObservable = new BABYLON.Observable();
  17476. // Behaviors
  17477. this._behaviors = new Array();
  17478. this.name = name;
  17479. this.id = name;
  17480. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17481. this.uniqueId = this._scene.getUniqueId();
  17482. this._initCache();
  17483. }
  17484. /**
  17485. * Gets a boolean indicating if the node has been disposed
  17486. * @returns true if the node was disposed
  17487. */
  17488. Node.prototype.isDisposed = function () {
  17489. return this._isDisposed;
  17490. };
  17491. Object.defineProperty(Node.prototype, "parent", {
  17492. get: function () {
  17493. return this._parentNode;
  17494. },
  17495. /**
  17496. * Gets or sets the parent of the node
  17497. */
  17498. set: function (parent) {
  17499. if (this._parentNode === parent) {
  17500. return;
  17501. }
  17502. // Remove self from list of children of parent
  17503. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17504. var index = this._parentNode._children.indexOf(this);
  17505. if (index !== -1) {
  17506. this._parentNode._children.splice(index, 1);
  17507. }
  17508. }
  17509. // Store new parent
  17510. this._parentNode = parent;
  17511. // Add as child to new parent
  17512. if (this._parentNode) {
  17513. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17514. this._parentNode._children = new Array();
  17515. }
  17516. this._parentNode._children.push(this);
  17517. }
  17518. },
  17519. enumerable: true,
  17520. configurable: true
  17521. });
  17522. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17523. /**
  17524. * Gets or sets the animation properties override
  17525. */
  17526. get: function () {
  17527. if (!this._animationPropertiesOverride) {
  17528. return this._scene.animationPropertiesOverride;
  17529. }
  17530. return this._animationPropertiesOverride;
  17531. },
  17532. set: function (value) {
  17533. this._animationPropertiesOverride = value;
  17534. },
  17535. enumerable: true,
  17536. configurable: true
  17537. });
  17538. /**
  17539. * Gets a string idenfifying the name of the class
  17540. * @returns "Node" string
  17541. */
  17542. Node.prototype.getClassName = function () {
  17543. return "Node";
  17544. };
  17545. Object.defineProperty(Node.prototype, "onDispose", {
  17546. /**
  17547. * Sets a callback that will be raised when the node will be disposed
  17548. */
  17549. set: function (callback) {
  17550. if (this._onDisposeObserver) {
  17551. this.onDisposeObservable.remove(this._onDisposeObserver);
  17552. }
  17553. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17554. },
  17555. enumerable: true,
  17556. configurable: true
  17557. });
  17558. /**
  17559. * Gets the scene of the node
  17560. * @returns a {BABYLON.Scene}
  17561. */
  17562. Node.prototype.getScene = function () {
  17563. return this._scene;
  17564. };
  17565. /**
  17566. * Gets the engine of the node
  17567. * @returns a {BABYLON.Engine}
  17568. */
  17569. Node.prototype.getEngine = function () {
  17570. return this._scene.getEngine();
  17571. };
  17572. /**
  17573. * Attach a behavior to the node
  17574. * @see http://doc.babylonjs.com/features/behaviour
  17575. * @param behavior defines the behavior to attach
  17576. * @returns the current Node
  17577. */
  17578. Node.prototype.addBehavior = function (behavior) {
  17579. var _this = this;
  17580. var index = this._behaviors.indexOf(behavior);
  17581. if (index !== -1) {
  17582. return this;
  17583. }
  17584. behavior.init();
  17585. if (this._scene.isLoading) {
  17586. // We defer the attach when the scene will be loaded
  17587. var observer = this._scene.onDataLoadedObservable.add(function () {
  17588. behavior.attach(_this);
  17589. setTimeout(function () {
  17590. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17591. _this._scene.onDataLoadedObservable.remove(observer);
  17592. }, 0);
  17593. });
  17594. }
  17595. else {
  17596. behavior.attach(this);
  17597. }
  17598. this._behaviors.push(behavior);
  17599. return this;
  17600. };
  17601. /**
  17602. * Remove an attached behavior
  17603. * @see http://doc.babylonjs.com/features/behaviour
  17604. * @param behavior defines the behavior to attach
  17605. * @returns the current Node
  17606. */
  17607. Node.prototype.removeBehavior = function (behavior) {
  17608. var index = this._behaviors.indexOf(behavior);
  17609. if (index === -1) {
  17610. return this;
  17611. }
  17612. this._behaviors[index].detach();
  17613. this._behaviors.splice(index, 1);
  17614. return this;
  17615. };
  17616. Object.defineProperty(Node.prototype, "behaviors", {
  17617. /**
  17618. * Gets the list of attached behaviors
  17619. * @see http://doc.babylonjs.com/features/behaviour
  17620. */
  17621. get: function () {
  17622. return this._behaviors;
  17623. },
  17624. enumerable: true,
  17625. configurable: true
  17626. });
  17627. /**
  17628. * Gets an attached behavior by name
  17629. * @param name defines the name of the behavior to look for
  17630. * @see http://doc.babylonjs.com/features/behaviour
  17631. * @returns null if behavior was not found else the requested behavior
  17632. */
  17633. Node.prototype.getBehaviorByName = function (name) {
  17634. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17635. var behavior = _a[_i];
  17636. if (behavior.name === name) {
  17637. return behavior;
  17638. }
  17639. }
  17640. return null;
  17641. };
  17642. /**
  17643. * Returns the world matrix of the node
  17644. * @returns a matrix containing the node's world matrix
  17645. */
  17646. Node.prototype.getWorldMatrix = function () {
  17647. return BABYLON.Matrix.Identity();
  17648. };
  17649. /** @hidden */
  17650. Node.prototype._getWorldMatrixDeterminant = function () {
  17651. return 1;
  17652. };
  17653. // override it in derived class if you add new variables to the cache
  17654. // and call the parent class method
  17655. /** @hidden */
  17656. Node.prototype._initCache = function () {
  17657. this._cache = {};
  17658. this._cache.parent = undefined;
  17659. };
  17660. /** @hidden */
  17661. Node.prototype.updateCache = function (force) {
  17662. if (!force && this.isSynchronized())
  17663. return;
  17664. this._cache.parent = this.parent;
  17665. this._updateCache();
  17666. };
  17667. // override it in derived class if you add new variables to the cache
  17668. // and call the parent class method if !ignoreParentClass
  17669. /** @hidden */
  17670. Node.prototype._updateCache = function (ignoreParentClass) {
  17671. };
  17672. // override it in derived class if you add new variables to the cache
  17673. /** @hidden */
  17674. Node.prototype._isSynchronized = function () {
  17675. return true;
  17676. };
  17677. /** @hidden */
  17678. Node.prototype._markSyncedWithParent = function () {
  17679. if (this.parent) {
  17680. this._parentRenderId = this.parent._childRenderId;
  17681. }
  17682. };
  17683. /** @hidden */
  17684. Node.prototype.isSynchronizedWithParent = function () {
  17685. if (!this.parent) {
  17686. return true;
  17687. }
  17688. if (this._parentRenderId !== this.parent._childRenderId) {
  17689. return false;
  17690. }
  17691. return this.parent.isSynchronized();
  17692. };
  17693. /** @hidden */
  17694. Node.prototype.isSynchronized = function (updateCache) {
  17695. var check = this.hasNewParent();
  17696. check = check || !this.isSynchronizedWithParent();
  17697. check = check || !this._isSynchronized();
  17698. if (updateCache)
  17699. this.updateCache(true);
  17700. return !check;
  17701. };
  17702. /** @hidden */
  17703. Node.prototype.hasNewParent = function (update) {
  17704. if (this._cache.parent === this.parent)
  17705. return false;
  17706. if (update)
  17707. this._cache.parent = this.parent;
  17708. return true;
  17709. };
  17710. /**
  17711. * Is this node ready to be used/rendered
  17712. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17713. * @return true if the node is ready
  17714. */
  17715. Node.prototype.isReady = function (completeCheck) {
  17716. if (completeCheck === void 0) { completeCheck = false; }
  17717. return this._isReady;
  17718. };
  17719. /**
  17720. * Is this node enabled?
  17721. * 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
  17722. * @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
  17723. * @return whether this node (and its parent) is enabled
  17724. */
  17725. Node.prototype.isEnabled = function (checkAncestors) {
  17726. if (checkAncestors === void 0) { checkAncestors = true; }
  17727. if (checkAncestors === false) {
  17728. return this._isEnabled;
  17729. }
  17730. if (this._isEnabled === false) {
  17731. return false;
  17732. }
  17733. if (this.parent !== undefined && this.parent !== null) {
  17734. return this.parent.isEnabled(checkAncestors);
  17735. }
  17736. return true;
  17737. };
  17738. /**
  17739. * Set the enabled state of this node
  17740. * @param value defines the new enabled state
  17741. */
  17742. Node.prototype.setEnabled = function (value) {
  17743. this._isEnabled = value;
  17744. };
  17745. /**
  17746. * Is this node a descendant of the given node?
  17747. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17748. * @param ancestor defines the parent node to inspect
  17749. * @returns a boolean indicating if this node is a descendant of the given node
  17750. */
  17751. Node.prototype.isDescendantOf = function (ancestor) {
  17752. if (this.parent) {
  17753. if (this.parent === ancestor) {
  17754. return true;
  17755. }
  17756. return this.parent.isDescendantOf(ancestor);
  17757. }
  17758. return false;
  17759. };
  17760. /** @hidden */
  17761. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17762. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17763. if (!this._children) {
  17764. return;
  17765. }
  17766. for (var index = 0; index < this._children.length; index++) {
  17767. var item = this._children[index];
  17768. if (!predicate || predicate(item)) {
  17769. results.push(item);
  17770. }
  17771. if (!directDescendantsOnly) {
  17772. item._getDescendants(results, false, predicate);
  17773. }
  17774. }
  17775. };
  17776. /**
  17777. * Will return all nodes that have this node as ascendant
  17778. * @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
  17779. * @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
  17780. * @return all children nodes of all types
  17781. */
  17782. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17783. var results = new Array();
  17784. this._getDescendants(results, directDescendantsOnly, predicate);
  17785. return results;
  17786. };
  17787. /**
  17788. * Get all child-meshes of this node
  17789. * @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
  17790. * @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
  17791. * @returns an array of {BABYLON.AbstractMesh}
  17792. */
  17793. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17794. var results = [];
  17795. this._getDescendants(results, directDescendantsOnly, function (node) {
  17796. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17797. });
  17798. return results;
  17799. };
  17800. /**
  17801. * Get all child-transformNodes of this node
  17802. * @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
  17803. * @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
  17804. * @returns an array of {BABYLON.TransformNode}
  17805. */
  17806. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17807. var results = [];
  17808. this._getDescendants(results, directDescendantsOnly, function (node) {
  17809. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17810. });
  17811. return results;
  17812. };
  17813. /**
  17814. * Get all direct children of this node
  17815. * @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
  17816. * @returns an array of {BABYLON.Node}
  17817. */
  17818. Node.prototype.getChildren = function (predicate) {
  17819. return this.getDescendants(true, predicate);
  17820. };
  17821. /** @hidden */
  17822. Node.prototype._setReady = function (state) {
  17823. if (state === this._isReady) {
  17824. return;
  17825. }
  17826. if (!state) {
  17827. this._isReady = false;
  17828. return;
  17829. }
  17830. if (this.onReady) {
  17831. this.onReady(this);
  17832. }
  17833. this._isReady = true;
  17834. };
  17835. /**
  17836. * Get an animation by name
  17837. * @param name defines the name of the animation to look for
  17838. * @returns null if not found else the requested animation
  17839. */
  17840. Node.prototype.getAnimationByName = function (name) {
  17841. for (var i = 0; i < this.animations.length; i++) {
  17842. var animation = this.animations[i];
  17843. if (animation.name === name) {
  17844. return animation;
  17845. }
  17846. }
  17847. return null;
  17848. };
  17849. /**
  17850. * Creates an animation range for this node
  17851. * @param name defines the name of the range
  17852. * @param from defines the starting key
  17853. * @param to defines the end key
  17854. */
  17855. Node.prototype.createAnimationRange = function (name, from, to) {
  17856. // check name not already in use
  17857. if (!this._ranges[name]) {
  17858. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17859. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17860. if (this.animations[i]) {
  17861. this.animations[i].createRange(name, from, to);
  17862. }
  17863. }
  17864. }
  17865. };
  17866. /**
  17867. * Delete a specific animation range
  17868. * @param name defines the name of the range to delete
  17869. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17870. */
  17871. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17872. if (deleteFrames === void 0) { deleteFrames = true; }
  17873. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17874. if (this.animations[i]) {
  17875. this.animations[i].deleteRange(name, deleteFrames);
  17876. }
  17877. }
  17878. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17879. };
  17880. /**
  17881. * Get an animation range by name
  17882. * @param name defines the name of the animation range to look for
  17883. * @returns null if not found else the requested animation range
  17884. */
  17885. Node.prototype.getAnimationRange = function (name) {
  17886. return this._ranges[name];
  17887. };
  17888. /**
  17889. * Will start the animation sequence
  17890. * @param name defines the range frames for animation sequence
  17891. * @param loop defines if the animation should loop (false by default)
  17892. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17893. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17894. * @returns the object created for this animation. If range does not exist, it will return null
  17895. */
  17896. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17897. var range = this.getAnimationRange(name);
  17898. if (!range) {
  17899. return null;
  17900. }
  17901. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17902. };
  17903. /**
  17904. * Serialize animation ranges into a JSON compatible object
  17905. * @returns serialization object
  17906. */
  17907. Node.prototype.serializeAnimationRanges = function () {
  17908. var serializationRanges = [];
  17909. for (var name in this._ranges) {
  17910. var localRange = this._ranges[name];
  17911. if (!localRange) {
  17912. continue;
  17913. }
  17914. var range = {};
  17915. range.name = name;
  17916. range.from = localRange.from;
  17917. range.to = localRange.to;
  17918. serializationRanges.push(range);
  17919. }
  17920. return serializationRanges;
  17921. };
  17922. /**
  17923. * Computes the world matrix of the node
  17924. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17925. * @returns the world matrix
  17926. */
  17927. Node.prototype.computeWorldMatrix = function (force) {
  17928. return BABYLON.Matrix.Identity();
  17929. };
  17930. /**
  17931. * Releases resources associated with this node.
  17932. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17933. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17934. */
  17935. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17936. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17937. if (!doNotRecurse) {
  17938. var nodes = this.getDescendants(true);
  17939. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17940. var node = nodes_1[_i];
  17941. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17942. }
  17943. }
  17944. else {
  17945. var transformNodes = this.getChildTransformNodes(true);
  17946. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17947. var transformNode = transformNodes_1[_a];
  17948. transformNode.parent = null;
  17949. transformNode.computeWorldMatrix(true);
  17950. }
  17951. }
  17952. this.parent = null;
  17953. // Callback
  17954. this.onDisposeObservable.notifyObservers(this);
  17955. this.onDisposeObservable.clear();
  17956. // Behaviors
  17957. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17958. var behavior = _c[_b];
  17959. behavior.detach();
  17960. }
  17961. this._behaviors = [];
  17962. this._isDisposed = true;
  17963. };
  17964. /**
  17965. * Parse animation range data from a serialization object and store them into a given node
  17966. * @param node defines where to store the animation ranges
  17967. * @param parsedNode defines the serialization object to read data from
  17968. * @param scene defines the hosting scene
  17969. */
  17970. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17971. if (parsedNode.ranges) {
  17972. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17973. var data = parsedNode.ranges[index];
  17974. node.createAnimationRange(data.name, data.from, data.to);
  17975. }
  17976. }
  17977. };
  17978. __decorate([
  17979. BABYLON.serialize()
  17980. ], Node.prototype, "name", void 0);
  17981. __decorate([
  17982. BABYLON.serialize()
  17983. ], Node.prototype, "id", void 0);
  17984. __decorate([
  17985. BABYLON.serialize()
  17986. ], Node.prototype, "uniqueId", void 0);
  17987. __decorate([
  17988. BABYLON.serialize()
  17989. ], Node.prototype, "state", void 0);
  17990. __decorate([
  17991. BABYLON.serialize()
  17992. ], Node.prototype, "metadata", void 0);
  17993. return Node;
  17994. }());
  17995. BABYLON.Node = Node;
  17996. })(BABYLON || (BABYLON = {}));
  17997. //# sourceMappingURL=babylon.node.js.map
  17998. var BABYLON;
  17999. (function (BABYLON) {
  18000. var BoundingSphere = /** @class */ (function () {
  18001. /**
  18002. * Creates a new bounding sphere
  18003. * @param min defines the minimum vector (in local space)
  18004. * @param max defines the maximum vector (in local space)
  18005. */
  18006. function BoundingSphere(min, max) {
  18007. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18008. this.reConstruct(min, max);
  18009. }
  18010. /**
  18011. * Recreates the entire bounding sphere from scratch
  18012. * @param min defines the new minimum vector (in local space)
  18013. * @param max defines the new maximum vector (in local space)
  18014. */
  18015. BoundingSphere.prototype.reConstruct = function (min, max) {
  18016. this.minimum = min.clone();
  18017. this.maximum = max.clone();
  18018. var distance = BABYLON.Vector3.Distance(min, max);
  18019. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18020. this.radius = distance * 0.5;
  18021. this.centerWorld = BABYLON.Vector3.Zero();
  18022. this._update(BABYLON.Matrix.Identity());
  18023. };
  18024. // Methods
  18025. BoundingSphere.prototype._update = function (world) {
  18026. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18027. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18028. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18029. };
  18030. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18031. for (var i = 0; i < 6; i++) {
  18032. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18033. return false;
  18034. }
  18035. return true;
  18036. };
  18037. BoundingSphere.prototype.intersectsPoint = function (point) {
  18038. var x = this.centerWorld.x - point.x;
  18039. var y = this.centerWorld.y - point.y;
  18040. var z = this.centerWorld.z - point.z;
  18041. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18042. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18043. return false;
  18044. return true;
  18045. };
  18046. // Statics
  18047. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18048. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18049. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18050. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18051. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18052. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18053. return false;
  18054. return true;
  18055. };
  18056. return BoundingSphere;
  18057. }());
  18058. BABYLON.BoundingSphere = BoundingSphere;
  18059. })(BABYLON || (BABYLON = {}));
  18060. //# sourceMappingURL=babylon.boundingSphere.js.map
  18061. var BABYLON;
  18062. (function (BABYLON) {
  18063. var BoundingBox = /** @class */ (function () {
  18064. /**
  18065. * Creates a new bounding box
  18066. * @param min defines the minimum vector (in local space)
  18067. * @param max defines the maximum vector (in local space)
  18068. */
  18069. function BoundingBox(min, max) {
  18070. this.vectorsWorld = new Array();
  18071. this.reConstruct(min, max);
  18072. }
  18073. // Methods
  18074. /**
  18075. * Recreates the entire bounding box from scratch
  18076. * @param min defines the new minimum vector (in local space)
  18077. * @param max defines the new maximum vector (in local space)
  18078. */
  18079. BoundingBox.prototype.reConstruct = function (min, max) {
  18080. this.minimum = min.clone();
  18081. this.maximum = max.clone();
  18082. // Bounding vectors
  18083. this.vectors = new Array();
  18084. this.vectors.push(this.minimum.clone());
  18085. this.vectors.push(this.maximum.clone());
  18086. this.vectors.push(this.minimum.clone());
  18087. this.vectors[2].x = this.maximum.x;
  18088. this.vectors.push(this.minimum.clone());
  18089. this.vectors[3].y = this.maximum.y;
  18090. this.vectors.push(this.minimum.clone());
  18091. this.vectors[4].z = this.maximum.z;
  18092. this.vectors.push(this.maximum.clone());
  18093. this.vectors[5].z = this.minimum.z;
  18094. this.vectors.push(this.maximum.clone());
  18095. this.vectors[6].x = this.minimum.x;
  18096. this.vectors.push(this.maximum.clone());
  18097. this.vectors[7].y = this.minimum.y;
  18098. // OBB
  18099. this.center = this.maximum.add(this.minimum).scale(0.5);
  18100. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18101. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18102. // World
  18103. for (var index = 0; index < this.vectors.length; index++) {
  18104. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18105. }
  18106. this.minimumWorld = BABYLON.Vector3.Zero();
  18107. this.maximumWorld = BABYLON.Vector3.Zero();
  18108. this.centerWorld = BABYLON.Vector3.Zero();
  18109. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18110. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18111. };
  18112. BoundingBox.prototype.getWorldMatrix = function () {
  18113. return this._worldMatrix;
  18114. };
  18115. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18116. this._worldMatrix.copyFrom(matrix);
  18117. return this;
  18118. };
  18119. BoundingBox.prototype._update = function (world) {
  18120. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18121. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18122. for (var index = 0; index < this.vectors.length; index++) {
  18123. var v = this.vectorsWorld[index];
  18124. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18125. if (v.x < this.minimumWorld.x)
  18126. this.minimumWorld.x = v.x;
  18127. if (v.y < this.minimumWorld.y)
  18128. this.minimumWorld.y = v.y;
  18129. if (v.z < this.minimumWorld.z)
  18130. this.minimumWorld.z = v.z;
  18131. if (v.x > this.maximumWorld.x)
  18132. this.maximumWorld.x = v.x;
  18133. if (v.y > this.maximumWorld.y)
  18134. this.maximumWorld.y = v.y;
  18135. if (v.z > this.maximumWorld.z)
  18136. this.maximumWorld.z = v.z;
  18137. }
  18138. // Extend
  18139. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18140. this.extendSizeWorld.scaleInPlace(0.5);
  18141. // OBB
  18142. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18143. this.centerWorld.scaleInPlace(0.5);
  18144. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18145. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18146. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18147. this._worldMatrix = world;
  18148. };
  18149. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18150. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18151. };
  18152. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18153. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18154. };
  18155. BoundingBox.prototype.intersectsPoint = function (point) {
  18156. var delta = -BABYLON.Epsilon;
  18157. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18158. return false;
  18159. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18160. return false;
  18161. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18162. return false;
  18163. return true;
  18164. };
  18165. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18166. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18167. };
  18168. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18169. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18170. return false;
  18171. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18172. return false;
  18173. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18174. return false;
  18175. return true;
  18176. };
  18177. // Statics
  18178. BoundingBox.Intersects = function (box0, box1) {
  18179. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18180. return false;
  18181. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18182. return false;
  18183. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18184. return false;
  18185. return true;
  18186. };
  18187. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18188. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18189. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18190. return (num <= (sphereRadius * sphereRadius));
  18191. };
  18192. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18193. for (var p = 0; p < 6; p++) {
  18194. for (var i = 0; i < 8; i++) {
  18195. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18196. return false;
  18197. }
  18198. }
  18199. }
  18200. return true;
  18201. };
  18202. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18203. for (var p = 0; p < 6; p++) {
  18204. var inCount = 8;
  18205. for (var i = 0; i < 8; i++) {
  18206. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18207. --inCount;
  18208. }
  18209. else {
  18210. break;
  18211. }
  18212. }
  18213. if (inCount === 0)
  18214. return false;
  18215. }
  18216. return true;
  18217. };
  18218. return BoundingBox;
  18219. }());
  18220. BABYLON.BoundingBox = BoundingBox;
  18221. })(BABYLON || (BABYLON = {}));
  18222. //# sourceMappingURL=babylon.boundingBox.js.map
  18223. var BABYLON;
  18224. (function (BABYLON) {
  18225. var computeBoxExtents = function (axis, box) {
  18226. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18227. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18228. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18229. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18230. var r = r0 + r1 + r2;
  18231. return {
  18232. min: p - r,
  18233. max: p + r
  18234. };
  18235. };
  18236. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18237. var axisOverlap = function (axis, box0, box1) {
  18238. var result0 = computeBoxExtents(axis, box0);
  18239. var result1 = computeBoxExtents(axis, box1);
  18240. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18241. };
  18242. var BoundingInfo = /** @class */ (function () {
  18243. function BoundingInfo(minimum, maximum) {
  18244. this.minimum = minimum;
  18245. this.maximum = maximum;
  18246. this._isLocked = false;
  18247. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18248. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18249. }
  18250. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18251. get: function () {
  18252. return this._isLocked;
  18253. },
  18254. set: function (value) {
  18255. this._isLocked = value;
  18256. },
  18257. enumerable: true,
  18258. configurable: true
  18259. });
  18260. // Methods
  18261. BoundingInfo.prototype.update = function (world) {
  18262. if (this._isLocked) {
  18263. return;
  18264. }
  18265. this.boundingBox._update(world);
  18266. this.boundingSphere._update(world);
  18267. };
  18268. /**
  18269. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18270. * @param center New center of the bounding info
  18271. * @param extend New extend of the bounding info
  18272. */
  18273. BoundingInfo.prototype.centerOn = function (center, extend) {
  18274. this.minimum = center.subtract(extend);
  18275. this.maximum = center.add(extend);
  18276. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18277. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18278. return this;
  18279. };
  18280. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18281. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18282. return false;
  18283. return this.boundingBox.isInFrustum(frustumPlanes);
  18284. };
  18285. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18286. /**
  18287. * Gets the world distance between the min and max points of the bounding box
  18288. */
  18289. get: function () {
  18290. var boundingBox = this.boundingBox;
  18291. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18292. return size.length();
  18293. },
  18294. enumerable: true,
  18295. configurable: true
  18296. });
  18297. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18298. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18299. };
  18300. BoundingInfo.prototype._checkCollision = function (collider) {
  18301. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18302. };
  18303. BoundingInfo.prototype.intersectsPoint = function (point) {
  18304. if (!this.boundingSphere.centerWorld) {
  18305. return false;
  18306. }
  18307. if (!this.boundingSphere.intersectsPoint(point)) {
  18308. return false;
  18309. }
  18310. if (!this.boundingBox.intersectsPoint(point)) {
  18311. return false;
  18312. }
  18313. return true;
  18314. };
  18315. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18316. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18317. return false;
  18318. }
  18319. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18320. return false;
  18321. }
  18322. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18323. return false;
  18324. }
  18325. if (!precise) {
  18326. return true;
  18327. }
  18328. var box0 = this.boundingBox;
  18329. var box1 = boundingInfo.boundingBox;
  18330. if (!axisOverlap(box0.directions[0], box0, box1))
  18331. return false;
  18332. if (!axisOverlap(box0.directions[1], box0, box1))
  18333. return false;
  18334. if (!axisOverlap(box0.directions[2], box0, box1))
  18335. return false;
  18336. if (!axisOverlap(box1.directions[0], box0, box1))
  18337. return false;
  18338. if (!axisOverlap(box1.directions[1], box0, box1))
  18339. return false;
  18340. if (!axisOverlap(box1.directions[2], box0, box1))
  18341. return false;
  18342. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18343. return false;
  18344. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18345. return false;
  18346. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18347. return false;
  18348. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18349. return false;
  18350. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18351. return false;
  18352. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18353. return false;
  18354. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18355. return false;
  18356. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18357. return false;
  18358. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18359. return false;
  18360. return true;
  18361. };
  18362. return BoundingInfo;
  18363. }());
  18364. BABYLON.BoundingInfo = BoundingInfo;
  18365. })(BABYLON || (BABYLON = {}));
  18366. //# sourceMappingURL=babylon.boundingInfo.js.map
  18367. var BABYLON;
  18368. (function (BABYLON) {
  18369. var TransformNode = /** @class */ (function (_super) {
  18370. __extends(TransformNode, _super);
  18371. function TransformNode(name, scene, isPure) {
  18372. if (scene === void 0) { scene = null; }
  18373. if (isPure === void 0) { isPure = true; }
  18374. var _this = _super.call(this, name, scene) || this;
  18375. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18376. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18377. _this._up = new BABYLON.Vector3(0, 1, 0);
  18378. _this._right = new BABYLON.Vector3(1, 0, 0);
  18379. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18380. // Properties
  18381. _this._rotation = BABYLON.Vector3.Zero();
  18382. _this._scaling = BABYLON.Vector3.One();
  18383. _this._isDirty = false;
  18384. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18385. _this.scalingDeterminant = 1;
  18386. _this.infiniteDistance = false;
  18387. _this.position = BABYLON.Vector3.Zero();
  18388. _this._localWorld = BABYLON.Matrix.Zero();
  18389. _this._worldMatrix = BABYLON.Matrix.Zero();
  18390. _this._worldMatrixDeterminant = 0;
  18391. _this._absolutePosition = BABYLON.Vector3.Zero();
  18392. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18393. _this._postMultiplyPivotMatrix = false;
  18394. _this._isWorldMatrixFrozen = false;
  18395. /**
  18396. * An event triggered after the world matrix is updated
  18397. */
  18398. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18399. _this._nonUniformScaling = false;
  18400. if (isPure) {
  18401. _this.getScene().addTransformNode(_this);
  18402. }
  18403. return _this;
  18404. }
  18405. /**
  18406. * Gets a string idenfifying the name of the class
  18407. * @returns "TransformNode" string
  18408. */
  18409. TransformNode.prototype.getClassName = function () {
  18410. return "TransformNode";
  18411. };
  18412. Object.defineProperty(TransformNode.prototype, "rotation", {
  18413. /**
  18414. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18415. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18416. * Default : (0.0, 0.0, 0.0)
  18417. */
  18418. get: function () {
  18419. return this._rotation;
  18420. },
  18421. set: function (newRotation) {
  18422. this._rotation = newRotation;
  18423. },
  18424. enumerable: true,
  18425. configurable: true
  18426. });
  18427. Object.defineProperty(TransformNode.prototype, "scaling", {
  18428. /**
  18429. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18430. * Default : (1.0, 1.0, 1.0)
  18431. */
  18432. get: function () {
  18433. return this._scaling;
  18434. },
  18435. /**
  18436. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18437. * Default : (1.0, 1.0, 1.0)
  18438. */
  18439. set: function (newScaling) {
  18440. this._scaling = newScaling;
  18441. },
  18442. enumerable: true,
  18443. configurable: true
  18444. });
  18445. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18446. /**
  18447. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18448. * It's null by default.
  18449. * 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)
  18450. */
  18451. get: function () {
  18452. return this._rotationQuaternion;
  18453. },
  18454. set: function (quaternion) {
  18455. this._rotationQuaternion = quaternion;
  18456. //reset the rotation vector.
  18457. if (quaternion && this.rotation.length()) {
  18458. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18459. }
  18460. },
  18461. enumerable: true,
  18462. configurable: true
  18463. });
  18464. Object.defineProperty(TransformNode.prototype, "forward", {
  18465. /**
  18466. * The forward direction of that transform in world space.
  18467. */
  18468. get: function () {
  18469. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18470. },
  18471. enumerable: true,
  18472. configurable: true
  18473. });
  18474. Object.defineProperty(TransformNode.prototype, "up", {
  18475. /**
  18476. * The up direction of that transform in world space.
  18477. */
  18478. get: function () {
  18479. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18480. },
  18481. enumerable: true,
  18482. configurable: true
  18483. });
  18484. Object.defineProperty(TransformNode.prototype, "right", {
  18485. /**
  18486. * The right direction of that transform in world space.
  18487. */
  18488. get: function () {
  18489. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18490. },
  18491. enumerable: true,
  18492. configurable: true
  18493. });
  18494. /**
  18495. * Returns the latest update of the World matrix
  18496. * Returns a Matrix.
  18497. */
  18498. TransformNode.prototype.getWorldMatrix = function () {
  18499. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18500. this.computeWorldMatrix();
  18501. }
  18502. return this._worldMatrix;
  18503. };
  18504. /** @hidden */
  18505. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18506. return this._worldMatrixDeterminant;
  18507. };
  18508. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18509. /**
  18510. * Returns directly the latest state of the mesh World matrix.
  18511. * A Matrix is returned.
  18512. */
  18513. get: function () {
  18514. return this._worldMatrix;
  18515. },
  18516. enumerable: true,
  18517. configurable: true
  18518. });
  18519. /**
  18520. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18521. * Returns the TransformNode.
  18522. */
  18523. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18524. this._poseMatrix.copyFrom(matrix);
  18525. return this;
  18526. };
  18527. /**
  18528. * Returns the mesh Pose matrix.
  18529. * Returned object : Matrix
  18530. */
  18531. TransformNode.prototype.getPoseMatrix = function () {
  18532. return this._poseMatrix;
  18533. };
  18534. TransformNode.prototype._isSynchronized = function () {
  18535. if (this._isDirty) {
  18536. return false;
  18537. }
  18538. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18539. return false;
  18540. if (this._cache.pivotMatrixUpdated) {
  18541. return false;
  18542. }
  18543. if (this.infiniteDistance) {
  18544. return false;
  18545. }
  18546. if (!this._cache.position.equals(this.position))
  18547. return false;
  18548. if (this.rotationQuaternion) {
  18549. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18550. return false;
  18551. }
  18552. if (!this._cache.rotation.equals(this.rotation))
  18553. return false;
  18554. if (!this._cache.scaling.equals(this.scaling))
  18555. return false;
  18556. return true;
  18557. };
  18558. TransformNode.prototype._initCache = function () {
  18559. _super.prototype._initCache.call(this);
  18560. this._cache.localMatrixUpdated = false;
  18561. this._cache.position = BABYLON.Vector3.Zero();
  18562. this._cache.scaling = BABYLON.Vector3.Zero();
  18563. this._cache.rotation = BABYLON.Vector3.Zero();
  18564. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18565. this._cache.billboardMode = -1;
  18566. };
  18567. TransformNode.prototype.markAsDirty = function (property) {
  18568. if (property === "rotation") {
  18569. this.rotationQuaternion = null;
  18570. }
  18571. this._currentRenderId = Number.MAX_VALUE;
  18572. this._isDirty = true;
  18573. return this;
  18574. };
  18575. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18576. /**
  18577. * Returns the current mesh absolute position.
  18578. * Retuns a Vector3.
  18579. */
  18580. get: function () {
  18581. return this._absolutePosition;
  18582. },
  18583. enumerable: true,
  18584. configurable: true
  18585. });
  18586. /**
  18587. * Sets a new matrix to apply before all other transformation
  18588. * @param matrix defines the transform matrix
  18589. * @returns the current TransformNode
  18590. */
  18591. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18592. return this.setPivotMatrix(matrix, false);
  18593. };
  18594. /**
  18595. * Sets a new pivot matrix to the current node
  18596. * @param matrix defines the new pivot matrix to use
  18597. * @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
  18598. * @returns the current TransformNode
  18599. */
  18600. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18601. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18602. this._pivotMatrix = matrix.clone();
  18603. this._cache.pivotMatrixUpdated = true;
  18604. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18605. if (this._postMultiplyPivotMatrix) {
  18606. if (!this._pivotMatrixInverse) {
  18607. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18608. }
  18609. else {
  18610. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18611. }
  18612. }
  18613. return this;
  18614. };
  18615. /**
  18616. * Returns the mesh pivot matrix.
  18617. * Default : Identity.
  18618. * A Matrix is returned.
  18619. */
  18620. TransformNode.prototype.getPivotMatrix = function () {
  18621. return this._pivotMatrix;
  18622. };
  18623. /**
  18624. * Prevents the World matrix to be computed any longer.
  18625. * Returns the TransformNode.
  18626. */
  18627. TransformNode.prototype.freezeWorldMatrix = function () {
  18628. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18629. this.computeWorldMatrix(true);
  18630. this._isWorldMatrixFrozen = true;
  18631. return this;
  18632. };
  18633. /**
  18634. * Allows back the World matrix computation.
  18635. * Returns the TransformNode.
  18636. */
  18637. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18638. this._isWorldMatrixFrozen = false;
  18639. this.computeWorldMatrix(true);
  18640. return this;
  18641. };
  18642. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18643. /**
  18644. * True if the World matrix has been frozen.
  18645. * Returns a boolean.
  18646. */
  18647. get: function () {
  18648. return this._isWorldMatrixFrozen;
  18649. },
  18650. enumerable: true,
  18651. configurable: true
  18652. });
  18653. /**
  18654. * Retuns the mesh absolute position in the World.
  18655. * Returns a Vector3.
  18656. */
  18657. TransformNode.prototype.getAbsolutePosition = function () {
  18658. this.computeWorldMatrix();
  18659. return this._absolutePosition;
  18660. };
  18661. /**
  18662. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18663. * Returns the TransformNode.
  18664. */
  18665. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18666. if (!absolutePosition) {
  18667. return this;
  18668. }
  18669. var absolutePositionX;
  18670. var absolutePositionY;
  18671. var absolutePositionZ;
  18672. if (absolutePosition.x === undefined) {
  18673. if (arguments.length < 3) {
  18674. return this;
  18675. }
  18676. absolutePositionX = arguments[0];
  18677. absolutePositionY = arguments[1];
  18678. absolutePositionZ = arguments[2];
  18679. }
  18680. else {
  18681. absolutePositionX = absolutePosition.x;
  18682. absolutePositionY = absolutePosition.y;
  18683. absolutePositionZ = absolutePosition.z;
  18684. }
  18685. if (this.parent) {
  18686. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18687. invertParentWorldMatrix.invert();
  18688. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18689. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18690. }
  18691. else {
  18692. this.position.x = absolutePositionX;
  18693. this.position.y = absolutePositionY;
  18694. this.position.z = absolutePositionZ;
  18695. }
  18696. return this;
  18697. };
  18698. /**
  18699. * Sets the mesh position in its local space.
  18700. * Returns the TransformNode.
  18701. */
  18702. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18703. this.computeWorldMatrix();
  18704. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18705. return this;
  18706. };
  18707. /**
  18708. * Returns the mesh position in the local space from the current World matrix values.
  18709. * Returns a new Vector3.
  18710. */
  18711. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18712. this.computeWorldMatrix();
  18713. var invLocalWorldMatrix = this._localWorld.clone();
  18714. invLocalWorldMatrix.invert();
  18715. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18716. };
  18717. /**
  18718. * Translates the mesh along the passed Vector3 in its local space.
  18719. * Returns the TransformNode.
  18720. */
  18721. TransformNode.prototype.locallyTranslate = function (vector3) {
  18722. this.computeWorldMatrix(true);
  18723. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18724. return this;
  18725. };
  18726. /**
  18727. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18728. * @param targetPoint the position (must be in same space as current mesh) to look at
  18729. * @param yawCor optional yaw (y-axis) correction in radians
  18730. * @param pitchCor optional pitch (x-axis) correction in radians
  18731. * @param rollCor optional roll (z-axis) correction in radians
  18732. * @param space the choosen space of the target
  18733. * @returns the TransformNode.
  18734. */
  18735. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18736. if (yawCor === void 0) { yawCor = 0; }
  18737. if (pitchCor === void 0) { pitchCor = 0; }
  18738. if (rollCor === void 0) { rollCor = 0; }
  18739. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18740. var dv = TransformNode._lookAtVectorCache;
  18741. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18742. targetPoint.subtractToRef(pos, dv);
  18743. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18744. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18745. var pitch = Math.atan2(dv.y, len);
  18746. if (this.rotationQuaternion) {
  18747. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18748. }
  18749. else {
  18750. this.rotation.x = pitch + pitchCor;
  18751. this.rotation.y = yaw + yawCor;
  18752. this.rotation.z = rollCor;
  18753. }
  18754. return this;
  18755. };
  18756. /**
  18757. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18758. * This Vector3 is expressed in the World space.
  18759. */
  18760. TransformNode.prototype.getDirection = function (localAxis) {
  18761. var result = BABYLON.Vector3.Zero();
  18762. this.getDirectionToRef(localAxis, result);
  18763. return result;
  18764. };
  18765. /**
  18766. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18767. * localAxis is expressed in the mesh local space.
  18768. * result is computed in the Wordl space from the mesh World matrix.
  18769. * Returns the TransformNode.
  18770. */
  18771. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18772. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18773. return this;
  18774. };
  18775. /**
  18776. * Sets a new pivot point to the current node
  18777. * @param point defines the new pivot point to use
  18778. * @param space defines if the point is in world or local space (local by default)
  18779. * @returns the current TransformNode
  18780. */
  18781. TransformNode.prototype.setPivotPoint = function (point, space) {
  18782. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18783. if (this.getScene().getRenderId() == 0) {
  18784. this.computeWorldMatrix(true);
  18785. }
  18786. var wm = this.getWorldMatrix();
  18787. if (space == BABYLON.Space.WORLD) {
  18788. var tmat = BABYLON.Tmp.Matrix[0];
  18789. wm.invertToRef(tmat);
  18790. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18791. }
  18792. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18793. };
  18794. /**
  18795. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18796. */
  18797. TransformNode.prototype.getPivotPoint = function () {
  18798. var point = BABYLON.Vector3.Zero();
  18799. this.getPivotPointToRef(point);
  18800. return point;
  18801. };
  18802. /**
  18803. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18804. * Returns the TransformNode.
  18805. */
  18806. TransformNode.prototype.getPivotPointToRef = function (result) {
  18807. result.x = -this._pivotMatrix.m[12];
  18808. result.y = -this._pivotMatrix.m[13];
  18809. result.z = -this._pivotMatrix.m[14];
  18810. return this;
  18811. };
  18812. /**
  18813. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18814. */
  18815. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18816. var point = BABYLON.Vector3.Zero();
  18817. this.getAbsolutePivotPointToRef(point);
  18818. return point;
  18819. };
  18820. /**
  18821. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18822. * Returns the TransformNode.
  18823. */
  18824. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18825. result.x = this._pivotMatrix.m[12];
  18826. result.y = this._pivotMatrix.m[13];
  18827. result.z = this._pivotMatrix.m[14];
  18828. this.getPivotPointToRef(result);
  18829. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18830. return this;
  18831. };
  18832. /**
  18833. * Defines the passed node as the parent of the current node.
  18834. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18835. * Returns the TransformNode.
  18836. */
  18837. TransformNode.prototype.setParent = function (node) {
  18838. if (node === null) {
  18839. var rotation = BABYLON.Tmp.Quaternion[0];
  18840. var position = BABYLON.Tmp.Vector3[0];
  18841. var scale = BABYLON.Tmp.Vector3[1];
  18842. if (this.parent && this.parent.computeWorldMatrix) {
  18843. this.parent.computeWorldMatrix(true);
  18844. }
  18845. this.computeWorldMatrix(true);
  18846. this.getWorldMatrix().decompose(scale, rotation, position);
  18847. if (this.rotationQuaternion) {
  18848. this.rotationQuaternion.copyFrom(rotation);
  18849. }
  18850. else {
  18851. rotation.toEulerAnglesToRef(this.rotation);
  18852. }
  18853. this.scaling.x = scale.x;
  18854. this.scaling.y = scale.y;
  18855. this.scaling.z = scale.z;
  18856. this.position.x = position.x;
  18857. this.position.y = position.y;
  18858. this.position.z = position.z;
  18859. }
  18860. else {
  18861. var rotation = BABYLON.Tmp.Quaternion[0];
  18862. var position = BABYLON.Tmp.Vector3[0];
  18863. var scale = BABYLON.Tmp.Vector3[1];
  18864. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18865. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18866. this.computeWorldMatrix(true);
  18867. node.computeWorldMatrix(true);
  18868. node.getWorldMatrix().invertToRef(invParentMatrix);
  18869. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18870. diffMatrix.decompose(scale, rotation, position);
  18871. if (this.rotationQuaternion) {
  18872. this.rotationQuaternion.copyFrom(rotation);
  18873. }
  18874. else {
  18875. rotation.toEulerAnglesToRef(this.rotation);
  18876. }
  18877. this.position.x = position.x;
  18878. this.position.y = position.y;
  18879. this.position.z = position.z;
  18880. this.scaling.x = scale.x;
  18881. this.scaling.y = scale.y;
  18882. this.scaling.z = scale.z;
  18883. }
  18884. this.parent = node;
  18885. return this;
  18886. };
  18887. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18888. get: function () {
  18889. return this._nonUniformScaling;
  18890. },
  18891. enumerable: true,
  18892. configurable: true
  18893. });
  18894. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18895. if (this._nonUniformScaling === value) {
  18896. return false;
  18897. }
  18898. this._nonUniformScaling = true;
  18899. return true;
  18900. };
  18901. /**
  18902. * Attach the current TransformNode to another TransformNode associated with a bone
  18903. * @param bone Bone affecting the TransformNode
  18904. * @param affectedTransformNode TransformNode associated with the bone
  18905. */
  18906. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18907. this._transformToBoneReferal = affectedTransformNode;
  18908. this.parent = bone;
  18909. if (bone.getWorldMatrix().determinant() < 0) {
  18910. this.scalingDeterminant *= -1;
  18911. }
  18912. return this;
  18913. };
  18914. TransformNode.prototype.detachFromBone = function () {
  18915. if (!this.parent) {
  18916. return this;
  18917. }
  18918. if (this.parent.getWorldMatrix().determinant() < 0) {
  18919. this.scalingDeterminant *= -1;
  18920. }
  18921. this._transformToBoneReferal = null;
  18922. this.parent = null;
  18923. return this;
  18924. };
  18925. /**
  18926. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18927. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18928. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18929. * The passed axis is also normalized.
  18930. * Returns the TransformNode.
  18931. */
  18932. TransformNode.prototype.rotate = function (axis, amount, space) {
  18933. axis.normalize();
  18934. if (!this.rotationQuaternion) {
  18935. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18936. this.rotation = BABYLON.Vector3.Zero();
  18937. }
  18938. var rotationQuaternion;
  18939. if (!space || space === BABYLON.Space.LOCAL) {
  18940. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18941. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18942. }
  18943. else {
  18944. if (this.parent) {
  18945. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18946. invertParentWorldMatrix.invert();
  18947. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18948. }
  18949. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18950. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18951. }
  18952. return this;
  18953. };
  18954. /**
  18955. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18956. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18957. * The passed axis is also normalized.
  18958. * Returns the TransformNode.
  18959. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18960. */
  18961. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18962. axis.normalize();
  18963. if (!this.rotationQuaternion) {
  18964. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18965. this.rotation.copyFromFloats(0, 0, 0);
  18966. }
  18967. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18968. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18969. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18970. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18971. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18972. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18973. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18974. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18975. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18976. return this;
  18977. };
  18978. /**
  18979. * Translates the mesh along the axis vector for the passed distance in the given space.
  18980. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18981. * Returns the TransformNode.
  18982. */
  18983. TransformNode.prototype.translate = function (axis, distance, space) {
  18984. var displacementVector = axis.scale(distance);
  18985. if (!space || space === BABYLON.Space.LOCAL) {
  18986. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18987. this.setPositionWithLocalVector(tempV3);
  18988. }
  18989. else {
  18990. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18991. }
  18992. return this;
  18993. };
  18994. /**
  18995. * Adds a rotation step to the mesh current rotation.
  18996. * x, y, z are Euler angles expressed in radians.
  18997. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18998. * This means this rotation is made in the mesh local space only.
  18999. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19000. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19001. * ```javascript
  19002. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19003. * ```
  19004. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19005. * 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.
  19006. * Returns the TransformNode.
  19007. */
  19008. TransformNode.prototype.addRotation = function (x, y, z) {
  19009. var rotationQuaternion;
  19010. if (this.rotationQuaternion) {
  19011. rotationQuaternion = this.rotationQuaternion;
  19012. }
  19013. else {
  19014. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19015. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19016. }
  19017. var accumulation = BABYLON.Tmp.Quaternion[0];
  19018. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19019. rotationQuaternion.multiplyInPlace(accumulation);
  19020. if (!this.rotationQuaternion) {
  19021. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19022. }
  19023. return this;
  19024. };
  19025. /**
  19026. * Computes the mesh World matrix and returns it.
  19027. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19028. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19029. * If the parameter `force`is set to `true`, the actual computation is done.
  19030. * Returns the mesh World Matrix.
  19031. */
  19032. TransformNode.prototype.computeWorldMatrix = function (force) {
  19033. if (this._isWorldMatrixFrozen) {
  19034. return this._worldMatrix;
  19035. }
  19036. if (!force && this.isSynchronized(true)) {
  19037. this._currentRenderId = this.getScene().getRenderId();
  19038. return this._worldMatrix;
  19039. }
  19040. this._cache.position.copyFrom(this.position);
  19041. this._cache.scaling.copyFrom(this.scaling);
  19042. this._cache.pivotMatrixUpdated = false;
  19043. this._cache.billboardMode = this.billboardMode;
  19044. this._currentRenderId = this.getScene().getRenderId();
  19045. this._childRenderId = this.getScene().getRenderId();
  19046. this._isDirty = false;
  19047. // Scaling
  19048. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19049. // Rotation
  19050. //rotate, if quaternion is set and rotation was used
  19051. if (this.rotationQuaternion) {
  19052. var len = this.rotation.length();
  19053. if (len) {
  19054. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19055. this.rotation.copyFromFloats(0, 0, 0);
  19056. }
  19057. }
  19058. if (this.rotationQuaternion) {
  19059. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19060. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19061. }
  19062. else {
  19063. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19064. this._cache.rotation.copyFrom(this.rotation);
  19065. }
  19066. // Translation
  19067. var camera = this.getScene().activeCamera;
  19068. if (this.infiniteDistance && !this.parent && camera) {
  19069. var cameraWorldMatrix = camera.getWorldMatrix();
  19070. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19071. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19072. }
  19073. else {
  19074. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19075. }
  19076. // Composing transformations
  19077. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19078. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19079. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19080. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19081. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19082. // Need to decompose each rotation here
  19083. var currentPosition = BABYLON.Tmp.Vector3[3];
  19084. if (this.parent && this.parent.getWorldMatrix) {
  19085. if (this._transformToBoneReferal) {
  19086. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19087. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19088. }
  19089. else {
  19090. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19091. }
  19092. }
  19093. else {
  19094. currentPosition.copyFrom(this.position);
  19095. }
  19096. currentPosition.subtractInPlace(camera.globalPosition);
  19097. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19098. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19099. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19100. }
  19101. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19102. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19103. }
  19104. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19105. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19106. }
  19107. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19108. }
  19109. else {
  19110. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19111. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19112. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19113. }
  19114. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19115. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19116. }
  19117. // Local world
  19118. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19119. // Parent
  19120. if (this.parent && this.parent.getWorldMatrix) {
  19121. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19122. if (this._transformToBoneReferal) {
  19123. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19124. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19125. }
  19126. else {
  19127. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19128. }
  19129. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19130. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19131. this._worldMatrix.copyFrom(this._localWorld);
  19132. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19133. }
  19134. else {
  19135. if (this._transformToBoneReferal) {
  19136. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19137. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19138. }
  19139. else {
  19140. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19141. }
  19142. }
  19143. this._markSyncedWithParent();
  19144. }
  19145. else {
  19146. this._worldMatrix.copyFrom(this._localWorld);
  19147. }
  19148. // Post multiply inverse of pivotMatrix
  19149. if (this._postMultiplyPivotMatrix) {
  19150. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19151. }
  19152. // Normal matrix
  19153. if (this.scaling.isNonUniform) {
  19154. this._updateNonUniformScalingState(true);
  19155. }
  19156. else if (this.parent && this.parent._nonUniformScaling) {
  19157. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19158. }
  19159. else {
  19160. this._updateNonUniformScalingState(false);
  19161. }
  19162. this._afterComputeWorldMatrix();
  19163. // Absolute position
  19164. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19165. // Callbacks
  19166. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19167. if (!this._poseMatrix) {
  19168. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19169. }
  19170. // Cache the determinant
  19171. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19172. return this._worldMatrix;
  19173. };
  19174. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19175. };
  19176. /**
  19177. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19178. * @param func: callback function to add
  19179. *
  19180. * Returns the TransformNode.
  19181. */
  19182. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19183. this.onAfterWorldMatrixUpdateObservable.add(func);
  19184. return this;
  19185. };
  19186. /**
  19187. * Removes a registered callback function.
  19188. * Returns the TransformNode.
  19189. */
  19190. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19191. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19192. return this;
  19193. };
  19194. /**
  19195. * Clone the current transform node
  19196. * Returns the new transform node
  19197. * @param name Name of the new clone
  19198. * @param newParent New parent for the clone
  19199. * @param doNotCloneChildren Do not clone children hierarchy
  19200. */
  19201. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19202. var _this = this;
  19203. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19204. result.name = name;
  19205. result.id = name;
  19206. if (newParent) {
  19207. result.parent = newParent;
  19208. }
  19209. if (!doNotCloneChildren) {
  19210. // Children
  19211. var directDescendants = this.getDescendants(true);
  19212. for (var index = 0; index < directDescendants.length; index++) {
  19213. var child = directDescendants[index];
  19214. if (child.clone) {
  19215. child.clone(name + "." + child.name, result);
  19216. }
  19217. }
  19218. }
  19219. return result;
  19220. };
  19221. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19222. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19223. serializationObject.type = this.getClassName();
  19224. // Parent
  19225. if (this.parent) {
  19226. serializationObject.parentId = this.parent.id;
  19227. }
  19228. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19229. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19230. }
  19231. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19232. serializationObject.isEnabled = this.isEnabled();
  19233. // Parent
  19234. if (this.parent) {
  19235. serializationObject.parentId = this.parent.id;
  19236. }
  19237. return serializationObject;
  19238. };
  19239. // Statics
  19240. /**
  19241. * Returns a new TransformNode object parsed from the source provided.
  19242. * The parameter `parsedMesh` is the source.
  19243. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19244. */
  19245. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19246. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19247. if (BABYLON.Tags) {
  19248. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19249. }
  19250. if (parsedTransformNode.localMatrix) {
  19251. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19252. }
  19253. else if (parsedTransformNode.pivotMatrix) {
  19254. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19255. }
  19256. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19257. // Parent
  19258. if (parsedTransformNode.parentId) {
  19259. transformNode._waitingParentId = parsedTransformNode.parentId;
  19260. }
  19261. return transformNode;
  19262. };
  19263. /**
  19264. * Releases resources associated with this transform node.
  19265. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19266. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19267. */
  19268. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19269. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19270. // Animations
  19271. this.getScene().stopAnimation(this);
  19272. // Remove from scene
  19273. this.getScene().removeTransformNode(this);
  19274. this.onAfterWorldMatrixUpdateObservable.clear();
  19275. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19276. };
  19277. // Statics
  19278. TransformNode.BILLBOARDMODE_NONE = 0;
  19279. TransformNode.BILLBOARDMODE_X = 1;
  19280. TransformNode.BILLBOARDMODE_Y = 2;
  19281. TransformNode.BILLBOARDMODE_Z = 4;
  19282. TransformNode.BILLBOARDMODE_ALL = 7;
  19283. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19284. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19285. __decorate([
  19286. BABYLON.serializeAsVector3()
  19287. ], TransformNode.prototype, "_rotation", void 0);
  19288. __decorate([
  19289. BABYLON.serializeAsQuaternion()
  19290. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19291. __decorate([
  19292. BABYLON.serializeAsVector3()
  19293. ], TransformNode.prototype, "_scaling", void 0);
  19294. __decorate([
  19295. BABYLON.serialize()
  19296. ], TransformNode.prototype, "billboardMode", void 0);
  19297. __decorate([
  19298. BABYLON.serialize()
  19299. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19300. __decorate([
  19301. BABYLON.serialize()
  19302. ], TransformNode.prototype, "infiniteDistance", void 0);
  19303. __decorate([
  19304. BABYLON.serializeAsVector3()
  19305. ], TransformNode.prototype, "position", void 0);
  19306. return TransformNode;
  19307. }(BABYLON.Node));
  19308. BABYLON.TransformNode = TransformNode;
  19309. })(BABYLON || (BABYLON = {}));
  19310. //# sourceMappingURL=babylon.transformNode.js.map
  19311. var BABYLON;
  19312. (function (BABYLON) {
  19313. /**
  19314. * Class used to store all common mesh properties
  19315. */
  19316. var AbstractMesh = /** @class */ (function (_super) {
  19317. __extends(AbstractMesh, _super);
  19318. // Constructor
  19319. /**
  19320. * Creates a new AbstractMesh
  19321. * @param name defines the name of the mesh
  19322. * @param scene defines the hosting scene
  19323. */
  19324. function AbstractMesh(name, scene) {
  19325. if (scene === void 0) { scene = null; }
  19326. var _this = _super.call(this, name, scene, false) || this;
  19327. _this._facetNb = 0; // facet number
  19328. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19329. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19330. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19331. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19332. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19333. _this._subDiv = {
  19334. max: 1,
  19335. X: 1,
  19336. Y: 1,
  19337. Z: 1
  19338. };
  19339. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19340. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19341. // Events
  19342. /**
  19343. * An event triggered when this mesh collides with another one
  19344. */
  19345. _this.onCollideObservable = new BABYLON.Observable();
  19346. /**
  19347. * An event triggered when the collision's position changes
  19348. */
  19349. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19350. /**
  19351. * An event triggered when material is changed
  19352. */
  19353. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19354. // Properties
  19355. /**
  19356. * Gets or sets the orientation for POV movement & rotation
  19357. */
  19358. _this.definedFacingForward = true;
  19359. /**
  19360. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19361. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19362. * * 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.
  19363. * @see http://doc.babylonjs.com/features/occlusionquery
  19364. */
  19365. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19366. /**
  19367. * 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:
  19368. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19369. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19370. * * 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.
  19371. * @see http://doc.babylonjs.com/features/occlusionquery
  19372. */
  19373. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19374. /**
  19375. * 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.
  19376. * The default value is -1 which means don't break the query and wait till the result
  19377. * @see http://doc.babylonjs.com/features/occlusionquery
  19378. */
  19379. _this.occlusionRetryCount = -1;
  19380. _this._occlusionInternalRetryCounter = 0;
  19381. _this._isOccluded = false;
  19382. _this._isOcclusionQueryInProgress = false;
  19383. _this._visibility = 1.0;
  19384. /** Gets or sets the alpha index used to sort transparent meshes
  19385. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19386. */
  19387. _this.alphaIndex = Number.MAX_VALUE;
  19388. /**
  19389. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19390. */
  19391. _this.isVisible = true;
  19392. /**
  19393. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19394. */
  19395. _this.isPickable = true;
  19396. /**
  19397. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19398. */
  19399. _this.showBoundingBox = false;
  19400. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19401. _this.showSubMeshesBoundingBox = false;
  19402. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19403. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19404. */
  19405. _this.isBlocker = false;
  19406. /**
  19407. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19408. */
  19409. _this.enablePointerMoveEvents = false;
  19410. /**
  19411. * Specifies the rendering group id for this mesh (0 by default)
  19412. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19413. */
  19414. _this.renderingGroupId = 0;
  19415. _this._receiveShadows = false;
  19416. /**
  19417. * Gets or sets a boolean indicating if the outline must be rendered as well
  19418. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19419. */
  19420. _this.renderOutline = false;
  19421. /** Defines color to use when rendering outline */
  19422. _this.outlineColor = BABYLON.Color3.Red();
  19423. /** Define width to use when rendering outline */
  19424. _this.outlineWidth = 0.02;
  19425. /**
  19426. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19427. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19428. */
  19429. _this.renderOverlay = false;
  19430. /** Defines color to use when rendering overlay */
  19431. _this.overlayColor = BABYLON.Color3.Red();
  19432. /** Defines alpha to use when rendering overlay */
  19433. _this.overlayAlpha = 0.5;
  19434. _this._hasVertexAlpha = false;
  19435. _this._useVertexColors = true;
  19436. _this._computeBonesUsingShaders = true;
  19437. _this._numBoneInfluencers = 4;
  19438. _this._applyFog = true;
  19439. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19440. _this.useOctreeForRenderingSelection = true;
  19441. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19442. _this.useOctreeForPicking = true;
  19443. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19444. _this.useOctreeForCollisions = true;
  19445. _this._layerMask = 0x0FFFFFFF;
  19446. /**
  19447. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19448. */
  19449. _this.alwaysSelectAsActiveMesh = false;
  19450. /**
  19451. * Gets or sets the current action manager
  19452. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19453. */
  19454. _this.actionManager = null;
  19455. /**
  19456. * Gets or sets impostor used for physic simulation
  19457. * @see http://doc.babylonjs.com/features/physics_engine
  19458. */
  19459. _this.physicsImpostor = null;
  19460. // Collisions
  19461. _this._checkCollisions = false;
  19462. _this._collisionMask = -1;
  19463. _this._collisionGroup = -1;
  19464. /**
  19465. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19466. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19467. */
  19468. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19469. /**
  19470. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19471. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19472. */
  19473. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19474. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19475. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19476. // Edges
  19477. /**
  19478. * Defines edge width used when edgesRenderer is enabled
  19479. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19480. */
  19481. _this.edgesWidth = 1;
  19482. /**
  19483. * Defines edge color used when edgesRenderer is enabled
  19484. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19485. */
  19486. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19487. // Cache
  19488. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19489. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19490. /** @hidden */
  19491. _this._renderId = 0;
  19492. /** @hidden */
  19493. _this._intersectionsInProgress = new Array();
  19494. /** @hidden */
  19495. _this._unIndexed = false;
  19496. /** @hidden */
  19497. _this._lightSources = new Array();
  19498. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19499. if (collidedMesh === void 0) { collidedMesh = null; }
  19500. //TODO move this to the collision coordinator!
  19501. if (_this.getScene().workerCollisions)
  19502. newPosition.multiplyInPlace(_this._collider._radius);
  19503. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19504. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19505. _this.position.addInPlace(_this._diffPositionForCollisions);
  19506. }
  19507. if (collidedMesh) {
  19508. _this.onCollideObservable.notifyObservers(collidedMesh);
  19509. }
  19510. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19511. };
  19512. _this.getScene().addMesh(_this);
  19513. _this._resyncLightSources();
  19514. return _this;
  19515. }
  19516. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19517. /**
  19518. * No billboard
  19519. */
  19520. get: function () {
  19521. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19522. },
  19523. enumerable: true,
  19524. configurable: true
  19525. });
  19526. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19527. /** Billboard on X axis */
  19528. get: function () {
  19529. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19530. },
  19531. enumerable: true,
  19532. configurable: true
  19533. });
  19534. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19535. /** Billboard on Y axis */
  19536. get: function () {
  19537. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19538. },
  19539. enumerable: true,
  19540. configurable: true
  19541. });
  19542. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19543. /** Billboard on Z axis */
  19544. get: function () {
  19545. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19546. },
  19547. enumerable: true,
  19548. configurable: true
  19549. });
  19550. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19551. /** Billboard on all axes */
  19552. get: function () {
  19553. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19554. },
  19555. enumerable: true,
  19556. configurable: true
  19557. });
  19558. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19559. /**
  19560. * Gets the number of facets in the mesh
  19561. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19562. */
  19563. get: function () {
  19564. return this._facetNb;
  19565. },
  19566. enumerable: true,
  19567. configurable: true
  19568. });
  19569. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19570. /**
  19571. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19572. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19573. */
  19574. get: function () {
  19575. return this._partitioningSubdivisions;
  19576. },
  19577. set: function (nb) {
  19578. this._partitioningSubdivisions = nb;
  19579. },
  19580. enumerable: true,
  19581. configurable: true
  19582. });
  19583. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19584. /**
  19585. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19586. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19587. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19588. */
  19589. get: function () {
  19590. return this._partitioningBBoxRatio;
  19591. },
  19592. set: function (ratio) {
  19593. this._partitioningBBoxRatio = ratio;
  19594. },
  19595. enumerable: true,
  19596. configurable: true
  19597. });
  19598. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19599. /**
  19600. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19601. * Works only for updatable meshes.
  19602. * Doesn't work with multi-materials
  19603. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19604. */
  19605. get: function () {
  19606. return this._facetDepthSort;
  19607. },
  19608. set: function (sort) {
  19609. this._facetDepthSort = sort;
  19610. },
  19611. enumerable: true,
  19612. configurable: true
  19613. });
  19614. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19615. /**
  19616. * The location (Vector3) where the facet depth sort must be computed from.
  19617. * By default, the active camera position.
  19618. * Used only when facet depth sort is enabled
  19619. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19620. */
  19621. get: function () {
  19622. return this._facetDepthSortFrom;
  19623. },
  19624. set: function (location) {
  19625. this._facetDepthSortFrom = location;
  19626. },
  19627. enumerable: true,
  19628. configurable: true
  19629. });
  19630. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19631. /**
  19632. * gets a boolean indicating if facetData is enabled
  19633. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19634. */
  19635. get: function () {
  19636. return this._facetDataEnabled;
  19637. },
  19638. enumerable: true,
  19639. configurable: true
  19640. });
  19641. /** @hidden */
  19642. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19643. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19644. return false;
  19645. }
  19646. this._markSubMeshesAsMiscDirty();
  19647. return true;
  19648. };
  19649. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19650. /** Set a function to call when this mesh collides with another one */
  19651. set: function (callback) {
  19652. if (this._onCollideObserver) {
  19653. this.onCollideObservable.remove(this._onCollideObserver);
  19654. }
  19655. this._onCollideObserver = this.onCollideObservable.add(callback);
  19656. },
  19657. enumerable: true,
  19658. configurable: true
  19659. });
  19660. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19661. /** Set a function to call when the collision's position changes */
  19662. set: function (callback) {
  19663. if (this._onCollisionPositionChangeObserver) {
  19664. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19665. }
  19666. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19667. },
  19668. enumerable: true,
  19669. configurable: true
  19670. });
  19671. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19672. /**
  19673. * 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
  19674. * @see http://doc.babylonjs.com/features/occlusionquery
  19675. */
  19676. get: function () {
  19677. return this._isOccluded;
  19678. },
  19679. set: function (value) {
  19680. this._isOccluded = value;
  19681. },
  19682. enumerable: true,
  19683. configurable: true
  19684. });
  19685. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19686. /**
  19687. * Flag to check the progress status of the query
  19688. * @see http://doc.babylonjs.com/features/occlusionquery
  19689. */
  19690. get: function () {
  19691. return this._isOcclusionQueryInProgress;
  19692. },
  19693. enumerable: true,
  19694. configurable: true
  19695. });
  19696. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19697. /**
  19698. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19699. */
  19700. get: function () {
  19701. return this._visibility;
  19702. },
  19703. /**
  19704. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19705. */
  19706. set: function (value) {
  19707. if (this._visibility === value) {
  19708. return;
  19709. }
  19710. this._visibility = value;
  19711. this._markSubMeshesAsMiscDirty();
  19712. },
  19713. enumerable: true,
  19714. configurable: true
  19715. });
  19716. Object.defineProperty(AbstractMesh.prototype, "material", {
  19717. /** Gets or sets current material */
  19718. get: function () {
  19719. return this._material;
  19720. },
  19721. set: function (value) {
  19722. if (this._material === value) {
  19723. return;
  19724. }
  19725. this._material = value;
  19726. if (this.onMaterialChangedObservable.hasObservers) {
  19727. this.onMaterialChangedObservable.notifyObservers(this);
  19728. }
  19729. if (!this.subMeshes) {
  19730. return;
  19731. }
  19732. this._unBindEffect();
  19733. },
  19734. enumerable: true,
  19735. configurable: true
  19736. });
  19737. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19738. /**
  19739. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19740. * @see http://doc.babylonjs.com/babylon101/shadows
  19741. */
  19742. get: function () {
  19743. return this._receiveShadows;
  19744. },
  19745. set: function (value) {
  19746. if (this._receiveShadows === value) {
  19747. return;
  19748. }
  19749. this._receiveShadows = value;
  19750. this._markSubMeshesAsLightDirty();
  19751. },
  19752. enumerable: true,
  19753. configurable: true
  19754. });
  19755. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19756. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19757. get: function () {
  19758. return this._hasVertexAlpha;
  19759. },
  19760. set: function (value) {
  19761. if (this._hasVertexAlpha === value) {
  19762. return;
  19763. }
  19764. this._hasVertexAlpha = value;
  19765. this._markSubMeshesAsAttributesDirty();
  19766. this._markSubMeshesAsMiscDirty();
  19767. },
  19768. enumerable: true,
  19769. configurable: true
  19770. });
  19771. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19772. /** 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) */
  19773. get: function () {
  19774. return this._useVertexColors;
  19775. },
  19776. set: function (value) {
  19777. if (this._useVertexColors === value) {
  19778. return;
  19779. }
  19780. this._useVertexColors = value;
  19781. this._markSubMeshesAsAttributesDirty();
  19782. },
  19783. enumerable: true,
  19784. configurable: true
  19785. });
  19786. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19787. /**
  19788. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19789. */
  19790. get: function () {
  19791. return this._computeBonesUsingShaders;
  19792. },
  19793. set: function (value) {
  19794. if (this._computeBonesUsingShaders === value) {
  19795. return;
  19796. }
  19797. this._computeBonesUsingShaders = value;
  19798. this._markSubMeshesAsAttributesDirty();
  19799. },
  19800. enumerable: true,
  19801. configurable: true
  19802. });
  19803. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19804. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19805. get: function () {
  19806. return this._numBoneInfluencers;
  19807. },
  19808. set: function (value) {
  19809. if (this._numBoneInfluencers === value) {
  19810. return;
  19811. }
  19812. this._numBoneInfluencers = value;
  19813. this._markSubMeshesAsAttributesDirty();
  19814. },
  19815. enumerable: true,
  19816. configurable: true
  19817. });
  19818. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19819. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19820. get: function () {
  19821. return this._applyFog;
  19822. },
  19823. set: function (value) {
  19824. if (this._applyFog === value) {
  19825. return;
  19826. }
  19827. this._applyFog = value;
  19828. this._markSubMeshesAsMiscDirty();
  19829. },
  19830. enumerable: true,
  19831. configurable: true
  19832. });
  19833. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19834. /**
  19835. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19836. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19837. */
  19838. get: function () {
  19839. return this._layerMask;
  19840. },
  19841. set: function (value) {
  19842. if (value === this._layerMask) {
  19843. return;
  19844. }
  19845. this._layerMask = value;
  19846. this._resyncLightSources();
  19847. },
  19848. enumerable: true,
  19849. configurable: true
  19850. });
  19851. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19852. /**
  19853. * Gets or sets a collision mask used to mask collisions (default is -1).
  19854. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19855. */
  19856. get: function () {
  19857. return this._collisionMask;
  19858. },
  19859. set: function (mask) {
  19860. this._collisionMask = !isNaN(mask) ? mask : -1;
  19861. },
  19862. enumerable: true,
  19863. configurable: true
  19864. });
  19865. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19866. /**
  19867. * Gets or sets the current collision group mask (-1 by default).
  19868. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19869. */
  19870. get: function () {
  19871. return this._collisionGroup;
  19872. },
  19873. set: function (mask) {
  19874. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19875. },
  19876. enumerable: true,
  19877. configurable: true
  19878. });
  19879. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19880. /** @hidden */
  19881. get: function () {
  19882. return null;
  19883. },
  19884. enumerable: true,
  19885. configurable: true
  19886. });
  19887. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19888. get: function () {
  19889. return this._skeleton;
  19890. },
  19891. /**
  19892. * Gets or sets a skeleton to apply skining transformations
  19893. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19894. */
  19895. set: function (value) {
  19896. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19897. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19898. }
  19899. if (value && value.needInitialSkinMatrix) {
  19900. value._registerMeshWithPoseMatrix(this);
  19901. }
  19902. this._skeleton = value;
  19903. if (!this._skeleton) {
  19904. this._bonesTransformMatrices = null;
  19905. }
  19906. this._markSubMeshesAsAttributesDirty();
  19907. },
  19908. enumerable: true,
  19909. configurable: true
  19910. });
  19911. /**
  19912. * Returns the string "AbstractMesh"
  19913. * @returns "AbstractMesh"
  19914. */
  19915. AbstractMesh.prototype.getClassName = function () {
  19916. return "AbstractMesh";
  19917. };
  19918. /**
  19919. * Gets a string representation of the current mesh
  19920. * @param fullDetails defines a boolean indicating if full details must be included
  19921. * @returns a string representation of the current mesh
  19922. */
  19923. AbstractMesh.prototype.toString = function (fullDetails) {
  19924. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19925. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19926. if (this._skeleton) {
  19927. ret += ", skeleton: " + this._skeleton.name;
  19928. }
  19929. if (fullDetails) {
  19930. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19931. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19932. }
  19933. return ret;
  19934. };
  19935. /** @hidden */
  19936. AbstractMesh.prototype._rebuild = function () {
  19937. if (this._occlusionQuery) {
  19938. this._occlusionQuery = null;
  19939. }
  19940. if (this._edgesRenderer) {
  19941. this._edgesRenderer._rebuild();
  19942. }
  19943. if (!this.subMeshes) {
  19944. return;
  19945. }
  19946. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19947. var subMesh = _a[_i];
  19948. subMesh._rebuild();
  19949. }
  19950. };
  19951. /** @hidden */
  19952. AbstractMesh.prototype._resyncLightSources = function () {
  19953. this._lightSources.length = 0;
  19954. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19955. var light = _a[_i];
  19956. if (!light.isEnabled()) {
  19957. continue;
  19958. }
  19959. if (light.canAffectMesh(this)) {
  19960. this._lightSources.push(light);
  19961. }
  19962. }
  19963. this._markSubMeshesAsLightDirty();
  19964. };
  19965. /** @hidden */
  19966. AbstractMesh.prototype._resyncLighSource = function (light) {
  19967. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19968. var index = this._lightSources.indexOf(light);
  19969. if (index === -1) {
  19970. if (!isIn) {
  19971. return;
  19972. }
  19973. this._lightSources.push(light);
  19974. }
  19975. else {
  19976. if (isIn) {
  19977. return;
  19978. }
  19979. this._lightSources.splice(index, 1);
  19980. }
  19981. this._markSubMeshesAsLightDirty();
  19982. };
  19983. /** @hidden */
  19984. AbstractMesh.prototype._unBindEffect = function () {
  19985. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19986. var subMesh = _a[_i];
  19987. subMesh.setEffect(null);
  19988. }
  19989. };
  19990. /** @hidden */
  19991. AbstractMesh.prototype._removeLightSource = function (light) {
  19992. var index = this._lightSources.indexOf(light);
  19993. if (index === -1) {
  19994. return;
  19995. }
  19996. this._lightSources.splice(index, 1);
  19997. this._markSubMeshesAsLightDirty();
  19998. };
  19999. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20000. if (!this.subMeshes) {
  20001. return;
  20002. }
  20003. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20004. var subMesh = _a[_i];
  20005. if (subMesh._materialDefines) {
  20006. func(subMesh._materialDefines);
  20007. }
  20008. }
  20009. };
  20010. /** @hidden */
  20011. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20012. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20013. };
  20014. /** @hidden */
  20015. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20016. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20017. };
  20018. /** @hidden */
  20019. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20020. if (!this.subMeshes) {
  20021. return;
  20022. }
  20023. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20024. var subMesh = _a[_i];
  20025. var material = subMesh.getMaterial();
  20026. if (material) {
  20027. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20028. }
  20029. }
  20030. };
  20031. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20032. /**
  20033. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20034. */
  20035. get: function () {
  20036. return this._scaling;
  20037. },
  20038. set: function (newScaling) {
  20039. this._scaling = newScaling;
  20040. if (this.physicsImpostor) {
  20041. this.physicsImpostor.forceUpdate();
  20042. }
  20043. },
  20044. enumerable: true,
  20045. configurable: true
  20046. });
  20047. // Methods
  20048. /**
  20049. * Disables the mesh edge rendering mode
  20050. * @returns the currentAbstractMesh
  20051. */
  20052. AbstractMesh.prototype.disableEdgesRendering = function () {
  20053. if (this._edgesRenderer) {
  20054. this._edgesRenderer.dispose();
  20055. this._edgesRenderer = null;
  20056. }
  20057. return this;
  20058. };
  20059. /**
  20060. * Enables the edge rendering mode on the mesh.
  20061. * This mode makes the mesh edges visible
  20062. * @param epsilon defines the maximal distance between two angles to detect a face
  20063. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20064. * @returns the currentAbstractMesh
  20065. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20066. */
  20067. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20068. if (epsilon === void 0) { epsilon = 0.95; }
  20069. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20070. this.disableEdgesRendering();
  20071. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20072. return this;
  20073. };
  20074. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20075. /**
  20076. * Returns true if the mesh is blocked. Implemented by child classes
  20077. */
  20078. get: function () {
  20079. return false;
  20080. },
  20081. enumerable: true,
  20082. configurable: true
  20083. });
  20084. /**
  20085. * Returns the mesh itself by default. Implemented by child classes
  20086. * @param camera defines the camera to use to pick the right LOD level
  20087. * @returns the currentAbstractMesh
  20088. */
  20089. AbstractMesh.prototype.getLOD = function (camera) {
  20090. return this;
  20091. };
  20092. /**
  20093. * Returns 0 by default. Implemented by child classes
  20094. * @returns an integer
  20095. */
  20096. AbstractMesh.prototype.getTotalVertices = function () {
  20097. return 0;
  20098. };
  20099. /**
  20100. * Returns null by default. Implemented by child classes
  20101. * @returns null
  20102. */
  20103. AbstractMesh.prototype.getIndices = function () {
  20104. return null;
  20105. };
  20106. /**
  20107. * Returns the array of the requested vertex data kind. Implemented by child classes
  20108. * @param kind defines the vertex data kind to use
  20109. * @returns null
  20110. */
  20111. AbstractMesh.prototype.getVerticesData = function (kind) {
  20112. return null;
  20113. };
  20114. /**
  20115. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20116. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20117. * Note that a new underlying VertexBuffer object is created each call.
  20118. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20119. * @param kind defines vertex data kind:
  20120. * * BABYLON.VertexBuffer.PositionKind
  20121. * * BABYLON.VertexBuffer.UVKind
  20122. * * BABYLON.VertexBuffer.UV2Kind
  20123. * * BABYLON.VertexBuffer.UV3Kind
  20124. * * BABYLON.VertexBuffer.UV4Kind
  20125. * * BABYLON.VertexBuffer.UV5Kind
  20126. * * BABYLON.VertexBuffer.UV6Kind
  20127. * * BABYLON.VertexBuffer.ColorKind
  20128. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20129. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20130. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20131. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20132. * @param data defines the data source
  20133. * @param updatable defines if the data must be flagged as updatable (or static)
  20134. * @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
  20135. * @returns the current mesh
  20136. */
  20137. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20138. return this;
  20139. };
  20140. /**
  20141. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20142. * If the mesh has no geometry, it is simply returned as it is.
  20143. * @param kind defines vertex data kind:
  20144. * * BABYLON.VertexBuffer.PositionKind
  20145. * * BABYLON.VertexBuffer.UVKind
  20146. * * BABYLON.VertexBuffer.UV2Kind
  20147. * * BABYLON.VertexBuffer.UV3Kind
  20148. * * BABYLON.VertexBuffer.UV4Kind
  20149. * * BABYLON.VertexBuffer.UV5Kind
  20150. * * BABYLON.VertexBuffer.UV6Kind
  20151. * * BABYLON.VertexBuffer.ColorKind
  20152. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20153. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20154. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20155. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20156. * @param data defines the data source
  20157. * @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
  20158. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20159. * @returns the current mesh
  20160. */
  20161. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20162. return this;
  20163. };
  20164. /**
  20165. * Sets the mesh indices,
  20166. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20167. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20168. * @param totalVertices Defines the total number of vertices
  20169. * @returns the current mesh
  20170. */
  20171. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20172. return this;
  20173. };
  20174. /**
  20175. * Gets a boolean indicating if specific vertex data is present
  20176. * @param kind defines the vertex data kind to use
  20177. * @returns true is data kind is present
  20178. */
  20179. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20180. return false;
  20181. };
  20182. /**
  20183. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20184. * @returns a BoundingInfo
  20185. */
  20186. AbstractMesh.prototype.getBoundingInfo = function () {
  20187. if (this._masterMesh) {
  20188. return this._masterMesh.getBoundingInfo();
  20189. }
  20190. if (!this._boundingInfo) {
  20191. // this._boundingInfo is being created here
  20192. this._updateBoundingInfo();
  20193. }
  20194. // cannot be null.
  20195. return this._boundingInfo;
  20196. };
  20197. /**
  20198. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20199. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20200. * @returns the current mesh
  20201. */
  20202. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20203. if (includeDescendants === void 0) { includeDescendants = true; }
  20204. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20205. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20206. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20207. if (maxDimension === 0) {
  20208. return this;
  20209. }
  20210. var scale = 1 / maxDimension;
  20211. this.scaling.scaleInPlace(scale);
  20212. return this;
  20213. };
  20214. /**
  20215. * Overwrite the current bounding info
  20216. * @param boundingInfo defines the new bounding info
  20217. * @returns the current mesh
  20218. */
  20219. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20220. this._boundingInfo = boundingInfo;
  20221. return this;
  20222. };
  20223. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20224. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20225. get: function () {
  20226. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20227. },
  20228. enumerable: true,
  20229. configurable: true
  20230. });
  20231. /** @hidden */
  20232. AbstractMesh.prototype._preActivate = function () {
  20233. };
  20234. /** @hidden */
  20235. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20236. };
  20237. /** @hidden */
  20238. AbstractMesh.prototype._activate = function (renderId) {
  20239. this._renderId = renderId;
  20240. };
  20241. /**
  20242. * Gets the current world matrix
  20243. * @returns a Matrix
  20244. */
  20245. AbstractMesh.prototype.getWorldMatrix = function () {
  20246. if (this._masterMesh) {
  20247. return this._masterMesh.getWorldMatrix();
  20248. }
  20249. return _super.prototype.getWorldMatrix.call(this);
  20250. };
  20251. /** @hidden */
  20252. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20253. if (this._masterMesh) {
  20254. return this._masterMesh._getWorldMatrixDeterminant();
  20255. }
  20256. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20257. };
  20258. // ================================== Point of View Movement =================================
  20259. /**
  20260. * Perform relative position change from the point of view of behind the front of the mesh.
  20261. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20262. * Supports definition of mesh facing forward or backward
  20263. * @param amountRight defines the distance on the right axis
  20264. * @param amountUp defines the distance on the up axis
  20265. * @param amountForward defines the distance on the forward axis
  20266. * @returns the current mesh
  20267. */
  20268. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20269. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20270. return this;
  20271. };
  20272. /**
  20273. * Calculate relative position change from the point of view of behind the front of the mesh.
  20274. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20275. * Supports definition of mesh facing forward or backward
  20276. * @param amountRight defines the distance on the right axis
  20277. * @param amountUp defines the distance on the up axis
  20278. * @param amountForward defines the distance on the forward axis
  20279. * @returns the new displacement vector
  20280. */
  20281. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20282. var rotMatrix = new BABYLON.Matrix();
  20283. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20284. rotQuaternion.toRotationMatrix(rotMatrix);
  20285. var translationDelta = BABYLON.Vector3.Zero();
  20286. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20287. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20288. return translationDelta;
  20289. };
  20290. // ================================== Point of View Rotation =================================
  20291. /**
  20292. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20293. * Supports definition of mesh facing forward or backward
  20294. * @param flipBack defines the flip
  20295. * @param twirlClockwise defines the twirl
  20296. * @param tiltRight defines the tilt
  20297. * @returns the current mesh
  20298. */
  20299. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20300. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20301. return this;
  20302. };
  20303. /**
  20304. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20305. * Supports definition of mesh facing forward or backward.
  20306. * @param flipBack defines the flip
  20307. * @param twirlClockwise defines the twirl
  20308. * @param tiltRight defines the tilt
  20309. * @returns the new rotation vector
  20310. */
  20311. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20312. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20313. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20314. };
  20315. /**
  20316. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20317. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20318. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20319. * @returns the new bounding vectors
  20320. */
  20321. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20322. if (includeDescendants === void 0) { includeDescendants = true; }
  20323. if (predicate === void 0) { predicate = null; }
  20324. // Ensures that all world matrix will be recomputed.
  20325. this.getScene().incrementRenderId();
  20326. this.computeWorldMatrix(true);
  20327. var min;
  20328. var max;
  20329. var boundingInfo = this.getBoundingInfo();
  20330. if (!this.subMeshes) {
  20331. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20332. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20333. }
  20334. else {
  20335. min = boundingInfo.boundingBox.minimumWorld;
  20336. max = boundingInfo.boundingBox.maximumWorld;
  20337. }
  20338. if (includeDescendants) {
  20339. var descendants = this.getDescendants(false);
  20340. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20341. var descendant = descendants_1[_i];
  20342. var childMesh = descendant;
  20343. childMesh.computeWorldMatrix(true);
  20344. // Filters meshes based on custom predicate function.
  20345. if (predicate && !predicate(childMesh)) {
  20346. continue;
  20347. }
  20348. //make sure we have the needed params to get mix and max
  20349. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20350. continue;
  20351. }
  20352. var childBoundingInfo = childMesh.getBoundingInfo();
  20353. var boundingBox = childBoundingInfo.boundingBox;
  20354. var minBox = boundingBox.minimumWorld;
  20355. var maxBox = boundingBox.maximumWorld;
  20356. BABYLON.Tools.CheckExtends(minBox, min, max);
  20357. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20358. }
  20359. }
  20360. return {
  20361. min: min,
  20362. max: max
  20363. };
  20364. };
  20365. /** @hidden */
  20366. AbstractMesh.prototype._updateBoundingInfo = function () {
  20367. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20368. this._boundingInfo.update(this.worldMatrixFromCache);
  20369. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20370. return this;
  20371. };
  20372. /** @hidden */
  20373. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20374. if (!this.subMeshes) {
  20375. return this;
  20376. }
  20377. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20378. var subMesh = this.subMeshes[subIndex];
  20379. if (!subMesh.IsGlobal) {
  20380. subMesh.updateBoundingInfo(matrix);
  20381. }
  20382. }
  20383. return this;
  20384. };
  20385. /** @hidden */
  20386. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20387. // Bounding info
  20388. this._updateBoundingInfo();
  20389. };
  20390. /**
  20391. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20392. * A mesh is in the frustum if its bounding box intersects the frustum
  20393. * @param frustumPlanes defines the frustum to test
  20394. * @returns true if the mesh is in the frustum planes
  20395. */
  20396. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20397. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20398. };
  20399. /**
  20400. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20401. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20402. * @param frustumPlanes defines the frustum to test
  20403. * @returns true if the mesh is completely in the frustum planes
  20404. */
  20405. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20406. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20407. };
  20408. /**
  20409. * True if the mesh intersects another mesh or a SolidParticle object
  20410. * @param mesh defines a target mesh or SolidParticle to test
  20411. * @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)
  20412. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20413. * @returns true if there is an intersection
  20414. */
  20415. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20416. if (precise === void 0) { precise = false; }
  20417. if (!this._boundingInfo || !mesh._boundingInfo) {
  20418. return false;
  20419. }
  20420. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20421. return true;
  20422. }
  20423. if (includeDescendants) {
  20424. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20425. var child = _a[_i];
  20426. if (child.intersectsMesh(mesh, precise, true)) {
  20427. return true;
  20428. }
  20429. }
  20430. }
  20431. return false;
  20432. };
  20433. /**
  20434. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20435. * @param point defines the point to test
  20436. * @returns true if there is an intersection
  20437. */
  20438. AbstractMesh.prototype.intersectsPoint = function (point) {
  20439. if (!this._boundingInfo) {
  20440. return false;
  20441. }
  20442. return this._boundingInfo.intersectsPoint(point);
  20443. };
  20444. /**
  20445. * Gets the current physics impostor
  20446. * @see http://doc.babylonjs.com/features/physics_engine
  20447. * @returns a physics impostor or null
  20448. */
  20449. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20450. return this.physicsImpostor;
  20451. };
  20452. /**
  20453. * Gets the position of the current mesh in camera space
  20454. * @param camera defines the camera to use
  20455. * @returns a position
  20456. */
  20457. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20458. if (camera === void 0) { camera = null; }
  20459. if (!camera) {
  20460. camera = this.getScene().activeCamera;
  20461. }
  20462. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20463. };
  20464. /**
  20465. * Returns the distance from the mesh to the active camera
  20466. * @param camera defines the camera to use
  20467. * @returns the distance
  20468. */
  20469. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20470. if (camera === void 0) { camera = null; }
  20471. if (!camera) {
  20472. camera = this.getScene().activeCamera;
  20473. }
  20474. return this.absolutePosition.subtract(camera.position).length();
  20475. };
  20476. /**
  20477. * Apply a physic impulse to the mesh
  20478. * @param force defines the force to apply
  20479. * @param contactPoint defines where to apply the force
  20480. * @returns the current mesh
  20481. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20482. */
  20483. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20484. if (!this.physicsImpostor) {
  20485. return this;
  20486. }
  20487. this.physicsImpostor.applyImpulse(force, contactPoint);
  20488. return this;
  20489. };
  20490. /**
  20491. * Creates a physic joint between two meshes
  20492. * @param otherMesh defines the other mesh to use
  20493. * @param pivot1 defines the pivot to use on this mesh
  20494. * @param pivot2 defines the pivot to use on the other mesh
  20495. * @param options defines additional options (can be plugin dependent)
  20496. * @returns the current mesh
  20497. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20498. */
  20499. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20500. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20501. return this;
  20502. }
  20503. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20504. mainPivot: pivot1,
  20505. connectedPivot: pivot2,
  20506. nativeParams: options
  20507. });
  20508. return this;
  20509. };
  20510. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20511. // Collisions
  20512. /**
  20513. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20514. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20515. */
  20516. get: function () {
  20517. return this._checkCollisions;
  20518. },
  20519. set: function (collisionEnabled) {
  20520. this._checkCollisions = collisionEnabled;
  20521. if (this.getScene().workerCollisions) {
  20522. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20523. }
  20524. },
  20525. enumerable: true,
  20526. configurable: true
  20527. });
  20528. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20529. /**
  20530. * Gets Collider object used to compute collisions (not physics)
  20531. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20532. */
  20533. get: function () {
  20534. return this._collider;
  20535. },
  20536. enumerable: true,
  20537. configurable: true
  20538. });
  20539. /**
  20540. * Move the mesh using collision engine
  20541. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20542. * @param displacement defines the requested displacement vector
  20543. * @returns the current mesh
  20544. */
  20545. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20546. var globalPosition = this.getAbsolutePosition();
  20547. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20548. if (!this._collider) {
  20549. this._collider = new BABYLON.Collider();
  20550. }
  20551. this._collider._radius = this.ellipsoid;
  20552. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20553. return this;
  20554. };
  20555. // Submeshes octree
  20556. /**
  20557. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20558. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20559. * @param maxCapacity defines the maximum size of each block (64 by default)
  20560. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20561. * @returns the new octree
  20562. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20563. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20564. */
  20565. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20566. if (maxCapacity === void 0) { maxCapacity = 64; }
  20567. if (maxDepth === void 0) { maxDepth = 2; }
  20568. if (!this._submeshesOctree) {
  20569. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20570. }
  20571. this.computeWorldMatrix(true);
  20572. var boundingInfo = this.getBoundingInfo();
  20573. // Update octree
  20574. var bbox = boundingInfo.boundingBox;
  20575. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20576. return this._submeshesOctree;
  20577. };
  20578. // Collisions
  20579. /** @hidden */
  20580. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20581. this._generatePointsArray();
  20582. if (!this._positions) {
  20583. return this;
  20584. }
  20585. // Transformation
  20586. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20587. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20588. subMesh._lastColliderWorldVertices = [];
  20589. subMesh._trianglePlanes = [];
  20590. var start = subMesh.verticesStart;
  20591. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20592. for (var i = start; i < end; i++) {
  20593. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20594. }
  20595. }
  20596. // Collide
  20597. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20598. if (collider.collisionFound) {
  20599. collider.collidedMesh = this;
  20600. }
  20601. return this;
  20602. };
  20603. /** @hidden */
  20604. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20605. var subMeshes;
  20606. var len;
  20607. // Octrees
  20608. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20609. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20610. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20611. len = intersections.length;
  20612. subMeshes = intersections.data;
  20613. }
  20614. else {
  20615. subMeshes = this.subMeshes;
  20616. len = subMeshes.length;
  20617. }
  20618. for (var index = 0; index < len; index++) {
  20619. var subMesh = subMeshes[index];
  20620. // Bounding test
  20621. if (len > 1 && !subMesh._checkCollision(collider))
  20622. continue;
  20623. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20624. }
  20625. return this;
  20626. };
  20627. /** @hidden */
  20628. AbstractMesh.prototype._checkCollision = function (collider) {
  20629. // Bounding box test
  20630. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20631. return this;
  20632. // Transformation matrix
  20633. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20634. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20635. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20636. return this;
  20637. };
  20638. // Picking
  20639. /** @hidden */
  20640. AbstractMesh.prototype._generatePointsArray = function () {
  20641. return false;
  20642. };
  20643. /**
  20644. * Checks if the passed Ray intersects with the mesh
  20645. * @param ray defines the ray to use
  20646. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20647. * @returns the picking info
  20648. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20649. */
  20650. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20651. var pickingInfo = new BABYLON.PickingInfo();
  20652. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20653. return pickingInfo;
  20654. }
  20655. if (!this._generatePointsArray()) {
  20656. return pickingInfo;
  20657. }
  20658. var intersectInfo = null;
  20659. // Octrees
  20660. var subMeshes;
  20661. var len;
  20662. if (this._submeshesOctree && this.useOctreeForPicking) {
  20663. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20664. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20665. len = intersections.length;
  20666. subMeshes = intersections.data;
  20667. }
  20668. else {
  20669. subMeshes = this.subMeshes;
  20670. len = subMeshes.length;
  20671. }
  20672. for (var index = 0; index < len; index++) {
  20673. var subMesh = subMeshes[index];
  20674. // Bounding test
  20675. if (len > 1 && !subMesh.canIntersects(ray))
  20676. continue;
  20677. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20678. if (currentIntersectInfo) {
  20679. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20680. intersectInfo = currentIntersectInfo;
  20681. intersectInfo.subMeshId = index;
  20682. if (fastCheck) {
  20683. break;
  20684. }
  20685. }
  20686. }
  20687. }
  20688. if (intersectInfo) {
  20689. // Get picked point
  20690. var world = this.getWorldMatrix();
  20691. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20692. var direction = ray.direction.clone();
  20693. direction = direction.scale(intersectInfo.distance);
  20694. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20695. var pickedPoint = worldOrigin.add(worldDirection);
  20696. // Return result
  20697. pickingInfo.hit = true;
  20698. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20699. pickingInfo.pickedPoint = pickedPoint;
  20700. pickingInfo.pickedMesh = this;
  20701. pickingInfo.bu = intersectInfo.bu || 0;
  20702. pickingInfo.bv = intersectInfo.bv || 0;
  20703. pickingInfo.faceId = intersectInfo.faceId;
  20704. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20705. return pickingInfo;
  20706. }
  20707. return pickingInfo;
  20708. };
  20709. /**
  20710. * Clones the current mesh
  20711. * @param name defines the mesh name
  20712. * @param newParent defines the new mesh parent
  20713. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20714. * @returns the new mesh
  20715. */
  20716. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20717. return null;
  20718. };
  20719. /**
  20720. * Disposes all the submeshes of the current meshnp
  20721. * @returns the current mesh
  20722. */
  20723. AbstractMesh.prototype.releaseSubMeshes = function () {
  20724. if (this.subMeshes) {
  20725. while (this.subMeshes.length) {
  20726. this.subMeshes[0].dispose();
  20727. }
  20728. }
  20729. else {
  20730. this.subMeshes = new Array();
  20731. }
  20732. return this;
  20733. };
  20734. /**
  20735. * Releases resources associated with this abstract mesh.
  20736. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20737. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20738. */
  20739. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20740. var _this = this;
  20741. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20742. var index;
  20743. // Smart Array Retainers.
  20744. this.getScene().freeActiveMeshes();
  20745. this.getScene().freeRenderingGroups();
  20746. // Action manager
  20747. if (this.actionManager !== undefined && this.actionManager !== null) {
  20748. this.actionManager.dispose();
  20749. this.actionManager = null;
  20750. }
  20751. // Skeleton
  20752. this._skeleton = null;
  20753. // Physics
  20754. if (this.physicsImpostor) {
  20755. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20756. }
  20757. // Intersections in progress
  20758. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20759. var other = this._intersectionsInProgress[index];
  20760. var pos = other._intersectionsInProgress.indexOf(this);
  20761. other._intersectionsInProgress.splice(pos, 1);
  20762. }
  20763. this._intersectionsInProgress = [];
  20764. // Lights
  20765. var lights = this.getScene().lights;
  20766. lights.forEach(function (light) {
  20767. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20768. if (meshIndex !== -1) {
  20769. light.includedOnlyMeshes.splice(meshIndex, 1);
  20770. }
  20771. meshIndex = light.excludedMeshes.indexOf(_this);
  20772. if (meshIndex !== -1) {
  20773. light.excludedMeshes.splice(meshIndex, 1);
  20774. }
  20775. // Shadow generators
  20776. var generator = light.getShadowGenerator();
  20777. if (generator) {
  20778. var shadowMap = generator.getShadowMap();
  20779. if (shadowMap && shadowMap.renderList) {
  20780. meshIndex = shadowMap.renderList.indexOf(_this);
  20781. if (meshIndex !== -1) {
  20782. shadowMap.renderList.splice(meshIndex, 1);
  20783. }
  20784. }
  20785. }
  20786. });
  20787. // Edges
  20788. if (this._edgesRenderer) {
  20789. this._edgesRenderer.dispose();
  20790. this._edgesRenderer = null;
  20791. }
  20792. // SubMeshes
  20793. if (this.getClassName() !== "InstancedMesh") {
  20794. this.releaseSubMeshes();
  20795. }
  20796. // Octree
  20797. var sceneOctree = this.getScene().selectionOctree;
  20798. if (sceneOctree !== undefined && sceneOctree !== null) {
  20799. var index = sceneOctree.dynamicContent.indexOf(this);
  20800. if (index !== -1) {
  20801. sceneOctree.dynamicContent.splice(index, 1);
  20802. }
  20803. }
  20804. // Query
  20805. var engine = this.getScene().getEngine();
  20806. if (this._occlusionQuery) {
  20807. this._isOcclusionQueryInProgress = false;
  20808. engine.deleteQuery(this._occlusionQuery);
  20809. this._occlusionQuery = null;
  20810. }
  20811. // Engine
  20812. engine.wipeCaches();
  20813. // Remove from scene
  20814. this.getScene().removeMesh(this);
  20815. if (disposeMaterialAndTextures) {
  20816. if (this.material) {
  20817. this.material.dispose(false, true);
  20818. }
  20819. }
  20820. if (!doNotRecurse) {
  20821. // Particles
  20822. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20823. if (this.getScene().particleSystems[index].emitter === this) {
  20824. this.getScene().particleSystems[index].dispose();
  20825. index--;
  20826. }
  20827. }
  20828. }
  20829. // facet data
  20830. if (this._facetDataEnabled) {
  20831. this.disableFacetData();
  20832. }
  20833. this.onAfterWorldMatrixUpdateObservable.clear();
  20834. this.onCollideObservable.clear();
  20835. this.onCollisionPositionChangeObservable.clear();
  20836. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20837. };
  20838. /**
  20839. * Adds the passed mesh as a child to the current mesh
  20840. * @param mesh defines the child mesh
  20841. * @returns the current mesh
  20842. */
  20843. AbstractMesh.prototype.addChild = function (mesh) {
  20844. mesh.setParent(this);
  20845. return this;
  20846. };
  20847. /**
  20848. * Removes the passed mesh from the current mesh children list
  20849. * @param mesh defines the child mesh
  20850. * @returns the current mesh
  20851. */
  20852. AbstractMesh.prototype.removeChild = function (mesh) {
  20853. mesh.setParent(null);
  20854. return this;
  20855. };
  20856. // Facet data
  20857. /** @hidden */
  20858. AbstractMesh.prototype._initFacetData = function () {
  20859. if (!this._facetNormals) {
  20860. this._facetNormals = new Array();
  20861. }
  20862. if (!this._facetPositions) {
  20863. this._facetPositions = new Array();
  20864. }
  20865. if (!this._facetPartitioning) {
  20866. this._facetPartitioning = new Array();
  20867. }
  20868. this._facetNb = (this.getIndices().length / 3) | 0;
  20869. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20870. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20871. for (var f = 0; f < this._facetNb; f++) {
  20872. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20873. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20874. }
  20875. this._facetDataEnabled = true;
  20876. return this;
  20877. };
  20878. /**
  20879. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20880. * This method can be called within the render loop.
  20881. * 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
  20882. * @returns the current mesh
  20883. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20884. */
  20885. AbstractMesh.prototype.updateFacetData = function () {
  20886. if (!this._facetDataEnabled) {
  20887. this._initFacetData();
  20888. }
  20889. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20890. var indices = this.getIndices();
  20891. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20892. var bInfo = this.getBoundingInfo();
  20893. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20894. // init arrays, matrix and sort function on first call
  20895. this._facetDepthSortEnabled = true;
  20896. if (indices instanceof Uint16Array) {
  20897. this._depthSortedIndices = new Uint16Array(indices);
  20898. }
  20899. else if (indices instanceof Uint32Array) {
  20900. this._depthSortedIndices = new Uint32Array(indices);
  20901. }
  20902. else {
  20903. var needs32bits = false;
  20904. for (var i = 0; i < indices.length; i++) {
  20905. if (indices[i] > 65535) {
  20906. needs32bits = true;
  20907. break;
  20908. }
  20909. }
  20910. if (needs32bits) {
  20911. this._depthSortedIndices = new Uint32Array(indices);
  20912. }
  20913. else {
  20914. this._depthSortedIndices = new Uint16Array(indices);
  20915. }
  20916. }
  20917. this._facetDepthSortFunction = function (f1, f2) {
  20918. return (f2.sqDistance - f1.sqDistance);
  20919. };
  20920. if (!this._facetDepthSortFrom) {
  20921. var camera = this.getScene().activeCamera;
  20922. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20923. }
  20924. this._depthSortedFacets = [];
  20925. for (var f = 0; f < this._facetNb; f++) {
  20926. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20927. this._depthSortedFacets.push(depthSortedFacet);
  20928. }
  20929. this._invertedMatrix = BABYLON.Matrix.Identity();
  20930. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20931. }
  20932. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20933. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20934. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20935. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20936. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20937. this._subDiv.max = this._partitioningSubdivisions;
  20938. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20939. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20940. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20941. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20942. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20943. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20944. // set the parameters for ComputeNormals()
  20945. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20946. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20947. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20948. this._facetParameters.bInfo = bInfo;
  20949. this._facetParameters.bbSize = this._bbSize;
  20950. this._facetParameters.subDiv = this._subDiv;
  20951. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20952. this._facetParameters.depthSort = this._facetDepthSort;
  20953. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20954. this.computeWorldMatrix(true);
  20955. this._worldMatrix.invertToRef(this._invertedMatrix);
  20956. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20957. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20958. }
  20959. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20960. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20961. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20962. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20963. var l = (this._depthSortedIndices.length / 3) | 0;
  20964. for (var f = 0; f < l; f++) {
  20965. var sind = this._depthSortedFacets[f].ind;
  20966. this._depthSortedIndices[f * 3] = indices[sind];
  20967. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20968. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20969. }
  20970. this.updateIndices(this._depthSortedIndices);
  20971. }
  20972. return this;
  20973. };
  20974. /**
  20975. * Returns the facetLocalNormals array.
  20976. * The normals are expressed in the mesh local spac
  20977. * @returns an array of Vector3
  20978. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20979. */
  20980. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20981. if (!this._facetNormals) {
  20982. this.updateFacetData();
  20983. }
  20984. return this._facetNormals;
  20985. };
  20986. /**
  20987. * Returns the facetLocalPositions array.
  20988. * The facet positions are expressed in the mesh local space
  20989. * @returns an array of Vector3
  20990. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20991. */
  20992. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20993. if (!this._facetPositions) {
  20994. this.updateFacetData();
  20995. }
  20996. return this._facetPositions;
  20997. };
  20998. /**
  20999. * Returns the facetLocalPartioning array
  21000. * @returns an array of array of numbers
  21001. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21002. */
  21003. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21004. if (!this._facetPartitioning) {
  21005. this.updateFacetData();
  21006. }
  21007. return this._facetPartitioning;
  21008. };
  21009. /**
  21010. * Returns the i-th facet position in the world system.
  21011. * This method allocates a new Vector3 per call
  21012. * @param i defines the facet index
  21013. * @returns a new Vector3
  21014. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21015. */
  21016. AbstractMesh.prototype.getFacetPosition = function (i) {
  21017. var pos = BABYLON.Vector3.Zero();
  21018. this.getFacetPositionToRef(i, pos);
  21019. return pos;
  21020. };
  21021. /**
  21022. * Sets the reference Vector3 with the i-th facet position in the world system
  21023. * @param i defines the facet index
  21024. * @param ref defines the target vector
  21025. * @returns the current mesh
  21026. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21027. */
  21028. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21029. var localPos = (this.getFacetLocalPositions())[i];
  21030. var world = this.getWorldMatrix();
  21031. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21032. return this;
  21033. };
  21034. /**
  21035. * Returns the i-th facet normal in the world system.
  21036. * This method allocates a new Vector3 per call
  21037. * @param i defines the facet index
  21038. * @returns a new Vector3
  21039. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21040. */
  21041. AbstractMesh.prototype.getFacetNormal = function (i) {
  21042. var norm = BABYLON.Vector3.Zero();
  21043. this.getFacetNormalToRef(i, norm);
  21044. return norm;
  21045. };
  21046. /**
  21047. * Sets the reference Vector3 with the i-th facet normal in the world system
  21048. * @param i defines the facet index
  21049. * @param ref defines the target vector
  21050. * @returns the current mesh
  21051. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21052. */
  21053. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21054. var localNorm = (this.getFacetLocalNormals())[i];
  21055. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21056. return this;
  21057. };
  21058. /**
  21059. * 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)
  21060. * @param x defines x coordinate
  21061. * @param y defines y coordinate
  21062. * @param z defines z coordinate
  21063. * @returns the array of facet indexes
  21064. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21065. */
  21066. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21067. var bInfo = this.getBoundingInfo();
  21068. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21069. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21070. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21071. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21072. return null;
  21073. }
  21074. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21075. };
  21076. /**
  21077. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21078. * @param projected sets as the (x,y,z) world projection on the facet
  21079. * @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
  21080. * @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
  21081. * @param x defines x coordinate
  21082. * @param y defines y coordinate
  21083. * @param z defines z coordinate
  21084. * @returns the face index if found (or null instead)
  21085. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21086. */
  21087. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21088. if (checkFace === void 0) { checkFace = false; }
  21089. if (facing === void 0) { facing = true; }
  21090. var world = this.getWorldMatrix();
  21091. var invMat = BABYLON.Tmp.Matrix[5];
  21092. world.invertToRef(invMat);
  21093. var invVect = BABYLON.Tmp.Vector3[8];
  21094. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21095. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21096. if (projected) {
  21097. // tranform the local computed projected vector to world coordinates
  21098. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21099. }
  21100. return closest;
  21101. };
  21102. /**
  21103. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21104. * @param projected sets as the (x,y,z) local projection on the facet
  21105. * @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
  21106. * @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
  21107. * @param x defines x coordinate
  21108. * @param y defines y coordinate
  21109. * @param z defines z coordinate
  21110. * @returns the face index if found (or null instead)
  21111. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21112. */
  21113. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21114. if (checkFace === void 0) { checkFace = false; }
  21115. if (facing === void 0) { facing = true; }
  21116. var closest = null;
  21117. var tmpx = 0.0;
  21118. var tmpy = 0.0;
  21119. var tmpz = 0.0;
  21120. var d = 0.0; // tmp dot facet normal * facet position
  21121. var t0 = 0.0;
  21122. var projx = 0.0;
  21123. var projy = 0.0;
  21124. var projz = 0.0;
  21125. // Get all the facets in the same partitioning block than (x, y, z)
  21126. var facetPositions = this.getFacetLocalPositions();
  21127. var facetNormals = this.getFacetLocalNormals();
  21128. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21129. if (!facetsInBlock) {
  21130. return null;
  21131. }
  21132. // Get the closest facet to (x, y, z)
  21133. var shortest = Number.MAX_VALUE; // init distance vars
  21134. var tmpDistance = shortest;
  21135. var fib; // current facet in the block
  21136. var norm; // current facet normal
  21137. var p0; // current facet barycenter position
  21138. // loop on all the facets in the current partitioning block
  21139. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21140. fib = facetsInBlock[idx];
  21141. norm = facetNormals[fib];
  21142. p0 = facetPositions[fib];
  21143. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21144. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21145. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21146. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21147. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21148. projx = x + norm.x * t0;
  21149. projy = y + norm.y * t0;
  21150. projz = z + norm.z * t0;
  21151. tmpx = projx - x;
  21152. tmpy = projy - y;
  21153. tmpz = projz - z;
  21154. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21155. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21156. shortest = tmpDistance;
  21157. closest = fib;
  21158. if (projected) {
  21159. projected.x = projx;
  21160. projected.y = projy;
  21161. projected.z = projz;
  21162. }
  21163. }
  21164. }
  21165. }
  21166. return closest;
  21167. };
  21168. /**
  21169. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21170. * @returns the parameters
  21171. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21172. */
  21173. AbstractMesh.prototype.getFacetDataParameters = function () {
  21174. return this._facetParameters;
  21175. };
  21176. /**
  21177. * Disables the feature FacetData and frees the related memory
  21178. * @returns the current mesh
  21179. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21180. */
  21181. AbstractMesh.prototype.disableFacetData = function () {
  21182. if (this._facetDataEnabled) {
  21183. this._facetDataEnabled = false;
  21184. this._facetPositions = new Array();
  21185. this._facetNormals = new Array();
  21186. this._facetPartitioning = new Array();
  21187. this._facetParameters = null;
  21188. this._depthSortedIndices = new Uint32Array(0);
  21189. }
  21190. return this;
  21191. };
  21192. /**
  21193. * Updates the AbstractMesh indices array
  21194. * @param indices defines the data source
  21195. * @returns the current mesh
  21196. */
  21197. AbstractMesh.prototype.updateIndices = function (indices) {
  21198. return this;
  21199. };
  21200. /**
  21201. * Creates new normals data for the mesh
  21202. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21203. * @returns the current mesh
  21204. */
  21205. AbstractMesh.prototype.createNormals = function (updatable) {
  21206. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21207. var indices = this.getIndices();
  21208. var normals;
  21209. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21210. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21211. }
  21212. else {
  21213. normals = [];
  21214. }
  21215. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21216. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21217. return this;
  21218. };
  21219. /**
  21220. * Align the mesh with a normal
  21221. * @param normal defines the normal to use
  21222. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21223. * @returns the current mesh
  21224. */
  21225. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21226. if (!upDirection) {
  21227. upDirection = BABYLON.Axis.Y;
  21228. }
  21229. var axisX = BABYLON.Tmp.Vector3[0];
  21230. var axisZ = BABYLON.Tmp.Vector3[1];
  21231. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21232. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21233. if (this.rotationQuaternion) {
  21234. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21235. }
  21236. else {
  21237. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21238. }
  21239. return this;
  21240. };
  21241. /** @hidden */
  21242. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21243. var engine = this.getEngine();
  21244. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21245. this._isOccluded = false;
  21246. return;
  21247. }
  21248. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21249. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21250. if (isOcclusionQueryAvailable) {
  21251. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21252. this._isOcclusionQueryInProgress = false;
  21253. this._occlusionInternalRetryCounter = 0;
  21254. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21255. }
  21256. else {
  21257. this._occlusionInternalRetryCounter++;
  21258. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21259. this._isOcclusionQueryInProgress = false;
  21260. this._occlusionInternalRetryCounter = 0;
  21261. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21262. // if strict continue the last state of the object.
  21263. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21264. }
  21265. else {
  21266. return;
  21267. }
  21268. }
  21269. }
  21270. var scene = this.getScene();
  21271. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21272. if (!this._occlusionQuery) {
  21273. this._occlusionQuery = engine.createQuery();
  21274. }
  21275. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21276. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21277. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21278. this._isOcclusionQueryInProgress = true;
  21279. };
  21280. /** No occlusion */
  21281. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21282. /** Occlusion set to optimisitic */
  21283. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21284. /** Occlusion set to strict */
  21285. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21286. /** Use an accurante occlusion algorithm */
  21287. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21288. /** Use a conservative occlusion algorithm */
  21289. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21290. return AbstractMesh;
  21291. }(BABYLON.TransformNode));
  21292. BABYLON.AbstractMesh = AbstractMesh;
  21293. })(BABYLON || (BABYLON = {}));
  21294. //# sourceMappingURL=babylon.abstractMesh.js.map
  21295. var BABYLON;
  21296. (function (BABYLON) {
  21297. /**
  21298. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21299. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21300. * 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.
  21301. */
  21302. var Light = /** @class */ (function (_super) {
  21303. __extends(Light, _super);
  21304. /**
  21305. * Creates a Light object in the scene.
  21306. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21307. * @param name The firendly name of the light
  21308. * @param scene The scene the light belongs too
  21309. */
  21310. function Light(name, scene) {
  21311. var _this = _super.call(this, name, scene) || this;
  21312. /**
  21313. * Diffuse gives the basic color to an object.
  21314. */
  21315. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21316. /**
  21317. * Specular produces a highlight color on an object.
  21318. * Note: This is note affecting PBR materials.
  21319. */
  21320. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21321. /**
  21322. * Strength of the light.
  21323. * Note: By default it is define in the framework own unit.
  21324. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21325. */
  21326. _this.intensity = 1.0;
  21327. /**
  21328. * Defines how far from the source the light is impacting in scene units.
  21329. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21330. */
  21331. _this.range = Number.MAX_VALUE;
  21332. /**
  21333. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21334. * of light.
  21335. */
  21336. _this._photometricScale = 1.0;
  21337. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21338. _this._radius = 0.00001;
  21339. /**
  21340. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21341. * exceeding the number allowed of the materials.
  21342. */
  21343. _this.renderPriority = 0;
  21344. _this._shadowEnabled = true;
  21345. _this._excludeWithLayerMask = 0;
  21346. _this._includeOnlyWithLayerMask = 0;
  21347. _this._lightmapMode = 0;
  21348. /**
  21349. * @hidden Internal use only.
  21350. */
  21351. _this._excludedMeshesIds = new Array();
  21352. /**
  21353. * @hidden Internal use only.
  21354. */
  21355. _this._includedOnlyMeshesIds = new Array();
  21356. _this.getScene().addLight(_this);
  21357. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21358. _this._buildUniformLayout();
  21359. _this.includedOnlyMeshes = new Array();
  21360. _this.excludedMeshes = new Array();
  21361. _this._resyncMeshes();
  21362. return _this;
  21363. }
  21364. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21365. /**
  21366. * If every light affecting the material is in this lightmapMode,
  21367. * material.lightmapTexture adds or multiplies
  21368. * (depends on material.useLightmapAsShadowmap)
  21369. * after every other light calculations.
  21370. */
  21371. get: function () {
  21372. return Light._LIGHTMAP_DEFAULT;
  21373. },
  21374. enumerable: true,
  21375. configurable: true
  21376. });
  21377. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21378. /**
  21379. * material.lightmapTexture as only diffuse lighting from this light
  21380. * adds only specular lighting from this light
  21381. * adds dynamic shadows
  21382. */
  21383. get: function () {
  21384. return Light._LIGHTMAP_SPECULAR;
  21385. },
  21386. enumerable: true,
  21387. configurable: true
  21388. });
  21389. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21390. /**
  21391. * material.lightmapTexture as only lighting
  21392. * no light calculation from this light
  21393. * only adds dynamic shadows from this light
  21394. */
  21395. get: function () {
  21396. return Light._LIGHTMAP_SHADOWSONLY;
  21397. },
  21398. enumerable: true,
  21399. configurable: true
  21400. });
  21401. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21402. /**
  21403. * Each light type uses the default quantity according to its type:
  21404. * point/spot lights use luminous intensity
  21405. * directional lights use illuminance
  21406. */
  21407. get: function () {
  21408. return Light._INTENSITYMODE_AUTOMATIC;
  21409. },
  21410. enumerable: true,
  21411. configurable: true
  21412. });
  21413. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21414. /**
  21415. * lumen (lm)
  21416. */
  21417. get: function () {
  21418. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21419. },
  21420. enumerable: true,
  21421. configurable: true
  21422. });
  21423. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21424. /**
  21425. * candela (lm/sr)
  21426. */
  21427. get: function () {
  21428. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21429. },
  21430. enumerable: true,
  21431. configurable: true
  21432. });
  21433. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21434. /**
  21435. * lux (lm/m^2)
  21436. */
  21437. get: function () {
  21438. return Light._INTENSITYMODE_ILLUMINANCE;
  21439. },
  21440. enumerable: true,
  21441. configurable: true
  21442. });
  21443. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21444. /**
  21445. * nit (cd/m^2)
  21446. */
  21447. get: function () {
  21448. return Light._INTENSITYMODE_LUMINANCE;
  21449. },
  21450. enumerable: true,
  21451. configurable: true
  21452. });
  21453. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21454. /**
  21455. * Light type const id of the point light.
  21456. */
  21457. get: function () {
  21458. return Light._LIGHTTYPEID_POINTLIGHT;
  21459. },
  21460. enumerable: true,
  21461. configurable: true
  21462. });
  21463. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21464. /**
  21465. * Light type const id of the directional light.
  21466. */
  21467. get: function () {
  21468. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21469. },
  21470. enumerable: true,
  21471. configurable: true
  21472. });
  21473. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21474. /**
  21475. * Light type const id of the spot light.
  21476. */
  21477. get: function () {
  21478. return Light._LIGHTTYPEID_SPOTLIGHT;
  21479. },
  21480. enumerable: true,
  21481. configurable: true
  21482. });
  21483. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21484. /**
  21485. * Light type const id of the hemispheric light.
  21486. */
  21487. get: function () {
  21488. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21489. },
  21490. enumerable: true,
  21491. configurable: true
  21492. });
  21493. Object.defineProperty(Light.prototype, "intensityMode", {
  21494. /**
  21495. * Gets the photometric scale used to interpret the intensity.
  21496. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21497. */
  21498. get: function () {
  21499. return this._intensityMode;
  21500. },
  21501. /**
  21502. * Sets the photometric scale used to interpret the intensity.
  21503. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21504. */
  21505. set: function (value) {
  21506. this._intensityMode = value;
  21507. this._computePhotometricScale();
  21508. },
  21509. enumerable: true,
  21510. configurable: true
  21511. });
  21512. ;
  21513. ;
  21514. Object.defineProperty(Light.prototype, "radius", {
  21515. /**
  21516. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21517. */
  21518. get: function () {
  21519. return this._radius;
  21520. },
  21521. /**
  21522. * sets the light radius used by PBR Materials to simulate soft area lights.
  21523. */
  21524. set: function (value) {
  21525. this._radius = value;
  21526. this._computePhotometricScale();
  21527. },
  21528. enumerable: true,
  21529. configurable: true
  21530. });
  21531. ;
  21532. ;
  21533. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21534. /**
  21535. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21536. * the current shadow generator.
  21537. */
  21538. get: function () {
  21539. return this._shadowEnabled;
  21540. },
  21541. /**
  21542. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21543. * the current shadow generator.
  21544. */
  21545. set: function (value) {
  21546. if (this._shadowEnabled === value) {
  21547. return;
  21548. }
  21549. this._shadowEnabled = value;
  21550. this._markMeshesAsLightDirty();
  21551. },
  21552. enumerable: true,
  21553. configurable: true
  21554. });
  21555. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21556. /**
  21557. * Gets the only meshes impacted by this light.
  21558. */
  21559. get: function () {
  21560. return this._includedOnlyMeshes;
  21561. },
  21562. /**
  21563. * Sets the only meshes impacted by this light.
  21564. */
  21565. set: function (value) {
  21566. this._includedOnlyMeshes = value;
  21567. this._hookArrayForIncludedOnly(value);
  21568. },
  21569. enumerable: true,
  21570. configurable: true
  21571. });
  21572. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21573. /**
  21574. * Gets the meshes not impacted by this light.
  21575. */
  21576. get: function () {
  21577. return this._excludedMeshes;
  21578. },
  21579. /**
  21580. * Sets the meshes not impacted by this light.
  21581. */
  21582. set: function (value) {
  21583. this._excludedMeshes = value;
  21584. this._hookArrayForExcluded(value);
  21585. },
  21586. enumerable: true,
  21587. configurable: true
  21588. });
  21589. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21590. /**
  21591. * Gets the layer id use to find what meshes are not impacted by the light.
  21592. * Inactive if 0
  21593. */
  21594. get: function () {
  21595. return this._excludeWithLayerMask;
  21596. },
  21597. /**
  21598. * Sets the layer id use to find what meshes are not impacted by the light.
  21599. * Inactive if 0
  21600. */
  21601. set: function (value) {
  21602. this._excludeWithLayerMask = value;
  21603. this._resyncMeshes();
  21604. },
  21605. enumerable: true,
  21606. configurable: true
  21607. });
  21608. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21609. /**
  21610. * Gets the layer id use to find what meshes are impacted by the light.
  21611. * Inactive if 0
  21612. */
  21613. get: function () {
  21614. return this._includeOnlyWithLayerMask;
  21615. },
  21616. /**
  21617. * Sets the layer id use to find what meshes are impacted by the light.
  21618. * Inactive if 0
  21619. */
  21620. set: function (value) {
  21621. this._includeOnlyWithLayerMask = value;
  21622. this._resyncMeshes();
  21623. },
  21624. enumerable: true,
  21625. configurable: true
  21626. });
  21627. Object.defineProperty(Light.prototype, "lightmapMode", {
  21628. /**
  21629. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21630. */
  21631. get: function () {
  21632. return this._lightmapMode;
  21633. },
  21634. /**
  21635. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21636. */
  21637. set: function (value) {
  21638. if (this._lightmapMode === value) {
  21639. return;
  21640. }
  21641. this._lightmapMode = value;
  21642. this._markMeshesAsLightDirty();
  21643. },
  21644. enumerable: true,
  21645. configurable: true
  21646. });
  21647. /**
  21648. * Returns the string "Light".
  21649. * @returns the class name
  21650. */
  21651. Light.prototype.getClassName = function () {
  21652. return "Light";
  21653. };
  21654. /**
  21655. * Converts the light information to a readable string for debug purpose.
  21656. * @param fullDetails Supports for multiple levels of logging within scene loading
  21657. * @returns the human readable light info
  21658. */
  21659. Light.prototype.toString = function (fullDetails) {
  21660. var ret = "Name: " + this.name;
  21661. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21662. if (this.animations) {
  21663. for (var i = 0; i < this.animations.length; i++) {
  21664. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21665. }
  21666. }
  21667. if (fullDetails) {
  21668. }
  21669. return ret;
  21670. };
  21671. /**
  21672. * Set the enabled state of this node.
  21673. * @param value - the new enabled state
  21674. */
  21675. Light.prototype.setEnabled = function (value) {
  21676. _super.prototype.setEnabled.call(this, value);
  21677. this._resyncMeshes();
  21678. };
  21679. /**
  21680. * Returns the Light associated shadow generator if any.
  21681. * @return the associated shadow generator.
  21682. */
  21683. Light.prototype.getShadowGenerator = function () {
  21684. return this._shadowGenerator;
  21685. };
  21686. /**
  21687. * Returns a Vector3, the absolute light position in the World.
  21688. * @returns the world space position of the light
  21689. */
  21690. Light.prototype.getAbsolutePosition = function () {
  21691. return BABYLON.Vector3.Zero();
  21692. };
  21693. /**
  21694. * Specifies if the light will affect the passed mesh.
  21695. * @param mesh The mesh to test against the light
  21696. * @return true the mesh is affected otherwise, false.
  21697. */
  21698. Light.prototype.canAffectMesh = function (mesh) {
  21699. if (!mesh) {
  21700. return true;
  21701. }
  21702. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21703. return false;
  21704. }
  21705. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21706. return false;
  21707. }
  21708. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21709. return false;
  21710. }
  21711. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21712. return false;
  21713. }
  21714. return true;
  21715. };
  21716. /**
  21717. * Computes and Returns the light World matrix.
  21718. * @returns the world matrix
  21719. */
  21720. Light.prototype.getWorldMatrix = function () {
  21721. this._currentRenderId = this.getScene().getRenderId();
  21722. this._childRenderId = this._currentRenderId;
  21723. var worldMatrix = this._getWorldMatrix();
  21724. if (this.parent && this.parent.getWorldMatrix) {
  21725. if (!this._parentedWorldMatrix) {
  21726. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21727. }
  21728. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21729. this._markSyncedWithParent();
  21730. return this._parentedWorldMatrix;
  21731. }
  21732. return worldMatrix;
  21733. };
  21734. /**
  21735. * Sort function to order lights for rendering.
  21736. * @param a First Light object to compare to second.
  21737. * @param b Second Light object to compare first.
  21738. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21739. */
  21740. Light.CompareLightsPriority = function (a, b) {
  21741. //shadow-casting lights have priority over non-shadow-casting lights
  21742. //the renderPrioirty is a secondary sort criterion
  21743. if (a.shadowEnabled !== b.shadowEnabled) {
  21744. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21745. }
  21746. return b.renderPriority - a.renderPriority;
  21747. };
  21748. /**
  21749. * Releases resources associated with this node.
  21750. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21751. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21752. */
  21753. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21754. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21755. if (this._shadowGenerator) {
  21756. this._shadowGenerator.dispose();
  21757. this._shadowGenerator = null;
  21758. }
  21759. // Animations
  21760. this.getScene().stopAnimation(this);
  21761. // Remove from meshes
  21762. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21763. var mesh = _a[_i];
  21764. mesh._removeLightSource(this);
  21765. }
  21766. this._uniformBuffer.dispose();
  21767. // Remove from scene
  21768. this.getScene().removeLight(this);
  21769. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21770. };
  21771. /**
  21772. * Returns the light type ID (integer).
  21773. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21774. */
  21775. Light.prototype.getTypeID = function () {
  21776. return 0;
  21777. };
  21778. /**
  21779. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21780. * @returns the scaled intensity in intensity mode unit
  21781. */
  21782. Light.prototype.getScaledIntensity = function () {
  21783. return this._photometricScale * this.intensity;
  21784. };
  21785. /**
  21786. * Returns a new Light object, named "name", from the current one.
  21787. * @param name The name of the cloned light
  21788. * @returns the new created light
  21789. */
  21790. Light.prototype.clone = function (name) {
  21791. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21792. if (!constructor) {
  21793. return null;
  21794. }
  21795. return BABYLON.SerializationHelper.Clone(constructor, this);
  21796. };
  21797. /**
  21798. * Serializes the current light into a Serialization object.
  21799. * @returns the serialized object.
  21800. */
  21801. Light.prototype.serialize = function () {
  21802. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21803. // Type
  21804. serializationObject.type = this.getTypeID();
  21805. // Parent
  21806. if (this.parent) {
  21807. serializationObject.parentId = this.parent.id;
  21808. }
  21809. // Inclusion / exclusions
  21810. if (this.excludedMeshes.length > 0) {
  21811. serializationObject.excludedMeshesIds = [];
  21812. this.excludedMeshes.forEach(function (mesh) {
  21813. serializationObject.excludedMeshesIds.push(mesh.id);
  21814. });
  21815. }
  21816. if (this.includedOnlyMeshes.length > 0) {
  21817. serializationObject.includedOnlyMeshesIds = [];
  21818. this.includedOnlyMeshes.forEach(function (mesh) {
  21819. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21820. });
  21821. }
  21822. // Animations
  21823. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21824. serializationObject.ranges = this.serializeAnimationRanges();
  21825. return serializationObject;
  21826. };
  21827. /**
  21828. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21829. * This new light is named "name" and added to the passed scene.
  21830. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21831. * @param name The friendly name of the light
  21832. * @param scene The scene the new light will belong to
  21833. * @returns the constructor function
  21834. */
  21835. Light.GetConstructorFromName = function (type, name, scene) {
  21836. switch (type) {
  21837. case 0:
  21838. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21839. case 1:
  21840. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21841. case 2:
  21842. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21843. case 3:
  21844. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21845. }
  21846. return null;
  21847. };
  21848. /**
  21849. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21850. * @param parsedLight The JSON representation of the light
  21851. * @param scene The scene to create the parsed light in
  21852. * @returns the created light after parsing
  21853. */
  21854. Light.Parse = function (parsedLight, scene) {
  21855. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21856. if (!constructor) {
  21857. return null;
  21858. }
  21859. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21860. // Inclusion / exclusions
  21861. if (parsedLight.excludedMeshesIds) {
  21862. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21863. }
  21864. if (parsedLight.includedOnlyMeshesIds) {
  21865. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21866. }
  21867. // Parent
  21868. if (parsedLight.parentId) {
  21869. light._waitingParentId = parsedLight.parentId;
  21870. }
  21871. // Animations
  21872. if (parsedLight.animations) {
  21873. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21874. var parsedAnimation = parsedLight.animations[animationIndex];
  21875. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21876. }
  21877. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21878. }
  21879. if (parsedLight.autoAnimate) {
  21880. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21881. }
  21882. return light;
  21883. };
  21884. Light.prototype._hookArrayForExcluded = function (array) {
  21885. var _this = this;
  21886. var oldPush = array.push;
  21887. array.push = function () {
  21888. var items = [];
  21889. for (var _i = 0; _i < arguments.length; _i++) {
  21890. items[_i] = arguments[_i];
  21891. }
  21892. var result = oldPush.apply(array, items);
  21893. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21894. var item = items_1[_a];
  21895. item._resyncLighSource(_this);
  21896. }
  21897. return result;
  21898. };
  21899. var oldSplice = array.splice;
  21900. array.splice = function (index, deleteCount) {
  21901. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21902. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21903. var item = deleted_1[_i];
  21904. item._resyncLighSource(_this);
  21905. }
  21906. return deleted;
  21907. };
  21908. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21909. var item = array_1[_i];
  21910. item._resyncLighSource(this);
  21911. }
  21912. };
  21913. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21914. var _this = this;
  21915. var oldPush = array.push;
  21916. array.push = function () {
  21917. var items = [];
  21918. for (var _i = 0; _i < arguments.length; _i++) {
  21919. items[_i] = arguments[_i];
  21920. }
  21921. var result = oldPush.apply(array, items);
  21922. _this._resyncMeshes();
  21923. return result;
  21924. };
  21925. var oldSplice = array.splice;
  21926. array.splice = function (index, deleteCount) {
  21927. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21928. _this._resyncMeshes();
  21929. return deleted;
  21930. };
  21931. this._resyncMeshes();
  21932. };
  21933. Light.prototype._resyncMeshes = function () {
  21934. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21935. var mesh = _a[_i];
  21936. mesh._resyncLighSource(this);
  21937. }
  21938. };
  21939. /**
  21940. * Forces the meshes to update their light related information in their rendering used effects
  21941. * @hidden Internal Use Only
  21942. */
  21943. Light.prototype._markMeshesAsLightDirty = function () {
  21944. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21945. var mesh = _a[_i];
  21946. if (mesh._lightSources.indexOf(this) !== -1) {
  21947. mesh._markSubMeshesAsLightDirty();
  21948. }
  21949. }
  21950. };
  21951. /**
  21952. * Recomputes the cached photometric scale if needed.
  21953. */
  21954. Light.prototype._computePhotometricScale = function () {
  21955. this._photometricScale = this._getPhotometricScale();
  21956. this.getScene().resetCachedMaterial();
  21957. };
  21958. /**
  21959. * Returns the Photometric Scale according to the light type and intensity mode.
  21960. */
  21961. Light.prototype._getPhotometricScale = function () {
  21962. var photometricScale = 0.0;
  21963. var lightTypeID = this.getTypeID();
  21964. //get photometric mode
  21965. var photometricMode = this.intensityMode;
  21966. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21967. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21968. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21969. }
  21970. else {
  21971. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21972. }
  21973. }
  21974. //compute photometric scale
  21975. switch (lightTypeID) {
  21976. case Light.LIGHTTYPEID_POINTLIGHT:
  21977. case Light.LIGHTTYPEID_SPOTLIGHT:
  21978. switch (photometricMode) {
  21979. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21980. photometricScale = 1.0 / (4.0 * Math.PI);
  21981. break;
  21982. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21983. photometricScale = 1.0;
  21984. break;
  21985. case Light.INTENSITYMODE_LUMINANCE:
  21986. photometricScale = this.radius * this.radius;
  21987. break;
  21988. }
  21989. break;
  21990. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21991. switch (photometricMode) {
  21992. case Light.INTENSITYMODE_ILLUMINANCE:
  21993. photometricScale = 1.0;
  21994. break;
  21995. case Light.INTENSITYMODE_LUMINANCE:
  21996. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21997. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21998. var apexAngleRadians = this.radius;
  21999. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22000. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22001. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22002. photometricScale = solidAngle;
  22003. break;
  22004. }
  22005. break;
  22006. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22007. // No fall off in hemisperic light.
  22008. photometricScale = 1.0;
  22009. break;
  22010. }
  22011. return photometricScale;
  22012. };
  22013. /**
  22014. * Reorder the light in the scene according to their defined priority.
  22015. * @hidden Internal Use Only
  22016. */
  22017. Light.prototype._reorderLightsInScene = function () {
  22018. var scene = this.getScene();
  22019. if (this._renderPriority != 0) {
  22020. scene.requireLightSorting = true;
  22021. }
  22022. this.getScene().sortLightsByPriority();
  22023. };
  22024. //lightmapMode Consts
  22025. Light._LIGHTMAP_DEFAULT = 0;
  22026. Light._LIGHTMAP_SPECULAR = 1;
  22027. Light._LIGHTMAP_SHADOWSONLY = 2;
  22028. // Intensity Mode Consts
  22029. Light._INTENSITYMODE_AUTOMATIC = 0;
  22030. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22031. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22032. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22033. Light._INTENSITYMODE_LUMINANCE = 4;
  22034. // Light types ids const.
  22035. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22036. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22037. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22038. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22039. __decorate([
  22040. BABYLON.serializeAsColor3()
  22041. ], Light.prototype, "diffuse", void 0);
  22042. __decorate([
  22043. BABYLON.serializeAsColor3()
  22044. ], Light.prototype, "specular", void 0);
  22045. __decorate([
  22046. BABYLON.serialize()
  22047. ], Light.prototype, "intensity", void 0);
  22048. __decorate([
  22049. BABYLON.serialize()
  22050. ], Light.prototype, "range", void 0);
  22051. __decorate([
  22052. BABYLON.serialize()
  22053. ], Light.prototype, "intensityMode", null);
  22054. __decorate([
  22055. BABYLON.serialize()
  22056. ], Light.prototype, "radius", null);
  22057. __decorate([
  22058. BABYLON.serialize()
  22059. ], Light.prototype, "_renderPriority", void 0);
  22060. __decorate([
  22061. BABYLON.expandToProperty("_reorderLightsInScene")
  22062. ], Light.prototype, "renderPriority", void 0);
  22063. __decorate([
  22064. BABYLON.serialize("shadowEnabled")
  22065. ], Light.prototype, "_shadowEnabled", void 0);
  22066. __decorate([
  22067. BABYLON.serialize("excludeWithLayerMask")
  22068. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22069. __decorate([
  22070. BABYLON.serialize("includeOnlyWithLayerMask")
  22071. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22072. __decorate([
  22073. BABYLON.serialize("lightmapMode")
  22074. ], Light.prototype, "_lightmapMode", void 0);
  22075. return Light;
  22076. }(BABYLON.Node));
  22077. BABYLON.Light = Light;
  22078. })(BABYLON || (BABYLON = {}));
  22079. //# sourceMappingURL=babylon.light.js.map
  22080. var BABYLON;
  22081. (function (BABYLON) {
  22082. var Camera = /** @class */ (function (_super) {
  22083. __extends(Camera, _super);
  22084. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22085. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22086. var _this = _super.call(this, name, scene) || this;
  22087. /**
  22088. * The vector the camera should consider as up.
  22089. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22090. */
  22091. _this.upVector = BABYLON.Vector3.Up();
  22092. _this.orthoLeft = null;
  22093. _this.orthoRight = null;
  22094. _this.orthoBottom = null;
  22095. _this.orthoTop = null;
  22096. /**
  22097. * FOV is set in Radians. (default is 0.8)
  22098. */
  22099. _this.fov = 0.8;
  22100. _this.minZ = 1;
  22101. _this.maxZ = 10000.0;
  22102. _this.inertia = 0.9;
  22103. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22104. _this.isIntermediate = false;
  22105. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22106. /**
  22107. * Restricts the camera to viewing objects with the same layerMask.
  22108. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22109. */
  22110. _this.layerMask = 0x0FFFFFFF;
  22111. /**
  22112. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22113. */
  22114. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22115. // Camera rig members
  22116. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22117. _this._rigCameras = new Array();
  22118. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22119. _this._skipRendering = false;
  22120. _this.customRenderTargets = new Array();
  22121. // Observables
  22122. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22123. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22124. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22125. _this.onRestoreStateObservable = new BABYLON.Observable();
  22126. // Cache
  22127. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22128. _this._projectionMatrix = new BABYLON.Matrix();
  22129. _this._doNotComputeProjectionMatrix = false;
  22130. _this._worldMatrix = BABYLON.Matrix.Identity();
  22131. _this._postProcesses = new Array();
  22132. _this._transformMatrix = BABYLON.Matrix.Zero();
  22133. _this._activeMeshes = new BABYLON.SmartArray(256);
  22134. _this._globalPosition = BABYLON.Vector3.Zero();
  22135. _this._refreshFrustumPlanes = true;
  22136. _this.getScene().addCamera(_this);
  22137. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22138. _this.getScene().activeCamera = _this;
  22139. }
  22140. _this.position = position;
  22141. return _this;
  22142. }
  22143. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22144. get: function () {
  22145. return Camera._PERSPECTIVE_CAMERA;
  22146. },
  22147. enumerable: true,
  22148. configurable: true
  22149. });
  22150. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22151. get: function () {
  22152. return Camera._ORTHOGRAPHIC_CAMERA;
  22153. },
  22154. enumerable: true,
  22155. configurable: true
  22156. });
  22157. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22158. /**
  22159. * This is the default FOV mode for perspective cameras.
  22160. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22161. *
  22162. */
  22163. get: function () {
  22164. return Camera._FOVMODE_VERTICAL_FIXED;
  22165. },
  22166. enumerable: true,
  22167. configurable: true
  22168. });
  22169. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22170. /**
  22171. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22172. *
  22173. */
  22174. get: function () {
  22175. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22176. },
  22177. enumerable: true,
  22178. configurable: true
  22179. });
  22180. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22181. get: function () {
  22182. return Camera._RIG_MODE_NONE;
  22183. },
  22184. enumerable: true,
  22185. configurable: true
  22186. });
  22187. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22188. get: function () {
  22189. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22190. },
  22191. enumerable: true,
  22192. configurable: true
  22193. });
  22194. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22195. get: function () {
  22196. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22197. },
  22198. enumerable: true,
  22199. configurable: true
  22200. });
  22201. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22202. get: function () {
  22203. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22204. },
  22205. enumerable: true,
  22206. configurable: true
  22207. });
  22208. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22209. get: function () {
  22210. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22211. },
  22212. enumerable: true,
  22213. configurable: true
  22214. });
  22215. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22216. get: function () {
  22217. return Camera._RIG_MODE_VR;
  22218. },
  22219. enumerable: true,
  22220. configurable: true
  22221. });
  22222. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22223. get: function () {
  22224. return Camera._RIG_MODE_WEBVR;
  22225. },
  22226. enumerable: true,
  22227. configurable: true
  22228. });
  22229. /**
  22230. * Store current camera state (fov, position, etc..)
  22231. */
  22232. Camera.prototype.storeState = function () {
  22233. this._stateStored = true;
  22234. this._storedFov = this.fov;
  22235. return this;
  22236. };
  22237. /**
  22238. * Restores the camera state values if it has been stored. You must call storeState() first
  22239. */
  22240. Camera.prototype._restoreStateValues = function () {
  22241. if (!this._stateStored) {
  22242. return false;
  22243. }
  22244. this.fov = this._storedFov;
  22245. return true;
  22246. };
  22247. /**
  22248. * Restored camera state. You must call storeState() first
  22249. */
  22250. Camera.prototype.restoreState = function () {
  22251. if (this._restoreStateValues()) {
  22252. this.onRestoreStateObservable.notifyObservers(this);
  22253. return true;
  22254. }
  22255. return false;
  22256. };
  22257. Camera.prototype.getClassName = function () {
  22258. return "Camera";
  22259. };
  22260. /**
  22261. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22262. */
  22263. Camera.prototype.toString = function (fullDetails) {
  22264. var ret = "Name: " + this.name;
  22265. ret += ", type: " + this.getClassName();
  22266. if (this.animations) {
  22267. for (var i = 0; i < this.animations.length; i++) {
  22268. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22269. }
  22270. }
  22271. if (fullDetails) {
  22272. }
  22273. return ret;
  22274. };
  22275. Object.defineProperty(Camera.prototype, "globalPosition", {
  22276. get: function () {
  22277. return this._globalPosition;
  22278. },
  22279. enumerable: true,
  22280. configurable: true
  22281. });
  22282. Camera.prototype.getActiveMeshes = function () {
  22283. return this._activeMeshes;
  22284. };
  22285. Camera.prototype.isActiveMesh = function (mesh) {
  22286. return (this._activeMeshes.indexOf(mesh) !== -1);
  22287. };
  22288. /**
  22289. * Is this camera ready to be used/rendered
  22290. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22291. * @return true if the camera is ready
  22292. */
  22293. Camera.prototype.isReady = function (completeCheck) {
  22294. if (completeCheck === void 0) { completeCheck = false; }
  22295. if (completeCheck) {
  22296. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22297. var pp = _a[_i];
  22298. if (pp && !pp.isReady()) {
  22299. return false;
  22300. }
  22301. }
  22302. }
  22303. return _super.prototype.isReady.call(this, completeCheck);
  22304. };
  22305. //Cache
  22306. Camera.prototype._initCache = function () {
  22307. _super.prototype._initCache.call(this);
  22308. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22309. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22310. this._cache.mode = undefined;
  22311. this._cache.minZ = undefined;
  22312. this._cache.maxZ = undefined;
  22313. this._cache.fov = undefined;
  22314. this._cache.fovMode = undefined;
  22315. this._cache.aspectRatio = undefined;
  22316. this._cache.orthoLeft = undefined;
  22317. this._cache.orthoRight = undefined;
  22318. this._cache.orthoBottom = undefined;
  22319. this._cache.orthoTop = undefined;
  22320. this._cache.renderWidth = undefined;
  22321. this._cache.renderHeight = undefined;
  22322. };
  22323. Camera.prototype._updateCache = function (ignoreParentClass) {
  22324. if (!ignoreParentClass) {
  22325. _super.prototype._updateCache.call(this);
  22326. }
  22327. this._cache.position.copyFrom(this.position);
  22328. this._cache.upVector.copyFrom(this.upVector);
  22329. };
  22330. // Synchronized
  22331. Camera.prototype._isSynchronized = function () {
  22332. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22333. };
  22334. Camera.prototype._isSynchronizedViewMatrix = function () {
  22335. if (!_super.prototype._isSynchronized.call(this))
  22336. return false;
  22337. return this._cache.position.equals(this.position)
  22338. && this._cache.upVector.equals(this.upVector)
  22339. && this.isSynchronizedWithParent();
  22340. };
  22341. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22342. var check = this._cache.mode === this.mode
  22343. && this._cache.minZ === this.minZ
  22344. && this._cache.maxZ === this.maxZ;
  22345. if (!check) {
  22346. return false;
  22347. }
  22348. var engine = this.getEngine();
  22349. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22350. check = this._cache.fov === this.fov
  22351. && this._cache.fovMode === this.fovMode
  22352. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22353. }
  22354. else {
  22355. check = this._cache.orthoLeft === this.orthoLeft
  22356. && this._cache.orthoRight === this.orthoRight
  22357. && this._cache.orthoBottom === this.orthoBottom
  22358. && this._cache.orthoTop === this.orthoTop
  22359. && this._cache.renderWidth === engine.getRenderWidth()
  22360. && this._cache.renderHeight === engine.getRenderHeight();
  22361. }
  22362. return check;
  22363. };
  22364. // Controls
  22365. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22366. };
  22367. Camera.prototype.detachControl = function (element) {
  22368. };
  22369. Camera.prototype.update = function () {
  22370. this._checkInputs();
  22371. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22372. this._updateRigCameras();
  22373. }
  22374. };
  22375. Camera.prototype._checkInputs = function () {
  22376. this.onAfterCheckInputsObservable.notifyObservers(this);
  22377. };
  22378. Object.defineProperty(Camera.prototype, "rigCameras", {
  22379. get: function () {
  22380. return this._rigCameras;
  22381. },
  22382. enumerable: true,
  22383. configurable: true
  22384. });
  22385. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22386. get: function () {
  22387. return this._rigPostProcess;
  22388. },
  22389. enumerable: true,
  22390. configurable: true
  22391. });
  22392. /**
  22393. * Internal, gets the first post proces.
  22394. * @returns the first post process to be run on this camera.
  22395. */
  22396. Camera.prototype._getFirstPostProcess = function () {
  22397. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22398. if (this._postProcesses[ppIndex] !== null) {
  22399. return this._postProcesses[ppIndex];
  22400. }
  22401. }
  22402. return null;
  22403. };
  22404. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22405. // invalidate framebuffer
  22406. var firstPostProcess = this._getFirstPostProcess();
  22407. if (firstPostProcess) {
  22408. firstPostProcess.markTextureDirty();
  22409. }
  22410. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22411. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22412. var cam = this._rigCameras[i];
  22413. var rigPostProcess = cam._rigPostProcess;
  22414. // for VR rig, there does not have to be a post process
  22415. if (rigPostProcess) {
  22416. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22417. if (isPass) {
  22418. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22419. cam.isIntermediate = this._postProcesses.length === 0;
  22420. }
  22421. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22422. rigPostProcess.markTextureDirty();
  22423. }
  22424. else {
  22425. cam._postProcesses = this._postProcesses.slice(0);
  22426. }
  22427. }
  22428. };
  22429. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22430. if (insertAt === void 0) { insertAt = null; }
  22431. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22432. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22433. return 0;
  22434. }
  22435. if (insertAt == null || insertAt < 0) {
  22436. this._postProcesses.push(postProcess);
  22437. }
  22438. else if (this._postProcesses[insertAt] === null) {
  22439. this._postProcesses[insertAt] = postProcess;
  22440. }
  22441. else {
  22442. this._postProcesses.splice(insertAt, 0, postProcess);
  22443. }
  22444. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22445. return this._postProcesses.indexOf(postProcess);
  22446. };
  22447. Camera.prototype.detachPostProcess = function (postProcess) {
  22448. var idx = this._postProcesses.indexOf(postProcess);
  22449. if (idx !== -1) {
  22450. this._postProcesses[idx] = null;
  22451. }
  22452. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22453. };
  22454. Camera.prototype.getWorldMatrix = function () {
  22455. if (this._isSynchronizedViewMatrix()) {
  22456. return this._worldMatrix;
  22457. }
  22458. // Getting the the view matrix will also compute the world matrix.
  22459. this.getViewMatrix();
  22460. return this._worldMatrix;
  22461. };
  22462. Camera.prototype._getViewMatrix = function () {
  22463. return BABYLON.Matrix.Identity();
  22464. };
  22465. Camera.prototype.getViewMatrix = function (force) {
  22466. if (!force && this._isSynchronizedViewMatrix()) {
  22467. return this._computedViewMatrix;
  22468. }
  22469. this.updateCache();
  22470. this._computedViewMatrix = this._getViewMatrix();
  22471. this._currentRenderId = this.getScene().getRenderId();
  22472. this._childRenderId = this._currentRenderId;
  22473. this._refreshFrustumPlanes = true;
  22474. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22475. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22476. }
  22477. this.onViewMatrixChangedObservable.notifyObservers(this);
  22478. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22479. return this._computedViewMatrix;
  22480. };
  22481. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22482. this._doNotComputeProjectionMatrix = true;
  22483. if (projection !== undefined) {
  22484. this._projectionMatrix = projection;
  22485. }
  22486. };
  22487. ;
  22488. Camera.prototype.unfreezeProjectionMatrix = function () {
  22489. this._doNotComputeProjectionMatrix = false;
  22490. };
  22491. ;
  22492. Camera.prototype.getProjectionMatrix = function (force) {
  22493. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22494. return this._projectionMatrix;
  22495. }
  22496. // Cache
  22497. this._cache.mode = this.mode;
  22498. this._cache.minZ = this.minZ;
  22499. this._cache.maxZ = this.maxZ;
  22500. // Matrix
  22501. this._refreshFrustumPlanes = true;
  22502. var engine = this.getEngine();
  22503. var scene = this.getScene();
  22504. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22505. this._cache.fov = this.fov;
  22506. this._cache.fovMode = this.fovMode;
  22507. this._cache.aspectRatio = engine.getAspectRatio(this);
  22508. if (this.minZ <= 0) {
  22509. this.minZ = 0.1;
  22510. }
  22511. if (scene.useRightHandedSystem) {
  22512. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22513. }
  22514. else {
  22515. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22516. }
  22517. }
  22518. else {
  22519. var halfWidth = engine.getRenderWidth() / 2.0;
  22520. var halfHeight = engine.getRenderHeight() / 2.0;
  22521. if (scene.useRightHandedSystem) {
  22522. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22523. }
  22524. else {
  22525. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22526. }
  22527. this._cache.orthoLeft = this.orthoLeft;
  22528. this._cache.orthoRight = this.orthoRight;
  22529. this._cache.orthoBottom = this.orthoBottom;
  22530. this._cache.orthoTop = this.orthoTop;
  22531. this._cache.renderWidth = engine.getRenderWidth();
  22532. this._cache.renderHeight = engine.getRenderHeight();
  22533. }
  22534. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22535. return this._projectionMatrix;
  22536. };
  22537. Camera.prototype.getTranformationMatrix = function () {
  22538. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22539. return this._transformMatrix;
  22540. };
  22541. Camera.prototype.updateFrustumPlanes = function () {
  22542. if (!this._refreshFrustumPlanes) {
  22543. return;
  22544. }
  22545. this.getTranformationMatrix();
  22546. if (!this._frustumPlanes) {
  22547. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22548. }
  22549. else {
  22550. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22551. }
  22552. this._refreshFrustumPlanes = false;
  22553. };
  22554. Camera.prototype.isInFrustum = function (target) {
  22555. this.updateFrustumPlanes();
  22556. return target.isInFrustum(this._frustumPlanes);
  22557. };
  22558. Camera.prototype.isCompletelyInFrustum = function (target) {
  22559. this.updateFrustumPlanes();
  22560. return target.isCompletelyInFrustum(this._frustumPlanes);
  22561. };
  22562. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22563. if (length === void 0) { length = 100; }
  22564. if (!transform) {
  22565. transform = this.getWorldMatrix();
  22566. }
  22567. if (!origin) {
  22568. origin = this.position;
  22569. }
  22570. var forward = new BABYLON.Vector3(0, 0, 1);
  22571. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22572. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22573. return new BABYLON.Ray(origin, direction, length);
  22574. };
  22575. /**
  22576. * Releases resources associated with this node.
  22577. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22578. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22579. */
  22580. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22581. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22582. // Observables
  22583. this.onViewMatrixChangedObservable.clear();
  22584. this.onProjectionMatrixChangedObservable.clear();
  22585. this.onAfterCheckInputsObservable.clear();
  22586. this.onRestoreStateObservable.clear();
  22587. // Inputs
  22588. if (this.inputs) {
  22589. this.inputs.clear();
  22590. }
  22591. // Animations
  22592. this.getScene().stopAnimation(this);
  22593. // Remove from scene
  22594. this.getScene().removeCamera(this);
  22595. while (this._rigCameras.length > 0) {
  22596. var camera = this._rigCameras.pop();
  22597. if (camera) {
  22598. camera.dispose();
  22599. }
  22600. }
  22601. // Postprocesses
  22602. if (this._rigPostProcess) {
  22603. this._rigPostProcess.dispose(this);
  22604. this._rigPostProcess = null;
  22605. this._postProcesses = [];
  22606. }
  22607. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22608. this._rigPostProcess = null;
  22609. this._postProcesses = [];
  22610. }
  22611. else {
  22612. var i = this._postProcesses.length;
  22613. while (--i >= 0) {
  22614. var postProcess = this._postProcesses[i];
  22615. if (postProcess) {
  22616. postProcess.dispose(this);
  22617. }
  22618. }
  22619. }
  22620. // Render targets
  22621. var i = this.customRenderTargets.length;
  22622. while (--i >= 0) {
  22623. this.customRenderTargets[i].dispose();
  22624. }
  22625. this.customRenderTargets = [];
  22626. // Active Meshes
  22627. this._activeMeshes.dispose();
  22628. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22629. };
  22630. Object.defineProperty(Camera.prototype, "leftCamera", {
  22631. // ---- Camera rigs section ----
  22632. get: function () {
  22633. if (this._rigCameras.length < 1) {
  22634. return null;
  22635. }
  22636. return this._rigCameras[0];
  22637. },
  22638. enumerable: true,
  22639. configurable: true
  22640. });
  22641. Object.defineProperty(Camera.prototype, "rightCamera", {
  22642. get: function () {
  22643. if (this._rigCameras.length < 2) {
  22644. return null;
  22645. }
  22646. return this._rigCameras[1];
  22647. },
  22648. enumerable: true,
  22649. configurable: true
  22650. });
  22651. Camera.prototype.getLeftTarget = function () {
  22652. if (this._rigCameras.length < 1) {
  22653. return null;
  22654. }
  22655. return this._rigCameras[0].getTarget();
  22656. };
  22657. Camera.prototype.getRightTarget = function () {
  22658. if (this._rigCameras.length < 2) {
  22659. return null;
  22660. }
  22661. return this._rigCameras[1].getTarget();
  22662. };
  22663. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22664. if (this.cameraRigMode === mode) {
  22665. return;
  22666. }
  22667. while (this._rigCameras.length > 0) {
  22668. var camera = this._rigCameras.pop();
  22669. if (camera) {
  22670. camera.dispose();
  22671. }
  22672. }
  22673. this.cameraRigMode = mode;
  22674. this._cameraRigParams = {};
  22675. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22676. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22677. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22678. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22679. // create the rig cameras, unless none
  22680. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22681. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22682. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22683. if (leftCamera && rightCamera) {
  22684. this._rigCameras.push(leftCamera);
  22685. this._rigCameras.push(rightCamera);
  22686. }
  22687. }
  22688. switch (this.cameraRigMode) {
  22689. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22690. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22691. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22692. break;
  22693. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22694. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22695. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22696. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22697. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22698. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22699. break;
  22700. case Camera.RIG_MODE_VR:
  22701. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22702. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22703. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22704. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22705. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22706. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22707. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22708. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22709. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22710. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22711. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22712. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22713. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22714. if (metrics.compensateDistortion) {
  22715. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22716. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22717. }
  22718. break;
  22719. case Camera.RIG_MODE_WEBVR:
  22720. if (rigParams.vrDisplay) {
  22721. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22722. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22723. //Left eye
  22724. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22725. this._rigCameras[0].setCameraRigParameter("left", true);
  22726. //leaving this for future reference
  22727. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22728. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22729. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22730. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22731. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22732. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22733. this._rigCameras[0].parent = this;
  22734. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22735. //Right eye
  22736. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22737. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22738. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22739. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22740. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22741. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22742. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22743. this._rigCameras[1].parent = this;
  22744. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22745. if (Camera.UseAlternateWebVRRendering) {
  22746. this._rigCameras[1]._skipRendering = true;
  22747. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22748. }
  22749. }
  22750. break;
  22751. }
  22752. this._cascadePostProcessesToRigCams();
  22753. this.update();
  22754. };
  22755. Camera.prototype._getVRProjectionMatrix = function () {
  22756. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22757. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22758. return this._projectionMatrix;
  22759. };
  22760. Camera.prototype._updateCameraRotationMatrix = function () {
  22761. //Here for WebVR
  22762. };
  22763. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22764. //Here for WebVR
  22765. };
  22766. /**
  22767. * This function MUST be overwritten by the different WebVR cameras available.
  22768. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22769. */
  22770. Camera.prototype._getWebVRProjectionMatrix = function () {
  22771. return BABYLON.Matrix.Identity();
  22772. };
  22773. /**
  22774. * This function MUST be overwritten by the different WebVR cameras available.
  22775. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22776. */
  22777. Camera.prototype._getWebVRViewMatrix = function () {
  22778. return BABYLON.Matrix.Identity();
  22779. };
  22780. Camera.prototype.setCameraRigParameter = function (name, value) {
  22781. if (!this._cameraRigParams) {
  22782. this._cameraRigParams = {};
  22783. }
  22784. this._cameraRigParams[name] = value;
  22785. //provisionnally:
  22786. if (name === "interaxialDistance") {
  22787. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22788. }
  22789. };
  22790. /**
  22791. * needs to be overridden by children so sub has required properties to be copied
  22792. */
  22793. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22794. return null;
  22795. };
  22796. /**
  22797. * May need to be overridden by children
  22798. */
  22799. Camera.prototype._updateRigCameras = function () {
  22800. for (var i = 0; i < this._rigCameras.length; i++) {
  22801. this._rigCameras[i].minZ = this.minZ;
  22802. this._rigCameras[i].maxZ = this.maxZ;
  22803. this._rigCameras[i].fov = this.fov;
  22804. }
  22805. // only update viewport when ANAGLYPH
  22806. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22807. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22808. }
  22809. };
  22810. Camera.prototype._setupInputs = function () {
  22811. };
  22812. Camera.prototype.serialize = function () {
  22813. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22814. // Type
  22815. serializationObject.type = this.getClassName();
  22816. // Parent
  22817. if (this.parent) {
  22818. serializationObject.parentId = this.parent.id;
  22819. }
  22820. if (this.inputs) {
  22821. this.inputs.serialize(serializationObject);
  22822. }
  22823. // Animations
  22824. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22825. serializationObject.ranges = this.serializeAnimationRanges();
  22826. return serializationObject;
  22827. };
  22828. Camera.prototype.clone = function (name) {
  22829. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22830. };
  22831. Camera.prototype.getDirection = function (localAxis) {
  22832. var result = BABYLON.Vector3.Zero();
  22833. this.getDirectionToRef(localAxis, result);
  22834. return result;
  22835. };
  22836. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22837. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22838. };
  22839. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22840. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22841. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22842. switch (type) {
  22843. case "ArcRotateCamera":
  22844. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22845. case "DeviceOrientationCamera":
  22846. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22847. case "FollowCamera":
  22848. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22849. case "ArcFollowCamera":
  22850. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22851. case "GamepadCamera":
  22852. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22853. case "TouchCamera":
  22854. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22855. case "VirtualJoysticksCamera":
  22856. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22857. case "WebVRFreeCamera":
  22858. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22859. case "WebVRGamepadCamera":
  22860. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22861. case "VRDeviceOrientationFreeCamera":
  22862. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22863. case "VRDeviceOrientationGamepadCamera":
  22864. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22865. case "AnaglyphArcRotateCamera":
  22866. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22867. case "AnaglyphFreeCamera":
  22868. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22869. case "AnaglyphGamepadCamera":
  22870. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22871. case "AnaglyphUniversalCamera":
  22872. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22873. case "StereoscopicArcRotateCamera":
  22874. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22875. case "StereoscopicFreeCamera":
  22876. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22877. case "StereoscopicGamepadCamera":
  22878. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22879. case "StereoscopicUniversalCamera":
  22880. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22881. case "FreeCamera": // Forcing Universal here
  22882. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22883. default: // Universal Camera is the default value
  22884. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22885. }
  22886. };
  22887. Camera.prototype.computeWorldMatrix = function () {
  22888. return this.getWorldMatrix();
  22889. };
  22890. Camera.Parse = function (parsedCamera, scene) {
  22891. var type = parsedCamera.type;
  22892. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22893. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22894. // Parent
  22895. if (parsedCamera.parentId) {
  22896. camera._waitingParentId = parsedCamera.parentId;
  22897. }
  22898. //If camera has an input manager, let it parse inputs settings
  22899. if (camera.inputs) {
  22900. camera.inputs.parse(parsedCamera);
  22901. camera._setupInputs();
  22902. }
  22903. if (camera.setPosition) { // need to force position
  22904. camera.position.copyFromFloats(0, 0, 0);
  22905. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22906. }
  22907. // Target
  22908. if (parsedCamera.target) {
  22909. if (camera.setTarget) {
  22910. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22911. }
  22912. }
  22913. // Apply 3d rig, when found
  22914. if (parsedCamera.cameraRigMode) {
  22915. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22916. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22917. }
  22918. // Animations
  22919. if (parsedCamera.animations) {
  22920. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22921. var parsedAnimation = parsedCamera.animations[animationIndex];
  22922. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22923. }
  22924. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22925. }
  22926. if (parsedCamera.autoAnimate) {
  22927. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22928. }
  22929. return camera;
  22930. };
  22931. // Statics
  22932. Camera._PERSPECTIVE_CAMERA = 0;
  22933. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22934. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22935. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22936. Camera._RIG_MODE_NONE = 0;
  22937. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22938. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22939. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22940. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22941. Camera._RIG_MODE_VR = 20;
  22942. Camera._RIG_MODE_WEBVR = 21;
  22943. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22944. Camera.UseAlternateWebVRRendering = false;
  22945. __decorate([
  22946. BABYLON.serializeAsVector3()
  22947. ], Camera.prototype, "position", void 0);
  22948. __decorate([
  22949. BABYLON.serializeAsVector3()
  22950. ], Camera.prototype, "upVector", void 0);
  22951. __decorate([
  22952. BABYLON.serialize()
  22953. ], Camera.prototype, "orthoLeft", void 0);
  22954. __decorate([
  22955. BABYLON.serialize()
  22956. ], Camera.prototype, "orthoRight", void 0);
  22957. __decorate([
  22958. BABYLON.serialize()
  22959. ], Camera.prototype, "orthoBottom", void 0);
  22960. __decorate([
  22961. BABYLON.serialize()
  22962. ], Camera.prototype, "orthoTop", void 0);
  22963. __decorate([
  22964. BABYLON.serialize()
  22965. ], Camera.prototype, "fov", void 0);
  22966. __decorate([
  22967. BABYLON.serialize()
  22968. ], Camera.prototype, "minZ", void 0);
  22969. __decorate([
  22970. BABYLON.serialize()
  22971. ], Camera.prototype, "maxZ", void 0);
  22972. __decorate([
  22973. BABYLON.serialize()
  22974. ], Camera.prototype, "inertia", void 0);
  22975. __decorate([
  22976. BABYLON.serialize()
  22977. ], Camera.prototype, "mode", void 0);
  22978. __decorate([
  22979. BABYLON.serialize()
  22980. ], Camera.prototype, "layerMask", void 0);
  22981. __decorate([
  22982. BABYLON.serialize()
  22983. ], Camera.prototype, "fovMode", void 0);
  22984. __decorate([
  22985. BABYLON.serialize()
  22986. ], Camera.prototype, "cameraRigMode", void 0);
  22987. __decorate([
  22988. BABYLON.serialize()
  22989. ], Camera.prototype, "interaxialDistance", void 0);
  22990. __decorate([
  22991. BABYLON.serialize()
  22992. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22993. return Camera;
  22994. }(BABYLON.Node));
  22995. BABYLON.Camera = Camera;
  22996. })(BABYLON || (BABYLON = {}));
  22997. //# sourceMappingURL=babylon.camera.js.map
  22998. var BABYLON;
  22999. (function (BABYLON) {
  23000. var RenderingManager = /** @class */ (function () {
  23001. function RenderingManager(scene) {
  23002. this._renderingGroups = new Array();
  23003. this._autoClearDepthStencil = {};
  23004. this._customOpaqueSortCompareFn = {};
  23005. this._customAlphaTestSortCompareFn = {};
  23006. this._customTransparentSortCompareFn = {};
  23007. this._renderinGroupInfo = null;
  23008. this._scene = scene;
  23009. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23010. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23011. }
  23012. }
  23013. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23014. if (depth === void 0) { depth = true; }
  23015. if (stencil === void 0) { stencil = true; }
  23016. if (this._depthStencilBufferAlreadyCleaned) {
  23017. return;
  23018. }
  23019. this._scene.getEngine().clear(null, false, depth, stencil);
  23020. this._depthStencilBufferAlreadyCleaned = true;
  23021. };
  23022. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23023. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23024. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23025. var info = null;
  23026. if (observable) {
  23027. if (!this._renderinGroupInfo) {
  23028. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23029. }
  23030. info = this._renderinGroupInfo;
  23031. info.scene = this._scene;
  23032. info.camera = this._scene.activeCamera;
  23033. }
  23034. // Dispatch sprites
  23035. if (renderSprites) {
  23036. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23037. var manager = this._scene.spriteManagers[index];
  23038. this.dispatchSprites(manager);
  23039. }
  23040. }
  23041. // Render
  23042. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23043. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23044. var renderingGroup = this._renderingGroups[index];
  23045. if (!renderingGroup && !observable)
  23046. continue;
  23047. var renderingGroupMask = 0;
  23048. // Fire PRECLEAR stage
  23049. if (observable && info) {
  23050. renderingGroupMask = Math.pow(2, index);
  23051. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23052. info.renderingGroupId = index;
  23053. observable.notifyObservers(info, renderingGroupMask);
  23054. }
  23055. // Clear depth/stencil if needed
  23056. if (RenderingManager.AUTOCLEAR) {
  23057. var autoClear = this._autoClearDepthStencil[index];
  23058. if (autoClear && autoClear.autoClear) {
  23059. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23060. }
  23061. }
  23062. if (observable && info) {
  23063. // Fire PREOPAQUE stage
  23064. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23065. observable.notifyObservers(info, renderingGroupMask);
  23066. // Fire PRETRANSPARENT stage
  23067. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23068. observable.notifyObservers(info, renderingGroupMask);
  23069. }
  23070. if (renderingGroup)
  23071. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23072. // Fire POSTTRANSPARENT stage
  23073. if (observable && info) {
  23074. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23075. observable.notifyObservers(info, renderingGroupMask);
  23076. }
  23077. }
  23078. };
  23079. RenderingManager.prototype.reset = function () {
  23080. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23081. var renderingGroup = this._renderingGroups[index];
  23082. if (renderingGroup) {
  23083. renderingGroup.prepare();
  23084. }
  23085. }
  23086. };
  23087. RenderingManager.prototype.dispose = function () {
  23088. this.freeRenderingGroups();
  23089. this._renderingGroups.length = 0;
  23090. };
  23091. /**
  23092. * Clear the info related to rendering groups preventing retention points during dispose.
  23093. */
  23094. RenderingManager.prototype.freeRenderingGroups = function () {
  23095. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23096. var renderingGroup = this._renderingGroups[index];
  23097. if (renderingGroup) {
  23098. renderingGroup.dispose();
  23099. }
  23100. }
  23101. };
  23102. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23103. if (this._renderingGroups[renderingGroupId] === undefined) {
  23104. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23105. }
  23106. };
  23107. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23108. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23109. this._prepareRenderingGroup(renderingGroupId);
  23110. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23111. };
  23112. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23113. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23114. this._prepareRenderingGroup(renderingGroupId);
  23115. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23116. };
  23117. /**
  23118. * @param subMesh The submesh to dispatch
  23119. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23120. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23121. */
  23122. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23123. if (mesh === undefined) {
  23124. mesh = subMesh.getMesh();
  23125. }
  23126. var renderingGroupId = mesh.renderingGroupId || 0;
  23127. this._prepareRenderingGroup(renderingGroupId);
  23128. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23129. };
  23130. /**
  23131. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23132. * This allowed control for front to back rendering or reversly depending of the special needs.
  23133. *
  23134. * @param renderingGroupId The rendering group id corresponding to its index
  23135. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23136. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23137. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23138. */
  23139. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23140. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23141. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23142. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23143. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23144. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23145. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23146. if (this._renderingGroups[renderingGroupId]) {
  23147. var group = this._renderingGroups[renderingGroupId];
  23148. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23149. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23150. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23151. }
  23152. };
  23153. /**
  23154. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23155. *
  23156. * @param renderingGroupId The rendering group id corresponding to its index
  23157. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23158. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23159. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23160. */
  23161. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23162. if (depth === void 0) { depth = true; }
  23163. if (stencil === void 0) { stencil = true; }
  23164. this._autoClearDepthStencil[renderingGroupId] = {
  23165. autoClear: autoClearDepthStencil,
  23166. depth: depth,
  23167. stencil: stencil
  23168. };
  23169. };
  23170. /**
  23171. * The max id used for rendering groups (not included)
  23172. */
  23173. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23174. /**
  23175. * The min id used for rendering groups (included)
  23176. */
  23177. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23178. /**
  23179. * Used to globally prevent autoclearing scenes.
  23180. */
  23181. RenderingManager.AUTOCLEAR = true;
  23182. return RenderingManager;
  23183. }());
  23184. BABYLON.RenderingManager = RenderingManager;
  23185. })(BABYLON || (BABYLON = {}));
  23186. //# sourceMappingURL=babylon.renderingManager.js.map
  23187. var BABYLON;
  23188. (function (BABYLON) {
  23189. var RenderingGroup = /** @class */ (function () {
  23190. /**
  23191. * Creates a new rendering group.
  23192. * @param index The rendering group index
  23193. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23194. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23195. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23196. */
  23197. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23198. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23199. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23200. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23201. this.index = index;
  23202. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23203. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23204. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23205. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23206. this._particleSystems = new BABYLON.SmartArray(256);
  23207. this._spriteManagers = new BABYLON.SmartArray(256);
  23208. this._edgesRenderers = new BABYLON.SmartArray(16);
  23209. this._scene = scene;
  23210. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23211. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23212. this.transparentSortCompareFn = transparentSortCompareFn;
  23213. }
  23214. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23215. /**
  23216. * Set the opaque sort comparison function.
  23217. * If null the sub meshes will be render in the order they were created
  23218. */
  23219. set: function (value) {
  23220. this._opaqueSortCompareFn = value;
  23221. if (value) {
  23222. this._renderOpaque = this.renderOpaqueSorted;
  23223. }
  23224. else {
  23225. this._renderOpaque = RenderingGroup.renderUnsorted;
  23226. }
  23227. },
  23228. enumerable: true,
  23229. configurable: true
  23230. });
  23231. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23232. /**
  23233. * Set the alpha test sort comparison function.
  23234. * If null the sub meshes will be render in the order they were created
  23235. */
  23236. set: function (value) {
  23237. this._alphaTestSortCompareFn = value;
  23238. if (value) {
  23239. this._renderAlphaTest = this.renderAlphaTestSorted;
  23240. }
  23241. else {
  23242. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23243. }
  23244. },
  23245. enumerable: true,
  23246. configurable: true
  23247. });
  23248. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23249. /**
  23250. * Set the transparent sort comparison function.
  23251. * If null the sub meshes will be render in the order they were created
  23252. */
  23253. set: function (value) {
  23254. if (value) {
  23255. this._transparentSortCompareFn = value;
  23256. }
  23257. else {
  23258. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23259. }
  23260. this._renderTransparent = this.renderTransparentSorted;
  23261. },
  23262. enumerable: true,
  23263. configurable: true
  23264. });
  23265. /**
  23266. * Render all the sub meshes contained in the group.
  23267. * @param customRenderFunction Used to override the default render behaviour of the group.
  23268. * @returns true if rendered some submeshes.
  23269. */
  23270. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23271. if (customRenderFunction) {
  23272. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23273. return;
  23274. }
  23275. var engine = this._scene.getEngine();
  23276. // Depth only
  23277. if (this._depthOnlySubMeshes.length !== 0) {
  23278. engine.setColorWrite(false);
  23279. this._renderAlphaTest(this._depthOnlySubMeshes);
  23280. engine.setColorWrite(true);
  23281. }
  23282. // Opaque
  23283. if (this._opaqueSubMeshes.length !== 0) {
  23284. this._renderOpaque(this._opaqueSubMeshes);
  23285. }
  23286. // Alpha test
  23287. if (this._alphaTestSubMeshes.length !== 0) {
  23288. this._renderAlphaTest(this._alphaTestSubMeshes);
  23289. }
  23290. var stencilState = engine.getStencilBuffer();
  23291. engine.setStencilBuffer(false);
  23292. // Sprites
  23293. if (renderSprites) {
  23294. this._renderSprites();
  23295. }
  23296. // Particles
  23297. if (renderParticles) {
  23298. this._renderParticles(activeMeshes);
  23299. }
  23300. if (this.onBeforeTransparentRendering) {
  23301. this.onBeforeTransparentRendering();
  23302. }
  23303. // Transparent
  23304. if (this._transparentSubMeshes.length !== 0) {
  23305. this._renderTransparent(this._transparentSubMeshes);
  23306. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23307. }
  23308. // Set back stencil to false in case it changes before the edge renderer.
  23309. engine.setStencilBuffer(false);
  23310. // Edges
  23311. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23312. this._edgesRenderers.data[edgesRendererIndex].render();
  23313. }
  23314. // Restore Stencil state.
  23315. engine.setStencilBuffer(stencilState);
  23316. };
  23317. /**
  23318. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23319. * @param subMeshes The submeshes to render
  23320. */
  23321. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23322. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23323. };
  23324. /**
  23325. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23326. * @param subMeshes The submeshes to render
  23327. */
  23328. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23329. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23330. };
  23331. /**
  23332. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23333. * @param subMeshes The submeshes to render
  23334. */
  23335. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23336. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23337. };
  23338. /**
  23339. * Renders the submeshes in a specified order.
  23340. * @param subMeshes The submeshes to sort before render
  23341. * @param sortCompareFn The comparison function use to sort
  23342. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23343. * @param transparent Specifies to activate blending if true
  23344. */
  23345. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23346. var subIndex = 0;
  23347. var subMesh;
  23348. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23349. for (; subIndex < subMeshes.length; subIndex++) {
  23350. subMesh = subMeshes.data[subIndex];
  23351. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23352. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23353. }
  23354. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23355. if (sortCompareFn) {
  23356. sortedArray.sort(sortCompareFn);
  23357. }
  23358. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23359. subMesh = sortedArray[subIndex];
  23360. if (transparent) {
  23361. var material = subMesh.getMaterial();
  23362. if (material && material.needDepthPrePass) {
  23363. var engine = material.getScene().getEngine();
  23364. engine.setColorWrite(false);
  23365. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23366. subMesh.render(false);
  23367. engine.setColorWrite(true);
  23368. }
  23369. }
  23370. subMesh.render(transparent);
  23371. }
  23372. };
  23373. /**
  23374. * Renders the submeshes in the order they were dispatched (no sort applied).
  23375. * @param subMeshes The submeshes to render
  23376. */
  23377. RenderingGroup.renderUnsorted = function (subMeshes) {
  23378. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23379. var submesh = subMeshes.data[subIndex];
  23380. submesh.render(false);
  23381. }
  23382. };
  23383. /**
  23384. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23385. * are rendered back to front if in the same alpha index.
  23386. *
  23387. * @param a The first submesh
  23388. * @param b The second submesh
  23389. * @returns The result of the comparison
  23390. */
  23391. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23392. // Alpha index first
  23393. if (a._alphaIndex > b._alphaIndex) {
  23394. return 1;
  23395. }
  23396. if (a._alphaIndex < b._alphaIndex) {
  23397. return -1;
  23398. }
  23399. // Then distance to camera
  23400. return RenderingGroup.backToFrontSortCompare(a, b);
  23401. };
  23402. /**
  23403. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23404. * are rendered back to front.
  23405. *
  23406. * @param a The first submesh
  23407. * @param b The second submesh
  23408. * @returns The result of the comparison
  23409. */
  23410. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23411. // Then distance to camera
  23412. if (a._distanceToCamera < b._distanceToCamera) {
  23413. return 1;
  23414. }
  23415. if (a._distanceToCamera > b._distanceToCamera) {
  23416. return -1;
  23417. }
  23418. return 0;
  23419. };
  23420. /**
  23421. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23422. * are rendered front to back (prevent overdraw).
  23423. *
  23424. * @param a The first submesh
  23425. * @param b The second submesh
  23426. * @returns The result of the comparison
  23427. */
  23428. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23429. // Then distance to camera
  23430. if (a._distanceToCamera < b._distanceToCamera) {
  23431. return -1;
  23432. }
  23433. if (a._distanceToCamera > b._distanceToCamera) {
  23434. return 1;
  23435. }
  23436. return 0;
  23437. };
  23438. /**
  23439. * Resets the different lists of submeshes to prepare a new frame.
  23440. */
  23441. RenderingGroup.prototype.prepare = function () {
  23442. this._opaqueSubMeshes.reset();
  23443. this._transparentSubMeshes.reset();
  23444. this._alphaTestSubMeshes.reset();
  23445. this._depthOnlySubMeshes.reset();
  23446. this._particleSystems.reset();
  23447. this._spriteManagers.reset();
  23448. this._edgesRenderers.reset();
  23449. };
  23450. RenderingGroup.prototype.dispose = function () {
  23451. this._opaqueSubMeshes.dispose();
  23452. this._transparentSubMeshes.dispose();
  23453. this._alphaTestSubMeshes.dispose();
  23454. this._depthOnlySubMeshes.dispose();
  23455. this._particleSystems.dispose();
  23456. this._spriteManagers.dispose();
  23457. this._edgesRenderers.dispose();
  23458. };
  23459. /**
  23460. * Inserts the submesh in its correct queue depending on its material.
  23461. * @param subMesh The submesh to dispatch
  23462. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23463. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23464. */
  23465. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23466. // Get mesh and materials if not provided
  23467. if (mesh === undefined) {
  23468. mesh = subMesh.getMesh();
  23469. }
  23470. if (material === undefined) {
  23471. material = subMesh.getMaterial();
  23472. }
  23473. if (material === null || material === undefined) {
  23474. return;
  23475. }
  23476. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23477. this._transparentSubMeshes.push(subMesh);
  23478. }
  23479. else if (material.needAlphaTesting()) { // Alpha test
  23480. if (material.needDepthPrePass) {
  23481. this._depthOnlySubMeshes.push(subMesh);
  23482. }
  23483. this._alphaTestSubMeshes.push(subMesh);
  23484. }
  23485. else {
  23486. if (material.needDepthPrePass) {
  23487. this._depthOnlySubMeshes.push(subMesh);
  23488. }
  23489. this._opaqueSubMeshes.push(subMesh); // Opaque
  23490. }
  23491. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23492. this._edgesRenderers.push(mesh._edgesRenderer);
  23493. }
  23494. };
  23495. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23496. this._spriteManagers.push(spriteManager);
  23497. };
  23498. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23499. this._particleSystems.push(particleSystem);
  23500. };
  23501. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23502. if (this._particleSystems.length === 0) {
  23503. return;
  23504. }
  23505. // Particles
  23506. var activeCamera = this._scene.activeCamera;
  23507. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23508. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23509. var particleSystem = this._particleSystems.data[particleIndex];
  23510. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23511. continue;
  23512. }
  23513. var emitter = particleSystem.emitter;
  23514. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23515. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23516. }
  23517. }
  23518. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23519. };
  23520. RenderingGroup.prototype._renderSprites = function () {
  23521. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23522. return;
  23523. }
  23524. // Sprites
  23525. var activeCamera = this._scene.activeCamera;
  23526. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23527. for (var id = 0; id < this._spriteManagers.length; id++) {
  23528. var spriteManager = this._spriteManagers.data[id];
  23529. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23530. spriteManager.render();
  23531. }
  23532. }
  23533. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23534. };
  23535. return RenderingGroup;
  23536. }());
  23537. BABYLON.RenderingGroup = RenderingGroup;
  23538. })(BABYLON || (BABYLON = {}));
  23539. //# sourceMappingURL=babylon.renderingGroup.js.map
  23540. var BABYLON;
  23541. (function (BABYLON) {
  23542. /** @hidden */
  23543. var ClickInfo = /** @class */ (function () {
  23544. function ClickInfo() {
  23545. this._singleClick = false;
  23546. this._doubleClick = false;
  23547. this._hasSwiped = false;
  23548. this._ignore = false;
  23549. }
  23550. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23551. get: function () {
  23552. return this._singleClick;
  23553. },
  23554. set: function (b) {
  23555. this._singleClick = b;
  23556. },
  23557. enumerable: true,
  23558. configurable: true
  23559. });
  23560. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23561. get: function () {
  23562. return this._doubleClick;
  23563. },
  23564. set: function (b) {
  23565. this._doubleClick = b;
  23566. },
  23567. enumerable: true,
  23568. configurable: true
  23569. });
  23570. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23571. get: function () {
  23572. return this._hasSwiped;
  23573. },
  23574. set: function (b) {
  23575. this._hasSwiped = b;
  23576. },
  23577. enumerable: true,
  23578. configurable: true
  23579. });
  23580. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23581. get: function () {
  23582. return this._ignore;
  23583. },
  23584. set: function (b) {
  23585. this._ignore = b;
  23586. },
  23587. enumerable: true,
  23588. configurable: true
  23589. });
  23590. return ClickInfo;
  23591. }());
  23592. /**
  23593. * This class is used by the onRenderingGroupObservable
  23594. */
  23595. var RenderingGroupInfo = /** @class */ (function () {
  23596. function RenderingGroupInfo() {
  23597. }
  23598. /**
  23599. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23600. * This stage will be fired no matter what
  23601. */
  23602. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23603. /**
  23604. * Called before opaque object are rendered.
  23605. * This stage will be fired only if there's 3D Opaque content to render
  23606. */
  23607. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23608. /**
  23609. * Called after the opaque objects are rendered and before the transparent ones
  23610. * This stage will be fired only if there's 3D transparent content to render
  23611. */
  23612. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23613. /**
  23614. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23615. * This stage will be fired no matter what
  23616. */
  23617. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23618. return RenderingGroupInfo;
  23619. }());
  23620. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23621. /**
  23622. * Represents a scene to be rendered by the engine.
  23623. * @see http://doc.babylonjs.com/features/scene
  23624. */
  23625. var Scene = /** @class */ (function () {
  23626. /**
  23627. * Creates a new Scene
  23628. * @param engine defines the engine to use to render this scene
  23629. */
  23630. function Scene(engine) {
  23631. // Members
  23632. /**
  23633. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23634. */
  23635. this.autoClear = true;
  23636. /**
  23637. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23638. */
  23639. this.autoClearDepthAndStencil = true;
  23640. /**
  23641. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23642. */
  23643. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23644. /**
  23645. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23646. */
  23647. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23648. this._forceWireframe = false;
  23649. this._forcePointsCloud = false;
  23650. /**
  23651. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23652. */
  23653. this.forceShowBoundingBoxes = false;
  23654. /**
  23655. * Gets or sets a boolean indicating if animations are enabled
  23656. */
  23657. this.animationsEnabled = true;
  23658. this._animationPropertiesOverride = null;
  23659. /**
  23660. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23661. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23662. */
  23663. this.useConstantAnimationDeltaTime = false;
  23664. /**
  23665. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23666. * Please note that it requires to run a ray cast through the scene on every frame
  23667. */
  23668. this.constantlyUpdateMeshUnderPointer = false;
  23669. /**
  23670. * Defines the HTML cursor to use when hovering over interactive elements
  23671. */
  23672. this.hoverCursor = "pointer";
  23673. /**
  23674. * Defines the HTML default cursor to use (empty by default)
  23675. */
  23676. this.defaultCursor = "";
  23677. /**
  23678. * This is used to call preventDefault() on pointer down
  23679. * in order to block unwanted artifacts like system double clicks
  23680. */
  23681. this.preventDefaultOnPointerDown = true;
  23682. // Metadata
  23683. /**
  23684. * Gets or sets user defined metadata
  23685. */
  23686. this.metadata = null;
  23687. /**
  23688. * Use this array to add regular expressions used to disable offline support for specific urls
  23689. */
  23690. this.disableOfflineSupportExceptionRules = new Array();
  23691. /**
  23692. * An event triggered when the scene is disposed.
  23693. */
  23694. this.onDisposeObservable = new BABYLON.Observable();
  23695. this._onDisposeObserver = null;
  23696. /**
  23697. * An event triggered before rendering the scene (right after animations and physics)
  23698. */
  23699. this.onBeforeRenderObservable = new BABYLON.Observable();
  23700. this._onBeforeRenderObserver = null;
  23701. /**
  23702. * An event triggered after rendering the scene
  23703. */
  23704. this.onAfterRenderObservable = new BABYLON.Observable();
  23705. this._onAfterRenderObserver = null;
  23706. /**
  23707. * An event triggered before animating the scene
  23708. */
  23709. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23710. /**
  23711. * An event triggered after animations processing
  23712. */
  23713. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23714. /**
  23715. * An event triggered before draw calls are ready to be sent
  23716. */
  23717. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23718. /**
  23719. * An event triggered after draw calls have been sent
  23720. */
  23721. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23722. /**
  23723. * An event triggered when physic simulation is about to be run
  23724. */
  23725. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23726. /**
  23727. * An event triggered when physic simulation has been done
  23728. */
  23729. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23730. /**
  23731. * An event triggered when the scene is ready
  23732. */
  23733. this.onReadyObservable = new BABYLON.Observable();
  23734. /**
  23735. * An event triggered before rendering a camera
  23736. */
  23737. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23738. this._onBeforeCameraRenderObserver = null;
  23739. /**
  23740. * An event triggered after rendering a camera
  23741. */
  23742. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23743. this._onAfterCameraRenderObserver = null;
  23744. /**
  23745. * An event triggered when active meshes evaluation is about to start
  23746. */
  23747. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23748. /**
  23749. * An event triggered when active meshes evaluation is done
  23750. */
  23751. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23752. /**
  23753. * An event triggered when particles rendering is about to start
  23754. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23755. */
  23756. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23757. /**
  23758. * An event triggered when particles rendering is done
  23759. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23760. */
  23761. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23762. /**
  23763. * An event triggered when sprites rendering is about to start
  23764. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23765. */
  23766. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23767. /**
  23768. * An event triggered when sprites rendering is done
  23769. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23770. */
  23771. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23772. /**
  23773. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23774. */
  23775. this.onDataLoadedObservable = new BABYLON.Observable();
  23776. /**
  23777. * An event triggered when a camera is created
  23778. */
  23779. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23780. /**
  23781. * An event triggered when a camera is removed
  23782. */
  23783. this.onCameraRemovedObservable = new BABYLON.Observable();
  23784. /**
  23785. * An event triggered when a light is created
  23786. */
  23787. this.onNewLightAddedObservable = new BABYLON.Observable();
  23788. /**
  23789. * An event triggered when a light is removed
  23790. */
  23791. this.onLightRemovedObservable = new BABYLON.Observable();
  23792. /**
  23793. * An event triggered when a geometry is created
  23794. */
  23795. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23796. /**
  23797. * An event triggered when a geometry is removed
  23798. */
  23799. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23800. /**
  23801. * An event triggered when a transform node is created
  23802. */
  23803. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23804. /**
  23805. * An event triggered when a transform node is removed
  23806. */
  23807. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23808. /**
  23809. * An event triggered when a mesh is created
  23810. */
  23811. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23812. /**
  23813. * An event triggered when a mesh is removed
  23814. */
  23815. this.onMeshRemovedObservable = new BABYLON.Observable();
  23816. /**
  23817. * An event triggered when render targets are about to be rendered
  23818. * Can happen multiple times per frame.
  23819. */
  23820. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23821. /**
  23822. * An event triggered when render targets were rendered.
  23823. * Can happen multiple times per frame.
  23824. */
  23825. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23826. /**
  23827. * An event triggered before calculating deterministic simulation step
  23828. */
  23829. this.onBeforeStepObservable = new BABYLON.Observable();
  23830. /**
  23831. * An event triggered after calculating deterministic simulation step
  23832. */
  23833. this.onAfterStepObservable = new BABYLON.Observable();
  23834. /**
  23835. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23836. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23837. * 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)
  23838. */
  23839. this.onRenderingGroupObservable = new BABYLON.Observable();
  23840. // Animations
  23841. /**
  23842. * Gets a list of Animations associated with the scene
  23843. */
  23844. this.animations = [];
  23845. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23846. /**
  23847. * 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).
  23848. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23849. */
  23850. this.onPrePointerObservable = new BABYLON.Observable();
  23851. /**
  23852. * Observable event triggered each time an input event is received from the rendering canvas
  23853. */
  23854. this.onPointerObservable = new BABYLON.Observable();
  23855. this._meshPickProceed = false;
  23856. this._currentPickResult = null;
  23857. this._previousPickResult = null;
  23858. this._totalPointersPressed = 0;
  23859. this._doubleClickOccured = false;
  23860. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23861. this.cameraToUseForPointers = null;
  23862. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23863. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23864. this._startingPointerTime = 0;
  23865. this._previousStartingPointerTime = 0;
  23866. this._pointerCaptures = {};
  23867. // Deterministic lockstep
  23868. this._timeAccumulator = 0;
  23869. this._currentStepId = 0;
  23870. this._currentInternalStep = 0;
  23871. // Keyboard
  23872. /**
  23873. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23874. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23875. */
  23876. this.onPreKeyboardObservable = new BABYLON.Observable();
  23877. /**
  23878. * Observable event triggered each time an keyboard event is received from the hosting window
  23879. */
  23880. this.onKeyboardObservable = new BABYLON.Observable();
  23881. // Coordinates system
  23882. this._useRightHandedSystem = false;
  23883. // Fog
  23884. this._fogEnabled = true;
  23885. this._fogMode = Scene.FOGMODE_NONE;
  23886. /**
  23887. * Gets or sets the fog color to use
  23888. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23889. */
  23890. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23891. /**
  23892. * Gets or sets the fog density to use
  23893. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23894. */
  23895. this.fogDensity = 0.1;
  23896. /**
  23897. * Gets or sets the fog start distance to use
  23898. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23899. */
  23900. this.fogStart = 0;
  23901. /**
  23902. * Gets or sets the fog end distance to use
  23903. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23904. */
  23905. this.fogEnd = 1000.0;
  23906. // Lights
  23907. this._shadowsEnabled = true;
  23908. this._lightsEnabled = true;
  23909. /**
  23910. * All of the lights added to this scene
  23911. * @see http://doc.babylonjs.com/babylon101/lights
  23912. */
  23913. this.lights = new Array();
  23914. // Cameras
  23915. /** All of the cameras added to this scene.
  23916. * @see http://doc.babylonjs.com/babylon101/cameras
  23917. */
  23918. this.cameras = new Array();
  23919. /** All of the active cameras added to this scene. */
  23920. this.activeCameras = new Array();
  23921. // Meshes
  23922. /**
  23923. * All of the tranform nodes added to this scene
  23924. * @see http://doc.babylonjs.com/how_to/transformnode
  23925. */
  23926. this.transformNodes = new Array();
  23927. /**
  23928. * All of the (abstract) meshes added to this scene
  23929. */
  23930. this.meshes = new Array();
  23931. /**
  23932. * All of the animation groups added to this scene
  23933. * @see http://doc.babylonjs.com/how_to/group
  23934. */
  23935. this.animationGroups = new Array();
  23936. // Geometries
  23937. this._geometries = new Array();
  23938. /**
  23939. * All of the materials added to this scene
  23940. * @see http://doc.babylonjs.com/babylon101/materials
  23941. */
  23942. this.materials = new Array();
  23943. /**
  23944. * All of the multi-materials added to this scene
  23945. * @see http://doc.babylonjs.com/how_to/multi_materials
  23946. */
  23947. this.multiMaterials = new Array();
  23948. // Textures
  23949. this._texturesEnabled = true;
  23950. /**
  23951. * All of the textures added to this scene
  23952. */
  23953. this.textures = new Array();
  23954. // Particles
  23955. /**
  23956. * Gets or sets a boolean indicating if particles are enabled on this scene
  23957. */
  23958. this.particlesEnabled = true;
  23959. /**
  23960. * All of the particle systems added to this scene
  23961. * @see http://doc.babylonjs.com/babylon101/particles
  23962. */
  23963. this.particleSystems = new Array();
  23964. // Sprites
  23965. /**
  23966. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23967. */
  23968. this.spritesEnabled = true;
  23969. /**
  23970. * All of the sprite managers added to this scene
  23971. * @see http://doc.babylonjs.com/babylon101/sprites
  23972. */
  23973. this.spriteManagers = new Array();
  23974. /**
  23975. * The list of layers (background and foreground) of the scene
  23976. */
  23977. this.layers = new Array();
  23978. /**
  23979. * The list of effect layers (highlights/glow) added to the scene
  23980. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23981. * @see http://doc.babylonjs.com/how_to/glow_layer
  23982. */
  23983. this.effectLayers = new Array();
  23984. // Skeletons
  23985. this._skeletonsEnabled = true;
  23986. /**
  23987. * The list of skeletons added to the scene
  23988. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23989. */
  23990. this.skeletons = new Array();
  23991. // Morph targets
  23992. /**
  23993. * The list of morph target managers added to the scene
  23994. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23995. */
  23996. this.morphTargetManagers = new Array();
  23997. // Lens flares
  23998. /**
  23999. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24000. */
  24001. this.lensFlaresEnabled = true;
  24002. /**
  24003. * The list of lens flare system added to the scene
  24004. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24005. */
  24006. this.lensFlareSystems = new Array();
  24007. // Collisions
  24008. /**
  24009. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24010. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24011. */
  24012. this.collisionsEnabled = true;
  24013. /**
  24014. * Defines the gravity applied to this scene (used only for collisions)
  24015. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24016. */
  24017. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24018. // Postprocesses
  24019. /**
  24020. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24021. */
  24022. this.postProcessesEnabled = true;
  24023. /**
  24024. * The list of postprocesses added to the scene
  24025. */
  24026. this.postProcesses = new Array();
  24027. // Customs render targets
  24028. /**
  24029. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24030. */
  24031. this.renderTargetsEnabled = true;
  24032. /**
  24033. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24034. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24035. */
  24036. this.dumpNextRenderTargets = false;
  24037. /**
  24038. * The list of user defined render targets added to the scene
  24039. */
  24040. this.customRenderTargets = new Array();
  24041. /**
  24042. * Gets the list of meshes imported to the scene through SceneLoader
  24043. */
  24044. this.importedMeshesFiles = new Array();
  24045. // Probes
  24046. /**
  24047. * Gets or sets a boolean indicating if probes are enabled on this scene
  24048. */
  24049. this.probesEnabled = true;
  24050. /**
  24051. * The list of reflection probes added to the scene
  24052. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24053. */
  24054. this.reflectionProbes = new Array();
  24055. /** @hidden */
  24056. this._actionManagers = new Array();
  24057. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24058. // Procedural textures
  24059. /**
  24060. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24061. */
  24062. this.proceduralTexturesEnabled = true;
  24063. /**
  24064. * The list of procedural textures added to the scene
  24065. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24066. */
  24067. this.proceduralTextures = new Array();
  24068. /**
  24069. * The list of sound tracks added to the scene
  24070. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24071. */
  24072. this.soundTracks = new Array();
  24073. this._audioEnabled = true;
  24074. this._headphone = false;
  24075. // Performance counters
  24076. this._totalVertices = new BABYLON.PerfCounter();
  24077. /** @hidden */
  24078. this._activeIndices = new BABYLON.PerfCounter();
  24079. /** @hidden */
  24080. this._activeParticles = new BABYLON.PerfCounter();
  24081. /** @hidden */
  24082. this._activeBones = new BABYLON.PerfCounter();
  24083. this._animationTime = 0;
  24084. /**
  24085. * Gets or sets a general scale for animation speed
  24086. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24087. */
  24088. this.animationTimeScale = 1;
  24089. this._renderId = 0;
  24090. this._executeWhenReadyTimeoutId = -1;
  24091. this._intermediateRendering = false;
  24092. this._viewUpdateFlag = -1;
  24093. this._projectionUpdateFlag = -1;
  24094. this._alternateViewUpdateFlag = -1;
  24095. this._alternateProjectionUpdateFlag = -1;
  24096. /** @hidden */
  24097. this._toBeDisposed = new BABYLON.SmartArray(256);
  24098. this._activeRequests = new Array();
  24099. this._pendingData = new Array();
  24100. this._isDisposed = false;
  24101. /**
  24102. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24103. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24104. */
  24105. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24106. this._activeMeshes = new BABYLON.SmartArray(256);
  24107. this._processedMaterials = new BABYLON.SmartArray(256);
  24108. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24109. /** @hidden */
  24110. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24111. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24112. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24113. /** @hidden */
  24114. this._activeAnimatables = new Array();
  24115. this._transformMatrix = BABYLON.Matrix.Zero();
  24116. this._useAlternateCameraConfiguration = false;
  24117. this._alternateRendering = false;
  24118. /**
  24119. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24120. * This is useful if there are more lights that the maximum simulteanous authorized
  24121. */
  24122. this.requireLightSorting = false;
  24123. this._depthRenderer = {};
  24124. this._activeMeshesFrozen = false;
  24125. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24126. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24127. this._engine.scenes.push(this);
  24128. this._uid = null;
  24129. this._renderingManager = new BABYLON.RenderingManager(this);
  24130. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24131. if (BABYLON.OutlineRenderer) {
  24132. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24133. }
  24134. if (BABYLON.Tools.IsWindowObjectExist()) {
  24135. this.attachControl();
  24136. }
  24137. //simplification queue
  24138. if (BABYLON.SimplificationQueue) {
  24139. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24140. }
  24141. //collision coordinator initialization. For now legacy per default.
  24142. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24143. // Uniform Buffer
  24144. this._createUbo();
  24145. // Default Image processing definition.
  24146. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24147. }
  24148. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24149. /** The fog is deactivated */
  24150. get: function () {
  24151. return Scene._FOGMODE_NONE;
  24152. },
  24153. enumerable: true,
  24154. configurable: true
  24155. });
  24156. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24157. /** The fog density is following an exponential function */
  24158. get: function () {
  24159. return Scene._FOGMODE_EXP;
  24160. },
  24161. enumerable: true,
  24162. configurable: true
  24163. });
  24164. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24165. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24166. get: function () {
  24167. return Scene._FOGMODE_EXP2;
  24168. },
  24169. enumerable: true,
  24170. configurable: true
  24171. });
  24172. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24173. /** The fog density is following a linear function. */
  24174. get: function () {
  24175. return Scene._FOGMODE_LINEAR;
  24176. },
  24177. enumerable: true,
  24178. configurable: true
  24179. });
  24180. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24181. /**
  24182. * Texture used in all pbr material as the reflection texture.
  24183. * As in the majority of the scene they are the same (exception for multi room and so on),
  24184. * this is easier to reference from here than from all the materials.
  24185. */
  24186. get: function () {
  24187. return this._environmentTexture;
  24188. },
  24189. /**
  24190. * Texture used in all pbr material as the reflection texture.
  24191. * As in the majority of the scene they are the same (exception for multi room and so on),
  24192. * this is easier to set here than in all the materials.
  24193. */
  24194. set: function (value) {
  24195. if (this._environmentTexture === value) {
  24196. return;
  24197. }
  24198. this._environmentTexture = value;
  24199. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24200. },
  24201. enumerable: true,
  24202. configurable: true
  24203. });
  24204. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24205. /**
  24206. * Default image processing configuration used either in the rendering
  24207. * Forward main pass or through the imageProcessingPostProcess if present.
  24208. * As in the majority of the scene they are the same (exception for multi camera),
  24209. * this is easier to reference from here than from all the materials and post process.
  24210. *
  24211. * No setter as we it is a shared configuration, you can set the values instead.
  24212. */
  24213. get: function () {
  24214. return this._imageProcessingConfiguration;
  24215. },
  24216. enumerable: true,
  24217. configurable: true
  24218. });
  24219. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24220. get: function () {
  24221. return this._forceWireframe;
  24222. },
  24223. /**
  24224. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24225. */
  24226. set: function (value) {
  24227. if (this._forceWireframe === value) {
  24228. return;
  24229. }
  24230. this._forceWireframe = value;
  24231. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24232. },
  24233. enumerable: true,
  24234. configurable: true
  24235. });
  24236. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24237. get: function () {
  24238. return this._forcePointsCloud;
  24239. },
  24240. /**
  24241. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24242. */
  24243. set: function (value) {
  24244. if (this._forcePointsCloud === value) {
  24245. return;
  24246. }
  24247. this._forcePointsCloud = value;
  24248. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24249. },
  24250. enumerable: true,
  24251. configurable: true
  24252. });
  24253. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24254. /**
  24255. * Gets or sets the animation properties override
  24256. */
  24257. get: function () {
  24258. return this._animationPropertiesOverride;
  24259. },
  24260. set: function (value) {
  24261. this._animationPropertiesOverride = value;
  24262. },
  24263. enumerable: true,
  24264. configurable: true
  24265. });
  24266. Object.defineProperty(Scene.prototype, "onDispose", {
  24267. /** Sets a function to be executed when this scene is disposed. */
  24268. set: function (callback) {
  24269. if (this._onDisposeObserver) {
  24270. this.onDisposeObservable.remove(this._onDisposeObserver);
  24271. }
  24272. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24273. },
  24274. enumerable: true,
  24275. configurable: true
  24276. });
  24277. Object.defineProperty(Scene.prototype, "beforeRender", {
  24278. /** Sets a function to be executed before rendering this scene */
  24279. set: function (callback) {
  24280. if (this._onBeforeRenderObserver) {
  24281. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24282. }
  24283. if (callback) {
  24284. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24285. }
  24286. },
  24287. enumerable: true,
  24288. configurable: true
  24289. });
  24290. Object.defineProperty(Scene.prototype, "afterRender", {
  24291. /** Sets a function to be executed after rendering this scene */
  24292. set: function (callback) {
  24293. if (this._onAfterRenderObserver) {
  24294. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24295. }
  24296. if (callback) {
  24297. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24298. }
  24299. },
  24300. enumerable: true,
  24301. configurable: true
  24302. });
  24303. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24304. /** Sets a function to be executed before rendering a camera*/
  24305. set: function (callback) {
  24306. if (this._onBeforeCameraRenderObserver) {
  24307. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24308. }
  24309. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24310. },
  24311. enumerable: true,
  24312. configurable: true
  24313. });
  24314. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24315. /** Sets a function to be executed after rendering a camera*/
  24316. set: function (callback) {
  24317. if (this._onAfterCameraRenderObserver) {
  24318. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24319. }
  24320. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24321. },
  24322. enumerable: true,
  24323. configurable: true
  24324. });
  24325. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24326. /**
  24327. * Gets the gamepad manager associated with the scene
  24328. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24329. */
  24330. get: function () {
  24331. if (!this._gamepadManager) {
  24332. this._gamepadManager = new BABYLON.GamepadManager(this);
  24333. }
  24334. return this._gamepadManager;
  24335. },
  24336. enumerable: true,
  24337. configurable: true
  24338. });
  24339. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24340. /**
  24341. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24342. */
  24343. get: function () {
  24344. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24345. },
  24346. enumerable: true,
  24347. configurable: true
  24348. });
  24349. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24350. get: function () {
  24351. return this._useRightHandedSystem;
  24352. },
  24353. /**
  24354. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24355. */
  24356. set: function (value) {
  24357. if (this._useRightHandedSystem === value) {
  24358. return;
  24359. }
  24360. this._useRightHandedSystem = value;
  24361. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24362. },
  24363. enumerable: true,
  24364. configurable: true
  24365. });
  24366. /**
  24367. * Sets the step Id used by deterministic lock step
  24368. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24369. * @param newStepId defines the step Id
  24370. */
  24371. Scene.prototype.setStepId = function (newStepId) {
  24372. this._currentStepId = newStepId;
  24373. };
  24374. ;
  24375. /**
  24376. * Gets the step Id used by deterministic lock step
  24377. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24378. * @returns the step Id
  24379. */
  24380. Scene.prototype.getStepId = function () {
  24381. return this._currentStepId;
  24382. };
  24383. ;
  24384. /**
  24385. * Gets the internal step used by deterministic lock step
  24386. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24387. * @returns the internal step
  24388. */
  24389. Scene.prototype.getInternalStep = function () {
  24390. return this._currentInternalStep;
  24391. };
  24392. ;
  24393. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24394. get: function () {
  24395. return this._fogEnabled;
  24396. },
  24397. /**
  24398. * Gets or sets a boolean indicating if fog is enabled on this scene
  24399. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24400. */
  24401. set: function (value) {
  24402. if (this._fogEnabled === value) {
  24403. return;
  24404. }
  24405. this._fogEnabled = value;
  24406. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24407. },
  24408. enumerable: true,
  24409. configurable: true
  24410. });
  24411. Object.defineProperty(Scene.prototype, "fogMode", {
  24412. get: function () {
  24413. return this._fogMode;
  24414. },
  24415. /**
  24416. * Gets or sets the fog mode to use
  24417. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24418. */
  24419. set: function (value) {
  24420. if (this._fogMode === value) {
  24421. return;
  24422. }
  24423. this._fogMode = value;
  24424. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24425. },
  24426. enumerable: true,
  24427. configurable: true
  24428. });
  24429. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24430. get: function () {
  24431. return this._shadowsEnabled;
  24432. },
  24433. /**
  24434. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24435. */
  24436. set: function (value) {
  24437. if (this._shadowsEnabled === value) {
  24438. return;
  24439. }
  24440. this._shadowsEnabled = value;
  24441. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24442. },
  24443. enumerable: true,
  24444. configurable: true
  24445. });
  24446. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24447. get: function () {
  24448. return this._lightsEnabled;
  24449. },
  24450. /**
  24451. * Gets or sets a boolean indicating if lights are enabled on this scene
  24452. */
  24453. set: function (value) {
  24454. if (this._lightsEnabled === value) {
  24455. return;
  24456. }
  24457. this._lightsEnabled = value;
  24458. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24459. },
  24460. enumerable: true,
  24461. configurable: true
  24462. });
  24463. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24464. /** The default material used on meshes when no material is affected */
  24465. get: function () {
  24466. if (!this._defaultMaterial) {
  24467. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24468. }
  24469. return this._defaultMaterial;
  24470. },
  24471. /** The default material used on meshes when no material is affected */
  24472. set: function (value) {
  24473. this._defaultMaterial = value;
  24474. },
  24475. enumerable: true,
  24476. configurable: true
  24477. });
  24478. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24479. get: function () {
  24480. return this._texturesEnabled;
  24481. },
  24482. /**
  24483. * Gets or sets a boolean indicating if textures are enabled on this scene
  24484. */
  24485. set: function (value) {
  24486. if (this._texturesEnabled === value) {
  24487. return;
  24488. }
  24489. this._texturesEnabled = value;
  24490. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24491. },
  24492. enumerable: true,
  24493. configurable: true
  24494. });
  24495. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24496. get: function () {
  24497. return this._skeletonsEnabled;
  24498. },
  24499. /**
  24500. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24501. */
  24502. set: function (value) {
  24503. if (this._skeletonsEnabled === value) {
  24504. return;
  24505. }
  24506. this._skeletonsEnabled = value;
  24507. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24508. },
  24509. enumerable: true,
  24510. configurable: true
  24511. });
  24512. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24513. /**
  24514. * Gets the postprocess render pipeline manager
  24515. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24516. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24517. */
  24518. get: function () {
  24519. if (!this._postProcessRenderPipelineManager) {
  24520. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24521. }
  24522. return this._postProcessRenderPipelineManager;
  24523. },
  24524. enumerable: true,
  24525. configurable: true
  24526. });
  24527. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24528. /**
  24529. * Gets the main soundtrack associated with the scene
  24530. */
  24531. get: function () {
  24532. if (!this._mainSoundTrack) {
  24533. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24534. }
  24535. return this._mainSoundTrack;
  24536. },
  24537. enumerable: true,
  24538. configurable: true
  24539. });
  24540. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24541. /** @hidden */
  24542. get: function () {
  24543. return this._alternateRendering;
  24544. },
  24545. enumerable: true,
  24546. configurable: true
  24547. });
  24548. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24549. /**
  24550. * Gets the list of frustum planes (built from the active camera)
  24551. */
  24552. get: function () {
  24553. return this._frustumPlanes;
  24554. },
  24555. enumerable: true,
  24556. configurable: true
  24557. });
  24558. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24559. /**
  24560. * Gets the current geometry buffer associated to the scene.
  24561. */
  24562. get: function () {
  24563. return this._geometryBufferRenderer;
  24564. },
  24565. /**
  24566. * Sets the current geometry buffer for the scene.
  24567. */
  24568. set: function (geometryBufferRenderer) {
  24569. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24570. this._geometryBufferRenderer = geometryBufferRenderer;
  24571. }
  24572. },
  24573. enumerable: true,
  24574. configurable: true
  24575. });
  24576. Object.defineProperty(Scene.prototype, "debugLayer", {
  24577. /**
  24578. * Gets the debug layer associated with the scene
  24579. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24580. */
  24581. get: function () {
  24582. if (!this._debugLayer) {
  24583. this._debugLayer = new BABYLON.DebugLayer(this);
  24584. }
  24585. return this._debugLayer;
  24586. },
  24587. enumerable: true,
  24588. configurable: true
  24589. });
  24590. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24591. /**
  24592. * Gets a boolean indicating if collisions are processed on a web worker
  24593. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24594. */
  24595. get: function () {
  24596. return this._workerCollisions;
  24597. },
  24598. set: function (enabled) {
  24599. if (!BABYLON.CollisionCoordinatorLegacy) {
  24600. return;
  24601. }
  24602. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24603. this._workerCollisions = enabled;
  24604. if (this.collisionCoordinator) {
  24605. this.collisionCoordinator.destroy();
  24606. }
  24607. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24608. this.collisionCoordinator.init(this);
  24609. },
  24610. enumerable: true,
  24611. configurable: true
  24612. });
  24613. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24614. /**
  24615. * Gets the octree used to boost mesh selection (picking)
  24616. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24617. */
  24618. get: function () {
  24619. return this._selectionOctree;
  24620. },
  24621. enumerable: true,
  24622. configurable: true
  24623. });
  24624. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24625. /**
  24626. * Gets the mesh that is currently under the pointer
  24627. */
  24628. get: function () {
  24629. return this._pointerOverMesh;
  24630. },
  24631. enumerable: true,
  24632. configurable: true
  24633. });
  24634. Object.defineProperty(Scene.prototype, "pointerX", {
  24635. /**
  24636. * Gets the current on-screen X position of the pointer
  24637. */
  24638. get: function () {
  24639. return this._pointerX;
  24640. },
  24641. enumerable: true,
  24642. configurable: true
  24643. });
  24644. Object.defineProperty(Scene.prototype, "pointerY", {
  24645. /**
  24646. * Gets the current on-screen Y position of the pointer
  24647. */
  24648. get: function () {
  24649. return this._pointerY;
  24650. },
  24651. enumerable: true,
  24652. configurable: true
  24653. });
  24654. /**
  24655. * Gets the cached material (ie. the latest rendered one)
  24656. * @returns the cached material
  24657. */
  24658. Scene.prototype.getCachedMaterial = function () {
  24659. return this._cachedMaterial;
  24660. };
  24661. /**
  24662. * Gets the cached effect (ie. the latest rendered one)
  24663. * @returns the cached effect
  24664. */
  24665. Scene.prototype.getCachedEffect = function () {
  24666. return this._cachedEffect;
  24667. };
  24668. /**
  24669. * Gets the cached visibility state (ie. the latest rendered one)
  24670. * @returns the cached visibility state
  24671. */
  24672. Scene.prototype.getCachedVisibility = function () {
  24673. return this._cachedVisibility;
  24674. };
  24675. /**
  24676. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24677. * @param material defines the current material
  24678. * @param effect defines the current effect
  24679. * @param visibility defines the current visibility state
  24680. * @returns true if one parameter is not cached
  24681. */
  24682. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24683. if (visibility === void 0) { visibility = 1; }
  24684. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24685. };
  24686. /**
  24687. * Gets the bounding box renderer associated with the scene
  24688. * @returns a BoundingBoxRenderer
  24689. */
  24690. Scene.prototype.getBoundingBoxRenderer = function () {
  24691. if (!this._boundingBoxRenderer) {
  24692. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24693. }
  24694. return this._boundingBoxRenderer;
  24695. };
  24696. /**
  24697. * Gets the outline renderer associated with the scene
  24698. * @returns a OutlineRenderer
  24699. */
  24700. Scene.prototype.getOutlineRenderer = function () {
  24701. return this._outlineRenderer;
  24702. };
  24703. /**
  24704. * Gets the engine associated with the scene
  24705. * @returns an Engine
  24706. */
  24707. Scene.prototype.getEngine = function () {
  24708. return this._engine;
  24709. };
  24710. /**
  24711. * Gets the total number of vertices rendered per frame
  24712. * @returns the total number of vertices rendered per frame
  24713. */
  24714. Scene.prototype.getTotalVertices = function () {
  24715. return this._totalVertices.current;
  24716. };
  24717. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24718. /**
  24719. * Gets the performance counter for total vertices
  24720. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24721. */
  24722. get: function () {
  24723. return this._totalVertices;
  24724. },
  24725. enumerable: true,
  24726. configurable: true
  24727. });
  24728. /**
  24729. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24730. * @returns the total number of active indices rendered per frame
  24731. */
  24732. Scene.prototype.getActiveIndices = function () {
  24733. return this._activeIndices.current;
  24734. };
  24735. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24736. /**
  24737. * Gets the performance counter for active indices
  24738. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24739. */
  24740. get: function () {
  24741. return this._activeIndices;
  24742. },
  24743. enumerable: true,
  24744. configurable: true
  24745. });
  24746. /**
  24747. * Gets the total number of active particles rendered per frame
  24748. * @returns the total number of active particles rendered per frame
  24749. */
  24750. Scene.prototype.getActiveParticles = function () {
  24751. return this._activeParticles.current;
  24752. };
  24753. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24754. /**
  24755. * Gets the performance counter for active particles
  24756. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24757. */
  24758. get: function () {
  24759. return this._activeParticles;
  24760. },
  24761. enumerable: true,
  24762. configurable: true
  24763. });
  24764. /**
  24765. * Gets the total number of active bones rendered per frame
  24766. * @returns the total number of active bones rendered per frame
  24767. */
  24768. Scene.prototype.getActiveBones = function () {
  24769. return this._activeBones.current;
  24770. };
  24771. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24772. /**
  24773. * Gets the performance counter for active bones
  24774. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24775. */
  24776. get: function () {
  24777. return this._activeBones;
  24778. },
  24779. enumerable: true,
  24780. configurable: true
  24781. });
  24782. /** @hidden */
  24783. Scene.prototype.getInterFramePerfCounter = function () {
  24784. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24785. return 0;
  24786. };
  24787. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24788. /** @hidden */
  24789. get: function () {
  24790. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24791. return null;
  24792. },
  24793. enumerable: true,
  24794. configurable: true
  24795. });
  24796. /** @hidden */
  24797. Scene.prototype.getLastFrameDuration = function () {
  24798. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24799. return 0;
  24800. };
  24801. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24802. /** @hidden */
  24803. get: function () {
  24804. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24805. return null;
  24806. },
  24807. enumerable: true,
  24808. configurable: true
  24809. });
  24810. /** @hidden */
  24811. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24812. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24813. return 0;
  24814. };
  24815. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24816. /** @hidden */
  24817. get: function () {
  24818. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24819. return null;
  24820. },
  24821. enumerable: true,
  24822. configurable: true
  24823. });
  24824. /**
  24825. * Gets the array of active meshes
  24826. * @returns an array of AbstractMesh
  24827. */
  24828. Scene.prototype.getActiveMeshes = function () {
  24829. return this._activeMeshes;
  24830. };
  24831. /** @hidden */
  24832. Scene.prototype.getRenderTargetsDuration = function () {
  24833. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24834. return 0;
  24835. };
  24836. /** @hidden */
  24837. Scene.prototype.getRenderDuration = function () {
  24838. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24839. return 0;
  24840. };
  24841. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24842. /** @hidden */
  24843. get: function () {
  24844. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24845. return null;
  24846. },
  24847. enumerable: true,
  24848. configurable: true
  24849. });
  24850. /** @hidden */
  24851. Scene.prototype.getParticlesDuration = function () {
  24852. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24853. return 0;
  24854. };
  24855. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24856. /** @hidden */
  24857. get: function () {
  24858. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24859. return null;
  24860. },
  24861. enumerable: true,
  24862. configurable: true
  24863. });
  24864. /** @hidden */
  24865. Scene.prototype.getSpritesDuration = function () {
  24866. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24867. return 0;
  24868. };
  24869. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24870. /** @hidden */
  24871. get: function () {
  24872. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24873. return null;
  24874. },
  24875. enumerable: true,
  24876. configurable: true
  24877. });
  24878. /**
  24879. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24880. * @returns a number
  24881. */
  24882. Scene.prototype.getAnimationRatio = function () {
  24883. return this._animationRatio;
  24884. };
  24885. /**
  24886. * Gets an unique Id for the current frame
  24887. * @returns a number
  24888. */
  24889. Scene.prototype.getRenderId = function () {
  24890. return this._renderId;
  24891. };
  24892. /** Call this function if you want to manually increment the render Id*/
  24893. Scene.prototype.incrementRenderId = function () {
  24894. this._renderId++;
  24895. };
  24896. Scene.prototype._updatePointerPosition = function (evt) {
  24897. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24898. if (!canvasRect) {
  24899. return;
  24900. }
  24901. this._pointerX = evt.clientX - canvasRect.left;
  24902. this._pointerY = evt.clientY - canvasRect.top;
  24903. this._unTranslatedPointerX = this._pointerX;
  24904. this._unTranslatedPointerY = this._pointerY;
  24905. };
  24906. Scene.prototype._createUbo = function () {
  24907. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24908. this._sceneUbo.addUniform("viewProjection", 16);
  24909. this._sceneUbo.addUniform("view", 16);
  24910. };
  24911. Scene.prototype._createAlternateUbo = function () {
  24912. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24913. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24914. this._alternateSceneUbo.addUniform("view", 16);
  24915. };
  24916. // Pointers handling
  24917. /**
  24918. * Use this method to simulate a pointer move on a mesh
  24919. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24920. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24921. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24922. * @returns the current scene
  24923. */
  24924. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24925. var evt = new PointerEvent("pointermove", pointerEventInit);
  24926. return this._processPointerMove(pickResult, evt);
  24927. };
  24928. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24929. var canvas = this._engine.getRenderingCanvas();
  24930. if (!canvas) {
  24931. return this;
  24932. }
  24933. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24934. this.setPointerOverSprite(null);
  24935. this.setPointerOverMesh(pickResult.pickedMesh);
  24936. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24937. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24938. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24939. }
  24940. else {
  24941. canvas.style.cursor = this.hoverCursor;
  24942. }
  24943. }
  24944. else {
  24945. canvas.style.cursor = this.defaultCursor;
  24946. }
  24947. }
  24948. else {
  24949. this.setPointerOverMesh(null);
  24950. // Sprites
  24951. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24952. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24953. this.setPointerOverSprite(pickResult.pickedSprite);
  24954. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24955. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24956. }
  24957. else {
  24958. canvas.style.cursor = this.hoverCursor;
  24959. }
  24960. }
  24961. else {
  24962. this.setPointerOverSprite(null);
  24963. // Restore pointer
  24964. canvas.style.cursor = this.defaultCursor;
  24965. }
  24966. }
  24967. if (pickResult) {
  24968. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24969. if (this.onPointerMove) {
  24970. this.onPointerMove(evt, pickResult, type);
  24971. }
  24972. if (this.onPointerObservable.hasObservers()) {
  24973. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24974. this.onPointerObservable.notifyObservers(pi, type);
  24975. }
  24976. }
  24977. return this;
  24978. };
  24979. /**
  24980. * Use this method to simulate a pointer down on a mesh
  24981. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24982. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24983. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24984. * @returns the current scene
  24985. */
  24986. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24987. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24988. return this._processPointerDown(pickResult, evt);
  24989. };
  24990. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24991. var _this = this;
  24992. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24993. this._pickedDownMesh = pickResult.pickedMesh;
  24994. var actionManager = pickResult.pickedMesh.actionManager;
  24995. if (actionManager) {
  24996. if (actionManager.hasPickTriggers) {
  24997. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24998. switch (evt.button) {
  24999. case 0:
  25000. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25001. break;
  25002. case 1:
  25003. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25004. break;
  25005. case 2:
  25006. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25007. break;
  25008. }
  25009. }
  25010. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25011. window.setTimeout(function () {
  25012. 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);
  25013. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25014. if (_this._totalPointersPressed !== 0 &&
  25015. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25016. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25017. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25018. _this._startingPointerTime = 0;
  25019. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25020. }
  25021. }
  25022. }, Scene.LongPressDelay);
  25023. }
  25024. }
  25025. }
  25026. if (pickResult) {
  25027. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25028. if (this.onPointerDown) {
  25029. this.onPointerDown(evt, pickResult, type);
  25030. }
  25031. if (this.onPointerObservable.hasObservers()) {
  25032. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25033. this.onPointerObservable.notifyObservers(pi, type);
  25034. }
  25035. }
  25036. return this;
  25037. };
  25038. /**
  25039. * Use this method to simulate a pointer up on a mesh
  25040. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25041. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25042. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25043. * @returns the current scene
  25044. */
  25045. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25046. var evt = new PointerEvent("pointerup", pointerEventInit);
  25047. var clickInfo = new ClickInfo();
  25048. clickInfo.singleClick = true;
  25049. clickInfo.ignore = true;
  25050. return this._processPointerUp(pickResult, evt, clickInfo);
  25051. };
  25052. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25053. if (pickResult && pickResult && pickResult.pickedMesh) {
  25054. this._pickedUpMesh = pickResult.pickedMesh;
  25055. if (this._pickedDownMesh === this._pickedUpMesh) {
  25056. if (this.onPointerPick) {
  25057. this.onPointerPick(evt, pickResult);
  25058. }
  25059. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25060. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25061. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25062. this.onPointerObservable.notifyObservers(pi, type_1);
  25063. }
  25064. }
  25065. if (pickResult.pickedMesh.actionManager) {
  25066. if (clickInfo.ignore) {
  25067. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25068. }
  25069. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25070. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25071. }
  25072. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25073. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25074. }
  25075. }
  25076. }
  25077. if (this._pickedDownMesh &&
  25078. this._pickedDownMesh.actionManager &&
  25079. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25080. this._pickedDownMesh !== this._pickedUpMesh) {
  25081. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25082. }
  25083. var type = BABYLON.PointerEventTypes.POINTERUP;
  25084. if (this.onPointerObservable.hasObservers()) {
  25085. if (!clickInfo.ignore) {
  25086. if (!clickInfo.hasSwiped) {
  25087. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25088. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25089. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25090. this.onPointerObservable.notifyObservers(pi, type_2);
  25091. }
  25092. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25093. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25094. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25095. this.onPointerObservable.notifyObservers(pi, type_3);
  25096. }
  25097. }
  25098. }
  25099. else {
  25100. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25101. this.onPointerObservable.notifyObservers(pi, type);
  25102. }
  25103. }
  25104. if (this.onPointerUp) {
  25105. this.onPointerUp(evt, pickResult, type);
  25106. }
  25107. return this;
  25108. };
  25109. /**
  25110. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25111. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25112. * @returns true if the pointer was captured
  25113. */
  25114. Scene.prototype.isPointerCaptured = function (pointerId) {
  25115. if (pointerId === void 0) { pointerId = 0; }
  25116. return this._pointerCaptures[pointerId];
  25117. };
  25118. /**
  25119. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25120. * @param attachUp defines if you want to attach events to pointerup
  25121. * @param attachDown defines if you want to attach events to pointerdown
  25122. * @param attachMove defines if you want to attach events to pointermove
  25123. */
  25124. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25125. var _this = this;
  25126. if (attachUp === void 0) { attachUp = true; }
  25127. if (attachDown === void 0) { attachDown = true; }
  25128. if (attachMove === void 0) { attachMove = true; }
  25129. this._initActionManager = function (act, clickInfo) {
  25130. if (!_this._meshPickProceed) {
  25131. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25132. _this._currentPickResult = pickResult;
  25133. if (pickResult) {
  25134. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25135. }
  25136. _this._meshPickProceed = true;
  25137. }
  25138. return act;
  25139. };
  25140. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25141. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25142. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25143. btn !== _this._previousButtonPressed) {
  25144. _this._doubleClickOccured = false;
  25145. clickInfo.singleClick = true;
  25146. clickInfo.ignore = false;
  25147. cb(clickInfo, _this._currentPickResult);
  25148. }
  25149. };
  25150. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25151. var clickInfo = new ClickInfo();
  25152. _this._currentPickResult = null;
  25153. var act = null;
  25154. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25155. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25156. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25157. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25158. act = _this._initActionManager(act, clickInfo);
  25159. if (act)
  25160. checkPicking = act.hasPickTriggers;
  25161. }
  25162. if (checkPicking) {
  25163. var btn = evt.button;
  25164. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25165. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25166. if (!clickInfo.hasSwiped) {
  25167. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25168. if (!checkSingleClickImmediately) {
  25169. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25170. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25171. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25172. act = _this._initActionManager(act, clickInfo);
  25173. if (act)
  25174. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25175. }
  25176. }
  25177. if (checkSingleClickImmediately) {
  25178. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25179. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25180. btn !== _this._previousButtonPressed) {
  25181. clickInfo.singleClick = true;
  25182. cb(clickInfo, _this._currentPickResult);
  25183. }
  25184. }
  25185. // at least one double click is required to be check and exclusive double click is enabled
  25186. else {
  25187. // wait that no double click has been raised during the double click delay
  25188. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25189. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25190. }
  25191. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25192. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25193. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25194. act = _this._initActionManager(act, clickInfo);
  25195. if (act)
  25196. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25197. }
  25198. if (checkDoubleClick) {
  25199. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25200. if (btn === _this._previousButtonPressed &&
  25201. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25202. !_this._doubleClickOccured) {
  25203. // pointer has not moved for 2 clicks, it's a double click
  25204. if (!clickInfo.hasSwiped &&
  25205. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25206. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25207. _this._previousStartingPointerTime = 0;
  25208. _this._doubleClickOccured = true;
  25209. clickInfo.doubleClick = true;
  25210. clickInfo.ignore = false;
  25211. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25212. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25213. }
  25214. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25215. cb(clickInfo, _this._currentPickResult);
  25216. }
  25217. // if the two successive clicks are too far, it's just two simple clicks
  25218. else {
  25219. _this._doubleClickOccured = false;
  25220. _this._previousStartingPointerTime = _this._startingPointerTime;
  25221. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25222. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25223. _this._previousButtonPressed = btn;
  25224. if (Scene.ExclusiveDoubleClickMode) {
  25225. if (_this._previousDelayedSimpleClickTimeout) {
  25226. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25227. }
  25228. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25229. cb(clickInfo, _this._previousPickResult);
  25230. }
  25231. else {
  25232. cb(clickInfo, _this._currentPickResult);
  25233. }
  25234. }
  25235. }
  25236. // just the first click of the double has been raised
  25237. else {
  25238. _this._doubleClickOccured = false;
  25239. _this._previousStartingPointerTime = _this._startingPointerTime;
  25240. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25241. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25242. _this._previousButtonPressed = btn;
  25243. }
  25244. }
  25245. }
  25246. }
  25247. clickInfo.ignore = true;
  25248. cb(clickInfo, _this._currentPickResult);
  25249. };
  25250. this._spritePredicate = function (sprite) {
  25251. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25252. };
  25253. this._onPointerMove = function (evt) {
  25254. _this._updatePointerPosition(evt);
  25255. // PreObservable support
  25256. if (_this.onPrePointerObservable.hasObservers() && !_this._pointerCaptures[evt.pointerId]) {
  25257. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25258. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25259. _this.onPrePointerObservable.notifyObservers(pi, type);
  25260. if (pi.skipOnPointerObservable) {
  25261. return;
  25262. }
  25263. }
  25264. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25265. return;
  25266. }
  25267. if (!_this.pointerMovePredicate) {
  25268. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25269. }
  25270. // Meshes
  25271. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25272. _this._processPointerMove(pickResult, evt);
  25273. };
  25274. this._onPointerDown = function (evt) {
  25275. _this._totalPointersPressed++;
  25276. _this._pickedDownMesh = null;
  25277. _this._meshPickProceed = false;
  25278. _this._updatePointerPosition(evt);
  25279. if (_this.preventDefaultOnPointerDown && canvas) {
  25280. evt.preventDefault();
  25281. canvas.focus();
  25282. }
  25283. // PreObservable support
  25284. if (_this.onPrePointerObservable.hasObservers()) {
  25285. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25286. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25287. _this.onPrePointerObservable.notifyObservers(pi, type);
  25288. if (pi.skipOnPointerObservable) {
  25289. return;
  25290. }
  25291. }
  25292. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25293. return;
  25294. }
  25295. _this._pointerCaptures[evt.pointerId] = true;
  25296. _this._startingPointerPosition.x = _this._pointerX;
  25297. _this._startingPointerPosition.y = _this._pointerY;
  25298. _this._startingPointerTime = Date.now();
  25299. if (!_this.pointerDownPredicate) {
  25300. _this.pointerDownPredicate = function (mesh) {
  25301. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25302. };
  25303. }
  25304. // Meshes
  25305. _this._pickedDownMesh = null;
  25306. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25307. _this._processPointerDown(pickResult, evt);
  25308. // Sprites
  25309. _this._pickedDownSprite = null;
  25310. if (_this.spriteManagers.length > 0) {
  25311. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25312. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25313. if (pickResult.pickedSprite.actionManager) {
  25314. _this._pickedDownSprite = pickResult.pickedSprite;
  25315. switch (evt.button) {
  25316. case 0:
  25317. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25318. break;
  25319. case 1:
  25320. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25321. break;
  25322. case 2:
  25323. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25324. break;
  25325. }
  25326. if (pickResult.pickedSprite.actionManager) {
  25327. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25328. }
  25329. }
  25330. }
  25331. }
  25332. };
  25333. this._onPointerUp = function (evt) {
  25334. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25335. return; // So we need to test it the pointer down was pressed before.
  25336. }
  25337. _this._totalPointersPressed--;
  25338. _this._pickedUpMesh = null;
  25339. _this._meshPickProceed = false;
  25340. _this._updatePointerPosition(evt);
  25341. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25342. // PreObservable support
  25343. if (_this.onPrePointerObservable.hasObservers()) {
  25344. if (!clickInfo.ignore) {
  25345. if (!clickInfo.hasSwiped) {
  25346. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25347. var type = BABYLON.PointerEventTypes.POINTERTAP;
  25348. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25349. _this.onPrePointerObservable.notifyObservers(pi, type);
  25350. if (pi.skipOnPointerObservable) {
  25351. return;
  25352. }
  25353. }
  25354. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25355. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25356. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25357. _this.onPrePointerObservable.notifyObservers(pi, type);
  25358. if (pi.skipOnPointerObservable) {
  25359. return;
  25360. }
  25361. }
  25362. }
  25363. }
  25364. else {
  25365. var type = BABYLON.PointerEventTypes.POINTERUP;
  25366. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25367. _this.onPrePointerObservable.notifyObservers(pi, type);
  25368. if (pi.skipOnPointerObservable) {
  25369. return;
  25370. }
  25371. }
  25372. }
  25373. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25374. return;
  25375. }
  25376. _this._pointerCaptures[evt.pointerId] = false;
  25377. if (!_this.pointerUpPredicate) {
  25378. _this.pointerUpPredicate = function (mesh) {
  25379. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25380. };
  25381. }
  25382. // Meshes
  25383. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25384. _this._initActionManager(null, clickInfo);
  25385. }
  25386. if (!pickResult) {
  25387. pickResult = _this._currentPickResult;
  25388. }
  25389. _this._processPointerUp(pickResult, evt, clickInfo);
  25390. // Sprites
  25391. if (!clickInfo.ignore) {
  25392. if (_this.spriteManagers.length > 0) {
  25393. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25394. if (spritePickResult) {
  25395. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25396. if (spritePickResult.pickedSprite.actionManager) {
  25397. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25398. if (spritePickResult.pickedSprite.actionManager) {
  25399. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25400. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25401. }
  25402. }
  25403. }
  25404. }
  25405. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25406. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25407. }
  25408. }
  25409. }
  25410. }
  25411. _this._previousPickResult = _this._currentPickResult;
  25412. });
  25413. };
  25414. this._onKeyDown = function (evt) {
  25415. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25416. if (_this.onPreKeyboardObservable.hasObservers()) {
  25417. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25418. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25419. if (pi.skipOnPointerObservable) {
  25420. return;
  25421. }
  25422. }
  25423. if (_this.onKeyboardObservable.hasObservers()) {
  25424. var pi = new BABYLON.KeyboardInfo(type, evt);
  25425. _this.onKeyboardObservable.notifyObservers(pi, type);
  25426. }
  25427. if (_this.actionManager) {
  25428. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25429. }
  25430. };
  25431. this._onKeyUp = function (evt) {
  25432. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25433. if (_this.onPreKeyboardObservable.hasObservers()) {
  25434. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25435. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25436. if (pi.skipOnPointerObservable) {
  25437. return;
  25438. }
  25439. }
  25440. if (_this.onKeyboardObservable.hasObservers()) {
  25441. var pi = new BABYLON.KeyboardInfo(type, evt);
  25442. _this.onKeyboardObservable.notifyObservers(pi, type);
  25443. }
  25444. if (_this.actionManager) {
  25445. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25446. }
  25447. };
  25448. var engine = this.getEngine();
  25449. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25450. if (!canvas) {
  25451. return;
  25452. }
  25453. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25454. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25455. });
  25456. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25457. if (!canvas) {
  25458. return;
  25459. }
  25460. canvas.removeEventListener("keydown", _this._onKeyDown);
  25461. canvas.removeEventListener("keyup", _this._onKeyUp);
  25462. });
  25463. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25464. var canvas = this._engine.getRenderingCanvas();
  25465. if (!canvas) {
  25466. return;
  25467. }
  25468. if (attachMove) {
  25469. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25470. // Wheel
  25471. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25472. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25473. }
  25474. if (attachDown) {
  25475. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25476. }
  25477. if (attachUp) {
  25478. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25479. }
  25480. canvas.tabIndex = 1;
  25481. };
  25482. /** Detaches all event handlers*/
  25483. Scene.prototype.detachControl = function () {
  25484. var engine = this.getEngine();
  25485. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25486. var canvas = engine.getRenderingCanvas();
  25487. if (!canvas) {
  25488. return;
  25489. }
  25490. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25491. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25492. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25493. if (this._onCanvasBlurObserver) {
  25494. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25495. }
  25496. if (this._onCanvasFocusObserver) {
  25497. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25498. }
  25499. // Wheel
  25500. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25501. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25502. // Keyboard
  25503. canvas.removeEventListener("keydown", this._onKeyDown);
  25504. canvas.removeEventListener("keyup", this._onKeyUp);
  25505. // Observables
  25506. this.onKeyboardObservable.clear();
  25507. this.onPreKeyboardObservable.clear();
  25508. this.onPointerObservable.clear();
  25509. this.onPrePointerObservable.clear();
  25510. };
  25511. /**
  25512. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25513. * Delay loaded resources are not taking in account
  25514. * @return true if all required resources are ready
  25515. */
  25516. Scene.prototype.isReady = function () {
  25517. if (this._isDisposed) {
  25518. return false;
  25519. }
  25520. if (this._pendingData.length > 0) {
  25521. return false;
  25522. }
  25523. var index;
  25524. var engine = this.getEngine();
  25525. // Geometries
  25526. for (index = 0; index < this._geometries.length; index++) {
  25527. var geometry = this._geometries[index];
  25528. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25529. return false;
  25530. }
  25531. }
  25532. // Meshes
  25533. for (index = 0; index < this.meshes.length; index++) {
  25534. var mesh = this.meshes[index];
  25535. if (!mesh.isEnabled()) {
  25536. continue;
  25537. }
  25538. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25539. continue;
  25540. }
  25541. if (!mesh.isReady(true)) {
  25542. return false;
  25543. }
  25544. // Effect layers
  25545. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25546. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25547. var layer = _a[_i];
  25548. if (!layer.hasMesh(mesh)) {
  25549. continue;
  25550. }
  25551. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25552. var subMesh = _c[_b];
  25553. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25554. return false;
  25555. }
  25556. }
  25557. }
  25558. }
  25559. // Post-processes
  25560. if (this.activeCameras && this.activeCameras.length > 0) {
  25561. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25562. var camera = _e[_d];
  25563. if (!camera.isReady(true)) {
  25564. return false;
  25565. }
  25566. }
  25567. }
  25568. else if (this.activeCamera) {
  25569. if (!this.activeCamera.isReady(true)) {
  25570. return false;
  25571. }
  25572. }
  25573. // Particles
  25574. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25575. var particleSystem = _g[_f];
  25576. if (!particleSystem.isReady()) {
  25577. return false;
  25578. }
  25579. }
  25580. return true;
  25581. };
  25582. /** Resets all cached information relative to material (including effect and visibility) */
  25583. Scene.prototype.resetCachedMaterial = function () {
  25584. this._cachedMaterial = null;
  25585. this._cachedEffect = null;
  25586. this._cachedVisibility = null;
  25587. };
  25588. /**
  25589. * Registers a function to be called before every frame render
  25590. * @param func defines the function to register
  25591. */
  25592. Scene.prototype.registerBeforeRender = function (func) {
  25593. this.onBeforeRenderObservable.add(func);
  25594. };
  25595. /**
  25596. * Unregisters a function called before every frame render
  25597. * @param func defines the function to unregister
  25598. */
  25599. Scene.prototype.unregisterBeforeRender = function (func) {
  25600. this.onBeforeRenderObservable.removeCallback(func);
  25601. };
  25602. /**
  25603. * Registers a function to be called after every frame render
  25604. * @param func defines the function to register
  25605. */
  25606. Scene.prototype.registerAfterRender = function (func) {
  25607. this.onAfterRenderObservable.add(func);
  25608. };
  25609. /**
  25610. * Unregisters a function called after every frame render
  25611. * @param func defines the function to unregister
  25612. */
  25613. Scene.prototype.unregisterAfterRender = function (func) {
  25614. this.onAfterRenderObservable.removeCallback(func);
  25615. };
  25616. Scene.prototype._executeOnceBeforeRender = function (func) {
  25617. var _this = this;
  25618. var execFunc = function () {
  25619. func();
  25620. setTimeout(function () {
  25621. _this.unregisterBeforeRender(execFunc);
  25622. });
  25623. };
  25624. this.registerBeforeRender(execFunc);
  25625. };
  25626. /**
  25627. * The provided function will run before render once and will be disposed afterwards.
  25628. * A timeout delay can be provided so that the function will be executed in N ms.
  25629. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25630. * @param func The function to be executed.
  25631. * @param timeout optional delay in ms
  25632. */
  25633. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25634. var _this = this;
  25635. if (timeout !== undefined) {
  25636. setTimeout(function () {
  25637. _this._executeOnceBeforeRender(func);
  25638. }, timeout);
  25639. }
  25640. else {
  25641. this._executeOnceBeforeRender(func);
  25642. }
  25643. };
  25644. /** @hidden */
  25645. Scene.prototype._addPendingData = function (data) {
  25646. this._pendingData.push(data);
  25647. };
  25648. /** @hidden */
  25649. Scene.prototype._removePendingData = function (data) {
  25650. var wasLoading = this.isLoading;
  25651. var index = this._pendingData.indexOf(data);
  25652. if (index !== -1) {
  25653. this._pendingData.splice(index, 1);
  25654. }
  25655. if (wasLoading && !this.isLoading) {
  25656. this.onDataLoadedObservable.notifyObservers(this);
  25657. }
  25658. };
  25659. /**
  25660. * Returns the number of items waiting to be loaded
  25661. * @returns the number of items waiting to be loaded
  25662. */
  25663. Scene.prototype.getWaitingItemsCount = function () {
  25664. return this._pendingData.length;
  25665. };
  25666. Object.defineProperty(Scene.prototype, "isLoading", {
  25667. /**
  25668. * Returns a boolean indicating if the scene is still loading data
  25669. */
  25670. get: function () {
  25671. return this._pendingData.length > 0;
  25672. },
  25673. enumerable: true,
  25674. configurable: true
  25675. });
  25676. /**
  25677. * Registers a function to be executed when the scene is ready
  25678. * @param {Function} func - the function to be executed
  25679. */
  25680. Scene.prototype.executeWhenReady = function (func) {
  25681. var _this = this;
  25682. this.onReadyObservable.add(func);
  25683. if (this._executeWhenReadyTimeoutId !== -1) {
  25684. return;
  25685. }
  25686. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25687. _this._checkIsReady();
  25688. }, 150);
  25689. };
  25690. /**
  25691. * Returns a promise that resolves when the scene is ready
  25692. * @returns A promise that resolves when the scene is ready
  25693. */
  25694. Scene.prototype.whenReadyAsync = function () {
  25695. var _this = this;
  25696. return new Promise(function (resolve) {
  25697. _this.executeWhenReady(function () {
  25698. resolve();
  25699. });
  25700. });
  25701. };
  25702. /** @hidden */
  25703. Scene.prototype._checkIsReady = function () {
  25704. var _this = this;
  25705. if (this.isReady()) {
  25706. this.onReadyObservable.notifyObservers(this);
  25707. this.onReadyObservable.clear();
  25708. this._executeWhenReadyTimeoutId = -1;
  25709. return;
  25710. }
  25711. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25712. _this._checkIsReady();
  25713. }, 150);
  25714. };
  25715. // Animations
  25716. /**
  25717. * Will start the animation sequence of a given target
  25718. * @param target defines the target
  25719. * @param from defines from which frame should animation start
  25720. * @param to defines until which frame should animation run.
  25721. * @param weight defines the weight to apply to the animation (1.0 by default)
  25722. * @param loop defines if the animation loops
  25723. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25724. * @param onAnimationEnd defines the function to be executed when the animation ends
  25725. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25726. * @returns the animatable object created for this animation
  25727. */
  25728. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25729. if (weight === void 0) { weight = 1.0; }
  25730. if (speedRatio === void 0) { speedRatio = 1.0; }
  25731. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25732. returnedAnimatable.weight = weight;
  25733. return returnedAnimatable;
  25734. };
  25735. /**
  25736. * Will start the animation sequence of a given target
  25737. * @param target defines the target
  25738. * @param from defines from which frame should animation start
  25739. * @param to defines until which frame should animation run.
  25740. * @param loop defines if the animation loops
  25741. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25742. * @param onAnimationEnd defines the function to be executed when the animation ends
  25743. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25744. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25745. * @returns the animatable object created for this animation
  25746. */
  25747. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25748. if (speedRatio === void 0) { speedRatio = 1.0; }
  25749. if (stopCurrent === void 0) { stopCurrent = true; }
  25750. if (from > to && speedRatio > 0) {
  25751. speedRatio *= -1;
  25752. }
  25753. if (stopCurrent) {
  25754. this.stopAnimation(target);
  25755. }
  25756. if (!animatable) {
  25757. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25758. }
  25759. // Local animations
  25760. if (target.animations) {
  25761. animatable.appendAnimations(target, target.animations);
  25762. }
  25763. // Children animations
  25764. if (target.getAnimatables) {
  25765. var animatables = target.getAnimatables();
  25766. for (var index = 0; index < animatables.length; index++) {
  25767. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25768. }
  25769. }
  25770. animatable.reset();
  25771. return animatable;
  25772. };
  25773. /**
  25774. * Begin a new animation on a given node
  25775. * @param target defines the target where the animation will take place
  25776. * @param animations defines the list of animations to start
  25777. * @param from defines the initial value
  25778. * @param to defines the final value
  25779. * @param loop defines if you want animation to loop (off by default)
  25780. * @param speedRatio defines the speed ratio to apply to all animations
  25781. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25782. * @returns the list of created animatables
  25783. */
  25784. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25785. if (speedRatio === undefined) {
  25786. speedRatio = 1.0;
  25787. }
  25788. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25789. return animatable;
  25790. };
  25791. /**
  25792. * Begin a new animation on a given node and its hierarchy
  25793. * @param target defines the root node where the animation will take place
  25794. * @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.
  25795. * @param animations defines the list of animations to start
  25796. * @param from defines the initial value
  25797. * @param to defines the final value
  25798. * @param loop defines if you want animation to loop (off by default)
  25799. * @param speedRatio defines the speed ratio to apply to all animations
  25800. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25801. * @returns the list of animatables created for all nodes
  25802. */
  25803. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25804. var children = target.getDescendants(directDescendantsOnly);
  25805. var result = [];
  25806. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25807. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25808. var child = children_1[_i];
  25809. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25810. }
  25811. return result;
  25812. };
  25813. /**
  25814. * Gets the animatable associated with a specific target
  25815. * @param target defines the target of the animatable
  25816. * @returns the required animatable if found
  25817. */
  25818. Scene.prototype.getAnimatableByTarget = function (target) {
  25819. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25820. if (this._activeAnimatables[index].target === target) {
  25821. return this._activeAnimatables[index];
  25822. }
  25823. }
  25824. return null;
  25825. };
  25826. /**
  25827. * Gets all animatables associated with a given target
  25828. * @param target defines the target to look animatables for
  25829. * @returns an array of Animatables
  25830. */
  25831. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25832. var result = [];
  25833. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25834. if (this._activeAnimatables[index].target === target) {
  25835. result.push(this._activeAnimatables[index]);
  25836. }
  25837. }
  25838. return result;
  25839. };
  25840. Object.defineProperty(Scene.prototype, "animatables", {
  25841. /**
  25842. * Gets all animatable attached to the scene
  25843. */
  25844. get: function () {
  25845. return this._activeAnimatables;
  25846. },
  25847. enumerable: true,
  25848. configurable: true
  25849. });
  25850. /**
  25851. * Will stop the animation of the given target
  25852. * @param target - the target
  25853. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25854. */
  25855. Scene.prototype.stopAnimation = function (target, animationName) {
  25856. var animatables = this.getAllAnimatablesByTarget(target);
  25857. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25858. var animatable = animatables_1[_i];
  25859. animatable.stop(animationName);
  25860. }
  25861. };
  25862. /**
  25863. * Stops and removes all animations that have been applied to the scene
  25864. */
  25865. Scene.prototype.stopAllAnimations = function () {
  25866. if (this._activeAnimatables) {
  25867. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25868. this._activeAnimatables[i].stop();
  25869. }
  25870. this._activeAnimatables = [];
  25871. }
  25872. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25873. var group = _a[_i];
  25874. group.stop();
  25875. }
  25876. };
  25877. Scene.prototype._animate = function () {
  25878. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25879. return;
  25880. }
  25881. // Getting time
  25882. var now = BABYLON.Tools.Now;
  25883. if (!this._animationTimeLast) {
  25884. if (this._pendingData.length > 0) {
  25885. return;
  25886. }
  25887. this._animationTimeLast = now;
  25888. }
  25889. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25890. this._animationTime += deltaTime;
  25891. this._animationTimeLast = now;
  25892. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25893. this._activeAnimatables[index]._animate(this._animationTime);
  25894. }
  25895. // Late animation bindings
  25896. this._processLateAnimationBindings();
  25897. };
  25898. /** @hidden */
  25899. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25900. var target = runtimeAnimation.target;
  25901. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25902. if (!target._lateAnimationHolders) {
  25903. target._lateAnimationHolders = {};
  25904. }
  25905. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25906. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25907. totalWeight: 0,
  25908. animations: [],
  25909. originalValue: originalValue
  25910. };
  25911. }
  25912. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25913. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25914. };
  25915. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25916. var normalizer = 1.0;
  25917. var finalPosition = BABYLON.Tmp.Vector3[0];
  25918. var finalScaling = BABYLON.Tmp.Vector3[1];
  25919. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25920. var startIndex = 0;
  25921. var originalAnimation = holder.animations[0];
  25922. var originalValue = holder.originalValue;
  25923. var scale = 1;
  25924. if (holder.totalWeight < 1.0) {
  25925. // We need to mix the original value in
  25926. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25927. scale = 1.0 - holder.totalWeight;
  25928. }
  25929. else {
  25930. startIndex = 1;
  25931. // We need to normalize the weights
  25932. normalizer = holder.totalWeight;
  25933. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25934. scale = originalAnimation.weight / normalizer;
  25935. if (scale == 1) {
  25936. return originalAnimation.currentValue;
  25937. }
  25938. }
  25939. finalScaling.scaleInPlace(scale);
  25940. finalPosition.scaleInPlace(scale);
  25941. finalQuaternion.scaleInPlace(scale);
  25942. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25943. var runtimeAnimation = holder.animations[animIndex];
  25944. var scale = runtimeAnimation.weight / normalizer;
  25945. var currentPosition = BABYLON.Tmp.Vector3[2];
  25946. var currentScaling = BABYLON.Tmp.Vector3[3];
  25947. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25948. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25949. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25950. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25951. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25952. }
  25953. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25954. return originalAnimation._workValue;
  25955. };
  25956. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  25957. var originalAnimation = holder.animations[0];
  25958. var originalValue = holder.originalValue;
  25959. if (holder.animations.length === 1) {
  25960. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  25961. }
  25962. var normalizer = 1.0;
  25963. var quaternions;
  25964. var weights;
  25965. if (holder.totalWeight < 1.0) {
  25966. var scale = 1.0 - holder.totalWeight;
  25967. quaternions = [];
  25968. weights = [];
  25969. quaternions.push(originalValue);
  25970. weights.push(scale);
  25971. }
  25972. else {
  25973. if (holder.animations.length === 2) { // Slerp as soon as we can
  25974. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  25975. }
  25976. quaternions = [];
  25977. weights = [];
  25978. normalizer = holder.totalWeight;
  25979. }
  25980. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  25981. var runtimeAnimation = holder.animations[animIndex];
  25982. quaternions.push(runtimeAnimation.currentValue);
  25983. weights.push(runtimeAnimation.weight / normalizer);
  25984. }
  25985. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  25986. var cumulativeAmount = 0;
  25987. var cumulativeQuaternion = null;
  25988. for (var index = 0; index < quaternions.length;) {
  25989. if (!cumulativeQuaternion) {
  25990. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  25991. cumulativeAmount = weights[index] + weights[index + 1];
  25992. index += 2;
  25993. continue;
  25994. }
  25995. cumulativeAmount += weights[index];
  25996. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  25997. index++;
  25998. }
  25999. return cumulativeQuaternion;
  26000. };
  26001. Scene.prototype._processLateAnimationBindings = function () {
  26002. if (!this._registeredForLateAnimationBindings.length) {
  26003. return;
  26004. }
  26005. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26006. var target = this._registeredForLateAnimationBindings.data[index];
  26007. for (var path in target._lateAnimationHolders) {
  26008. var holder = target._lateAnimationHolders[path];
  26009. var originalAnimation = holder.animations[0];
  26010. var originalValue = holder.originalValue;
  26011. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26012. var finalValue = void 0;
  26013. if (matrixDecomposeMode) {
  26014. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26015. }
  26016. else {
  26017. var quaternionMode = originalValue.w !== undefined;
  26018. if (quaternionMode) {
  26019. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26020. }
  26021. else {
  26022. var startIndex = 0;
  26023. var normalizer = 1.0;
  26024. if (holder.totalWeight < 1.0) {
  26025. // We need to mix the original value in
  26026. if (originalValue.scale) {
  26027. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26028. }
  26029. else {
  26030. finalValue = originalValue * (1.0 - holder.totalWeight);
  26031. }
  26032. }
  26033. else {
  26034. // We need to normalize the weights
  26035. normalizer = holder.totalWeight;
  26036. var scale_1 = originalAnimation.weight / normalizer;
  26037. if (scale_1 !== 1) {
  26038. if (originalAnimation.currentValue.scale) {
  26039. finalValue = originalAnimation.currentValue.scale(scale_1);
  26040. }
  26041. else {
  26042. finalValue = originalAnimation.currentValue * scale_1;
  26043. }
  26044. }
  26045. else {
  26046. finalValue = originalAnimation.currentValue;
  26047. }
  26048. startIndex = 1;
  26049. }
  26050. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26051. var runtimeAnimation = holder.animations[animIndex];
  26052. var scale = runtimeAnimation.weight / normalizer;
  26053. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26054. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26055. }
  26056. else {
  26057. finalValue += runtimeAnimation.currentValue * scale;
  26058. }
  26059. }
  26060. }
  26061. }
  26062. target[path] = finalValue;
  26063. }
  26064. target._lateAnimationHolders = {};
  26065. }
  26066. this._registeredForLateAnimationBindings.reset();
  26067. };
  26068. // Matrix
  26069. /** @hidden */
  26070. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26071. this._useAlternateCameraConfiguration = active;
  26072. };
  26073. /**
  26074. * Gets the current view matrix
  26075. * @returns a Matrix
  26076. */
  26077. Scene.prototype.getViewMatrix = function () {
  26078. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26079. };
  26080. /**
  26081. * Gets the current projection matrix
  26082. * @returns a Matrix
  26083. */
  26084. Scene.prototype.getProjectionMatrix = function () {
  26085. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26086. };
  26087. /**
  26088. * Gets the current transform matrix
  26089. * @returns a Matrix made of View * Projection
  26090. */
  26091. Scene.prototype.getTransformMatrix = function () {
  26092. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26093. };
  26094. /**
  26095. * Sets the current transform matrix
  26096. * @param view defines the View matrix to use
  26097. * @param projection defines the Projection matrix to use
  26098. */
  26099. Scene.prototype.setTransformMatrix = function (view, projection) {
  26100. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26101. return;
  26102. }
  26103. this._viewUpdateFlag = view.updateFlag;
  26104. this._projectionUpdateFlag = projection.updateFlag;
  26105. this._viewMatrix = view;
  26106. this._projectionMatrix = projection;
  26107. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26108. // Update frustum
  26109. if (!this._frustumPlanes) {
  26110. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26111. }
  26112. else {
  26113. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26114. }
  26115. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26116. var otherCamera = this.activeCamera._alternateCamera;
  26117. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26118. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26119. }
  26120. if (this._sceneUbo.useUbo) {
  26121. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26122. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26123. this._sceneUbo.update();
  26124. }
  26125. };
  26126. /** @hidden */
  26127. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26128. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26129. return;
  26130. }
  26131. this._alternateViewUpdateFlag = view.updateFlag;
  26132. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26133. this._alternateViewMatrix = view;
  26134. this._alternateProjectionMatrix = projection;
  26135. if (!this._alternateTransformMatrix) {
  26136. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26137. }
  26138. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26139. if (!this._alternateSceneUbo) {
  26140. this._createAlternateUbo();
  26141. }
  26142. if (this._alternateSceneUbo.useUbo) {
  26143. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26144. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26145. this._alternateSceneUbo.update();
  26146. }
  26147. };
  26148. /**
  26149. * Gets the uniform buffer used to store scene data
  26150. * @returns a UniformBuffer
  26151. */
  26152. Scene.prototype.getSceneUniformBuffer = function () {
  26153. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26154. };
  26155. /**
  26156. * Gets an unique (relatively to the current scene) Id
  26157. * @returns an unique number for the scene
  26158. */
  26159. Scene.prototype.getUniqueId = function () {
  26160. var result = Scene._uniqueIdCounter;
  26161. Scene._uniqueIdCounter++;
  26162. return result;
  26163. };
  26164. /**
  26165. * Add a mesh to the list of scene's meshes
  26166. * @param newMesh defines the mesh to add
  26167. * @param recursive if all child meshes should also be added to the scene
  26168. */
  26169. Scene.prototype.addMesh = function (newMesh, recursive) {
  26170. var _this = this;
  26171. if (recursive === void 0) { recursive = false; }
  26172. this.meshes.push(newMesh);
  26173. //notify the collision coordinator
  26174. if (this.collisionCoordinator) {
  26175. this.collisionCoordinator.onMeshAdded(newMesh);
  26176. }
  26177. newMesh._resyncLightSources();
  26178. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26179. if (recursive) {
  26180. newMesh.getChildMeshes().forEach(function (m) {
  26181. _this.addMesh(m);
  26182. });
  26183. }
  26184. };
  26185. /**
  26186. * Remove a mesh for the list of scene's meshes
  26187. * @param toRemove defines the mesh to remove
  26188. * @param recursive if all child meshes should also be removed from the scene
  26189. * @returns the index where the mesh was in the mesh list
  26190. */
  26191. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26192. var _this = this;
  26193. if (recursive === void 0) { recursive = false; }
  26194. var index = this.meshes.indexOf(toRemove);
  26195. if (index !== -1) {
  26196. // Remove from the scene if mesh found
  26197. this.meshes.splice(index, 1);
  26198. }
  26199. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26200. if (recursive) {
  26201. toRemove.getChildMeshes().forEach(function (m) {
  26202. _this.removeMesh(m);
  26203. });
  26204. }
  26205. return index;
  26206. };
  26207. /**
  26208. * Add a transform node to the list of scene's transform nodes
  26209. * @param newTransformNode defines the transform node to add
  26210. */
  26211. Scene.prototype.addTransformNode = function (newTransformNode) {
  26212. this.transformNodes.push(newTransformNode);
  26213. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26214. };
  26215. /**
  26216. * Remove a transform node for the list of scene's transform nodes
  26217. * @param toRemove defines the transform node to remove
  26218. * @returns the index where the transform node was in the transform node list
  26219. */
  26220. Scene.prototype.removeTransformNode = function (toRemove) {
  26221. var index = this.transformNodes.indexOf(toRemove);
  26222. if (index !== -1) {
  26223. // Remove from the scene if found
  26224. this.transformNodes.splice(index, 1);
  26225. }
  26226. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26227. return index;
  26228. };
  26229. /**
  26230. * Remove a skeleton for the list of scene's skeletons
  26231. * @param toRemove defines the skeleton to remove
  26232. * @returns the index where the skeleton was in the skeleton list
  26233. */
  26234. Scene.prototype.removeSkeleton = function (toRemove) {
  26235. var index = this.skeletons.indexOf(toRemove);
  26236. if (index !== -1) {
  26237. // Remove from the scene if found
  26238. this.skeletons.splice(index, 1);
  26239. }
  26240. return index;
  26241. };
  26242. /**
  26243. * Remove a morph target for the list of scene's morph targets
  26244. * @param toRemove defines the morph target to remove
  26245. * @returns the index where the morph target was in the morph target list
  26246. */
  26247. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26248. var index = this.morphTargetManagers.indexOf(toRemove);
  26249. if (index !== -1) {
  26250. // Remove from the scene if found
  26251. this.morphTargetManagers.splice(index, 1);
  26252. }
  26253. return index;
  26254. };
  26255. /**
  26256. * Remove a light for the list of scene's lights
  26257. * @param toRemove defines the light to remove
  26258. * @returns the index where the light was in the light list
  26259. */
  26260. Scene.prototype.removeLight = function (toRemove) {
  26261. var index = this.lights.indexOf(toRemove);
  26262. if (index !== -1) {
  26263. // Remove from meshes
  26264. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26265. var mesh = _a[_i];
  26266. mesh._removeLightSource(toRemove);
  26267. }
  26268. // Remove from the scene if mesh found
  26269. this.lights.splice(index, 1);
  26270. this.sortLightsByPriority();
  26271. }
  26272. this.onLightRemovedObservable.notifyObservers(toRemove);
  26273. return index;
  26274. };
  26275. /**
  26276. * Remove a camera for the list of scene's cameras
  26277. * @param toRemove defines the camera to remove
  26278. * @returns the index where the camera was in the camera list
  26279. */
  26280. Scene.prototype.removeCamera = function (toRemove) {
  26281. var index = this.cameras.indexOf(toRemove);
  26282. if (index !== -1) {
  26283. // Remove from the scene if mesh found
  26284. this.cameras.splice(index, 1);
  26285. }
  26286. // Remove from activeCameras
  26287. var index2 = this.activeCameras.indexOf(toRemove);
  26288. if (index2 !== -1) {
  26289. // Remove from the scene if mesh found
  26290. this.activeCameras.splice(index2, 1);
  26291. }
  26292. // Reset the activeCamera
  26293. if (this.activeCamera === toRemove) {
  26294. if (this.cameras.length > 0) {
  26295. this.activeCamera = this.cameras[0];
  26296. }
  26297. else {
  26298. this.activeCamera = null;
  26299. }
  26300. }
  26301. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26302. return index;
  26303. };
  26304. /**
  26305. * Remove a particle system for the list of scene's particle systems
  26306. * @param toRemove defines the particle system to remove
  26307. * @returns the index where the particle system was in the particle system list
  26308. */
  26309. Scene.prototype.removeParticleSystem = function (toRemove) {
  26310. var index = this.particleSystems.indexOf(toRemove);
  26311. if (index !== -1) {
  26312. this.particleSystems.splice(index, 1);
  26313. }
  26314. return index;
  26315. };
  26316. /**
  26317. * Remove a animation for the list of scene's animations
  26318. * @param toRemove defines the animation to remove
  26319. * @returns the index where the animation was in the animation list
  26320. */
  26321. Scene.prototype.removeAnimation = function (toRemove) {
  26322. var index = this.animations.indexOf(toRemove);
  26323. if (index !== -1) {
  26324. this.animations.splice(index, 1);
  26325. }
  26326. return index;
  26327. };
  26328. /**
  26329. * Removes the given animation group from this scene.
  26330. * @param toRemove The animation group to remove
  26331. * @returns The index of the removed animation group
  26332. */
  26333. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26334. var index = this.animationGroups.indexOf(toRemove);
  26335. if (index !== -1) {
  26336. this.animationGroups.splice(index, 1);
  26337. }
  26338. return index;
  26339. };
  26340. /**
  26341. * Removes the given multi-material from this scene.
  26342. * @param toRemove The multi-material to remove
  26343. * @returns The index of the removed multi-material
  26344. */
  26345. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26346. var index = this.multiMaterials.indexOf(toRemove);
  26347. if (index !== -1) {
  26348. this.multiMaterials.splice(index, 1);
  26349. }
  26350. return index;
  26351. };
  26352. /**
  26353. * Removes the given material from this scene.
  26354. * @param toRemove The material to remove
  26355. * @returns The index of the removed material
  26356. */
  26357. Scene.prototype.removeMaterial = function (toRemove) {
  26358. var index = this.materials.indexOf(toRemove);
  26359. if (index !== -1) {
  26360. this.materials.splice(index, 1);
  26361. }
  26362. return index;
  26363. };
  26364. /**
  26365. * Removes the given lens flare system from this scene.
  26366. * @param toRemove The lens flare system to remove
  26367. * @returns The index of the removed lens flare system
  26368. */
  26369. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26370. var index = this.lensFlareSystems.indexOf(toRemove);
  26371. if (index !== -1) {
  26372. this.lensFlareSystems.splice(index, 1);
  26373. }
  26374. return index;
  26375. };
  26376. /**
  26377. * Removes the given action manager from this scene.
  26378. * @param toRemove The action manager to remove
  26379. * @returns The index of the removed action manager
  26380. */
  26381. Scene.prototype.removeActionManager = function (toRemove) {
  26382. var index = this._actionManagers.indexOf(toRemove);
  26383. if (index !== -1) {
  26384. this._actionManagers.splice(index, 1);
  26385. }
  26386. return index;
  26387. };
  26388. /**
  26389. * Removes the given effect layer from this scene.
  26390. * @param toRemove defines the effect layer to remove
  26391. * @returns the index of the removed effect layer
  26392. */
  26393. Scene.prototype.removeEffectLayer = function (toRemove) {
  26394. var index = this.effectLayers.indexOf(toRemove);
  26395. if (index !== -1) {
  26396. this.effectLayers.splice(index, 1);
  26397. }
  26398. return index;
  26399. };
  26400. /**
  26401. * Removes the given texture from this scene.
  26402. * @param toRemove The texture to remove
  26403. * @returns The index of the removed texture
  26404. */
  26405. Scene.prototype.removeTexture = function (toRemove) {
  26406. var index = this.textures.indexOf(toRemove);
  26407. if (index !== -1) {
  26408. this.textures.splice(index, 1);
  26409. }
  26410. return index;
  26411. };
  26412. /**
  26413. * Adds the given light to this scene
  26414. * @param newLight The light to add
  26415. */
  26416. Scene.prototype.addLight = function (newLight) {
  26417. this.lights.push(newLight);
  26418. this.sortLightsByPriority();
  26419. // Add light to all meshes (To support if the light is removed and then readded)
  26420. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26421. var mesh = _a[_i];
  26422. if (mesh._lightSources.indexOf(newLight) === -1) {
  26423. mesh._lightSources.push(newLight);
  26424. mesh._resyncLightSources();
  26425. }
  26426. }
  26427. this.onNewLightAddedObservable.notifyObservers(newLight);
  26428. };
  26429. /**
  26430. * Sorts the list list based on light priorities
  26431. */
  26432. Scene.prototype.sortLightsByPriority = function () {
  26433. if (this.requireLightSorting) {
  26434. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26435. }
  26436. };
  26437. /**
  26438. * Adds the given camera to this scene
  26439. * @param newCamera The camera to add
  26440. */
  26441. Scene.prototype.addCamera = function (newCamera) {
  26442. this.cameras.push(newCamera);
  26443. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26444. };
  26445. /**
  26446. * Adds the given skeleton to this scene
  26447. * @param newSkeleton The skeleton to add
  26448. */
  26449. Scene.prototype.addSkeleton = function (newSkeleton) {
  26450. this.skeletons.push(newSkeleton);
  26451. };
  26452. /**
  26453. * Adds the given particle system to this scene
  26454. * @param newParticleSystem The particle system to add
  26455. */
  26456. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26457. this.particleSystems.push(newParticleSystem);
  26458. };
  26459. /**
  26460. * Adds the given animation to this scene
  26461. * @param newAnimation The animation to add
  26462. */
  26463. Scene.prototype.addAnimation = function (newAnimation) {
  26464. this.animations.push(newAnimation);
  26465. };
  26466. /**
  26467. * Adds the given animation group to this scene.
  26468. * @param newAnimationGroup The animation group to add
  26469. */
  26470. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26471. this.animationGroups.push(newAnimationGroup);
  26472. };
  26473. /**
  26474. * Adds the given multi-material to this scene
  26475. * @param newMultiMaterial The multi-material to add
  26476. */
  26477. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26478. this.multiMaterials.push(newMultiMaterial);
  26479. };
  26480. /**
  26481. * Adds the given material to this scene
  26482. * @param newMaterial The material to add
  26483. */
  26484. Scene.prototype.addMaterial = function (newMaterial) {
  26485. this.materials.push(newMaterial);
  26486. };
  26487. /**
  26488. * Adds the given morph target to this scene
  26489. * @param newMorphTargetManager The morph target to add
  26490. */
  26491. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26492. this.morphTargetManagers.push(newMorphTargetManager);
  26493. };
  26494. /**
  26495. * Adds the given geometry to this scene
  26496. * @param newGeometry The geometry to add
  26497. */
  26498. Scene.prototype.addGeometry = function (newGeometry) {
  26499. this._geometries.push(newGeometry);
  26500. };
  26501. /**
  26502. * Adds the given lens flare system to this scene
  26503. * @param newLensFlareSystem The lens flare system to add
  26504. */
  26505. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26506. this.lensFlareSystems.push(newLensFlareSystem);
  26507. };
  26508. /**
  26509. * Adds the given effect layer to this scene
  26510. * @param newEffectLayer defines the effect layer to add
  26511. */
  26512. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26513. this.effectLayers.push(newEffectLayer);
  26514. };
  26515. /**
  26516. * Adds the given action manager to this scene
  26517. * @param newActionManager The action manager to add
  26518. */
  26519. Scene.prototype.addActionManager = function (newActionManager) {
  26520. this._actionManagers.push(newActionManager);
  26521. };
  26522. /**
  26523. * Adds the given texture to this scene.
  26524. * @param newTexture The texture to add
  26525. */
  26526. Scene.prototype.addTexture = function (newTexture) {
  26527. this.textures.push(newTexture);
  26528. };
  26529. /**
  26530. * Switch active camera
  26531. * @param newCamera defines the new active camera
  26532. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26533. */
  26534. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26535. if (attachControl === void 0) { attachControl = true; }
  26536. var canvas = this._engine.getRenderingCanvas();
  26537. if (!canvas) {
  26538. return;
  26539. }
  26540. if (this.activeCamera) {
  26541. this.activeCamera.detachControl(canvas);
  26542. }
  26543. this.activeCamera = newCamera;
  26544. if (attachControl) {
  26545. newCamera.attachControl(canvas);
  26546. }
  26547. };
  26548. /**
  26549. * sets the active camera of the scene using its ID
  26550. * @param id defines the camera's ID
  26551. * @return the new active camera or null if none found.
  26552. */
  26553. Scene.prototype.setActiveCameraByID = function (id) {
  26554. var camera = this.getCameraByID(id);
  26555. if (camera) {
  26556. this.activeCamera = camera;
  26557. return camera;
  26558. }
  26559. return null;
  26560. };
  26561. /**
  26562. * sets the active camera of the scene using its name
  26563. * @param name defines the camera's name
  26564. * @returns the new active camera or null if none found.
  26565. */
  26566. Scene.prototype.setActiveCameraByName = function (name) {
  26567. var camera = this.getCameraByName(name);
  26568. if (camera) {
  26569. this.activeCamera = camera;
  26570. return camera;
  26571. }
  26572. return null;
  26573. };
  26574. /**
  26575. * get an animation group using its name
  26576. * @param name defines the material's name
  26577. * @return the animation group or null if none found.
  26578. */
  26579. Scene.prototype.getAnimationGroupByName = function (name) {
  26580. for (var index = 0; index < this.animationGroups.length; index++) {
  26581. if (this.animationGroups[index].name === name) {
  26582. return this.animationGroups[index];
  26583. }
  26584. }
  26585. return null;
  26586. };
  26587. /**
  26588. * get a material using its id
  26589. * @param id defines the material's ID
  26590. * @return the material or null if none found.
  26591. */
  26592. Scene.prototype.getMaterialByID = function (id) {
  26593. for (var index = 0; index < this.materials.length; index++) {
  26594. if (this.materials[index].id === id) {
  26595. return this.materials[index];
  26596. }
  26597. }
  26598. return null;
  26599. };
  26600. /**
  26601. * Gets a material using its name
  26602. * @param name defines the material's name
  26603. * @return the material or null if none found.
  26604. */
  26605. Scene.prototype.getMaterialByName = function (name) {
  26606. for (var index = 0; index < this.materials.length; index++) {
  26607. if (this.materials[index].name === name) {
  26608. return this.materials[index];
  26609. }
  26610. }
  26611. return null;
  26612. };
  26613. /**
  26614. * Gets a lens flare system using its name
  26615. * @param name defines the name to look for
  26616. * @returns the lens flare system or null if not found
  26617. */
  26618. Scene.prototype.getLensFlareSystemByName = function (name) {
  26619. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26620. if (this.lensFlareSystems[index].name === name) {
  26621. return this.lensFlareSystems[index];
  26622. }
  26623. }
  26624. return null;
  26625. };
  26626. /**
  26627. * Gets a lens flare system using its id
  26628. * @param id defines the id to look for
  26629. * @returns the lens flare system or null if not found
  26630. */
  26631. Scene.prototype.getLensFlareSystemByID = function (id) {
  26632. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26633. if (this.lensFlareSystems[index].id === id) {
  26634. return this.lensFlareSystems[index];
  26635. }
  26636. }
  26637. return null;
  26638. };
  26639. /**
  26640. * Gets a camera using its id
  26641. * @param id defines the id to look for
  26642. * @returns the camera or null if not found
  26643. */
  26644. Scene.prototype.getCameraByID = function (id) {
  26645. for (var index = 0; index < this.cameras.length; index++) {
  26646. if (this.cameras[index].id === id) {
  26647. return this.cameras[index];
  26648. }
  26649. }
  26650. return null;
  26651. };
  26652. /**
  26653. * Gets a camera using its unique id
  26654. * @param uniqueId defines the unique id to look for
  26655. * @returns the camera or null if not found
  26656. */
  26657. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26658. for (var index = 0; index < this.cameras.length; index++) {
  26659. if (this.cameras[index].uniqueId === uniqueId) {
  26660. return this.cameras[index];
  26661. }
  26662. }
  26663. return null;
  26664. };
  26665. /**
  26666. * Gets a camera using its name
  26667. * @param name defines the camera's name
  26668. * @return the camera or null if none found.
  26669. */
  26670. Scene.prototype.getCameraByName = function (name) {
  26671. for (var index = 0; index < this.cameras.length; index++) {
  26672. if (this.cameras[index].name === name) {
  26673. return this.cameras[index];
  26674. }
  26675. }
  26676. return null;
  26677. };
  26678. /**
  26679. * Gets a bone using its id
  26680. * @param id defines the bone's id
  26681. * @return the bone or null if not found
  26682. */
  26683. Scene.prototype.getBoneByID = function (id) {
  26684. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26685. var skeleton = this.skeletons[skeletonIndex];
  26686. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26687. if (skeleton.bones[boneIndex].id === id) {
  26688. return skeleton.bones[boneIndex];
  26689. }
  26690. }
  26691. }
  26692. return null;
  26693. };
  26694. /**
  26695. * Gets a bone using its id
  26696. * @param name defines the bone's name
  26697. * @return the bone or null if not found
  26698. */
  26699. Scene.prototype.getBoneByName = function (name) {
  26700. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26701. var skeleton = this.skeletons[skeletonIndex];
  26702. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26703. if (skeleton.bones[boneIndex].name === name) {
  26704. return skeleton.bones[boneIndex];
  26705. }
  26706. }
  26707. }
  26708. return null;
  26709. };
  26710. /**
  26711. * Gets a light node using its name
  26712. * @param name defines the the light's name
  26713. * @return the light or null if none found.
  26714. */
  26715. Scene.prototype.getLightByName = function (name) {
  26716. for (var index = 0; index < this.lights.length; index++) {
  26717. if (this.lights[index].name === name) {
  26718. return this.lights[index];
  26719. }
  26720. }
  26721. return null;
  26722. };
  26723. /**
  26724. * Gets a light node using its id
  26725. * @param id defines the light's id
  26726. * @return the light or null if none found.
  26727. */
  26728. Scene.prototype.getLightByID = function (id) {
  26729. for (var index = 0; index < this.lights.length; index++) {
  26730. if (this.lights[index].id === id) {
  26731. return this.lights[index];
  26732. }
  26733. }
  26734. return null;
  26735. };
  26736. /**
  26737. * Gets a light node using its scene-generated unique ID
  26738. * @param uniqueId defines the light's unique id
  26739. * @return the light or null if none found.
  26740. */
  26741. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26742. for (var index = 0; index < this.lights.length; index++) {
  26743. if (this.lights[index].uniqueId === uniqueId) {
  26744. return this.lights[index];
  26745. }
  26746. }
  26747. return null;
  26748. };
  26749. /**
  26750. * Gets a particle system by id
  26751. * @param id defines the particle system id
  26752. * @return the corresponding system or null if none found
  26753. */
  26754. Scene.prototype.getParticleSystemByID = function (id) {
  26755. for (var index = 0; index < this.particleSystems.length; index++) {
  26756. if (this.particleSystems[index].id === id) {
  26757. return this.particleSystems[index];
  26758. }
  26759. }
  26760. return null;
  26761. };
  26762. /**
  26763. * Gets a geometry using its ID
  26764. * @param id defines the geometry's id
  26765. * @return the geometry or null if none found.
  26766. */
  26767. Scene.prototype.getGeometryByID = function (id) {
  26768. for (var index = 0; index < this._geometries.length; index++) {
  26769. if (this._geometries[index].id === id) {
  26770. return this._geometries[index];
  26771. }
  26772. }
  26773. return null;
  26774. };
  26775. /**
  26776. * Add a new geometry to this scene
  26777. * @param geometry defines the geometry to be added to the scene.
  26778. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26779. * @return a boolean defining if the geometry was added or not
  26780. */
  26781. Scene.prototype.pushGeometry = function (geometry, force) {
  26782. if (!force && this.getGeometryByID(geometry.id)) {
  26783. return false;
  26784. }
  26785. this._geometries.push(geometry);
  26786. //notify the collision coordinator
  26787. if (this.collisionCoordinator) {
  26788. this.collisionCoordinator.onGeometryAdded(geometry);
  26789. }
  26790. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26791. return true;
  26792. };
  26793. /**
  26794. * Removes an existing geometry
  26795. * @param geometry defines the geometry to be removed from the scene
  26796. * @return a boolean defining if the geometry was removed or not
  26797. */
  26798. Scene.prototype.removeGeometry = function (geometry) {
  26799. var index = this._geometries.indexOf(geometry);
  26800. if (index > -1) {
  26801. this._geometries.splice(index, 1);
  26802. //notify the collision coordinator
  26803. if (this.collisionCoordinator) {
  26804. this.collisionCoordinator.onGeometryDeleted(geometry);
  26805. }
  26806. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26807. return true;
  26808. }
  26809. return false;
  26810. };
  26811. /**
  26812. * Gets the list of geometries attached to the scene
  26813. * @returns an array of Geometry
  26814. */
  26815. Scene.prototype.getGeometries = function () {
  26816. return this._geometries;
  26817. };
  26818. /**
  26819. * Gets the first added mesh found of a given ID
  26820. * @param id defines the id to search for
  26821. * @return the mesh found or null if not found at all
  26822. */
  26823. Scene.prototype.getMeshByID = function (id) {
  26824. for (var index = 0; index < this.meshes.length; index++) {
  26825. if (this.meshes[index].id === id) {
  26826. return this.meshes[index];
  26827. }
  26828. }
  26829. return null;
  26830. };
  26831. /**
  26832. * Gets a list of meshes using their id
  26833. * @param id defines the id to search for
  26834. * @returns a list of meshes
  26835. */
  26836. Scene.prototype.getMeshesByID = function (id) {
  26837. return this.meshes.filter(function (m) {
  26838. return m.id === id;
  26839. });
  26840. };
  26841. /**
  26842. * Gets the first added transform node found of a given ID
  26843. * @param id defines the id to search for
  26844. * @return the found transform node or null if not found at all.
  26845. */
  26846. Scene.prototype.getTransformNodeByID = function (id) {
  26847. for (var index = 0; index < this.transformNodes.length; index++) {
  26848. if (this.transformNodes[index].id === id) {
  26849. return this.transformNodes[index];
  26850. }
  26851. }
  26852. return null;
  26853. };
  26854. /**
  26855. * Gets a list of transform nodes using their id
  26856. * @param id defines the id to search for
  26857. * @returns a list of transform nodes
  26858. */
  26859. Scene.prototype.getTransformNodesByID = function (id) {
  26860. return this.transformNodes.filter(function (m) {
  26861. return m.id === id;
  26862. });
  26863. };
  26864. /**
  26865. * Gets a mesh with its auto-generated unique id
  26866. * @param uniqueId defines the unique id to search for
  26867. * @return the found mesh or null if not found at all.
  26868. */
  26869. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26870. for (var index = 0; index < this.meshes.length; index++) {
  26871. if (this.meshes[index].uniqueId === uniqueId) {
  26872. return this.meshes[index];
  26873. }
  26874. }
  26875. return null;
  26876. };
  26877. /**
  26878. * Gets a the last added mesh using a given id
  26879. * @param id defines the id to search for
  26880. * @return the found mesh or null if not found at all.
  26881. */
  26882. Scene.prototype.getLastMeshByID = function (id) {
  26883. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26884. if (this.meshes[index].id === id) {
  26885. return this.meshes[index];
  26886. }
  26887. }
  26888. return null;
  26889. };
  26890. /**
  26891. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26892. * @param id defines the id to search for
  26893. * @return the found node or null if not found at all
  26894. */
  26895. Scene.prototype.getLastEntryByID = function (id) {
  26896. var index;
  26897. for (index = this.meshes.length - 1; index >= 0; index--) {
  26898. if (this.meshes[index].id === id) {
  26899. return this.meshes[index];
  26900. }
  26901. }
  26902. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26903. if (this.transformNodes[index].id === id) {
  26904. return this.transformNodes[index];
  26905. }
  26906. }
  26907. for (index = this.cameras.length - 1; index >= 0; index--) {
  26908. if (this.cameras[index].id === id) {
  26909. return this.cameras[index];
  26910. }
  26911. }
  26912. for (index = this.lights.length - 1; index >= 0; index--) {
  26913. if (this.lights[index].id === id) {
  26914. return this.lights[index];
  26915. }
  26916. }
  26917. return null;
  26918. };
  26919. /**
  26920. * Gets a node (Mesh, Camera, Light) using a given id
  26921. * @param id defines the id to search for
  26922. * @return the found node or null if not found at all
  26923. */
  26924. Scene.prototype.getNodeByID = function (id) {
  26925. var mesh = this.getMeshByID(id);
  26926. if (mesh) {
  26927. return mesh;
  26928. }
  26929. var light = this.getLightByID(id);
  26930. if (light) {
  26931. return light;
  26932. }
  26933. var camera = this.getCameraByID(id);
  26934. if (camera) {
  26935. return camera;
  26936. }
  26937. var bone = this.getBoneByID(id);
  26938. return bone;
  26939. };
  26940. /**
  26941. * Gets a node (Mesh, Camera, Light) using a given name
  26942. * @param name defines the name to search for
  26943. * @return the found node or null if not found at all.
  26944. */
  26945. Scene.prototype.getNodeByName = function (name) {
  26946. var mesh = this.getMeshByName(name);
  26947. if (mesh) {
  26948. return mesh;
  26949. }
  26950. var light = this.getLightByName(name);
  26951. if (light) {
  26952. return light;
  26953. }
  26954. var camera = this.getCameraByName(name);
  26955. if (camera) {
  26956. return camera;
  26957. }
  26958. var bone = this.getBoneByName(name);
  26959. return bone;
  26960. };
  26961. /**
  26962. * Gets a mesh using a given name
  26963. * @param name defines the name to search for
  26964. * @return the found mesh or null if not found at all.
  26965. */
  26966. Scene.prototype.getMeshByName = function (name) {
  26967. for (var index = 0; index < this.meshes.length; index++) {
  26968. if (this.meshes[index].name === name) {
  26969. return this.meshes[index];
  26970. }
  26971. }
  26972. return null;
  26973. };
  26974. /**
  26975. * Gets a transform node using a given name
  26976. * @param name defines the name to search for
  26977. * @return the found transform node or null if not found at all.
  26978. */
  26979. Scene.prototype.getTransformNodeByName = function (name) {
  26980. for (var index = 0; index < this.transformNodes.length; index++) {
  26981. if (this.transformNodes[index].name === name) {
  26982. return this.transformNodes[index];
  26983. }
  26984. }
  26985. return null;
  26986. };
  26987. /**
  26988. * Gets a sound using a given name
  26989. * @param name defines the name to search for
  26990. * @return the found sound or null if not found at all.
  26991. */
  26992. Scene.prototype.getSoundByName = function (name) {
  26993. var index;
  26994. if (BABYLON.AudioEngine) {
  26995. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26996. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26997. return this.mainSoundTrack.soundCollection[index];
  26998. }
  26999. }
  27000. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27001. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27002. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27003. return this.soundTracks[sdIndex].soundCollection[index];
  27004. }
  27005. }
  27006. }
  27007. }
  27008. return null;
  27009. };
  27010. /**
  27011. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27012. * @param id defines the id to search for
  27013. * @return the found skeleton or null if not found at all.
  27014. */
  27015. Scene.prototype.getLastSkeletonByID = function (id) {
  27016. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27017. if (this.skeletons[index].id === id) {
  27018. return this.skeletons[index];
  27019. }
  27020. }
  27021. return null;
  27022. };
  27023. /**
  27024. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27025. * @param id defines the id to search for
  27026. * @return the found skeleton or null if not found at all.
  27027. */
  27028. Scene.prototype.getSkeletonById = function (id) {
  27029. for (var index = 0; index < this.skeletons.length; index++) {
  27030. if (this.skeletons[index].id === id) {
  27031. return this.skeletons[index];
  27032. }
  27033. }
  27034. return null;
  27035. };
  27036. /**
  27037. * Gets a skeleton using a given name
  27038. * @param name defines the name to search for
  27039. * @return the found skeleton or null if not found at all.
  27040. */
  27041. Scene.prototype.getSkeletonByName = function (name) {
  27042. for (var index = 0; index < this.skeletons.length; index++) {
  27043. if (this.skeletons[index].name === name) {
  27044. return this.skeletons[index];
  27045. }
  27046. }
  27047. return null;
  27048. };
  27049. /**
  27050. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27051. * @param id defines the id to search for
  27052. * @return the found morph target manager or null if not found at all.
  27053. */
  27054. Scene.prototype.getMorphTargetManagerById = function (id) {
  27055. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27056. if (this.morphTargetManagers[index].uniqueId === id) {
  27057. return this.morphTargetManagers[index];
  27058. }
  27059. }
  27060. return null;
  27061. };
  27062. /**
  27063. * Gets a boolean indicating if the given mesh is active
  27064. * @param mesh defines the mesh to look for
  27065. * @returns true if the mesh is in the active list
  27066. */
  27067. Scene.prototype.isActiveMesh = function (mesh) {
  27068. return (this._activeMeshes.indexOf(mesh) !== -1);
  27069. };
  27070. /**
  27071. * Return a the first highlight layer of the scene with a given name.
  27072. * @param name The name of the highlight layer to look for.
  27073. * @return The highlight layer if found otherwise null.
  27074. */
  27075. Scene.prototype.getHighlightLayerByName = function (name) {
  27076. for (var index = 0; index < this.effectLayers.length; index++) {
  27077. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27078. return this.effectLayers[index];
  27079. }
  27080. }
  27081. return null;
  27082. };
  27083. /**
  27084. * Return a the first highlight layer of the scene with a given name.
  27085. * @param name The name of the highlight layer to look for.
  27086. * @return The highlight layer if found otherwise null.
  27087. */
  27088. Scene.prototype.getGlowLayerByName = function (name) {
  27089. for (var index = 0; index < this.effectLayers.length; index++) {
  27090. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27091. return this.effectLayers[index];
  27092. }
  27093. }
  27094. return null;
  27095. };
  27096. Object.defineProperty(Scene.prototype, "uid", {
  27097. /**
  27098. * Return a unique id as a string which can serve as an identifier for the scene
  27099. */
  27100. get: function () {
  27101. if (!this._uid) {
  27102. this._uid = BABYLON.Tools.RandomId();
  27103. }
  27104. return this._uid;
  27105. },
  27106. enumerable: true,
  27107. configurable: true
  27108. });
  27109. /**
  27110. * Add an externaly attached data from its key.
  27111. * This method call will fail and return false, if such key already exists.
  27112. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27113. * @param key the unique key that identifies the data
  27114. * @param data the data object to associate to the key for this Engine instance
  27115. * @return true if no such key were already present and the data was added successfully, false otherwise
  27116. */
  27117. Scene.prototype.addExternalData = function (key, data) {
  27118. if (!this._externalData) {
  27119. this._externalData = new BABYLON.StringDictionary();
  27120. }
  27121. return this._externalData.add(key, data);
  27122. };
  27123. /**
  27124. * Get an externaly attached data from its key
  27125. * @param key the unique key that identifies the data
  27126. * @return the associated data, if present (can be null), or undefined if not present
  27127. */
  27128. Scene.prototype.getExternalData = function (key) {
  27129. if (!this._externalData) {
  27130. return null;
  27131. }
  27132. return this._externalData.get(key);
  27133. };
  27134. /**
  27135. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27136. * @param key the unique key that identifies the data
  27137. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27138. * @return the associated data, can be null if the factory returned null.
  27139. */
  27140. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27141. if (!this._externalData) {
  27142. this._externalData = new BABYLON.StringDictionary();
  27143. }
  27144. return this._externalData.getOrAddWithFactory(key, factory);
  27145. };
  27146. /**
  27147. * Remove an externaly attached data from the Engine instance
  27148. * @param key the unique key that identifies the data
  27149. * @return true if the data was successfully removed, false if it doesn't exist
  27150. */
  27151. Scene.prototype.removeExternalData = function (key) {
  27152. return this._externalData.remove(key);
  27153. };
  27154. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27155. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27156. if (mesh.showSubMeshesBoundingBox) {
  27157. var boundingInfo = subMesh.getBoundingInfo();
  27158. if (boundingInfo !== null && boundingInfo !== undefined) {
  27159. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27160. }
  27161. }
  27162. var material = subMesh.getMaterial();
  27163. if (material !== null && material !== undefined) {
  27164. // Render targets
  27165. if (material.getRenderTargetTextures !== undefined) {
  27166. if (this._processedMaterials.indexOf(material) === -1) {
  27167. this._processedMaterials.push(material);
  27168. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27169. }
  27170. }
  27171. // Dispatch
  27172. this._activeIndices.addCount(subMesh.indexCount, false);
  27173. this._renderingManager.dispatch(subMesh, mesh, material);
  27174. }
  27175. }
  27176. };
  27177. /**
  27178. * Clear the processed materials smart array preventing retention point in material dispose.
  27179. */
  27180. Scene.prototype.freeProcessedMaterials = function () {
  27181. this._processedMaterials.dispose();
  27182. };
  27183. /**
  27184. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27185. */
  27186. Scene.prototype.freeActiveMeshes = function () {
  27187. this._activeMeshes.dispose();
  27188. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27189. this.activeCamera._activeMeshes.dispose();
  27190. }
  27191. if (this.activeCameras) {
  27192. for (var i = 0; i < this.activeCameras.length; i++) {
  27193. var activeCamera = this.activeCameras[i];
  27194. if (activeCamera && activeCamera._activeMeshes) {
  27195. activeCamera._activeMeshes.dispose();
  27196. }
  27197. }
  27198. }
  27199. };
  27200. /**
  27201. * Clear the info related to rendering groups preventing retention points during dispose.
  27202. */
  27203. Scene.prototype.freeRenderingGroups = function () {
  27204. if (this._renderingManager) {
  27205. this._renderingManager.freeRenderingGroups();
  27206. }
  27207. if (this.textures) {
  27208. for (var i = 0; i < this.textures.length; i++) {
  27209. var texture = this.textures[i];
  27210. if (texture && texture.renderList) {
  27211. texture.freeRenderingGroups();
  27212. }
  27213. }
  27214. }
  27215. };
  27216. /** @hidden */
  27217. Scene.prototype._isInIntermediateRendering = function () {
  27218. return this._intermediateRendering;
  27219. };
  27220. /**
  27221. * Defines the current active mesh candidate provider
  27222. * @param provider defines the provider to use
  27223. */
  27224. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27225. this._activeMeshCandidateProvider = provider;
  27226. };
  27227. /**
  27228. * Gets the current active mesh candidate provider
  27229. * @returns the current active mesh candidate provider
  27230. */
  27231. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27232. return this._activeMeshCandidateProvider;
  27233. };
  27234. /**
  27235. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27236. * @returns the current scene
  27237. */
  27238. Scene.prototype.freezeActiveMeshes = function () {
  27239. if (!this.activeCamera) {
  27240. return this;
  27241. }
  27242. if (!this._frustumPlanes) {
  27243. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27244. }
  27245. this._evaluateActiveMeshes();
  27246. this._activeMeshesFrozen = true;
  27247. return this;
  27248. };
  27249. /**
  27250. * Use this function to restart evaluating active meshes on every frame
  27251. * @returns the current scene
  27252. */
  27253. Scene.prototype.unfreezeActiveMeshes = function () {
  27254. this._activeMeshesFrozen = false;
  27255. return this;
  27256. };
  27257. Scene.prototype._evaluateActiveMeshes = function () {
  27258. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27259. return;
  27260. }
  27261. if (!this.activeCamera) {
  27262. return;
  27263. }
  27264. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27265. this.activeCamera._activeMeshes.reset();
  27266. this._activeMeshes.reset();
  27267. this._renderingManager.reset();
  27268. this._processedMaterials.reset();
  27269. this._activeParticleSystems.reset();
  27270. this._activeSkeletons.reset();
  27271. this._softwareSkinnedMeshes.reset();
  27272. if (this._boundingBoxRenderer) {
  27273. this._boundingBoxRenderer.reset();
  27274. }
  27275. // Meshes
  27276. var meshes;
  27277. var len;
  27278. var checkIsEnabled = true;
  27279. // Determine mesh candidates
  27280. if (this._activeMeshCandidateProvider !== undefined) {
  27281. // Use _activeMeshCandidateProvider
  27282. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27283. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27284. if (meshes !== undefined) {
  27285. len = meshes.length;
  27286. }
  27287. else {
  27288. len = 0;
  27289. }
  27290. }
  27291. else if (this._selectionOctree !== undefined) {
  27292. // Octree
  27293. var selection = this._selectionOctree.select(this._frustumPlanes);
  27294. meshes = selection.data;
  27295. len = selection.length;
  27296. }
  27297. else {
  27298. // Full scene traversal
  27299. len = this.meshes.length;
  27300. meshes = this.meshes;
  27301. }
  27302. // Check each mesh
  27303. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27304. mesh = meshes[meshIndex];
  27305. if (mesh.isBlocked) {
  27306. continue;
  27307. }
  27308. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27309. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27310. continue;
  27311. }
  27312. mesh.computeWorldMatrix();
  27313. // Intersections
  27314. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27315. this._meshesForIntersections.pushNoDuplicate(mesh);
  27316. }
  27317. // Switch to current LOD
  27318. meshLOD = mesh.getLOD(this.activeCamera);
  27319. if (meshLOD === undefined || meshLOD === null) {
  27320. continue;
  27321. }
  27322. mesh._preActivate();
  27323. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27324. this._activeMeshes.push(mesh);
  27325. this.activeCamera._activeMeshes.push(mesh);
  27326. mesh._activate(this._renderId);
  27327. if (meshLOD !== mesh) {
  27328. meshLOD._activate(this._renderId);
  27329. }
  27330. this._activeMesh(mesh, meshLOD);
  27331. }
  27332. }
  27333. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27334. // Particle systems
  27335. if (this.particlesEnabled) {
  27336. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27337. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27338. var particleSystem = this.particleSystems[particleIndex];
  27339. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27340. continue;
  27341. }
  27342. var emitter = particleSystem.emitter;
  27343. if (!emitter.position || emitter.isEnabled()) {
  27344. this._activeParticleSystems.push(particleSystem);
  27345. particleSystem.animate();
  27346. this._renderingManager.dispatchParticles(particleSystem);
  27347. }
  27348. }
  27349. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27350. }
  27351. };
  27352. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27353. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27354. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27355. mesh.skeleton.prepare();
  27356. }
  27357. if (!mesh.computeBonesUsingShaders) {
  27358. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27359. }
  27360. }
  27361. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27362. var boundingInfo = sourceMesh.getBoundingInfo();
  27363. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27364. }
  27365. if (mesh !== undefined && mesh !== null
  27366. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27367. // Submeshes Octrees
  27368. var len;
  27369. var subMeshes;
  27370. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27371. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27372. len = intersections.length;
  27373. subMeshes = intersections.data;
  27374. }
  27375. else {
  27376. subMeshes = mesh.subMeshes;
  27377. len = subMeshes.length;
  27378. }
  27379. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27380. subMesh = subMeshes[subIndex];
  27381. this._evaluateSubMesh(subMesh, mesh);
  27382. }
  27383. }
  27384. };
  27385. /**
  27386. * Update the transform matrix to update from the current active camera
  27387. * @param force defines a boolean used to force the update even if cache is up to date
  27388. */
  27389. Scene.prototype.updateTransformMatrix = function (force) {
  27390. if (!this.activeCamera) {
  27391. return;
  27392. }
  27393. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27394. };
  27395. /**
  27396. * 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)
  27397. * @param alternateCamera defines the camera to use
  27398. */
  27399. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27400. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27401. };
  27402. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27403. if (camera && camera._skipRendering) {
  27404. return;
  27405. }
  27406. var engine = this._engine;
  27407. this.activeCamera = camera;
  27408. if (!this.activeCamera)
  27409. throw new Error("Active camera not set");
  27410. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27411. // Viewport
  27412. engine.setViewport(this.activeCamera.viewport);
  27413. // Camera
  27414. this.resetCachedMaterial();
  27415. this._renderId++;
  27416. this.updateTransformMatrix();
  27417. if (camera._alternateCamera) {
  27418. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27419. this._alternateRendering = true;
  27420. }
  27421. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27422. // Meshes
  27423. this._evaluateActiveMeshes();
  27424. // Software skinning
  27425. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27426. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27427. mesh.applySkeleton(mesh.skeleton);
  27428. }
  27429. // Render targets
  27430. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27431. var needsRestoreFrameBuffer = false;
  27432. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27433. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27434. }
  27435. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27436. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27437. }
  27438. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27439. this._intermediateRendering = true;
  27440. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27441. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27442. var renderTarget = this._renderTargets.data[renderIndex];
  27443. if (renderTarget._shouldRender()) {
  27444. this._renderId++;
  27445. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27446. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27447. }
  27448. }
  27449. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27450. this._intermediateRendering = false;
  27451. this._renderId++;
  27452. needsRestoreFrameBuffer = true; // Restore back buffer
  27453. }
  27454. // Render EffecttLayer Texture
  27455. var stencilState = this._engine.getStencilBuffer();
  27456. var renderEffects = false;
  27457. var needStencil = false;
  27458. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27459. this._intermediateRendering = true;
  27460. for (var i = 0; i < this.effectLayers.length; i++) {
  27461. var effectLayer = this.effectLayers[i];
  27462. if (effectLayer.shouldRender() &&
  27463. (!effectLayer.camera ||
  27464. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27465. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27466. renderEffects = true;
  27467. needStencil = needStencil || effectLayer.needStencil();
  27468. var renderTarget = effectLayer._mainTexture;
  27469. if (renderTarget._shouldRender()) {
  27470. this._renderId++;
  27471. renderTarget.render(false, false);
  27472. needsRestoreFrameBuffer = true;
  27473. }
  27474. }
  27475. }
  27476. this._intermediateRendering = false;
  27477. this._renderId++;
  27478. }
  27479. if (needsRestoreFrameBuffer) {
  27480. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27481. }
  27482. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27483. // Prepare Frame
  27484. this.postProcessManager._prepareFrame();
  27485. // Backgrounds
  27486. var layerIndex;
  27487. var layer;
  27488. if (this.layers.length) {
  27489. engine.setDepthBuffer(false);
  27490. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27491. layer = this.layers[layerIndex];
  27492. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27493. layer.render();
  27494. }
  27495. }
  27496. engine.setDepthBuffer(true);
  27497. }
  27498. // Activate effect Layer stencil
  27499. if (needStencil) {
  27500. this._engine.setStencilBuffer(true);
  27501. }
  27502. // Render
  27503. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27504. this._renderingManager.render(null, null, true, true);
  27505. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27506. // Restore effect Layer stencil
  27507. if (needStencil) {
  27508. this._engine.setStencilBuffer(stencilState);
  27509. }
  27510. // Bounding boxes
  27511. if (this._boundingBoxRenderer) {
  27512. this._boundingBoxRenderer.render();
  27513. }
  27514. // Lens flares
  27515. if (this.lensFlaresEnabled) {
  27516. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27517. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27518. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27519. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27520. lensFlareSystem.render();
  27521. }
  27522. }
  27523. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27524. }
  27525. // Effect Layer
  27526. if (renderEffects) {
  27527. engine.setDepthBuffer(false);
  27528. for (var i = 0; i < this.effectLayers.length; i++) {
  27529. if (this.effectLayers[i].shouldRender()) {
  27530. this.effectLayers[i].render();
  27531. }
  27532. }
  27533. engine.setDepthBuffer(true);
  27534. }
  27535. // Foregrounds
  27536. if (this.layers.length) {
  27537. engine.setDepthBuffer(false);
  27538. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27539. layer = this.layers[layerIndex];
  27540. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27541. layer.render();
  27542. }
  27543. }
  27544. engine.setDepthBuffer(true);
  27545. }
  27546. // Finalize frame
  27547. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27548. // Reset some special arrays
  27549. this._renderTargets.reset();
  27550. this._alternateRendering = false;
  27551. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27552. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27553. };
  27554. Scene.prototype._processSubCameras = function (camera) {
  27555. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27556. this._renderForCamera(camera);
  27557. return;
  27558. }
  27559. // rig cameras
  27560. for (var index = 0; index < camera._rigCameras.length; index++) {
  27561. this._renderForCamera(camera._rigCameras[index], camera);
  27562. }
  27563. this.activeCamera = camera;
  27564. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27565. };
  27566. Scene.prototype._checkIntersections = function () {
  27567. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27568. var sourceMesh = this._meshesForIntersections.data[index];
  27569. if (!sourceMesh.actionManager) {
  27570. continue;
  27571. }
  27572. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27573. var action = sourceMesh.actionManager.actions[actionIndex];
  27574. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27575. var parameters = action.getTriggerParameter();
  27576. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27577. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27578. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27579. if (areIntersecting && currentIntersectionInProgress === -1) {
  27580. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27581. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27582. sourceMesh._intersectionsInProgress.push(otherMesh);
  27583. }
  27584. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27585. sourceMesh._intersectionsInProgress.push(otherMesh);
  27586. }
  27587. }
  27588. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27589. //They intersected, and now they don't.
  27590. //is this trigger an exit trigger? execute an event.
  27591. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27592. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27593. }
  27594. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27595. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27596. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27597. return otherMesh === parameterMesh;
  27598. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27599. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27600. }
  27601. }
  27602. }
  27603. }
  27604. }
  27605. };
  27606. /**
  27607. * Render the scene
  27608. */
  27609. Scene.prototype.render = function () {
  27610. if (this.isDisposed) {
  27611. return;
  27612. }
  27613. this._activeParticles.fetchNewFrame();
  27614. this._totalVertices.fetchNewFrame();
  27615. this._activeIndices.fetchNewFrame();
  27616. this._activeBones.fetchNewFrame();
  27617. this._meshesForIntersections.reset();
  27618. this.resetCachedMaterial();
  27619. this.onBeforeAnimationsObservable.notifyObservers(this);
  27620. // Actions
  27621. if (this.actionManager) {
  27622. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27623. }
  27624. //Simplification Queue
  27625. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27626. this.simplificationQueue.executeNext();
  27627. }
  27628. if (this._engine.isDeterministicLockStep()) {
  27629. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27630. var defaultFPS = (60.0 / 1000.0);
  27631. var defaultFrameTime = 1000 / 60; // frame time in MS
  27632. if (this._physicsEngine) {
  27633. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27634. }
  27635. var stepsTaken = 0;
  27636. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27637. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27638. internalSteps = Math.min(internalSteps, maxSubSteps);
  27639. do {
  27640. this.onBeforeStepObservable.notifyObservers(this);
  27641. // Animations
  27642. this._animationRatio = defaultFrameTime * defaultFPS;
  27643. this._animate();
  27644. this.onAfterAnimationsObservable.notifyObservers(this);
  27645. // Physics
  27646. if (this._physicsEngine) {
  27647. this.onBeforePhysicsObservable.notifyObservers(this);
  27648. this._physicsEngine._step(defaultFrameTime / 1000);
  27649. this.onAfterPhysicsObservable.notifyObservers(this);
  27650. }
  27651. this.onAfterStepObservable.notifyObservers(this);
  27652. this._currentStepId++;
  27653. stepsTaken++;
  27654. deltaTime -= defaultFrameTime;
  27655. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27656. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27657. }
  27658. else {
  27659. // Animations
  27660. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27661. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27662. this._animate();
  27663. this.onAfterAnimationsObservable.notifyObservers(this);
  27664. // Physics
  27665. if (this._physicsEngine) {
  27666. this.onBeforePhysicsObservable.notifyObservers(this);
  27667. this._physicsEngine._step(deltaTime / 1000.0);
  27668. this.onAfterPhysicsObservable.notifyObservers(this);
  27669. }
  27670. }
  27671. // update gamepad manager
  27672. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27673. this._gamepadManager._checkGamepadsStatus();
  27674. }
  27675. // Update Cameras
  27676. if (this.activeCameras.length > 0) {
  27677. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27678. var camera = this.activeCameras[cameraIndex];
  27679. camera.update();
  27680. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27681. // rig cameras
  27682. for (var index = 0; index < camera._rigCameras.length; index++) {
  27683. camera._rigCameras[index].update();
  27684. }
  27685. }
  27686. }
  27687. }
  27688. else if (this.activeCamera) {
  27689. this.activeCamera.update();
  27690. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27691. // rig cameras
  27692. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27693. this.activeCamera._rigCameras[index].update();
  27694. }
  27695. }
  27696. }
  27697. // Before render
  27698. this.onBeforeRenderObservable.notifyObservers(this);
  27699. // Customs render targets
  27700. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27701. var engine = this.getEngine();
  27702. var currentActiveCamera = this.activeCamera;
  27703. if (this.renderTargetsEnabled) {
  27704. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27705. this._intermediateRendering = true;
  27706. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27707. var renderTarget = this.customRenderTargets[customIndex];
  27708. if (renderTarget._shouldRender()) {
  27709. this._renderId++;
  27710. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27711. if (!this.activeCamera)
  27712. throw new Error("Active camera not set");
  27713. // Viewport
  27714. engine.setViewport(this.activeCamera.viewport);
  27715. // Camera
  27716. this.updateTransformMatrix();
  27717. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27718. }
  27719. }
  27720. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27721. this._intermediateRendering = false;
  27722. this._renderId++;
  27723. }
  27724. // Restore back buffer
  27725. if (this.customRenderTargets.length > 0) {
  27726. engine.restoreDefaultFramebuffer();
  27727. }
  27728. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27729. this.activeCamera = currentActiveCamera;
  27730. // Procedural textures
  27731. if (this.proceduralTexturesEnabled) {
  27732. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27733. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27734. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27735. if (proceduralTexture._shouldRender()) {
  27736. proceduralTexture.render();
  27737. }
  27738. }
  27739. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27740. }
  27741. // Clear
  27742. if (this.autoClearDepthAndStencil || this.autoClear) {
  27743. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27744. }
  27745. // Shadows
  27746. if (this.shadowsEnabled) {
  27747. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27748. var light = this.lights[lightIndex];
  27749. var shadowGenerator = light.getShadowGenerator();
  27750. if (light.isEnabled() && light.shadowEnabled && shadowGenerator && shadowGenerator.arePostProcessesReady()) {
  27751. var shadowMap = (shadowGenerator.getShadowMap());
  27752. if (this.textures.indexOf(shadowMap) !== -1) {
  27753. this._renderTargets.push(shadowMap);
  27754. }
  27755. }
  27756. }
  27757. }
  27758. // Depth renderer
  27759. for (var key in this._depthRenderer) {
  27760. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27761. }
  27762. // Geometry renderer
  27763. if (this._geometryBufferRenderer) {
  27764. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27765. }
  27766. // RenderPipeline
  27767. if (this._postProcessRenderPipelineManager) {
  27768. this._postProcessRenderPipelineManager.update();
  27769. }
  27770. // Multi-cameras?
  27771. if (this.activeCameras.length > 0) {
  27772. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27773. if (cameraIndex > 0) {
  27774. this._engine.clear(null, false, true, true);
  27775. }
  27776. this._processSubCameras(this.activeCameras[cameraIndex]);
  27777. }
  27778. }
  27779. else {
  27780. if (!this.activeCamera) {
  27781. throw new Error("No camera defined");
  27782. }
  27783. this._processSubCameras(this.activeCamera);
  27784. }
  27785. // Intersection checks
  27786. this._checkIntersections();
  27787. // Update the audio listener attached to the camera
  27788. if (BABYLON.AudioEngine) {
  27789. this._updateAudioParameters();
  27790. }
  27791. // After render
  27792. if (this.afterRender) {
  27793. this.afterRender();
  27794. }
  27795. this.onAfterRenderObservable.notifyObservers(this);
  27796. // Cleaning
  27797. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27798. var data = this._toBeDisposed.data[index];
  27799. if (data) {
  27800. data.dispose();
  27801. }
  27802. this._toBeDisposed[index] = null;
  27803. }
  27804. this._toBeDisposed.reset();
  27805. if (this.dumpNextRenderTargets) {
  27806. this.dumpNextRenderTargets = false;
  27807. }
  27808. this._activeBones.addCount(0, true);
  27809. this._activeIndices.addCount(0, true);
  27810. this._activeParticles.addCount(0, true);
  27811. };
  27812. Scene.prototype._updateAudioParameters = function () {
  27813. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27814. return;
  27815. }
  27816. var listeningCamera;
  27817. var audioEngine = BABYLON.Engine.audioEngine;
  27818. if (this.activeCameras.length > 0) {
  27819. listeningCamera = this.activeCameras[0];
  27820. }
  27821. else {
  27822. listeningCamera = this.activeCamera;
  27823. }
  27824. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27825. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27826. // for VR cameras
  27827. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27828. listeningCamera = listeningCamera.rigCameras[0];
  27829. }
  27830. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27831. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27832. cameraDirection.normalize();
  27833. // To avoid some errors on GearVR
  27834. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27835. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27836. }
  27837. var i;
  27838. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27839. var sound = this.mainSoundTrack.soundCollection[i];
  27840. if (sound.useCustomAttenuation) {
  27841. sound.updateDistanceFromListener();
  27842. }
  27843. }
  27844. for (i = 0; i < this.soundTracks.length; i++) {
  27845. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27846. sound = this.soundTracks[i].soundCollection[j];
  27847. if (sound.useCustomAttenuation) {
  27848. sound.updateDistanceFromListener();
  27849. }
  27850. }
  27851. }
  27852. }
  27853. };
  27854. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27855. // Audio
  27856. /**
  27857. * Gets or sets if audio support is enabled
  27858. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27859. */
  27860. get: function () {
  27861. return this._audioEnabled;
  27862. },
  27863. set: function (value) {
  27864. this._audioEnabled = value;
  27865. if (BABYLON.AudioEngine) {
  27866. if (this._audioEnabled) {
  27867. this._enableAudio();
  27868. }
  27869. else {
  27870. this._disableAudio();
  27871. }
  27872. }
  27873. },
  27874. enumerable: true,
  27875. configurable: true
  27876. });
  27877. Scene.prototype._disableAudio = function () {
  27878. var i;
  27879. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27880. this.mainSoundTrack.soundCollection[i].pause();
  27881. }
  27882. for (i = 0; i < this.soundTracks.length; i++) {
  27883. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27884. this.soundTracks[i].soundCollection[j].pause();
  27885. }
  27886. }
  27887. };
  27888. Scene.prototype._enableAudio = function () {
  27889. var i;
  27890. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27891. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27892. this.mainSoundTrack.soundCollection[i].play();
  27893. }
  27894. }
  27895. for (i = 0; i < this.soundTracks.length; i++) {
  27896. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27897. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27898. this.soundTracks[i].soundCollection[j].play();
  27899. }
  27900. }
  27901. }
  27902. };
  27903. Object.defineProperty(Scene.prototype, "headphone", {
  27904. /**
  27905. * Gets or sets if audio will be output to headphones
  27906. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27907. */
  27908. get: function () {
  27909. return this._headphone;
  27910. },
  27911. set: function (value) {
  27912. this._headphone = value;
  27913. if (BABYLON.AudioEngine) {
  27914. if (this._headphone) {
  27915. this._switchAudioModeForHeadphones();
  27916. }
  27917. else {
  27918. this._switchAudioModeForNormalSpeakers();
  27919. }
  27920. }
  27921. },
  27922. enumerable: true,
  27923. configurable: true
  27924. });
  27925. Scene.prototype._switchAudioModeForHeadphones = function () {
  27926. this.mainSoundTrack.switchPanningModelToHRTF();
  27927. for (var i = 0; i < this.soundTracks.length; i++) {
  27928. this.soundTracks[i].switchPanningModelToHRTF();
  27929. }
  27930. };
  27931. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27932. this.mainSoundTrack.switchPanningModelToEqualPower();
  27933. for (var i = 0; i < this.soundTracks.length; i++) {
  27934. this.soundTracks[i].switchPanningModelToEqualPower();
  27935. }
  27936. };
  27937. /**
  27938. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27939. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27940. * @returns the created depth renderer
  27941. */
  27942. Scene.prototype.enableDepthRenderer = function (camera) {
  27943. camera = camera || this.activeCamera;
  27944. if (!camera) {
  27945. throw "No camera available to enable depth renderer";
  27946. }
  27947. if (!this._depthRenderer[camera.id]) {
  27948. var textureType = 0;
  27949. if (this._engine.getCaps().textureHalfFloatRender) {
  27950. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27951. }
  27952. else if (this._engine.getCaps().textureFloatRender) {
  27953. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27954. }
  27955. else {
  27956. throw "Depth renderer does not support int texture type";
  27957. }
  27958. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27959. }
  27960. return this._depthRenderer[camera.id];
  27961. };
  27962. /**
  27963. * Disables a depth renderer for a given camera
  27964. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27965. */
  27966. Scene.prototype.disableDepthRenderer = function (camera) {
  27967. camera = camera || this.activeCamera;
  27968. if (!camera || !this._depthRenderer[camera.id]) {
  27969. return;
  27970. }
  27971. this._depthRenderer[camera.id].dispose();
  27972. delete this._depthRenderer[camera.id];
  27973. };
  27974. /**
  27975. * Enables a GeometryBufferRender and associates it with the scene
  27976. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27977. * @returns the GeometryBufferRenderer
  27978. */
  27979. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27980. if (ratio === void 0) { ratio = 1; }
  27981. if (this._geometryBufferRenderer) {
  27982. return this._geometryBufferRenderer;
  27983. }
  27984. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27985. if (!this._geometryBufferRenderer.isSupported) {
  27986. this._geometryBufferRenderer = null;
  27987. }
  27988. return this._geometryBufferRenderer;
  27989. };
  27990. /**
  27991. * Disables the GeometryBufferRender associated with the scene
  27992. */
  27993. Scene.prototype.disableGeometryBufferRenderer = function () {
  27994. if (!this._geometryBufferRenderer) {
  27995. return;
  27996. }
  27997. this._geometryBufferRenderer.dispose();
  27998. this._geometryBufferRenderer = null;
  27999. };
  28000. /**
  28001. * Freeze all materials
  28002. * A frozen material will not be updatable but should be faster to render
  28003. */
  28004. Scene.prototype.freezeMaterials = function () {
  28005. for (var i = 0; i < this.materials.length; i++) {
  28006. this.materials[i].freeze();
  28007. }
  28008. };
  28009. /**
  28010. * Unfreeze all materials
  28011. * A frozen material will not be updatable but should be faster to render
  28012. */
  28013. Scene.prototype.unfreezeMaterials = function () {
  28014. for (var i = 0; i < this.materials.length; i++) {
  28015. this.materials[i].unfreeze();
  28016. }
  28017. };
  28018. /**
  28019. * Releases all held ressources
  28020. */
  28021. Scene.prototype.dispose = function () {
  28022. this.beforeRender = null;
  28023. this.afterRender = null;
  28024. this.skeletons = [];
  28025. this.morphTargetManagers = [];
  28026. this.importedMeshesFiles = new Array();
  28027. this.stopAllAnimations();
  28028. this.resetCachedMaterial();
  28029. for (var key in this._depthRenderer) {
  28030. this._depthRenderer[key].dispose();
  28031. }
  28032. if (this._gamepadManager) {
  28033. this._gamepadManager.dispose();
  28034. this._gamepadManager = null;
  28035. }
  28036. // Smart arrays
  28037. if (this.activeCamera) {
  28038. this.activeCamera._activeMeshes.dispose();
  28039. this.activeCamera = null;
  28040. }
  28041. this._activeMeshes.dispose();
  28042. this._renderingManager.dispose();
  28043. this._processedMaterials.dispose();
  28044. this._activeParticleSystems.dispose();
  28045. this._activeSkeletons.dispose();
  28046. this._softwareSkinnedMeshes.dispose();
  28047. this._renderTargets.dispose();
  28048. this._registeredForLateAnimationBindings.dispose();
  28049. if (this._boundingBoxRenderer) {
  28050. this._boundingBoxRenderer.dispose();
  28051. }
  28052. this._meshesForIntersections.dispose();
  28053. this._toBeDisposed.dispose();
  28054. // Abort active requests
  28055. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28056. var request = _a[_i];
  28057. request.abort();
  28058. }
  28059. // Debug layer
  28060. if (this._debugLayer) {
  28061. this._debugLayer.hide();
  28062. }
  28063. // Events
  28064. this.onDisposeObservable.notifyObservers(this);
  28065. this.onDisposeObservable.clear();
  28066. this.onBeforeRenderObservable.clear();
  28067. this.onAfterRenderObservable.clear();
  28068. this.onBeforeRenderTargetsRenderObservable.clear();
  28069. this.onAfterRenderTargetsRenderObservable.clear();
  28070. this.onAfterStepObservable.clear();
  28071. this.onBeforeStepObservable.clear();
  28072. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28073. this.onAfterActiveMeshesEvaluationObservable.clear();
  28074. this.onBeforeParticlesRenderingObservable.clear();
  28075. this.onAfterParticlesRenderingObservable.clear();
  28076. this.onBeforeSpritesRenderingObservable.clear();
  28077. this.onAfterSpritesRenderingObservable.clear();
  28078. this.onBeforeDrawPhaseObservable.clear();
  28079. this.onAfterDrawPhaseObservable.clear();
  28080. this.onBeforePhysicsObservable.clear();
  28081. this.onAfterPhysicsObservable.clear();
  28082. this.onBeforeAnimationsObservable.clear();
  28083. this.onAfterAnimationsObservable.clear();
  28084. this.onDataLoadedObservable.clear();
  28085. this.detachControl();
  28086. // Release sounds & sounds tracks
  28087. if (BABYLON.AudioEngine) {
  28088. this.disposeSounds();
  28089. }
  28090. // VR Helper
  28091. if (this.VRHelper) {
  28092. this.VRHelper.dispose();
  28093. }
  28094. // Detach cameras
  28095. var canvas = this._engine.getRenderingCanvas();
  28096. if (canvas) {
  28097. var index;
  28098. for (index = 0; index < this.cameras.length; index++) {
  28099. this.cameras[index].detachControl(canvas);
  28100. }
  28101. }
  28102. // Release animation groups
  28103. while (this.animationGroups.length) {
  28104. this.animationGroups[0].dispose();
  28105. }
  28106. // Release lights
  28107. while (this.lights.length) {
  28108. this.lights[0].dispose();
  28109. }
  28110. // Release meshes
  28111. while (this.meshes.length) {
  28112. this.meshes[0].dispose(true);
  28113. }
  28114. while (this.transformNodes.length) {
  28115. this.removeTransformNode(this.transformNodes[0]);
  28116. }
  28117. // Release cameras
  28118. while (this.cameras.length) {
  28119. this.cameras[0].dispose();
  28120. }
  28121. // Release materials
  28122. if (this.defaultMaterial) {
  28123. this.defaultMaterial.dispose();
  28124. }
  28125. while (this.multiMaterials.length) {
  28126. this.multiMaterials[0].dispose();
  28127. }
  28128. while (this.materials.length) {
  28129. this.materials[0].dispose();
  28130. }
  28131. // Release particles
  28132. while (this.particleSystems.length) {
  28133. this.particleSystems[0].dispose();
  28134. }
  28135. // Release sprites
  28136. while (this.spriteManagers.length) {
  28137. this.spriteManagers[0].dispose();
  28138. }
  28139. // Release postProcesses
  28140. while (this.postProcesses.length) {
  28141. this.postProcesses[0].dispose();
  28142. }
  28143. // Release layers
  28144. while (this.layers.length) {
  28145. this.layers[0].dispose();
  28146. }
  28147. while (this.effectLayers.length) {
  28148. this.effectLayers[0].dispose();
  28149. }
  28150. // Release textures
  28151. while (this.textures.length) {
  28152. this.textures[0].dispose();
  28153. }
  28154. // Release UBO
  28155. this._sceneUbo.dispose();
  28156. if (this._alternateSceneUbo) {
  28157. this._alternateSceneUbo.dispose();
  28158. }
  28159. // Post-processes
  28160. this.postProcessManager.dispose();
  28161. if (this._postProcessRenderPipelineManager) {
  28162. this._postProcessRenderPipelineManager.dispose();
  28163. }
  28164. // Physics
  28165. if (this._physicsEngine) {
  28166. this.disablePhysicsEngine();
  28167. }
  28168. // Remove from engine
  28169. index = this._engine.scenes.indexOf(this);
  28170. if (index > -1) {
  28171. this._engine.scenes.splice(index, 1);
  28172. }
  28173. this._engine.wipeCaches(true);
  28174. this._isDisposed = true;
  28175. };
  28176. Object.defineProperty(Scene.prototype, "isDisposed", {
  28177. /**
  28178. * Gets if the scene is already disposed
  28179. */
  28180. get: function () {
  28181. return this._isDisposed;
  28182. },
  28183. enumerable: true,
  28184. configurable: true
  28185. });
  28186. /**
  28187. * Releases sounds & soundtracks
  28188. */
  28189. Scene.prototype.disposeSounds = function () {
  28190. if (!this._mainSoundTrack) {
  28191. return;
  28192. }
  28193. this.mainSoundTrack.dispose();
  28194. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28195. this.soundTracks[scIndex].dispose();
  28196. }
  28197. };
  28198. // Octrees
  28199. /**
  28200. * Get the world extend vectors with an optional filter
  28201. *
  28202. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28203. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28204. */
  28205. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28206. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28207. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28208. filterPredicate = filterPredicate || (function () { return true; });
  28209. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28210. mesh.computeWorldMatrix(true);
  28211. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28212. return;
  28213. }
  28214. var boundingInfo = mesh.getBoundingInfo();
  28215. var minBox = boundingInfo.boundingBox.minimumWorld;
  28216. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28217. BABYLON.Tools.CheckExtends(minBox, min, max);
  28218. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28219. });
  28220. return {
  28221. min: min,
  28222. max: max
  28223. };
  28224. };
  28225. /**
  28226. * Creates or updates the octree used to boost selection (picking)
  28227. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28228. * @param maxCapacity defines the maximum capacity per leaf
  28229. * @param maxDepth defines the maximum depth of the octree
  28230. * @returns an octree of AbstractMesh
  28231. */
  28232. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28233. if (maxCapacity === void 0) { maxCapacity = 64; }
  28234. if (maxDepth === void 0) { maxDepth = 2; }
  28235. if (!this._selectionOctree) {
  28236. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28237. }
  28238. var worldExtends = this.getWorldExtends();
  28239. // Update octree
  28240. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28241. return this._selectionOctree;
  28242. };
  28243. // Picking
  28244. /**
  28245. * Creates a ray that can be used to pick in the scene
  28246. * @param x defines the x coordinate of the origin (on-screen)
  28247. * @param y defines the y coordinate of the origin (on-screen)
  28248. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28249. * @param camera defines the camera to use for the picking
  28250. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28251. * @returns a Ray
  28252. */
  28253. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28254. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28255. var result = BABYLON.Ray.Zero();
  28256. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28257. return result;
  28258. };
  28259. /**
  28260. * Creates a ray that can be used to pick in the scene
  28261. * @param x defines the x coordinate of the origin (on-screen)
  28262. * @param y defines the y coordinate of the origin (on-screen)
  28263. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28264. * @param result defines the ray where to store the picking ray
  28265. * @param camera defines the camera to use for the picking
  28266. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28267. * @returns the current scene
  28268. */
  28269. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28270. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28271. var engine = this._engine;
  28272. if (!camera) {
  28273. if (!this.activeCamera)
  28274. throw new Error("Active camera not set");
  28275. camera = this.activeCamera;
  28276. }
  28277. var cameraViewport = camera.viewport;
  28278. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28279. // Moving coordinates to local viewport world
  28280. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28281. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28282. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28283. return this;
  28284. };
  28285. /**
  28286. * Creates a ray that can be used to pick in the scene
  28287. * @param x defines the x coordinate of the origin (on-screen)
  28288. * @param y defines the y coordinate of the origin (on-screen)
  28289. * @param camera defines the camera to use for the picking
  28290. * @returns a Ray
  28291. */
  28292. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28293. var result = BABYLON.Ray.Zero();
  28294. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28295. return result;
  28296. };
  28297. /**
  28298. * Creates a ray that can be used to pick in the scene
  28299. * @param x defines the x coordinate of the origin (on-screen)
  28300. * @param y defines the y coordinate of the origin (on-screen)
  28301. * @param result defines the ray where to store the picking ray
  28302. * @param camera defines the camera to use for the picking
  28303. * @returns the current scene
  28304. */
  28305. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28306. if (!BABYLON.PickingInfo) {
  28307. return this;
  28308. }
  28309. var engine = this._engine;
  28310. if (!camera) {
  28311. if (!this.activeCamera)
  28312. throw new Error("Active camera not set");
  28313. camera = this.activeCamera;
  28314. }
  28315. var cameraViewport = camera.viewport;
  28316. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28317. var identity = BABYLON.Matrix.Identity();
  28318. // Moving coordinates to local viewport world
  28319. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28320. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28321. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28322. return this;
  28323. };
  28324. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28325. if (!BABYLON.PickingInfo) {
  28326. return null;
  28327. }
  28328. var pickingInfo = null;
  28329. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28330. var mesh = this.meshes[meshIndex];
  28331. if (predicate) {
  28332. if (!predicate(mesh)) {
  28333. continue;
  28334. }
  28335. }
  28336. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28337. continue;
  28338. }
  28339. var world = mesh.getWorldMatrix();
  28340. var ray = rayFunction(world);
  28341. var result = mesh.intersects(ray, fastCheck);
  28342. if (!result || !result.hit)
  28343. continue;
  28344. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28345. continue;
  28346. pickingInfo = result;
  28347. if (fastCheck) {
  28348. break;
  28349. }
  28350. }
  28351. return pickingInfo || new BABYLON.PickingInfo();
  28352. };
  28353. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28354. if (!BABYLON.PickingInfo) {
  28355. return null;
  28356. }
  28357. var pickingInfos = new Array();
  28358. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28359. var mesh = this.meshes[meshIndex];
  28360. if (predicate) {
  28361. if (!predicate(mesh)) {
  28362. continue;
  28363. }
  28364. }
  28365. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28366. continue;
  28367. }
  28368. var world = mesh.getWorldMatrix();
  28369. var ray = rayFunction(world);
  28370. var result = mesh.intersects(ray, false);
  28371. if (!result || !result.hit)
  28372. continue;
  28373. pickingInfos.push(result);
  28374. }
  28375. return pickingInfos;
  28376. };
  28377. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28378. if (!BABYLON.PickingInfo) {
  28379. return null;
  28380. }
  28381. var pickingInfo = null;
  28382. if (!camera) {
  28383. if (!this.activeCamera) {
  28384. return null;
  28385. }
  28386. camera = this.activeCamera;
  28387. }
  28388. if (this.spriteManagers.length > 0) {
  28389. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28390. var spriteManager = this.spriteManagers[spriteIndex];
  28391. if (!spriteManager.isPickable) {
  28392. continue;
  28393. }
  28394. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28395. if (!result || !result.hit)
  28396. continue;
  28397. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28398. continue;
  28399. pickingInfo = result;
  28400. if (fastCheck) {
  28401. break;
  28402. }
  28403. }
  28404. }
  28405. return pickingInfo || new BABYLON.PickingInfo();
  28406. };
  28407. /** Launch a ray to try to pick a mesh in the scene
  28408. * @param x position on screen
  28409. * @param y position on screen
  28410. * @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
  28411. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28412. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28413. * @returns a PickingInfo
  28414. */
  28415. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28416. var _this = this;
  28417. if (!BABYLON.PickingInfo) {
  28418. return null;
  28419. }
  28420. return this._internalPick(function (world) {
  28421. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28422. return _this._tempPickingRay;
  28423. }, predicate, fastCheck);
  28424. };
  28425. /** Launch a ray to try to pick a sprite in the scene
  28426. * @param x position on screen
  28427. * @param y position on screen
  28428. * @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
  28429. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28430. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28431. * @returns a PickingInfo
  28432. */
  28433. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28434. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28435. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28436. };
  28437. /** Use the given ray to pick a mesh in the scene
  28438. * @param ray The ray to use to pick meshes
  28439. * @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
  28440. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28441. * @returns a PickingInfo
  28442. */
  28443. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28444. var _this = this;
  28445. return this._internalPick(function (world) {
  28446. if (!_this._pickWithRayInverseMatrix) {
  28447. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28448. }
  28449. world.invertToRef(_this._pickWithRayInverseMatrix);
  28450. if (!_this._cachedRayForTransform) {
  28451. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28452. }
  28453. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28454. return _this._cachedRayForTransform;
  28455. }, predicate, fastCheck);
  28456. };
  28457. /**
  28458. * Launch a ray to try to pick a mesh in the scene
  28459. * @param x X position on screen
  28460. * @param y Y position on screen
  28461. * @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
  28462. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28463. * @returns an array of PickingInfo
  28464. */
  28465. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28466. var _this = this;
  28467. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28468. };
  28469. /**
  28470. * Launch a ray to try to pick a mesh in the scene
  28471. * @param ray Ray to use
  28472. * @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
  28473. * @returns an array of PickingInfo
  28474. */
  28475. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28476. var _this = this;
  28477. return this._internalMultiPick(function (world) {
  28478. if (!_this._pickWithRayInverseMatrix) {
  28479. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28480. }
  28481. world.invertToRef(_this._pickWithRayInverseMatrix);
  28482. if (!_this._cachedRayForTransform) {
  28483. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28484. }
  28485. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28486. return _this._cachedRayForTransform;
  28487. }, predicate);
  28488. };
  28489. /**
  28490. * Force the value of meshUnderPointer
  28491. * @param mesh defines the mesh to use
  28492. */
  28493. Scene.prototype.setPointerOverMesh = function (mesh) {
  28494. if (this._pointerOverMesh === mesh) {
  28495. return;
  28496. }
  28497. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28498. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28499. }
  28500. this._pointerOverMesh = mesh;
  28501. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28502. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28503. }
  28504. };
  28505. /**
  28506. * Gets the mesh under the pointer
  28507. * @returns a Mesh or null if no mesh is under the pointer
  28508. */
  28509. Scene.prototype.getPointerOverMesh = function () {
  28510. return this._pointerOverMesh;
  28511. };
  28512. /**
  28513. * Force the sprite under the pointer
  28514. * @param sprite defines the sprite to use
  28515. */
  28516. Scene.prototype.setPointerOverSprite = function (sprite) {
  28517. if (this._pointerOverSprite === sprite) {
  28518. return;
  28519. }
  28520. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28521. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28522. }
  28523. this._pointerOverSprite = sprite;
  28524. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28525. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28526. }
  28527. };
  28528. /**
  28529. * Gets the sprite under the pointer
  28530. * @returns a Sprite or null if no sprite is under the pointer
  28531. */
  28532. Scene.prototype.getPointerOverSprite = function () {
  28533. return this._pointerOverSprite;
  28534. };
  28535. // Physics
  28536. /**
  28537. * Gets the current physics engine
  28538. * @returns a PhysicsEngine or null if none attached
  28539. */
  28540. Scene.prototype.getPhysicsEngine = function () {
  28541. return this._physicsEngine;
  28542. };
  28543. /**
  28544. * Enables physics to the current scene
  28545. * @param gravity defines the scene's gravity for the physics engine
  28546. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28547. * @return a boolean indicating if the physics engine was initialized
  28548. */
  28549. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28550. if (gravity === void 0) { gravity = null; }
  28551. if (this._physicsEngine) {
  28552. return true;
  28553. }
  28554. try {
  28555. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28556. return true;
  28557. }
  28558. catch (e) {
  28559. BABYLON.Tools.Error(e.message);
  28560. return false;
  28561. }
  28562. };
  28563. /**
  28564. * Disables and disposes the physics engine associated with the scene
  28565. */
  28566. Scene.prototype.disablePhysicsEngine = function () {
  28567. if (!this._physicsEngine) {
  28568. return;
  28569. }
  28570. this._physicsEngine.dispose();
  28571. this._physicsEngine = null;
  28572. };
  28573. /**
  28574. * Gets a boolean indicating if there is an active physics engine
  28575. * @returns a boolean indicating if there is an active physics engine
  28576. */
  28577. Scene.prototype.isPhysicsEnabled = function () {
  28578. return this._physicsEngine !== undefined;
  28579. };
  28580. /**
  28581. * Deletes a physics compound impostor
  28582. * @param compound defines the compound to delete
  28583. */
  28584. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28585. var mesh = compound.parts[0].mesh;
  28586. if (mesh.physicsImpostor) {
  28587. mesh.physicsImpostor.dispose( /*true*/);
  28588. mesh.physicsImpostor = null;
  28589. }
  28590. };
  28591. // Misc.
  28592. /** @hidden */
  28593. Scene.prototype._rebuildGeometries = function () {
  28594. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28595. var geometry = _a[_i];
  28596. geometry._rebuild();
  28597. }
  28598. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28599. var mesh = _c[_b];
  28600. mesh._rebuild();
  28601. }
  28602. if (this.postProcessManager) {
  28603. this.postProcessManager._rebuild();
  28604. }
  28605. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28606. var layer = _e[_d];
  28607. layer._rebuild();
  28608. }
  28609. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28610. var effectLayer = _g[_f];
  28611. effectLayer._rebuild();
  28612. }
  28613. if (this._boundingBoxRenderer) {
  28614. this._boundingBoxRenderer._rebuild();
  28615. }
  28616. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28617. var system = _j[_h];
  28618. system.rebuild();
  28619. }
  28620. if (this._postProcessRenderPipelineManager) {
  28621. this._postProcessRenderPipelineManager._rebuild();
  28622. }
  28623. };
  28624. /** @hidden */
  28625. Scene.prototype._rebuildTextures = function () {
  28626. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28627. var texture = _a[_i];
  28628. texture._rebuild();
  28629. }
  28630. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28631. };
  28632. /**
  28633. * Creates a default light for the scene.
  28634. * @param replace Whether to replace the existing lights in the scene.
  28635. */
  28636. Scene.prototype.createDefaultLight = function (replace) {
  28637. if (replace === void 0) { replace = false; }
  28638. // Dispose existing light in replace mode.
  28639. if (replace) {
  28640. if (this.lights) {
  28641. for (var i = 0; i < this.lights.length; i++) {
  28642. this.lights[i].dispose();
  28643. }
  28644. }
  28645. }
  28646. // Light
  28647. if (this.lights.length === 0) {
  28648. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28649. }
  28650. };
  28651. /**
  28652. * Creates a default camera for the scene.
  28653. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28654. * @param replace Whether to replace the existing active camera in the scene.
  28655. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28656. */
  28657. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28658. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28659. if (replace === void 0) { replace = false; }
  28660. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28661. // Dispose existing camera in replace mode.
  28662. if (replace) {
  28663. if (this.activeCamera) {
  28664. this.activeCamera.dispose();
  28665. this.activeCamera = null;
  28666. }
  28667. }
  28668. // Camera
  28669. if (!this.activeCamera) {
  28670. var worldExtends = this.getWorldExtends();
  28671. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28672. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28673. var camera;
  28674. var radius = worldSize.length() * 1.5;
  28675. // empty scene scenario!
  28676. if (!isFinite(radius)) {
  28677. radius = 1;
  28678. worldCenter.copyFromFloats(0, 0, 0);
  28679. }
  28680. if (createArcRotateCamera) {
  28681. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28682. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28683. arcRotateCamera.wheelPrecision = 100 / radius;
  28684. camera = arcRotateCamera;
  28685. }
  28686. else {
  28687. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28688. freeCamera.setTarget(worldCenter);
  28689. camera = freeCamera;
  28690. }
  28691. camera.minZ = radius * 0.01;
  28692. camera.maxZ = radius * 1000;
  28693. camera.speed = radius * 0.2;
  28694. this.activeCamera = camera;
  28695. var canvas = this.getEngine().getRenderingCanvas();
  28696. if (attachCameraControls && canvas) {
  28697. camera.attachControl(canvas);
  28698. }
  28699. }
  28700. };
  28701. /**
  28702. * Creates a default camera and a default light
  28703. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28704. * @param replace defines if the camera and/or light will replace the existing ones
  28705. * @param attachCameraControls defines if attachControl will be called on the new camera
  28706. */
  28707. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28708. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28709. if (replace === void 0) { replace = false; }
  28710. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28711. this.createDefaultLight(replace);
  28712. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28713. };
  28714. /**
  28715. * Creates a new sky box
  28716. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28717. * @param environmentTexture defines the texture to use as environment texture
  28718. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28719. * @param scale defines the overall scale of the skybox
  28720. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28721. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28722. * @returns a new mesh holding the sky box
  28723. */
  28724. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28725. if (pbr === void 0) { pbr = false; }
  28726. if (scale === void 0) { scale = 1000; }
  28727. if (blur === void 0) { blur = 0; }
  28728. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28729. if (!environmentTexture) {
  28730. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28731. return null;
  28732. }
  28733. if (setGlobalEnvTexture) {
  28734. if (environmentTexture) {
  28735. this.environmentTexture = environmentTexture;
  28736. }
  28737. }
  28738. // Skybox
  28739. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28740. if (pbr) {
  28741. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28742. hdrSkyboxMaterial.backFaceCulling = false;
  28743. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28744. if (hdrSkyboxMaterial.reflectionTexture) {
  28745. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28746. }
  28747. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28748. hdrSkyboxMaterial.disableLighting = true;
  28749. hdrSkyboxMaterial.twoSidedLighting = true;
  28750. hdrSkybox.infiniteDistance = true;
  28751. hdrSkybox.material = hdrSkyboxMaterial;
  28752. }
  28753. else {
  28754. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28755. skyboxMaterial.backFaceCulling = false;
  28756. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28757. if (skyboxMaterial.reflectionTexture) {
  28758. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28759. }
  28760. skyboxMaterial.disableLighting = true;
  28761. hdrSkybox.infiniteDistance = true;
  28762. hdrSkybox.material = skyboxMaterial;
  28763. }
  28764. return hdrSkybox;
  28765. };
  28766. /**
  28767. * Creates a new environment
  28768. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28769. * @param options defines the options you can use to configure the environment
  28770. * @returns the new EnvironmentHelper
  28771. */
  28772. Scene.prototype.createDefaultEnvironment = function (options) {
  28773. if (BABYLON.EnvironmentHelper) {
  28774. return new BABYLON.EnvironmentHelper(options, this);
  28775. }
  28776. return null;
  28777. };
  28778. /**
  28779. * Creates a new VREXperienceHelper
  28780. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28781. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28782. * @returns a new VREXperienceHelper
  28783. */
  28784. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28785. if (webVROptions === void 0) { webVROptions = {}; }
  28786. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28787. };
  28788. // Tags
  28789. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28790. if (tagsQuery === undefined) {
  28791. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28792. return list;
  28793. }
  28794. var listByTags = [];
  28795. forEach = forEach || (function (item) { return; });
  28796. for (var i in list) {
  28797. var item = list[i];
  28798. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28799. listByTags.push(item);
  28800. forEach(item);
  28801. }
  28802. }
  28803. return listByTags;
  28804. };
  28805. /**
  28806. * Get a list of meshes by tags
  28807. * @param tagsQuery defines the tags query to use
  28808. * @param forEach defines a predicate used to filter results
  28809. * @returns an array of Mesh
  28810. */
  28811. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28812. return this._getByTags(this.meshes, tagsQuery, forEach);
  28813. };
  28814. /**
  28815. * Get a list of cameras by tags
  28816. * @param tagsQuery defines the tags query to use
  28817. * @param forEach defines a predicate used to filter results
  28818. * @returns an array of Camera
  28819. */
  28820. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28821. return this._getByTags(this.cameras, tagsQuery, forEach);
  28822. };
  28823. /**
  28824. * Get a list of lights by tags
  28825. * @param tagsQuery defines the tags query to use
  28826. * @param forEach defines a predicate used to filter results
  28827. * @returns an array of Light
  28828. */
  28829. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28830. return this._getByTags(this.lights, tagsQuery, forEach);
  28831. };
  28832. /**
  28833. * Get a list of materials by tags
  28834. * @param tagsQuery defines the tags query to use
  28835. * @param forEach defines a predicate used to filter results
  28836. * @returns an array of Material
  28837. */
  28838. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28839. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28840. };
  28841. /**
  28842. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28843. * This allowed control for front to back rendering or reversly depending of the special needs.
  28844. *
  28845. * @param renderingGroupId The rendering group id corresponding to its index
  28846. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28847. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28848. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28849. */
  28850. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28851. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28852. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28853. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28854. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28855. };
  28856. /**
  28857. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28858. *
  28859. * @param renderingGroupId The rendering group id corresponding to its index
  28860. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28861. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28862. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28863. */
  28864. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28865. if (depth === void 0) { depth = true; }
  28866. if (stencil === void 0) { stencil = true; }
  28867. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28868. };
  28869. /**
  28870. * Will flag all materials as dirty to trigger new shader compilation
  28871. * @param flag defines the flag used to specify which material part must be marked as dirty
  28872. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28873. */
  28874. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28875. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28876. var material = _a[_i];
  28877. if (predicate && !predicate(material)) {
  28878. continue;
  28879. }
  28880. material.markAsDirty(flag);
  28881. }
  28882. };
  28883. /** @hidden */
  28884. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28885. var _this = this;
  28886. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28887. this._activeRequests.push(request);
  28888. request.onCompleteObservable.add(function (request) {
  28889. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28890. });
  28891. return request;
  28892. };
  28893. /** @hidden */
  28894. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28895. var _this = this;
  28896. return new Promise(function (resolve, reject) {
  28897. _this._loadFile(url, function (data) {
  28898. resolve(data);
  28899. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28900. reject(exception);
  28901. });
  28902. });
  28903. };
  28904. // Statics
  28905. Scene._FOGMODE_NONE = 0;
  28906. Scene._FOGMODE_EXP = 1;
  28907. Scene._FOGMODE_EXP2 = 2;
  28908. Scene._FOGMODE_LINEAR = 3;
  28909. Scene._uniqueIdCounter = 0;
  28910. /**
  28911. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28912. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28913. */
  28914. Scene.MinDeltaTime = 1.0;
  28915. /**
  28916. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28917. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28918. */
  28919. Scene.MaxDeltaTime = 1000.0;
  28920. /** The distance in pixel that you have to move to prevent some events */
  28921. Scene.DragMovementThreshold = 10; // in pixels
  28922. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28923. Scene.LongPressDelay = 500; // in milliseconds
  28924. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28925. Scene.DoubleClickDelay = 300; // in milliseconds
  28926. /** If you need to check double click without raising a single click at first click, enable this flag */
  28927. Scene.ExclusiveDoubleClickMode = false;
  28928. return Scene;
  28929. }());
  28930. BABYLON.Scene = Scene;
  28931. })(BABYLON || (BABYLON = {}));
  28932. //# sourceMappingURL=babylon.scene.js.map
  28933. var BABYLON;
  28934. (function (BABYLON) {
  28935. /**
  28936. * Set of assets to keep when moving a scene into an asset container.
  28937. */
  28938. var KeepAssets = /** @class */ (function () {
  28939. function KeepAssets() {
  28940. /**
  28941. * Cameras to keep.
  28942. */
  28943. this.cameras = new Array();
  28944. /**
  28945. * Lights to keep.
  28946. */
  28947. this.lights = new Array();
  28948. /**
  28949. * Meshes to keep.
  28950. */
  28951. this.meshes = new Array();
  28952. /**
  28953. * Skeletons to keep.
  28954. */
  28955. this.skeletons = new Array();
  28956. /**
  28957. * ParticleSystems to keep.
  28958. */
  28959. this.particleSystems = new Array();
  28960. /**
  28961. * Animations to keep.
  28962. */
  28963. this.animations = new Array();
  28964. /**
  28965. * AnimationGroups to keep.
  28966. */
  28967. this.animationGroups = new Array();
  28968. /**
  28969. * MultiMaterials to keep.
  28970. */
  28971. this.multiMaterials = new Array();
  28972. /**
  28973. * Materials to keep.
  28974. */
  28975. this.materials = new Array();
  28976. /**
  28977. * MorphTargetManagers to keep.
  28978. */
  28979. this.morphTargetManagers = new Array();
  28980. /**
  28981. * Geometries to keep.
  28982. */
  28983. this.geometries = new Array();
  28984. /**
  28985. * TransformNodes to keep.
  28986. */
  28987. this.transformNodes = new Array();
  28988. /**
  28989. * LensFlareSystems to keep.
  28990. */
  28991. this.lensFlareSystems = new Array();
  28992. /**
  28993. * ShadowGenerators to keep.
  28994. */
  28995. this.shadowGenerators = new Array();
  28996. /**
  28997. * ActionManagers to keep.
  28998. */
  28999. this.actionManagers = new Array();
  29000. /**
  29001. * Sounds to keep.
  29002. */
  29003. this.sounds = new Array();
  29004. /**
  29005. * Textures to keep.
  29006. */
  29007. this.textures = new Array();
  29008. /**
  29009. * Effect layers to keep.
  29010. */
  29011. this.effectLayers = new Array();
  29012. }
  29013. return KeepAssets;
  29014. }());
  29015. BABYLON.KeepAssets = KeepAssets;
  29016. /**
  29017. * Container with a set of assets that can be added or removed from a scene.
  29018. */
  29019. var AssetContainer = /** @class */ (function () {
  29020. /**
  29021. * Instantiates an AssetContainer.
  29022. * @param scene The scene the AssetContainer belongs to.
  29023. */
  29024. function AssetContainer(scene) {
  29025. // Objects
  29026. /**
  29027. * Cameras populated in the container.
  29028. */
  29029. this.cameras = new Array();
  29030. /**
  29031. * Lights populated in the container.
  29032. */
  29033. this.lights = new Array();
  29034. /**
  29035. * Meshes populated in the container.
  29036. */
  29037. this.meshes = new Array();
  29038. /**
  29039. * Skeletons populated in the container.
  29040. */
  29041. this.skeletons = new Array();
  29042. /**
  29043. * ParticleSystems populated in the container.
  29044. */
  29045. this.particleSystems = new Array();
  29046. /**
  29047. * Animations populated in the container.
  29048. */
  29049. this.animations = new Array();
  29050. /**
  29051. * AnimationGroups populated in the container.
  29052. */
  29053. this.animationGroups = new Array();
  29054. /**
  29055. * MultiMaterials populated in the container.
  29056. */
  29057. this.multiMaterials = new Array();
  29058. /**
  29059. * Materials populated in the container.
  29060. */
  29061. this.materials = new Array();
  29062. /**
  29063. * MorphTargetManagers populated in the container.
  29064. */
  29065. this.morphTargetManagers = new Array();
  29066. /**
  29067. * Geometries populated in the container.
  29068. */
  29069. this.geometries = new Array();
  29070. /**
  29071. * TransformNodes populated in the container.
  29072. */
  29073. this.transformNodes = new Array();
  29074. /**
  29075. * LensFlareSystems populated in the container.
  29076. */
  29077. this.lensFlareSystems = new Array();
  29078. /**
  29079. * ShadowGenerators populated in the container.
  29080. */
  29081. this.shadowGenerators = new Array();
  29082. /**
  29083. * ActionManagers populated in the container.
  29084. */
  29085. this.actionManagers = new Array();
  29086. /**
  29087. * Sounds populated in the container.
  29088. */
  29089. this.sounds = new Array();
  29090. /**
  29091. * Textures populated in the container.
  29092. */
  29093. this.textures = new Array();
  29094. /**
  29095. * Effect layers populated in the container.
  29096. */
  29097. this.effectLayers = new Array();
  29098. this.scene = scene;
  29099. }
  29100. /**
  29101. * Adds all the assets from the container to the scene.
  29102. */
  29103. AssetContainer.prototype.addAllToScene = function () {
  29104. var _this = this;
  29105. this.cameras.forEach(function (o) {
  29106. _this.scene.addCamera(o);
  29107. });
  29108. this.lights.forEach(function (o) {
  29109. _this.scene.addLight(o);
  29110. });
  29111. this.meshes.forEach(function (o) {
  29112. _this.scene.addMesh(o);
  29113. });
  29114. this.skeletons.forEach(function (o) {
  29115. _this.scene.addSkeleton(o);
  29116. });
  29117. this.particleSystems.forEach(function (o) {
  29118. _this.scene.addParticleSystem(o);
  29119. });
  29120. this.animations.forEach(function (o) {
  29121. _this.scene.addAnimation(o);
  29122. });
  29123. this.animationGroups.forEach(function (o) {
  29124. _this.scene.addAnimationGroup(o);
  29125. });
  29126. this.multiMaterials.forEach(function (o) {
  29127. _this.scene.addMultiMaterial(o);
  29128. });
  29129. this.materials.forEach(function (o) {
  29130. _this.scene.addMaterial(o);
  29131. });
  29132. this.morphTargetManagers.forEach(function (o) {
  29133. _this.scene.addMorphTargetManager(o);
  29134. });
  29135. this.geometries.forEach(function (o) {
  29136. _this.scene.addGeometry(o);
  29137. });
  29138. this.transformNodes.forEach(function (o) {
  29139. _this.scene.addTransformNode(o);
  29140. });
  29141. this.lensFlareSystems.forEach(function (o) {
  29142. _this.scene.addLensFlareSystem(o);
  29143. });
  29144. this.actionManagers.forEach(function (o) {
  29145. _this.scene.addActionManager(o);
  29146. });
  29147. this.sounds.forEach(function (o) {
  29148. o.play();
  29149. o.autoplay = true;
  29150. _this.scene.mainSoundTrack.AddSound(o);
  29151. });
  29152. this.textures.forEach(function (o) {
  29153. _this.scene.addTexture(o);
  29154. });
  29155. this.effectLayers.forEach(function (o) {
  29156. _this.scene.addEffectLayer(o);
  29157. });
  29158. };
  29159. /**
  29160. * Removes all the assets in the container from the scene
  29161. */
  29162. AssetContainer.prototype.removeAllFromScene = function () {
  29163. var _this = this;
  29164. this.cameras.forEach(function (o) {
  29165. _this.scene.removeCamera(o);
  29166. });
  29167. this.lights.forEach(function (o) {
  29168. _this.scene.removeLight(o);
  29169. });
  29170. this.meshes.forEach(function (o) {
  29171. _this.scene.removeMesh(o);
  29172. });
  29173. this.skeletons.forEach(function (o) {
  29174. _this.scene.removeSkeleton(o);
  29175. });
  29176. this.particleSystems.forEach(function (o) {
  29177. _this.scene.removeParticleSystem(o);
  29178. });
  29179. this.animations.forEach(function (o) {
  29180. _this.scene.removeAnimation(o);
  29181. });
  29182. this.animationGroups.forEach(function (o) {
  29183. _this.scene.removeAnimationGroup(o);
  29184. });
  29185. this.multiMaterials.forEach(function (o) {
  29186. _this.scene.removeMultiMaterial(o);
  29187. });
  29188. this.materials.forEach(function (o) {
  29189. _this.scene.removeMaterial(o);
  29190. });
  29191. this.morphTargetManagers.forEach(function (o) {
  29192. _this.scene.removeMorphTargetManager(o);
  29193. });
  29194. this.geometries.forEach(function (o) {
  29195. _this.scene.removeGeometry(o);
  29196. });
  29197. this.transformNodes.forEach(function (o) {
  29198. _this.scene.removeTransformNode(o);
  29199. });
  29200. this.lensFlareSystems.forEach(function (o) {
  29201. _this.scene.removeLensFlareSystem(o);
  29202. });
  29203. this.actionManagers.forEach(function (o) {
  29204. _this.scene.removeActionManager(o);
  29205. });
  29206. this.sounds.forEach(function (o) {
  29207. o.stop();
  29208. o.autoplay = false;
  29209. _this.scene.mainSoundTrack.RemoveSound(o);
  29210. });
  29211. this.textures.forEach(function (o) {
  29212. _this.scene.removeTexture(o);
  29213. });
  29214. this.effectLayers.forEach(function (o) {
  29215. _this.scene.removeEffectLayer(o);
  29216. });
  29217. };
  29218. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29219. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29220. var asset = sourceAssets_1[_i];
  29221. var move = true;
  29222. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29223. var keepAsset = keepAssets_1[_a];
  29224. if (asset === keepAsset) {
  29225. move = false;
  29226. break;
  29227. }
  29228. }
  29229. if (move) {
  29230. targetAssets.push(asset);
  29231. }
  29232. }
  29233. };
  29234. /**
  29235. * Removes all the assets contained in the scene and adds them to the container.
  29236. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29237. */
  29238. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29239. if (keepAssets === undefined) {
  29240. keepAssets = new KeepAssets();
  29241. }
  29242. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29243. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29244. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29245. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29246. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29247. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29248. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29249. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29250. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29251. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29252. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29253. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29254. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29255. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29256. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29257. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29258. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29259. this.removeAllFromScene();
  29260. };
  29261. /**
  29262. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  29263. * @returns the root mesh
  29264. */
  29265. AssetContainer.prototype.createRootMesh = function () {
  29266. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29267. this.meshes.forEach(function (m) {
  29268. if (!m.parent) {
  29269. rootMesh.addChild(m);
  29270. }
  29271. });
  29272. this.meshes.unshift(rootMesh);
  29273. return rootMesh;
  29274. };
  29275. return AssetContainer;
  29276. }());
  29277. BABYLON.AssetContainer = AssetContainer;
  29278. })(BABYLON || (BABYLON = {}));
  29279. //# sourceMappingURL=babylon.assetContainer.js.map
  29280. var BABYLON;
  29281. (function (BABYLON) {
  29282. var Buffer = /** @class */ (function () {
  29283. /**
  29284. * Constructor
  29285. * @param engine the engine
  29286. * @param data the data to use for this buffer
  29287. * @param updatable whether the data is updatable
  29288. * @param stride the stride (optional)
  29289. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29290. * @param instanced whether the buffer is instanced (optional)
  29291. * @param useBytes set to true if the stride in in bytes (optional)
  29292. */
  29293. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29294. if (stride === void 0) { stride = 0; }
  29295. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29296. if (instanced === void 0) { instanced = false; }
  29297. if (useBytes === void 0) { useBytes = false; }
  29298. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29299. this._engine = engine.getScene().getEngine();
  29300. }
  29301. else {
  29302. this._engine = engine;
  29303. }
  29304. this._updatable = updatable;
  29305. this._instanced = instanced;
  29306. this._data = data;
  29307. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29308. if (!postponeInternalCreation) { // by default
  29309. this.create();
  29310. }
  29311. }
  29312. /**
  29313. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29314. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29315. * @param offset defines offset in the buffer (0 by default)
  29316. * @param size defines the size in floats of attributes (position is 3 for instance)
  29317. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29318. * @param instanced defines if the vertex buffer contains indexed data
  29319. * @param useBytes defines if the offset and stride are in bytes
  29320. * @returns the new vertex buffer
  29321. */
  29322. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29323. if (useBytes === void 0) { useBytes = false; }
  29324. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29325. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29326. // a lot of these parameters are ignored as they are overriden by the buffer
  29327. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29328. };
  29329. // Properties
  29330. Buffer.prototype.isUpdatable = function () {
  29331. return this._updatable;
  29332. };
  29333. Buffer.prototype.getData = function () {
  29334. return this._data;
  29335. };
  29336. Buffer.prototype.getBuffer = function () {
  29337. return this._buffer;
  29338. };
  29339. /**
  29340. * Gets the stride in float32 units (i.e. byte stride / 4).
  29341. * May not be an integer if the byte stride is not divisible by 4.
  29342. * DEPRECATED. Use byteStride instead.
  29343. * @returns the stride in float32 units
  29344. */
  29345. Buffer.prototype.getStrideSize = function () {
  29346. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29347. };
  29348. // Methods
  29349. Buffer.prototype.create = function (data) {
  29350. if (data === void 0) { data = null; }
  29351. if (!data && this._buffer) {
  29352. return; // nothing to do
  29353. }
  29354. data = data || this._data;
  29355. if (!data) {
  29356. return;
  29357. }
  29358. if (!this._buffer) { // create buffer
  29359. if (this._updatable) {
  29360. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29361. this._data = data;
  29362. }
  29363. else {
  29364. this._buffer = this._engine.createVertexBuffer(data);
  29365. }
  29366. }
  29367. else if (this._updatable) { // update buffer
  29368. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29369. this._data = data;
  29370. }
  29371. };
  29372. Buffer.prototype._rebuild = function () {
  29373. this._buffer = null;
  29374. this.create(this._data);
  29375. };
  29376. Buffer.prototype.update = function (data) {
  29377. this.create(data);
  29378. };
  29379. /**
  29380. * Updates the data directly.
  29381. * @param data the new data
  29382. * @param offset the new offset
  29383. * @param vertexCount the vertex count (optional)
  29384. * @param useBytes set to true if the offset is in bytes
  29385. */
  29386. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29387. if (useBytes === void 0) { useBytes = false; }
  29388. if (!this._buffer) {
  29389. return;
  29390. }
  29391. if (this._updatable) { // update buffer
  29392. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29393. this._data = null;
  29394. }
  29395. };
  29396. Buffer.prototype.dispose = function () {
  29397. if (!this._buffer) {
  29398. return;
  29399. }
  29400. if (this._engine._releaseBuffer(this._buffer)) {
  29401. this._buffer = null;
  29402. }
  29403. };
  29404. return Buffer;
  29405. }());
  29406. BABYLON.Buffer = Buffer;
  29407. })(BABYLON || (BABYLON = {}));
  29408. //# sourceMappingURL=babylon.buffer.js.map
  29409. var BABYLON;
  29410. (function (BABYLON) {
  29411. var VertexBuffer = /** @class */ (function () {
  29412. /**
  29413. * Constructor
  29414. * @param engine the engine
  29415. * @param data the data to use for this vertex buffer
  29416. * @param kind the vertex buffer kind
  29417. * @param updatable whether the data is updatable
  29418. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29419. * @param stride the stride (optional)
  29420. * @param instanced whether the buffer is instanced (optional)
  29421. * @param offset the offset of the data (optional)
  29422. * @param size the number of components (optional)
  29423. * @param type the type of the component (optional)
  29424. * @param normalized whether the data contains normalized data (optional)
  29425. * @param useBytes set to true if stride and offset are in bytes (optional)
  29426. */
  29427. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29428. if (normalized === void 0) { normalized = false; }
  29429. if (useBytes === void 0) { useBytes = false; }
  29430. if (data instanceof BABYLON.Buffer) {
  29431. this._buffer = data;
  29432. this._ownsBuffer = false;
  29433. }
  29434. else {
  29435. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29436. this._ownsBuffer = true;
  29437. }
  29438. this._kind = kind;
  29439. if (type == undefined) {
  29440. var data_1 = this.getData();
  29441. this.type = VertexBuffer.FLOAT;
  29442. if (data_1 instanceof Int8Array)
  29443. this.type = VertexBuffer.BYTE;
  29444. else if (data_1 instanceof Uint8Array)
  29445. this.type = VertexBuffer.UNSIGNED_BYTE;
  29446. else if (data_1 instanceof Int16Array)
  29447. this.type = VertexBuffer.SHORT;
  29448. else if (data_1 instanceof Uint16Array)
  29449. this.type = VertexBuffer.UNSIGNED_SHORT;
  29450. else if (data_1 instanceof Int32Array)
  29451. this.type = VertexBuffer.INT;
  29452. else if (data_1 instanceof Uint32Array)
  29453. this.type = VertexBuffer.UNSIGNED_INT;
  29454. }
  29455. else {
  29456. this.type = type;
  29457. }
  29458. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29459. if (useBytes) {
  29460. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29461. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29462. this.byteOffset = offset || 0;
  29463. }
  29464. else {
  29465. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29466. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29467. this.byteOffset = (offset || 0) * typeByteLength;
  29468. }
  29469. this.normalized = normalized;
  29470. this._instanced = instanced !== undefined ? instanced : false;
  29471. this._instanceDivisor = instanced ? 1 : 0;
  29472. }
  29473. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29474. /**
  29475. * Gets or sets the instance divisor when in instanced mode
  29476. */
  29477. get: function () {
  29478. return this._instanceDivisor;
  29479. },
  29480. set: function (value) {
  29481. this._instanceDivisor = value;
  29482. if (value == 0) {
  29483. this._instanced = false;
  29484. }
  29485. else {
  29486. this._instanced = true;
  29487. }
  29488. },
  29489. enumerable: true,
  29490. configurable: true
  29491. });
  29492. VertexBuffer.prototype._rebuild = function () {
  29493. if (!this._buffer) {
  29494. return;
  29495. }
  29496. this._buffer._rebuild();
  29497. };
  29498. /**
  29499. * Returns the kind of the VertexBuffer (string).
  29500. */
  29501. VertexBuffer.prototype.getKind = function () {
  29502. return this._kind;
  29503. };
  29504. // Properties
  29505. /**
  29506. * Boolean : is the VertexBuffer updatable ?
  29507. */
  29508. VertexBuffer.prototype.isUpdatable = function () {
  29509. return this._buffer.isUpdatable();
  29510. };
  29511. /**
  29512. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29513. */
  29514. VertexBuffer.prototype.getData = function () {
  29515. return this._buffer.getData();
  29516. };
  29517. /**
  29518. * Returns the WebGLBuffer associated to the VertexBuffer.
  29519. */
  29520. VertexBuffer.prototype.getBuffer = function () {
  29521. return this._buffer.getBuffer();
  29522. };
  29523. /**
  29524. * Returns the stride as a multiple of the type byte length.
  29525. * DEPRECATED. Use byteStride instead.
  29526. */
  29527. VertexBuffer.prototype.getStrideSize = function () {
  29528. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29529. };
  29530. /**
  29531. * Returns the offset as a multiple of the type byte length.
  29532. * DEPRECATED. Use byteOffset instead.
  29533. */
  29534. VertexBuffer.prototype.getOffset = function () {
  29535. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29536. };
  29537. /**
  29538. * Returns the number of components per vertex attribute (integer).
  29539. */
  29540. VertexBuffer.prototype.getSize = function () {
  29541. return this._size;
  29542. };
  29543. /**
  29544. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29545. */
  29546. VertexBuffer.prototype.getIsInstanced = function () {
  29547. return this._instanced;
  29548. };
  29549. /**
  29550. * Returns the instancing divisor, zero for non-instanced (integer).
  29551. */
  29552. VertexBuffer.prototype.getInstanceDivisor = function () {
  29553. return this._instanceDivisor;
  29554. };
  29555. // Methods
  29556. /**
  29557. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29558. * Returns the created WebGLBuffer.
  29559. */
  29560. VertexBuffer.prototype.create = function (data) {
  29561. return this._buffer.create(data);
  29562. };
  29563. /**
  29564. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29565. * This function will create a new buffer if the current one is not updatable
  29566. * Returns the updated WebGLBuffer.
  29567. */
  29568. VertexBuffer.prototype.update = function (data) {
  29569. return this._buffer.update(data);
  29570. };
  29571. /**
  29572. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29573. * Returns the directly updated WebGLBuffer.
  29574. * @param data the new data
  29575. * @param offset the new offset
  29576. * @param useBytes set to true if the offset is in bytes
  29577. */
  29578. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29579. if (useBytes === void 0) { useBytes = false; }
  29580. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29581. };
  29582. /**
  29583. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29584. */
  29585. VertexBuffer.prototype.dispose = function () {
  29586. if (this._ownsBuffer) {
  29587. this._buffer.dispose();
  29588. }
  29589. };
  29590. /**
  29591. * Enumerates each value of this vertex buffer as numbers.
  29592. * @param count the number of values to enumerate
  29593. * @param callback the callback function called for each value
  29594. */
  29595. VertexBuffer.prototype.forEach = function (count, callback) {
  29596. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29597. };
  29598. Object.defineProperty(VertexBuffer, "PositionKind", {
  29599. get: function () {
  29600. return VertexBuffer._PositionKind;
  29601. },
  29602. enumerable: true,
  29603. configurable: true
  29604. });
  29605. Object.defineProperty(VertexBuffer, "NormalKind", {
  29606. get: function () {
  29607. return VertexBuffer._NormalKind;
  29608. },
  29609. enumerable: true,
  29610. configurable: true
  29611. });
  29612. Object.defineProperty(VertexBuffer, "TangentKind", {
  29613. get: function () {
  29614. return VertexBuffer._TangentKind;
  29615. },
  29616. enumerable: true,
  29617. configurable: true
  29618. });
  29619. Object.defineProperty(VertexBuffer, "UVKind", {
  29620. get: function () {
  29621. return VertexBuffer._UVKind;
  29622. },
  29623. enumerable: true,
  29624. configurable: true
  29625. });
  29626. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29627. get: function () {
  29628. return VertexBuffer._UV2Kind;
  29629. },
  29630. enumerable: true,
  29631. configurable: true
  29632. });
  29633. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29634. get: function () {
  29635. return VertexBuffer._UV3Kind;
  29636. },
  29637. enumerable: true,
  29638. configurable: true
  29639. });
  29640. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29641. get: function () {
  29642. return VertexBuffer._UV4Kind;
  29643. },
  29644. enumerable: true,
  29645. configurable: true
  29646. });
  29647. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29648. get: function () {
  29649. return VertexBuffer._UV5Kind;
  29650. },
  29651. enumerable: true,
  29652. configurable: true
  29653. });
  29654. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29655. get: function () {
  29656. return VertexBuffer._UV6Kind;
  29657. },
  29658. enumerable: true,
  29659. configurable: true
  29660. });
  29661. Object.defineProperty(VertexBuffer, "ColorKind", {
  29662. get: function () {
  29663. return VertexBuffer._ColorKind;
  29664. },
  29665. enumerable: true,
  29666. configurable: true
  29667. });
  29668. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29669. get: function () {
  29670. return VertexBuffer._MatricesIndicesKind;
  29671. },
  29672. enumerable: true,
  29673. configurable: true
  29674. });
  29675. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29676. get: function () {
  29677. return VertexBuffer._MatricesWeightsKind;
  29678. },
  29679. enumerable: true,
  29680. configurable: true
  29681. });
  29682. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29683. get: function () {
  29684. return VertexBuffer._MatricesIndicesExtraKind;
  29685. },
  29686. enumerable: true,
  29687. configurable: true
  29688. });
  29689. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29690. get: function () {
  29691. return VertexBuffer._MatricesWeightsExtraKind;
  29692. },
  29693. enumerable: true,
  29694. configurable: true
  29695. });
  29696. /**
  29697. * Deduces the stride given a kind.
  29698. * @param kind The kind string to deduce
  29699. * @returns The deduced stride
  29700. */
  29701. VertexBuffer.DeduceStride = function (kind) {
  29702. switch (kind) {
  29703. case VertexBuffer.UVKind:
  29704. case VertexBuffer.UV2Kind:
  29705. case VertexBuffer.UV3Kind:
  29706. case VertexBuffer.UV4Kind:
  29707. case VertexBuffer.UV5Kind:
  29708. case VertexBuffer.UV6Kind:
  29709. return 2;
  29710. case VertexBuffer.NormalKind:
  29711. case VertexBuffer.PositionKind:
  29712. return 3;
  29713. case VertexBuffer.ColorKind:
  29714. case VertexBuffer.MatricesIndicesKind:
  29715. case VertexBuffer.MatricesIndicesExtraKind:
  29716. case VertexBuffer.MatricesWeightsKind:
  29717. case VertexBuffer.MatricesWeightsExtraKind:
  29718. case VertexBuffer.TangentKind:
  29719. return 4;
  29720. default:
  29721. throw new Error("Invalid kind '" + kind + "'");
  29722. }
  29723. };
  29724. /**
  29725. * Gets the byte length of the given type.
  29726. * @param type the type
  29727. * @returns the number of bytes
  29728. */
  29729. VertexBuffer.GetTypeByteLength = function (type) {
  29730. switch (type) {
  29731. case VertexBuffer.BYTE:
  29732. case VertexBuffer.UNSIGNED_BYTE:
  29733. return 1;
  29734. case VertexBuffer.SHORT:
  29735. case VertexBuffer.UNSIGNED_SHORT:
  29736. return 2;
  29737. case VertexBuffer.INT:
  29738. case VertexBuffer.FLOAT:
  29739. return 4;
  29740. default:
  29741. throw new Error("Invalid type '" + type + "'");
  29742. }
  29743. };
  29744. /**
  29745. * Enumerates each value of the given parameters as numbers.
  29746. * @param data the data to enumerate
  29747. * @param byteOffset the byte offset of the data
  29748. * @param byteStride the byte stride of the data
  29749. * @param componentCount the number of components per element
  29750. * @param componentType the type of the component
  29751. * @param count the total number of components
  29752. * @param normalized whether the data is normalized
  29753. * @param callback the callback function called for each value
  29754. */
  29755. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29756. if (data instanceof Array) {
  29757. var offset = byteOffset / 4;
  29758. var stride = byteStride / 4;
  29759. for (var index = 0; index < count; index += componentCount) {
  29760. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29761. callback(data[offset + componentIndex], index + componentIndex);
  29762. }
  29763. offset += stride;
  29764. }
  29765. }
  29766. else {
  29767. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29768. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29769. for (var index = 0; index < count; index += componentCount) {
  29770. var componentByteOffset = byteOffset;
  29771. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29772. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29773. callback(value, index + componentIndex);
  29774. componentByteOffset += componentByteLength;
  29775. }
  29776. byteOffset += byteStride;
  29777. }
  29778. }
  29779. };
  29780. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29781. switch (type) {
  29782. case VertexBuffer.BYTE: {
  29783. var value = dataView.getInt8(byteOffset);
  29784. if (normalized) {
  29785. value = Math.max(value / 127, -1);
  29786. }
  29787. return value;
  29788. }
  29789. case VertexBuffer.UNSIGNED_BYTE: {
  29790. var value = dataView.getUint8(byteOffset);
  29791. if (normalized) {
  29792. value = value / 255;
  29793. }
  29794. return value;
  29795. }
  29796. case VertexBuffer.SHORT: {
  29797. var value = dataView.getInt16(byteOffset, true);
  29798. if (normalized) {
  29799. value = Math.max(value / 16383, -1);
  29800. }
  29801. return value;
  29802. }
  29803. case VertexBuffer.UNSIGNED_SHORT: {
  29804. var value = dataView.getUint16(byteOffset, true);
  29805. if (normalized) {
  29806. value = value / 65535;
  29807. }
  29808. return value;
  29809. }
  29810. case VertexBuffer.FLOAT: {
  29811. return dataView.getFloat32(byteOffset, true);
  29812. }
  29813. default: {
  29814. throw new Error("Invalid component type " + type);
  29815. }
  29816. }
  29817. };
  29818. /**
  29819. * The byte type.
  29820. */
  29821. VertexBuffer.BYTE = 5120;
  29822. /**
  29823. * The unsigned byte type.
  29824. */
  29825. VertexBuffer.UNSIGNED_BYTE = 5121;
  29826. /**
  29827. * The short type.
  29828. */
  29829. VertexBuffer.SHORT = 5122;
  29830. /**
  29831. * The unsigned short type.
  29832. */
  29833. VertexBuffer.UNSIGNED_SHORT = 5123;
  29834. /**
  29835. * The integer type.
  29836. */
  29837. VertexBuffer.INT = 5124;
  29838. /**
  29839. * The unsigned integer type.
  29840. */
  29841. VertexBuffer.UNSIGNED_INT = 5125;
  29842. /**
  29843. * The float type.
  29844. */
  29845. VertexBuffer.FLOAT = 5126;
  29846. // Enums
  29847. VertexBuffer._PositionKind = "position";
  29848. VertexBuffer._NormalKind = "normal";
  29849. VertexBuffer._TangentKind = "tangent";
  29850. VertexBuffer._UVKind = "uv";
  29851. VertexBuffer._UV2Kind = "uv2";
  29852. VertexBuffer._UV3Kind = "uv3";
  29853. VertexBuffer._UV4Kind = "uv4";
  29854. VertexBuffer._UV5Kind = "uv5";
  29855. VertexBuffer._UV6Kind = "uv6";
  29856. VertexBuffer._ColorKind = "color";
  29857. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29858. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29859. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29860. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29861. return VertexBuffer;
  29862. }());
  29863. BABYLON.VertexBuffer = VertexBuffer;
  29864. })(BABYLON || (BABYLON = {}));
  29865. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29866. var BABYLON;
  29867. (function (BABYLON) {
  29868. /**
  29869. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29870. */
  29871. var DummyInternalTextureTracker = /** @class */ (function () {
  29872. function DummyInternalTextureTracker() {
  29873. /**
  29874. * Gets or set the previous tracker in the list
  29875. */
  29876. this.previous = null;
  29877. /**
  29878. * Gets or set the next tracker in the list
  29879. */
  29880. this.next = null;
  29881. }
  29882. return DummyInternalTextureTracker;
  29883. }());
  29884. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29885. })(BABYLON || (BABYLON = {}));
  29886. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29887. var BABYLON;
  29888. (function (BABYLON) {
  29889. /**
  29890. * Class used to store data associated with WebGL texture data for the engine
  29891. * This class should not be used directly
  29892. */
  29893. var InternalTexture = /** @class */ (function () {
  29894. /**
  29895. * Creates a new InternalTexture
  29896. * @param engine defines the engine to use
  29897. * @param dataSource defines the type of data that will be used
  29898. */
  29899. function InternalTexture(engine, dataSource) {
  29900. /**
  29901. * Observable called when the texture is loaded
  29902. */
  29903. this.onLoadedObservable = new BABYLON.Observable();
  29904. /**
  29905. * Gets or set the previous tracker in the list
  29906. */
  29907. this.previous = null;
  29908. /**
  29909. * Gets or set the next tracker in the list
  29910. */
  29911. this.next = null;
  29912. // Private
  29913. /** @hidden */
  29914. this._initialSlot = -1;
  29915. /** @hidden */
  29916. this._designatedSlot = -1;
  29917. /** @hidden */
  29918. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29919. /** @hidden */
  29920. this._comparisonFunction = 0;
  29921. /** @hidden */
  29922. this._references = 1;
  29923. this._engine = engine;
  29924. this._dataSource = dataSource;
  29925. this._webGLTexture = engine._createTexture();
  29926. }
  29927. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29928. /**
  29929. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29930. */
  29931. get: function () {
  29932. return this._dataSource;
  29933. },
  29934. enumerable: true,
  29935. configurable: true
  29936. });
  29937. /**
  29938. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29939. */
  29940. InternalTexture.prototype.incrementReferences = function () {
  29941. this._references++;
  29942. };
  29943. /**
  29944. * Change the size of the texture (not the size of the content)
  29945. * @param width defines the new width
  29946. * @param height defines the new height
  29947. * @param depth defines the new depth (1 by default)
  29948. */
  29949. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29950. if (depth === void 0) { depth = 1; }
  29951. this.width = width;
  29952. this.height = height;
  29953. this.depth = depth;
  29954. this.baseWidth = width;
  29955. this.baseHeight = height;
  29956. this.baseDepth = depth;
  29957. this._size = width * height * depth;
  29958. };
  29959. /** @hidden */
  29960. InternalTexture.prototype._rebuild = function () {
  29961. var _this = this;
  29962. var proxy;
  29963. this.isReady = false;
  29964. this._cachedCoordinatesMode = null;
  29965. this._cachedWrapU = null;
  29966. this._cachedWrapV = null;
  29967. this._cachedAnisotropicFilteringLevel = null;
  29968. switch (this._dataSource) {
  29969. case InternalTexture.DATASOURCE_TEMP:
  29970. return;
  29971. case InternalTexture.DATASOURCE_URL:
  29972. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29973. _this.isReady = true;
  29974. }, null, this._buffer, undefined, this.format);
  29975. proxy._swapAndDie(this);
  29976. return;
  29977. case InternalTexture.DATASOURCE_RAW:
  29978. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29979. proxy._swapAndDie(this);
  29980. this.isReady = true;
  29981. return;
  29982. case InternalTexture.DATASOURCE_RAW3D:
  29983. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29984. proxy._swapAndDie(this);
  29985. this.isReady = true;
  29986. return;
  29987. case InternalTexture.DATASOURCE_DYNAMIC:
  29988. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29989. proxy._swapAndDie(this);
  29990. // The engine will make sure to update content so no need to flag it as isReady = true
  29991. return;
  29992. case InternalTexture.DATASOURCE_RENDERTARGET:
  29993. var options = new BABYLON.RenderTargetCreationOptions();
  29994. options.generateDepthBuffer = this._generateDepthBuffer;
  29995. options.generateMipMaps = this.generateMipMaps;
  29996. options.generateStencilBuffer = this._generateStencilBuffer;
  29997. options.samplingMode = this.samplingMode;
  29998. options.type = this.type;
  29999. if (this.isCube) {
  30000. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30001. }
  30002. else {
  30003. var size = {
  30004. width: this.width,
  30005. height: this.height
  30006. };
  30007. proxy = this._engine.createRenderTargetTexture(size, options);
  30008. }
  30009. proxy._swapAndDie(this);
  30010. this.isReady = true;
  30011. return;
  30012. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30013. var depthTextureOptions = {
  30014. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30015. comparisonFunction: this._comparisonFunction,
  30016. generateStencil: this._generateStencilBuffer,
  30017. isCube: this.isCube
  30018. };
  30019. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30020. proxy._swapAndDie(this);
  30021. this.isReady = true;
  30022. return;
  30023. case InternalTexture.DATASOURCE_CUBE:
  30024. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30025. _this.isReady = true;
  30026. }, null, this.format, this._extension);
  30027. proxy._swapAndDie(this);
  30028. return;
  30029. case InternalTexture.DATASOURCE_CUBERAW:
  30030. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30031. proxy._swapAndDie(this);
  30032. this.isReady = true;
  30033. return;
  30034. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30035. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30036. if (proxy) {
  30037. proxy._swapAndDie(_this);
  30038. }
  30039. _this.isReady = true;
  30040. }, null, this.format, this._extension);
  30041. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30042. return;
  30043. }
  30044. };
  30045. InternalTexture.prototype._swapAndDie = function (target) {
  30046. target._webGLTexture = this._webGLTexture;
  30047. if (this._framebuffer) {
  30048. target._framebuffer = this._framebuffer;
  30049. }
  30050. if (this._depthStencilBuffer) {
  30051. target._depthStencilBuffer = this._depthStencilBuffer;
  30052. }
  30053. if (this._lodTextureHigh) {
  30054. if (target._lodTextureHigh) {
  30055. target._lodTextureHigh.dispose();
  30056. }
  30057. target._lodTextureHigh = this._lodTextureHigh;
  30058. }
  30059. if (this._lodTextureMid) {
  30060. if (target._lodTextureMid) {
  30061. target._lodTextureMid.dispose();
  30062. }
  30063. target._lodTextureMid = this._lodTextureMid;
  30064. }
  30065. if (this._lodTextureLow) {
  30066. if (target._lodTextureLow) {
  30067. target._lodTextureLow.dispose();
  30068. }
  30069. target._lodTextureLow = this._lodTextureLow;
  30070. }
  30071. var cache = this._engine.getLoadedTexturesCache();
  30072. var index = cache.indexOf(this);
  30073. if (index !== -1) {
  30074. cache.splice(index, 1);
  30075. }
  30076. };
  30077. /**
  30078. * Dispose the current allocated resources
  30079. */
  30080. InternalTexture.prototype.dispose = function () {
  30081. if (!this._webGLTexture) {
  30082. return;
  30083. }
  30084. this._references--;
  30085. if (this._references === 0) {
  30086. this._engine._releaseTexture(this);
  30087. this._webGLTexture = null;
  30088. this.previous = null;
  30089. this.next = null;
  30090. }
  30091. };
  30092. /**
  30093. * The source of the texture data is unknown
  30094. */
  30095. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30096. /**
  30097. * Texture data comes from an URL
  30098. */
  30099. InternalTexture.DATASOURCE_URL = 1;
  30100. /**
  30101. * Texture data is only used for temporary storage
  30102. */
  30103. InternalTexture.DATASOURCE_TEMP = 2;
  30104. /**
  30105. * Texture data comes from raw data (ArrayBuffer)
  30106. */
  30107. InternalTexture.DATASOURCE_RAW = 3;
  30108. /**
  30109. * Texture content is dynamic (video or dynamic texture)
  30110. */
  30111. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30112. /**
  30113. * Texture content is generated by rendering to it
  30114. */
  30115. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30116. /**
  30117. * Texture content is part of a multi render target process
  30118. */
  30119. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30120. /**
  30121. * Texture data comes from a cube data file
  30122. */
  30123. InternalTexture.DATASOURCE_CUBE = 7;
  30124. /**
  30125. * Texture data comes from a raw cube data
  30126. */
  30127. InternalTexture.DATASOURCE_CUBERAW = 8;
  30128. /**
  30129. * Texture data come from a prefiltered cube data file
  30130. */
  30131. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30132. /**
  30133. * Texture content is raw 3D data
  30134. */
  30135. InternalTexture.DATASOURCE_RAW3D = 10;
  30136. /**
  30137. * Texture content is a depth texture
  30138. */
  30139. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30140. return InternalTexture;
  30141. }());
  30142. BABYLON.InternalTexture = InternalTexture;
  30143. })(BABYLON || (BABYLON = {}));
  30144. //# sourceMappingURL=babylon.internalTexture.js.map
  30145. var BABYLON;
  30146. (function (BABYLON) {
  30147. var BaseTexture = /** @class */ (function () {
  30148. function BaseTexture(scene) {
  30149. this._hasAlpha = false;
  30150. this.getAlphaFromRGB = false;
  30151. this.level = 1;
  30152. this.coordinatesIndex = 0;
  30153. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30154. /**
  30155. * | Value | Type | Description |
  30156. * | ----- | ------------------ | ----------- |
  30157. * | 0 | CLAMP_ADDRESSMODE | |
  30158. * | 1 | WRAP_ADDRESSMODE | |
  30159. * | 2 | MIRROR_ADDRESSMODE | |
  30160. */
  30161. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30162. /**
  30163. * | Value | Type | Description |
  30164. * | ----- | ------------------ | ----------- |
  30165. * | 0 | CLAMP_ADDRESSMODE | |
  30166. * | 1 | WRAP_ADDRESSMODE | |
  30167. * | 2 | MIRROR_ADDRESSMODE | |
  30168. */
  30169. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30170. /**
  30171. * | Value | Type | Description |
  30172. * | ----- | ------------------ | ----------- |
  30173. * | 0 | CLAMP_ADDRESSMODE | |
  30174. * | 1 | WRAP_ADDRESSMODE | |
  30175. * | 2 | MIRROR_ADDRESSMODE | |
  30176. */
  30177. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30178. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30179. this.isCube = false;
  30180. this.is3D = false;
  30181. this.gammaSpace = true;
  30182. this.invertZ = false;
  30183. this.lodLevelInAlpha = false;
  30184. this.lodGenerationOffset = 0.0;
  30185. this.lodGenerationScale = 0.8;
  30186. this.isRenderTarget = false;
  30187. this.animations = new Array();
  30188. /**
  30189. * An event triggered when the texture is disposed.
  30190. */
  30191. this.onDisposeObservable = new BABYLON.Observable();
  30192. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30193. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30194. if (this._scene) {
  30195. this._scene.textures.push(this);
  30196. }
  30197. this._uid = null;
  30198. }
  30199. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30200. get: function () {
  30201. return this._hasAlpha;
  30202. },
  30203. set: function (value) {
  30204. if (this._hasAlpha === value) {
  30205. return;
  30206. }
  30207. this._hasAlpha = value;
  30208. if (this._scene) {
  30209. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30210. }
  30211. },
  30212. enumerable: true,
  30213. configurable: true
  30214. });
  30215. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30216. get: function () {
  30217. return this._coordinatesMode;
  30218. },
  30219. /**
  30220. * How a texture is mapped.
  30221. *
  30222. * | Value | Type | Description |
  30223. * | ----- | ----------------------------------- | ----------- |
  30224. * | 0 | EXPLICIT_MODE | |
  30225. * | 1 | SPHERICAL_MODE | |
  30226. * | 2 | PLANAR_MODE | |
  30227. * | 3 | CUBIC_MODE | |
  30228. * | 4 | PROJECTION_MODE | |
  30229. * | 5 | SKYBOX_MODE | |
  30230. * | 6 | INVCUBIC_MODE | |
  30231. * | 7 | EQUIRECTANGULAR_MODE | |
  30232. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30233. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30234. */
  30235. set: function (value) {
  30236. if (this._coordinatesMode === value) {
  30237. return;
  30238. }
  30239. this._coordinatesMode = value;
  30240. if (this._scene) {
  30241. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30242. }
  30243. },
  30244. enumerable: true,
  30245. configurable: true
  30246. });
  30247. Object.defineProperty(BaseTexture.prototype, "uid", {
  30248. get: function () {
  30249. if (!this._uid) {
  30250. this._uid = BABYLON.Tools.RandomId();
  30251. }
  30252. return this._uid;
  30253. },
  30254. enumerable: true,
  30255. configurable: true
  30256. });
  30257. BaseTexture.prototype.toString = function () {
  30258. return this.name;
  30259. };
  30260. BaseTexture.prototype.getClassName = function () {
  30261. return "BaseTexture";
  30262. };
  30263. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30264. set: function (callback) {
  30265. if (this._onDisposeObserver) {
  30266. this.onDisposeObservable.remove(this._onDisposeObserver);
  30267. }
  30268. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30269. },
  30270. enumerable: true,
  30271. configurable: true
  30272. });
  30273. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30274. get: function () {
  30275. return true;
  30276. },
  30277. enumerable: true,
  30278. configurable: true
  30279. });
  30280. BaseTexture.prototype.getScene = function () {
  30281. return this._scene;
  30282. };
  30283. BaseTexture.prototype.getTextureMatrix = function () {
  30284. return BABYLON.Matrix.IdentityReadOnly;
  30285. };
  30286. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30287. return BABYLON.Matrix.IdentityReadOnly;
  30288. };
  30289. BaseTexture.prototype.getInternalTexture = function () {
  30290. return this._texture;
  30291. };
  30292. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30293. return !this.isBlocking || this.isReady();
  30294. };
  30295. BaseTexture.prototype.isReady = function () {
  30296. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30297. this.delayLoad();
  30298. return false;
  30299. }
  30300. if (this._texture) {
  30301. return this._texture.isReady;
  30302. }
  30303. return false;
  30304. };
  30305. BaseTexture.prototype.getSize = function () {
  30306. if (this._texture && this._texture.width) {
  30307. return new BABYLON.Size(this._texture.width, this._texture.height);
  30308. }
  30309. if (this._texture && this._texture._size) {
  30310. return new BABYLON.Size(this._texture._size, this._texture._size);
  30311. }
  30312. return BABYLON.Size.Zero();
  30313. };
  30314. BaseTexture.prototype.getBaseSize = function () {
  30315. if (!this.isReady() || !this._texture)
  30316. return BABYLON.Size.Zero();
  30317. if (this._texture._size) {
  30318. return new BABYLON.Size(this._texture._size, this._texture._size);
  30319. }
  30320. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30321. };
  30322. BaseTexture.prototype.scale = function (ratio) {
  30323. };
  30324. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30325. get: function () {
  30326. return false;
  30327. },
  30328. enumerable: true,
  30329. configurable: true
  30330. });
  30331. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30332. if (!this._scene) {
  30333. return null;
  30334. }
  30335. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30336. for (var index = 0; index < texturesCache.length; index++) {
  30337. var texturesCacheEntry = texturesCache[index];
  30338. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30339. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30340. texturesCacheEntry.incrementReferences();
  30341. return texturesCacheEntry;
  30342. }
  30343. }
  30344. }
  30345. return null;
  30346. };
  30347. BaseTexture.prototype._rebuild = function () {
  30348. };
  30349. BaseTexture.prototype.delayLoad = function () {
  30350. };
  30351. BaseTexture.prototype.clone = function () {
  30352. return null;
  30353. };
  30354. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30355. get: function () {
  30356. if (!this._texture) {
  30357. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30358. }
  30359. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30360. },
  30361. enumerable: true,
  30362. configurable: true
  30363. });
  30364. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30365. get: function () {
  30366. if (!this._texture) {
  30367. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30368. }
  30369. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30370. },
  30371. enumerable: true,
  30372. configurable: true
  30373. });
  30374. BaseTexture.prototype.readPixels = function (faceIndex) {
  30375. if (faceIndex === void 0) { faceIndex = 0; }
  30376. if (!this._texture) {
  30377. return null;
  30378. }
  30379. var size = this.getSize();
  30380. var scene = this.getScene();
  30381. if (!scene) {
  30382. return null;
  30383. }
  30384. var engine = scene.getEngine();
  30385. if (this._texture.isCube) {
  30386. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30387. }
  30388. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30389. };
  30390. BaseTexture.prototype.releaseInternalTexture = function () {
  30391. if (this._texture) {
  30392. this._texture.dispose();
  30393. this._texture = null;
  30394. }
  30395. };
  30396. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30397. get: function () {
  30398. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30399. return null;
  30400. }
  30401. if (!this._texture._sphericalPolynomial) {
  30402. this._texture._sphericalPolynomial =
  30403. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30404. }
  30405. return this._texture._sphericalPolynomial;
  30406. },
  30407. set: function (value) {
  30408. if (this._texture) {
  30409. this._texture._sphericalPolynomial = value;
  30410. }
  30411. },
  30412. enumerable: true,
  30413. configurable: true
  30414. });
  30415. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30416. get: function () {
  30417. if (this._texture) {
  30418. return this._texture._lodTextureHigh;
  30419. }
  30420. return null;
  30421. },
  30422. enumerable: true,
  30423. configurable: true
  30424. });
  30425. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30426. get: function () {
  30427. if (this._texture) {
  30428. return this._texture._lodTextureMid;
  30429. }
  30430. return null;
  30431. },
  30432. enumerable: true,
  30433. configurable: true
  30434. });
  30435. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30436. get: function () {
  30437. if (this._texture) {
  30438. return this._texture._lodTextureLow;
  30439. }
  30440. return null;
  30441. },
  30442. enumerable: true,
  30443. configurable: true
  30444. });
  30445. BaseTexture.prototype.dispose = function () {
  30446. if (!this._scene) {
  30447. return;
  30448. }
  30449. // Animations
  30450. this._scene.stopAnimation(this);
  30451. // Remove from scene
  30452. this._scene._removePendingData(this);
  30453. var index = this._scene.textures.indexOf(this);
  30454. if (index >= 0) {
  30455. this._scene.textures.splice(index, 1);
  30456. }
  30457. if (this._texture === undefined) {
  30458. return;
  30459. }
  30460. // Release
  30461. this.releaseInternalTexture();
  30462. // Callback
  30463. this.onDisposeObservable.notifyObservers(this);
  30464. this.onDisposeObservable.clear();
  30465. };
  30466. BaseTexture.prototype.serialize = function () {
  30467. if (!this.name) {
  30468. return null;
  30469. }
  30470. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30471. // Animations
  30472. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30473. return serializationObject;
  30474. };
  30475. BaseTexture.WhenAllReady = function (textures, callback) {
  30476. var numRemaining = textures.length;
  30477. if (numRemaining === 0) {
  30478. callback();
  30479. return;
  30480. }
  30481. var _loop_1 = function () {
  30482. texture = textures[i];
  30483. if (texture.isReady()) {
  30484. if (--numRemaining === 0) {
  30485. callback();
  30486. }
  30487. }
  30488. else {
  30489. onLoadObservable = texture.onLoadObservable;
  30490. var onLoadCallback_1 = function () {
  30491. onLoadObservable.removeCallback(onLoadCallback_1);
  30492. if (--numRemaining === 0) {
  30493. callback();
  30494. }
  30495. };
  30496. onLoadObservable.add(onLoadCallback_1);
  30497. }
  30498. };
  30499. var texture, onLoadObservable;
  30500. for (var i = 0; i < textures.length; i++) {
  30501. _loop_1();
  30502. }
  30503. };
  30504. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30505. __decorate([
  30506. BABYLON.serialize()
  30507. ], BaseTexture.prototype, "name", void 0);
  30508. __decorate([
  30509. BABYLON.serialize("hasAlpha")
  30510. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30511. __decorate([
  30512. BABYLON.serialize()
  30513. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30514. __decorate([
  30515. BABYLON.serialize()
  30516. ], BaseTexture.prototype, "level", void 0);
  30517. __decorate([
  30518. BABYLON.serialize()
  30519. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30520. __decorate([
  30521. BABYLON.serialize("coordinatesMode")
  30522. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30523. __decorate([
  30524. BABYLON.serialize()
  30525. ], BaseTexture.prototype, "wrapU", void 0);
  30526. __decorate([
  30527. BABYLON.serialize()
  30528. ], BaseTexture.prototype, "wrapV", void 0);
  30529. __decorate([
  30530. BABYLON.serialize()
  30531. ], BaseTexture.prototype, "wrapR", void 0);
  30532. __decorate([
  30533. BABYLON.serialize()
  30534. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30535. __decorate([
  30536. BABYLON.serialize()
  30537. ], BaseTexture.prototype, "isCube", void 0);
  30538. __decorate([
  30539. BABYLON.serialize()
  30540. ], BaseTexture.prototype, "is3D", void 0);
  30541. __decorate([
  30542. BABYLON.serialize()
  30543. ], BaseTexture.prototype, "gammaSpace", void 0);
  30544. __decorate([
  30545. BABYLON.serialize()
  30546. ], BaseTexture.prototype, "invertZ", void 0);
  30547. __decorate([
  30548. BABYLON.serialize()
  30549. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30550. __decorate([
  30551. BABYLON.serialize()
  30552. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30553. __decorate([
  30554. BABYLON.serialize()
  30555. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30556. __decorate([
  30557. BABYLON.serialize()
  30558. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30559. return BaseTexture;
  30560. }());
  30561. BABYLON.BaseTexture = BaseTexture;
  30562. })(BABYLON || (BABYLON = {}));
  30563. //# sourceMappingURL=babylon.baseTexture.js.map
  30564. var BABYLON;
  30565. (function (BABYLON) {
  30566. var Texture = /** @class */ (function (_super) {
  30567. __extends(Texture, _super);
  30568. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30569. if (noMipmap === void 0) { noMipmap = false; }
  30570. if (invertY === void 0) { invertY = true; }
  30571. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30572. if (onLoad === void 0) { onLoad = null; }
  30573. if (onError === void 0) { onError = null; }
  30574. if (buffer === void 0) { buffer = null; }
  30575. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30576. var _this = _super.call(this, scene) || this;
  30577. _this.uOffset = 0;
  30578. _this.vOffset = 0;
  30579. _this.uScale = 1.0;
  30580. _this.vScale = 1.0;
  30581. _this.uAng = 0;
  30582. _this.vAng = 0;
  30583. _this.wAng = 0;
  30584. /**
  30585. * Defines the center of rotation (U)
  30586. */
  30587. _this.uRotationCenter = 0.5;
  30588. /**
  30589. * Defines the center of rotation (V)
  30590. */
  30591. _this.vRotationCenter = 0.5;
  30592. /**
  30593. * Defines the center of rotation (W)
  30594. */
  30595. _this.wRotationCenter = 0.5;
  30596. _this._isBlocking = true;
  30597. _this.name = url || "";
  30598. _this.url = url;
  30599. _this._noMipmap = noMipmap;
  30600. _this._invertY = invertY;
  30601. _this._samplingMode = samplingMode;
  30602. _this._buffer = buffer;
  30603. _this._deleteBuffer = deleteBuffer;
  30604. if (format) {
  30605. _this._format = format;
  30606. }
  30607. scene = _this.getScene();
  30608. if (!scene) {
  30609. return _this;
  30610. }
  30611. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30612. var load = function () {
  30613. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30614. _this.onLoadObservable.notifyObservers(_this);
  30615. }
  30616. if (onLoad) {
  30617. onLoad();
  30618. }
  30619. if (!_this.isBlocking && scene) {
  30620. scene.resetCachedMaterial();
  30621. }
  30622. };
  30623. if (!_this.url) {
  30624. _this._delayedOnLoad = load;
  30625. _this._delayedOnError = onError;
  30626. return _this;
  30627. }
  30628. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30629. if (!_this._texture) {
  30630. if (!scene.useDelayedTextureLoading) {
  30631. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30632. if (deleteBuffer) {
  30633. delete _this._buffer;
  30634. }
  30635. }
  30636. else {
  30637. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30638. _this._delayedOnLoad = load;
  30639. _this._delayedOnError = onError;
  30640. }
  30641. }
  30642. else {
  30643. if (_this._texture.isReady) {
  30644. BABYLON.Tools.SetImmediate(function () { return load(); });
  30645. }
  30646. else {
  30647. _this._texture.onLoadedObservable.add(load);
  30648. }
  30649. }
  30650. return _this;
  30651. }
  30652. Object.defineProperty(Texture.prototype, "noMipmap", {
  30653. get: function () {
  30654. return this._noMipmap;
  30655. },
  30656. enumerable: true,
  30657. configurable: true
  30658. });
  30659. Object.defineProperty(Texture.prototype, "isBlocking", {
  30660. get: function () {
  30661. return this._isBlocking;
  30662. },
  30663. set: function (value) {
  30664. this._isBlocking = value;
  30665. },
  30666. enumerable: true,
  30667. configurable: true
  30668. });
  30669. Object.defineProperty(Texture.prototype, "samplingMode", {
  30670. get: function () {
  30671. return this._samplingMode;
  30672. },
  30673. enumerable: true,
  30674. configurable: true
  30675. });
  30676. /**
  30677. * Update the url (and optional buffer) of this texture if url was null during construction.
  30678. * @param url the url of the texture
  30679. * @param buffer the buffer of the texture (defaults to null)
  30680. */
  30681. Texture.prototype.updateURL = function (url, buffer) {
  30682. if (buffer === void 0) { buffer = null; }
  30683. if (this.url) {
  30684. throw new Error("URL is already set");
  30685. }
  30686. this.url = url;
  30687. this._buffer = buffer;
  30688. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30689. this.delayLoad();
  30690. };
  30691. Texture.prototype.delayLoad = function () {
  30692. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30693. return;
  30694. }
  30695. var scene = this.getScene();
  30696. if (!scene) {
  30697. return;
  30698. }
  30699. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30700. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30701. if (!this._texture) {
  30702. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30703. if (this._deleteBuffer) {
  30704. delete this._buffer;
  30705. }
  30706. }
  30707. else {
  30708. if (this._delayedOnLoad) {
  30709. if (this._texture.isReady) {
  30710. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30711. }
  30712. else {
  30713. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30714. }
  30715. }
  30716. }
  30717. this._delayedOnLoad = null;
  30718. this._delayedOnError = null;
  30719. };
  30720. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30721. if (!this._texture) {
  30722. return;
  30723. }
  30724. var scene = this.getScene();
  30725. if (!scene) {
  30726. return;
  30727. }
  30728. this._samplingMode = samplingMode;
  30729. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30730. };
  30731. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30732. x *= this.uScale;
  30733. y *= this.vScale;
  30734. x -= this.uRotationCenter * this.uScale;
  30735. y -= this.vRotationCenter * this.vScale;
  30736. z -= this.wRotationCenter;
  30737. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30738. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30739. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30740. t.z += this.wRotationCenter;
  30741. };
  30742. Texture.prototype.getTextureMatrix = function () {
  30743. var _this = this;
  30744. if (this.uOffset === this._cachedUOffset &&
  30745. this.vOffset === this._cachedVOffset &&
  30746. this.uScale === this._cachedUScale &&
  30747. this.vScale === this._cachedVScale &&
  30748. this.uAng === this._cachedUAng &&
  30749. this.vAng === this._cachedVAng &&
  30750. this.wAng === this._cachedWAng) {
  30751. return this._cachedTextureMatrix;
  30752. }
  30753. this._cachedUOffset = this.uOffset;
  30754. this._cachedVOffset = this.vOffset;
  30755. this._cachedUScale = this.uScale;
  30756. this._cachedVScale = this.vScale;
  30757. this._cachedUAng = this.uAng;
  30758. this._cachedVAng = this.vAng;
  30759. this._cachedWAng = this.wAng;
  30760. if (!this._cachedTextureMatrix) {
  30761. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30762. this._rowGenerationMatrix = new BABYLON.Matrix();
  30763. this._t0 = BABYLON.Vector3.Zero();
  30764. this._t1 = BABYLON.Vector3.Zero();
  30765. this._t2 = BABYLON.Vector3.Zero();
  30766. }
  30767. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30768. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30769. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30770. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30771. this._t1.subtractInPlace(this._t0);
  30772. this._t2.subtractInPlace(this._t0);
  30773. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30774. this._cachedTextureMatrix.m[0] = this._t1.x;
  30775. this._cachedTextureMatrix.m[1] = this._t1.y;
  30776. this._cachedTextureMatrix.m[2] = this._t1.z;
  30777. this._cachedTextureMatrix.m[4] = this._t2.x;
  30778. this._cachedTextureMatrix.m[5] = this._t2.y;
  30779. this._cachedTextureMatrix.m[6] = this._t2.z;
  30780. this._cachedTextureMatrix.m[8] = this._t0.x;
  30781. this._cachedTextureMatrix.m[9] = this._t0.y;
  30782. this._cachedTextureMatrix.m[10] = this._t0.z;
  30783. var scene = this.getScene();
  30784. if (!scene) {
  30785. return this._cachedTextureMatrix;
  30786. }
  30787. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30788. return mat.hasTexture(_this);
  30789. });
  30790. return this._cachedTextureMatrix;
  30791. };
  30792. Texture.prototype.getReflectionTextureMatrix = function () {
  30793. var _this = this;
  30794. var scene = this.getScene();
  30795. if (!scene) {
  30796. return this._cachedTextureMatrix;
  30797. }
  30798. if (this.uOffset === this._cachedUOffset &&
  30799. this.vOffset === this._cachedVOffset &&
  30800. this.uScale === this._cachedUScale &&
  30801. this.vScale === this._cachedVScale &&
  30802. this.coordinatesMode === this._cachedCoordinatesMode) {
  30803. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30804. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30805. return this._cachedTextureMatrix;
  30806. }
  30807. }
  30808. else {
  30809. return this._cachedTextureMatrix;
  30810. }
  30811. }
  30812. if (!this._cachedTextureMatrix) {
  30813. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30814. }
  30815. if (!this._projectionModeMatrix) {
  30816. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30817. }
  30818. this._cachedUOffset = this.uOffset;
  30819. this._cachedVOffset = this.vOffset;
  30820. this._cachedUScale = this.uScale;
  30821. this._cachedVScale = this.vScale;
  30822. this._cachedCoordinatesMode = this.coordinatesMode;
  30823. switch (this.coordinatesMode) {
  30824. case Texture.PLANAR_MODE:
  30825. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30826. this._cachedTextureMatrix[0] = this.uScale;
  30827. this._cachedTextureMatrix[5] = this.vScale;
  30828. this._cachedTextureMatrix[12] = this.uOffset;
  30829. this._cachedTextureMatrix[13] = this.vOffset;
  30830. break;
  30831. case Texture.PROJECTION_MODE:
  30832. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30833. this._projectionModeMatrix.m[0] = 0.5;
  30834. this._projectionModeMatrix.m[5] = -0.5;
  30835. this._projectionModeMatrix.m[10] = 0.0;
  30836. this._projectionModeMatrix.m[12] = 0.5;
  30837. this._projectionModeMatrix.m[13] = 0.5;
  30838. this._projectionModeMatrix.m[14] = 1.0;
  30839. this._projectionModeMatrix.m[15] = 1.0;
  30840. var projectionMatrix = scene.getProjectionMatrix();
  30841. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30842. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30843. break;
  30844. default:
  30845. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30846. break;
  30847. }
  30848. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30849. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30850. });
  30851. return this._cachedTextureMatrix;
  30852. };
  30853. Texture.prototype.clone = function () {
  30854. var _this = this;
  30855. return BABYLON.SerializationHelper.Clone(function () {
  30856. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30857. }, this);
  30858. };
  30859. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30860. get: function () {
  30861. if (!this._onLoadObservable) {
  30862. this._onLoadObservable = new BABYLON.Observable();
  30863. }
  30864. return this._onLoadObservable;
  30865. },
  30866. enumerable: true,
  30867. configurable: true
  30868. });
  30869. Texture.prototype.serialize = function () {
  30870. var serializationObject = _super.prototype.serialize.call(this);
  30871. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30872. serializationObject.base64String = this._buffer;
  30873. serializationObject.name = serializationObject.name.replace("data:", "");
  30874. }
  30875. serializationObject.invertY = this._invertY;
  30876. serializationObject.samplingMode = this.samplingMode;
  30877. return serializationObject;
  30878. };
  30879. Texture.prototype.getClassName = function () {
  30880. return "Texture";
  30881. };
  30882. Texture.prototype.dispose = function () {
  30883. _super.prototype.dispose.call(this);
  30884. if (this.onLoadObservable) {
  30885. this.onLoadObservable.clear();
  30886. this._onLoadObservable = null;
  30887. }
  30888. this._delayedOnLoad = null;
  30889. this._delayedOnError = null;
  30890. };
  30891. // Statics
  30892. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30893. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30894. if (onLoad === void 0) { onLoad = null; }
  30895. if (onError === void 0) { onError = null; }
  30896. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30897. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30898. };
  30899. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30900. if (parsedTexture.customType) {
  30901. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30902. // Update Sampling Mode
  30903. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30904. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30905. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30906. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30907. }
  30908. }
  30909. return parsedCustomTexture;
  30910. }
  30911. if (parsedTexture.isCube) {
  30912. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30913. }
  30914. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30915. return null;
  30916. }
  30917. var texture = BABYLON.SerializationHelper.Parse(function () {
  30918. var generateMipMaps = true;
  30919. if (parsedTexture.noMipmap) {
  30920. generateMipMaps = false;
  30921. }
  30922. if (parsedTexture.mirrorPlane) {
  30923. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30924. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30925. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30926. return mirrorTexture;
  30927. }
  30928. else if (parsedTexture.isRenderTarget) {
  30929. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30930. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30931. return renderTargetTexture;
  30932. }
  30933. else {
  30934. var texture;
  30935. if (parsedTexture.base64String) {
  30936. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30937. }
  30938. else {
  30939. var url = rootUrl + parsedTexture.name;
  30940. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30941. url = parsedTexture.url;
  30942. }
  30943. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30944. }
  30945. return texture;
  30946. }
  30947. }, parsedTexture, scene);
  30948. // Update Sampling Mode
  30949. if (parsedTexture.samplingMode) {
  30950. var sampling = parsedTexture.samplingMode;
  30951. if (texture._samplingMode !== sampling) {
  30952. texture.updateSamplingMode(sampling);
  30953. }
  30954. }
  30955. // Animations
  30956. if (parsedTexture.animations) {
  30957. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30958. var parsedAnimation = parsedTexture.animations[animationIndex];
  30959. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30960. }
  30961. }
  30962. return texture;
  30963. };
  30964. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30965. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30966. if (noMipmap === void 0) { noMipmap = false; }
  30967. if (invertY === void 0) { invertY = true; }
  30968. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30969. if (onLoad === void 0) { onLoad = null; }
  30970. if (onError === void 0) { onError = null; }
  30971. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30972. if (name.substr(0, 5) !== "data:") {
  30973. name = "data:" + name;
  30974. }
  30975. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30976. };
  30977. // Constants
  30978. Texture.NEAREST_SAMPLINGMODE = 1;
  30979. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30980. Texture.BILINEAR_SAMPLINGMODE = 2;
  30981. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30982. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30983. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30984. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30985. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30986. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30987. Texture.NEAREST_LINEAR = 7;
  30988. Texture.NEAREST_NEAREST = 8;
  30989. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30990. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30991. Texture.LINEAR_LINEAR = 11;
  30992. Texture.LINEAR_NEAREST = 12;
  30993. Texture.EXPLICIT_MODE = 0;
  30994. Texture.SPHERICAL_MODE = 1;
  30995. Texture.PLANAR_MODE = 2;
  30996. Texture.CUBIC_MODE = 3;
  30997. Texture.PROJECTION_MODE = 4;
  30998. Texture.SKYBOX_MODE = 5;
  30999. Texture.INVCUBIC_MODE = 6;
  31000. Texture.EQUIRECTANGULAR_MODE = 7;
  31001. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31002. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31003. Texture.CLAMP_ADDRESSMODE = 0;
  31004. Texture.WRAP_ADDRESSMODE = 1;
  31005. Texture.MIRROR_ADDRESSMODE = 2;
  31006. /**
  31007. * 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
  31008. */
  31009. Texture.UseSerializedUrlIfAny = false;
  31010. __decorate([
  31011. BABYLON.serialize()
  31012. ], Texture.prototype, "url", void 0);
  31013. __decorate([
  31014. BABYLON.serialize()
  31015. ], Texture.prototype, "uOffset", void 0);
  31016. __decorate([
  31017. BABYLON.serialize()
  31018. ], Texture.prototype, "vOffset", void 0);
  31019. __decorate([
  31020. BABYLON.serialize()
  31021. ], Texture.prototype, "uScale", void 0);
  31022. __decorate([
  31023. BABYLON.serialize()
  31024. ], Texture.prototype, "vScale", void 0);
  31025. __decorate([
  31026. BABYLON.serialize()
  31027. ], Texture.prototype, "uAng", void 0);
  31028. __decorate([
  31029. BABYLON.serialize()
  31030. ], Texture.prototype, "vAng", void 0);
  31031. __decorate([
  31032. BABYLON.serialize()
  31033. ], Texture.prototype, "wAng", void 0);
  31034. __decorate([
  31035. BABYLON.serialize()
  31036. ], Texture.prototype, "uRotationCenter", void 0);
  31037. __decorate([
  31038. BABYLON.serialize()
  31039. ], Texture.prototype, "vRotationCenter", void 0);
  31040. __decorate([
  31041. BABYLON.serialize()
  31042. ], Texture.prototype, "wRotationCenter", void 0);
  31043. __decorate([
  31044. BABYLON.serialize()
  31045. ], Texture.prototype, "isBlocking", null);
  31046. return Texture;
  31047. }(BABYLON.BaseTexture));
  31048. BABYLON.Texture = Texture;
  31049. })(BABYLON || (BABYLON = {}));
  31050. //# sourceMappingURL=babylon.texture.js.map
  31051. var BABYLON;
  31052. (function (BABYLON) {
  31053. /**
  31054. * @hidden
  31055. **/
  31056. var _InstancesBatch = /** @class */ (function () {
  31057. function _InstancesBatch() {
  31058. this.mustReturn = false;
  31059. this.visibleInstances = new Array();
  31060. this.renderSelf = new Array();
  31061. }
  31062. return _InstancesBatch;
  31063. }());
  31064. BABYLON._InstancesBatch = _InstancesBatch;
  31065. var Mesh = /** @class */ (function (_super) {
  31066. __extends(Mesh, _super);
  31067. /**
  31068. * @constructor
  31069. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31070. * @param {Scene} scene The scene to add this mesh to.
  31071. * @param {Node} parent The parent of this mesh, if it has one
  31072. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31073. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31074. * When false, achieved by calling a clone(), also passing False.
  31075. * This will make creation of children, recursive.
  31076. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31077. */
  31078. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31079. if (scene === void 0) { scene = null; }
  31080. if (parent === void 0) { parent = null; }
  31081. if (source === void 0) { source = null; }
  31082. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31083. var _this = _super.call(this, name, scene) || this;
  31084. // Events
  31085. /**
  31086. * An event triggered before rendering the mesh
  31087. */
  31088. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31089. /**
  31090. * An event triggered after rendering the mesh
  31091. */
  31092. _this.onAfterRenderObservable = new BABYLON.Observable();
  31093. /**
  31094. * An event triggered before drawing the mesh
  31095. */
  31096. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31097. // Members
  31098. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31099. _this.instances = new Array();
  31100. _this._LODLevels = new Array();
  31101. _this._visibleInstances = {};
  31102. _this._renderIdForInstances = new Array();
  31103. _this._batchCache = new _InstancesBatch();
  31104. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31105. // Use by builder only to know what orientation were the mesh build in.
  31106. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31107. _this.overrideMaterialSideOrientation = null;
  31108. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31109. // Will be used to save a source mesh reference, If any
  31110. _this._source = null;
  31111. scene = _this.getScene();
  31112. if (source) {
  31113. // Geometry
  31114. if (source._geometry) {
  31115. source._geometry.applyToMesh(_this);
  31116. }
  31117. // Deep copy
  31118. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31119. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31120. // Source mesh
  31121. _this._source = source;
  31122. // Metadata
  31123. if (source.metadata && source.metadata.clone) {
  31124. _this.metadata = source.metadata.clone();
  31125. }
  31126. else {
  31127. _this.metadata = source.metadata;
  31128. }
  31129. // Tags
  31130. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31131. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31132. }
  31133. // Parent
  31134. _this.parent = source.parent;
  31135. // Pivot
  31136. _this.setPivotMatrix(source.getPivotMatrix());
  31137. _this.id = name + "." + source.id;
  31138. // Material
  31139. _this.material = source.material;
  31140. var index;
  31141. if (!doNotCloneChildren) {
  31142. // Children
  31143. var directDescendants = source.getDescendants(true);
  31144. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31145. var child = directDescendants[index_1];
  31146. if (child.clone) {
  31147. child.clone(name + "." + child.name, _this);
  31148. }
  31149. }
  31150. }
  31151. // Physics clone
  31152. var physicsEngine = _this.getScene().getPhysicsEngine();
  31153. if (clonePhysicsImpostor && physicsEngine) {
  31154. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31155. if (impostor) {
  31156. _this.physicsImpostor = impostor.clone(_this);
  31157. }
  31158. }
  31159. // Particles
  31160. for (index = 0; index < scene.particleSystems.length; index++) {
  31161. var system = scene.particleSystems[index];
  31162. if (system.emitter === source) {
  31163. system.clone(system.name, _this);
  31164. }
  31165. }
  31166. _this.computeWorldMatrix(true);
  31167. }
  31168. // Parent
  31169. if (parent !== null) {
  31170. _this.parent = parent;
  31171. }
  31172. return _this;
  31173. }
  31174. Object.defineProperty(Mesh, "FRONTSIDE", {
  31175. /**
  31176. * Mesh side orientation : usually the external or front surface
  31177. */
  31178. get: function () {
  31179. return Mesh._FRONTSIDE;
  31180. },
  31181. enumerable: true,
  31182. configurable: true
  31183. });
  31184. Object.defineProperty(Mesh, "BACKSIDE", {
  31185. /**
  31186. * Mesh side orientation : usually the internal or back surface
  31187. */
  31188. get: function () {
  31189. return Mesh._BACKSIDE;
  31190. },
  31191. enumerable: true,
  31192. configurable: true
  31193. });
  31194. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31195. /**
  31196. * Mesh side orientation : both internal and external or front and back surfaces
  31197. */
  31198. get: function () {
  31199. return Mesh._DOUBLESIDE;
  31200. },
  31201. enumerable: true,
  31202. configurable: true
  31203. });
  31204. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31205. /**
  31206. * Mesh side orientation : by default, `FRONTSIDE`
  31207. */
  31208. get: function () {
  31209. return Mesh._DEFAULTSIDE;
  31210. },
  31211. enumerable: true,
  31212. configurable: true
  31213. });
  31214. Object.defineProperty(Mesh, "NO_CAP", {
  31215. /**
  31216. * Mesh cap setting : no cap
  31217. */
  31218. get: function () {
  31219. return Mesh._NO_CAP;
  31220. },
  31221. enumerable: true,
  31222. configurable: true
  31223. });
  31224. Object.defineProperty(Mesh, "CAP_START", {
  31225. /**
  31226. * Mesh cap setting : one cap at the beginning of the mesh
  31227. */
  31228. get: function () {
  31229. return Mesh._CAP_START;
  31230. },
  31231. enumerable: true,
  31232. configurable: true
  31233. });
  31234. Object.defineProperty(Mesh, "CAP_END", {
  31235. /**
  31236. * Mesh cap setting : one cap at the end of the mesh
  31237. */
  31238. get: function () {
  31239. return Mesh._CAP_END;
  31240. },
  31241. enumerable: true,
  31242. configurable: true
  31243. });
  31244. Object.defineProperty(Mesh, "CAP_ALL", {
  31245. /**
  31246. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31247. */
  31248. get: function () {
  31249. return Mesh._CAP_ALL;
  31250. },
  31251. enumerable: true,
  31252. configurable: true
  31253. });
  31254. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31255. set: function (callback) {
  31256. if (this._onBeforeDrawObserver) {
  31257. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31258. }
  31259. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31260. },
  31261. enumerable: true,
  31262. configurable: true
  31263. });
  31264. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31265. get: function () {
  31266. return this._morphTargetManager;
  31267. },
  31268. set: function (value) {
  31269. if (this._morphTargetManager === value) {
  31270. return;
  31271. }
  31272. this._morphTargetManager = value;
  31273. this._syncGeometryWithMorphTargetManager();
  31274. },
  31275. enumerable: true,
  31276. configurable: true
  31277. });
  31278. Object.defineProperty(Mesh.prototype, "source", {
  31279. get: function () {
  31280. return this._source;
  31281. },
  31282. enumerable: true,
  31283. configurable: true
  31284. });
  31285. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31286. get: function () {
  31287. return this._unIndexed;
  31288. },
  31289. set: function (value) {
  31290. if (this._unIndexed !== value) {
  31291. this._unIndexed = value;
  31292. this._markSubMeshesAsAttributesDirty();
  31293. }
  31294. },
  31295. enumerable: true,
  31296. configurable: true
  31297. });
  31298. // Methods
  31299. /**
  31300. * Returns the string "Mesh".
  31301. */
  31302. Mesh.prototype.getClassName = function () {
  31303. return "Mesh";
  31304. };
  31305. /**
  31306. * Returns a string.
  31307. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31308. */
  31309. Mesh.prototype.toString = function (fullDetails) {
  31310. var ret = _super.prototype.toString.call(this, fullDetails);
  31311. ret += ", n vertices: " + this.getTotalVertices();
  31312. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31313. if (this.animations) {
  31314. for (var i = 0; i < this.animations.length; i++) {
  31315. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31316. }
  31317. }
  31318. if (fullDetails) {
  31319. if (this._geometry) {
  31320. var ib = this.getIndices();
  31321. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31322. if (vb && ib) {
  31323. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31324. }
  31325. }
  31326. else {
  31327. ret += ", flat shading: UNKNOWN";
  31328. }
  31329. }
  31330. return ret;
  31331. };
  31332. Mesh.prototype._unBindEffect = function () {
  31333. _super.prototype._unBindEffect.call(this);
  31334. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31335. var instance = _a[_i];
  31336. instance._unBindEffect();
  31337. }
  31338. };
  31339. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31340. /**
  31341. * True if the mesh has some Levels Of Details (LOD).
  31342. * Returns a boolean.
  31343. */
  31344. get: function () {
  31345. return this._LODLevels.length > 0;
  31346. },
  31347. enumerable: true,
  31348. configurable: true
  31349. });
  31350. /**
  31351. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31352. * @returns an array of {BABYLON.MeshLODLevel}
  31353. */
  31354. Mesh.prototype.getLODLevels = function () {
  31355. return this._LODLevels;
  31356. };
  31357. Mesh.prototype._sortLODLevels = function () {
  31358. this._LODLevels.sort(function (a, b) {
  31359. if (a.distance < b.distance) {
  31360. return 1;
  31361. }
  31362. if (a.distance > b.distance) {
  31363. return -1;
  31364. }
  31365. return 0;
  31366. });
  31367. };
  31368. /**
  31369. * Add a mesh as LOD level triggered at the given distance.
  31370. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31371. * @param {number} distance The distance from the center of the object to show this level
  31372. * @param {Mesh} mesh The mesh to be added as LOD level
  31373. * @return {Mesh} This mesh (for chaining)
  31374. */
  31375. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31376. if (mesh && mesh._masterMesh) {
  31377. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31378. return this;
  31379. }
  31380. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31381. this._LODLevels.push(level);
  31382. if (mesh) {
  31383. mesh._masterMesh = this;
  31384. }
  31385. this._sortLODLevels();
  31386. return this;
  31387. };
  31388. /**
  31389. * Returns the LOD level mesh at the passed distance or null if not found.
  31390. * It is related to the method `addLODLevel(distance, mesh)`.
  31391. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31392. * Returns an object Mesh or `null`.
  31393. */
  31394. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31395. for (var index = 0; index < this._LODLevels.length; index++) {
  31396. var level = this._LODLevels[index];
  31397. if (level.distance === distance) {
  31398. return level.mesh;
  31399. }
  31400. }
  31401. return null;
  31402. };
  31403. /**
  31404. * Remove a mesh from the LOD array
  31405. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31406. * @param {Mesh} mesh The mesh to be removed.
  31407. * @return {Mesh} This mesh (for chaining)
  31408. */
  31409. Mesh.prototype.removeLODLevel = function (mesh) {
  31410. for (var index = 0; index < this._LODLevels.length; index++) {
  31411. if (this._LODLevels[index].mesh === mesh) {
  31412. this._LODLevels.splice(index, 1);
  31413. if (mesh) {
  31414. mesh._masterMesh = null;
  31415. }
  31416. }
  31417. }
  31418. this._sortLODLevels();
  31419. return this;
  31420. };
  31421. /**
  31422. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31423. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31424. */
  31425. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31426. if (!this._LODLevels || this._LODLevels.length === 0) {
  31427. return this;
  31428. }
  31429. var bSphere;
  31430. if (boundingSphere) {
  31431. bSphere = boundingSphere;
  31432. }
  31433. else {
  31434. var boundingInfo = this.getBoundingInfo();
  31435. bSphere = boundingInfo.boundingSphere;
  31436. }
  31437. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31438. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31439. if (this.onLODLevelSelection) {
  31440. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31441. }
  31442. return this;
  31443. }
  31444. for (var index = 0; index < this._LODLevels.length; index++) {
  31445. var level = this._LODLevels[index];
  31446. if (level.distance < distanceToCamera) {
  31447. if (level.mesh) {
  31448. level.mesh._preActivate();
  31449. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31450. }
  31451. if (this.onLODLevelSelection) {
  31452. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31453. }
  31454. return level.mesh;
  31455. }
  31456. }
  31457. if (this.onLODLevelSelection) {
  31458. this.onLODLevelSelection(distanceToCamera, this, this);
  31459. }
  31460. return this;
  31461. };
  31462. Object.defineProperty(Mesh.prototype, "geometry", {
  31463. /**
  31464. * Returns the mesh internal Geometry object.
  31465. */
  31466. get: function () {
  31467. return this._geometry;
  31468. },
  31469. enumerable: true,
  31470. configurable: true
  31471. });
  31472. /**
  31473. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31474. */
  31475. Mesh.prototype.getTotalVertices = function () {
  31476. if (this._geometry === null || this._geometry === undefined) {
  31477. return 0;
  31478. }
  31479. return this._geometry.getTotalVertices();
  31480. };
  31481. /**
  31482. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31483. * 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.
  31484. * You can force the copy with forceCopy === true
  31485. * Returns null if the mesh has no geometry or no vertex buffer.
  31486. * Possible `kind` values :
  31487. * - BABYLON.VertexBuffer.PositionKind
  31488. * - BABYLON.VertexBuffer.UVKind
  31489. * - BABYLON.VertexBuffer.UV2Kind
  31490. * - BABYLON.VertexBuffer.UV3Kind
  31491. * - BABYLON.VertexBuffer.UV4Kind
  31492. * - BABYLON.VertexBuffer.UV5Kind
  31493. * - BABYLON.VertexBuffer.UV6Kind
  31494. * - BABYLON.VertexBuffer.ColorKind
  31495. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31496. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31497. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31498. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31499. */
  31500. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31501. if (!this._geometry) {
  31502. return null;
  31503. }
  31504. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31505. };
  31506. /**
  31507. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31508. * Returns `null` if the mesh has no geometry.
  31509. * Possible `kind` values :
  31510. * - BABYLON.VertexBuffer.PositionKind
  31511. * - BABYLON.VertexBuffer.UVKind
  31512. * - BABYLON.VertexBuffer.UV2Kind
  31513. * - BABYLON.VertexBuffer.UV3Kind
  31514. * - BABYLON.VertexBuffer.UV4Kind
  31515. * - BABYLON.VertexBuffer.UV5Kind
  31516. * - BABYLON.VertexBuffer.UV6Kind
  31517. * - BABYLON.VertexBuffer.ColorKind
  31518. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31519. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31520. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31521. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31522. */
  31523. Mesh.prototype.getVertexBuffer = function (kind) {
  31524. if (!this._geometry) {
  31525. return null;
  31526. }
  31527. return this._geometry.getVertexBuffer(kind);
  31528. };
  31529. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31530. if (!this._geometry) {
  31531. if (this._delayInfo) {
  31532. return this._delayInfo.indexOf(kind) !== -1;
  31533. }
  31534. return false;
  31535. }
  31536. return this._geometry.isVerticesDataPresent(kind);
  31537. };
  31538. /**
  31539. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31540. * Possible `kind` values :
  31541. * - BABYLON.VertexBuffer.PositionKind
  31542. * - BABYLON.VertexBuffer.UVKind
  31543. * - BABYLON.VertexBuffer.UV2Kind
  31544. * - BABYLON.VertexBuffer.UV3Kind
  31545. * - BABYLON.VertexBuffer.UV4Kind
  31546. * - BABYLON.VertexBuffer.UV5Kind
  31547. * - BABYLON.VertexBuffer.UV6Kind
  31548. * - BABYLON.VertexBuffer.ColorKind
  31549. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31550. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31551. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31552. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31553. */
  31554. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31555. if (!this._geometry) {
  31556. if (this._delayInfo) {
  31557. return this._delayInfo.indexOf(kind) !== -1;
  31558. }
  31559. return false;
  31560. }
  31561. return this._geometry.isVertexBufferUpdatable(kind);
  31562. };
  31563. /**
  31564. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31565. * Possible `kind` values :
  31566. * - BABYLON.VertexBuffer.PositionKind
  31567. * - BABYLON.VertexBuffer.UVKind
  31568. * - BABYLON.VertexBuffer.UV2Kind
  31569. * - BABYLON.VertexBuffer.UV3Kind
  31570. * - BABYLON.VertexBuffer.UV4Kind
  31571. * - BABYLON.VertexBuffer.UV5Kind
  31572. * - BABYLON.VertexBuffer.UV6Kind
  31573. * - BABYLON.VertexBuffer.ColorKind
  31574. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31575. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31576. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31577. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31578. */
  31579. Mesh.prototype.getVerticesDataKinds = function () {
  31580. if (!this._geometry) {
  31581. var result = new Array();
  31582. if (this._delayInfo) {
  31583. this._delayInfo.forEach(function (kind, index, array) {
  31584. result.push(kind);
  31585. });
  31586. }
  31587. return result;
  31588. }
  31589. return this._geometry.getVerticesDataKinds();
  31590. };
  31591. /**
  31592. * Returns a positive integer : the total number of indices in this mesh geometry.
  31593. * Returns zero if the mesh has no geometry.
  31594. */
  31595. Mesh.prototype.getTotalIndices = function () {
  31596. if (!this._geometry) {
  31597. return 0;
  31598. }
  31599. return this._geometry.getTotalIndices();
  31600. };
  31601. /**
  31602. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31603. * 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.
  31604. * Returns an empty array if the mesh has no geometry.
  31605. */
  31606. Mesh.prototype.getIndices = function (copyWhenShared) {
  31607. if (!this._geometry) {
  31608. return [];
  31609. }
  31610. return this._geometry.getIndices(copyWhenShared);
  31611. };
  31612. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31613. get: function () {
  31614. return this._masterMesh !== null && this._masterMesh !== undefined;
  31615. },
  31616. enumerable: true,
  31617. configurable: true
  31618. });
  31619. /**
  31620. * Determine if the current mesh is ready to be rendered
  31621. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31622. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31623. * @returns true if all associated assets are ready (material, textures, shaders)
  31624. */
  31625. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31626. if (completeCheck === void 0) { completeCheck = false; }
  31627. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31628. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31629. return false;
  31630. }
  31631. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31632. return false;
  31633. }
  31634. if (!this.subMeshes || this.subMeshes.length === 0) {
  31635. return true;
  31636. }
  31637. if (!completeCheck) {
  31638. return true;
  31639. }
  31640. var engine = this.getEngine();
  31641. var scene = this.getScene();
  31642. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31643. this.computeWorldMatrix();
  31644. var mat = this.material || scene.defaultMaterial;
  31645. if (mat) {
  31646. if (mat.storeEffectOnSubMeshes) {
  31647. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31648. var subMesh = _a[_i];
  31649. var effectiveMaterial = subMesh.getMaterial();
  31650. if (effectiveMaterial) {
  31651. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31652. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31653. return false;
  31654. }
  31655. }
  31656. else {
  31657. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31658. return false;
  31659. }
  31660. }
  31661. }
  31662. }
  31663. }
  31664. else {
  31665. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31666. return false;
  31667. }
  31668. }
  31669. }
  31670. // Shadows
  31671. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31672. var light = _c[_b];
  31673. var generator = light.getShadowGenerator();
  31674. if (generator) {
  31675. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31676. var subMesh = _e[_d];
  31677. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31678. return false;
  31679. }
  31680. }
  31681. }
  31682. }
  31683. // LOD
  31684. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31685. var lod = _g[_f];
  31686. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31687. return false;
  31688. }
  31689. }
  31690. return true;
  31691. };
  31692. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31693. /**
  31694. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31695. * This property is pertinent only for updatable parametric shapes.
  31696. */
  31697. get: function () {
  31698. return this._areNormalsFrozen;
  31699. },
  31700. enumerable: true,
  31701. configurable: true
  31702. });
  31703. /**
  31704. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31705. * It has no effect at all on other shapes.
  31706. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31707. * Returns the Mesh.
  31708. */
  31709. Mesh.prototype.freezeNormals = function () {
  31710. this._areNormalsFrozen = true;
  31711. return this;
  31712. };
  31713. /**
  31714. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31715. * It has no effect at all on other shapes.
  31716. * It reactivates the mesh normals computation if it was previously frozen.
  31717. * Returns the Mesh.
  31718. */
  31719. Mesh.prototype.unfreezeNormals = function () {
  31720. this._areNormalsFrozen = false;
  31721. return this;
  31722. };
  31723. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31724. /**
  31725. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31726. */
  31727. set: function (count) {
  31728. this._overridenInstanceCount = count;
  31729. },
  31730. enumerable: true,
  31731. configurable: true
  31732. });
  31733. // Methods
  31734. Mesh.prototype._preActivate = function () {
  31735. var sceneRenderId = this.getScene().getRenderId();
  31736. if (this._preActivateId === sceneRenderId) {
  31737. return this;
  31738. }
  31739. this._preActivateId = sceneRenderId;
  31740. this._visibleInstances = null;
  31741. return this;
  31742. };
  31743. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31744. if (this._visibleInstances) {
  31745. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31746. }
  31747. return this;
  31748. };
  31749. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31750. if (!this._visibleInstances) {
  31751. this._visibleInstances = {};
  31752. this._visibleInstances.defaultRenderId = renderId;
  31753. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31754. }
  31755. if (!this._visibleInstances[renderId]) {
  31756. this._visibleInstances[renderId] = new Array();
  31757. }
  31758. this._visibleInstances[renderId].push(instance);
  31759. return this;
  31760. };
  31761. /**
  31762. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31763. * This means the mesh underlying bounding box and sphere are recomputed.
  31764. * Returns the Mesh.
  31765. */
  31766. Mesh.prototype.refreshBoundingInfo = function () {
  31767. return this._refreshBoundingInfo(false);
  31768. };
  31769. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31770. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31771. return this;
  31772. }
  31773. var data = this._getPositionData(applySkeleton);
  31774. if (data) {
  31775. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31776. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31777. }
  31778. if (this.subMeshes) {
  31779. for (var index = 0; index < this.subMeshes.length; index++) {
  31780. this.subMeshes[index].refreshBoundingInfo();
  31781. }
  31782. }
  31783. this._updateBoundingInfo();
  31784. return this;
  31785. };
  31786. Mesh.prototype._getPositionData = function (applySkeleton) {
  31787. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31788. if (data && applySkeleton && this.skeleton) {
  31789. data = BABYLON.Tools.Slice(data);
  31790. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31791. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31792. if (matricesWeightsData && matricesIndicesData) {
  31793. var needExtras = this.numBoneInfluencers > 4;
  31794. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31795. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31796. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31797. var tempVector = BABYLON.Tmp.Vector3[0];
  31798. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31799. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31800. var matWeightIdx = 0;
  31801. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31802. finalMatrix.reset();
  31803. var inf;
  31804. var weight;
  31805. for (inf = 0; inf < 4; inf++) {
  31806. weight = matricesWeightsData[matWeightIdx + inf];
  31807. if (weight <= 0)
  31808. break;
  31809. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31810. finalMatrix.addToSelf(tempMatrix);
  31811. }
  31812. if (needExtras) {
  31813. for (inf = 0; inf < 4; inf++) {
  31814. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31815. if (weight <= 0)
  31816. break;
  31817. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31818. finalMatrix.addToSelf(tempMatrix);
  31819. }
  31820. }
  31821. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31822. tempVector.toArray(data, index);
  31823. }
  31824. }
  31825. }
  31826. return data;
  31827. };
  31828. Mesh.prototype._createGlobalSubMesh = function (force) {
  31829. var totalVertices = this.getTotalVertices();
  31830. if (!totalVertices || !this.getIndices()) {
  31831. return null;
  31832. }
  31833. // Check if we need to recreate the submeshes
  31834. if (this.subMeshes && this.subMeshes.length > 0) {
  31835. var ib = this.getIndices();
  31836. if (!ib) {
  31837. return null;
  31838. }
  31839. var totalIndices = ib.length;
  31840. var needToRecreate = false;
  31841. if (force) {
  31842. needToRecreate = true;
  31843. }
  31844. else {
  31845. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31846. var submesh = _a[_i];
  31847. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31848. needToRecreate = true;
  31849. break;
  31850. }
  31851. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31852. needToRecreate = true;
  31853. break;
  31854. }
  31855. }
  31856. }
  31857. if (!needToRecreate) {
  31858. return this.subMeshes[0];
  31859. }
  31860. }
  31861. this.releaseSubMeshes();
  31862. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31863. };
  31864. Mesh.prototype.subdivide = function (count) {
  31865. if (count < 1) {
  31866. return;
  31867. }
  31868. var totalIndices = this.getTotalIndices();
  31869. var subdivisionSize = (totalIndices / count) | 0;
  31870. var offset = 0;
  31871. // Ensure that subdivisionSize is a multiple of 3
  31872. while (subdivisionSize % 3 !== 0) {
  31873. subdivisionSize++;
  31874. }
  31875. this.releaseSubMeshes();
  31876. for (var index = 0; index < count; index++) {
  31877. if (offset >= totalIndices) {
  31878. break;
  31879. }
  31880. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31881. offset += subdivisionSize;
  31882. }
  31883. this.synchronizeInstances();
  31884. };
  31885. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31886. if (updatable === void 0) { updatable = false; }
  31887. if (!this._geometry) {
  31888. var vertexData = new BABYLON.VertexData();
  31889. vertexData.set(data, kind);
  31890. var scene = this.getScene();
  31891. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31892. }
  31893. else {
  31894. this._geometry.setVerticesData(kind, data, updatable, stride);
  31895. }
  31896. return this;
  31897. };
  31898. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31899. if (updatable === void 0) { updatable = true; }
  31900. var vb = this.getVertexBuffer(kind);
  31901. if (!vb || vb.isUpdatable() === updatable) {
  31902. return;
  31903. }
  31904. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31905. };
  31906. /**
  31907. * Sets the mesh VertexBuffer.
  31908. * Returns the Mesh.
  31909. */
  31910. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31911. if (!this._geometry) {
  31912. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31913. }
  31914. this._geometry.setVerticesBuffer(buffer);
  31915. return this;
  31916. };
  31917. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31918. if (!this._geometry) {
  31919. return this;
  31920. }
  31921. if (!makeItUnique) {
  31922. this._geometry.updateVerticesData(kind, data, updateExtends);
  31923. }
  31924. else {
  31925. this.makeGeometryUnique();
  31926. this.updateVerticesData(kind, data, updateExtends, false);
  31927. }
  31928. return this;
  31929. };
  31930. /**
  31931. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31932. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31933. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31934. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31935. * Returns the Mesh.
  31936. */
  31937. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31938. if (computeNormals === void 0) { computeNormals = true; }
  31939. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31940. if (!positions) {
  31941. return this;
  31942. }
  31943. positionFunction(positions);
  31944. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31945. if (computeNormals) {
  31946. var indices = this.getIndices();
  31947. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31948. if (!normals) {
  31949. return this;
  31950. }
  31951. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31952. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31953. }
  31954. return this;
  31955. };
  31956. /**
  31957. * Creates a un-shared specific occurence of the geometry for the mesh.
  31958. * Returns the Mesh.
  31959. */
  31960. Mesh.prototype.makeGeometryUnique = function () {
  31961. if (!this._geometry) {
  31962. return this;
  31963. }
  31964. var oldGeometry = this._geometry;
  31965. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31966. oldGeometry.releaseForMesh(this, true);
  31967. geometry.applyToMesh(this);
  31968. return this;
  31969. };
  31970. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31971. if (totalVertices === void 0) { totalVertices = null; }
  31972. if (updatable === void 0) { updatable = false; }
  31973. if (!this._geometry) {
  31974. var vertexData = new BABYLON.VertexData();
  31975. vertexData.indices = indices;
  31976. var scene = this.getScene();
  31977. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31978. }
  31979. else {
  31980. this._geometry.setIndices(indices, totalVertices, updatable);
  31981. }
  31982. return this;
  31983. };
  31984. /**
  31985. * Update the current index buffer
  31986. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31987. * Returns the Mesh.
  31988. */
  31989. Mesh.prototype.updateIndices = function (indices, offset) {
  31990. if (!this._geometry) {
  31991. return this;
  31992. }
  31993. this._geometry.updateIndices(indices, offset);
  31994. return this;
  31995. };
  31996. /**
  31997. * Invert the geometry to move from a right handed system to a left handed one.
  31998. * Returns the Mesh.
  31999. */
  32000. Mesh.prototype.toLeftHanded = function () {
  32001. if (!this._geometry) {
  32002. return this;
  32003. }
  32004. this._geometry.toLeftHanded();
  32005. return this;
  32006. };
  32007. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32008. if (!this._geometry) {
  32009. return this;
  32010. }
  32011. var engine = this.getScene().getEngine();
  32012. // Wireframe
  32013. var indexToBind;
  32014. if (this._unIndexed) {
  32015. indexToBind = null;
  32016. }
  32017. else {
  32018. switch (fillMode) {
  32019. case BABYLON.Material.PointFillMode:
  32020. indexToBind = null;
  32021. break;
  32022. case BABYLON.Material.WireFrameFillMode:
  32023. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32024. break;
  32025. default:
  32026. case BABYLON.Material.TriangleFillMode:
  32027. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32028. break;
  32029. }
  32030. }
  32031. // VBOs
  32032. this._geometry._bind(effect, indexToBind);
  32033. return this;
  32034. };
  32035. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32036. if (alternate === void 0) { alternate = false; }
  32037. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32038. return this;
  32039. }
  32040. this.onBeforeDrawObservable.notifyObservers(this);
  32041. var scene = this.getScene();
  32042. var engine = scene.getEngine();
  32043. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32044. // or triangles as points
  32045. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32046. }
  32047. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32048. // Triangles as wireframe
  32049. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32050. }
  32051. else {
  32052. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32053. }
  32054. if (scene._isAlternateRenderingEnabled && !alternate) {
  32055. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32056. if (!effect || !scene.activeCamera) {
  32057. return this;
  32058. }
  32059. scene._switchToAlternateCameraConfiguration(true);
  32060. this._effectiveMaterial.bindView(effect);
  32061. this._effectiveMaterial.bindViewProjection(effect);
  32062. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32063. this._draw(subMesh, fillMode, instancesCount, true);
  32064. engine.setViewport(scene.activeCamera.viewport);
  32065. scene._switchToAlternateCameraConfiguration(false);
  32066. this._effectiveMaterial.bindView(effect);
  32067. this._effectiveMaterial.bindViewProjection(effect);
  32068. }
  32069. return this;
  32070. };
  32071. /**
  32072. * Registers for this mesh a javascript function called just before the rendering process.
  32073. * This function is passed the current mesh.
  32074. * Return the Mesh.
  32075. */
  32076. Mesh.prototype.registerBeforeRender = function (func) {
  32077. this.onBeforeRenderObservable.add(func);
  32078. return this;
  32079. };
  32080. /**
  32081. * Disposes a previously registered javascript function called before the rendering.
  32082. * This function is passed the current mesh.
  32083. * Returns the Mesh.
  32084. */
  32085. Mesh.prototype.unregisterBeforeRender = function (func) {
  32086. this.onBeforeRenderObservable.removeCallback(func);
  32087. return this;
  32088. };
  32089. /**
  32090. * Registers for this mesh a javascript function called just after the rendering is complete.
  32091. * This function is passed the current mesh.
  32092. * Returns the Mesh.
  32093. */
  32094. Mesh.prototype.registerAfterRender = function (func) {
  32095. this.onAfterRenderObservable.add(func);
  32096. return this;
  32097. };
  32098. /**
  32099. * Disposes a previously registered javascript function called after the rendering.
  32100. * This function is passed the current mesh.
  32101. * Return the Mesh.
  32102. */
  32103. Mesh.prototype.unregisterAfterRender = function (func) {
  32104. this.onAfterRenderObservable.removeCallback(func);
  32105. return this;
  32106. };
  32107. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32108. var scene = this.getScene();
  32109. this._batchCache.mustReturn = false;
  32110. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32111. this._batchCache.visibleInstances[subMeshId] = null;
  32112. if (this._visibleInstances) {
  32113. var currentRenderId = scene.getRenderId();
  32114. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32115. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32116. var selfRenderId = this._renderId;
  32117. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32118. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32119. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32120. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32121. }
  32122. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32123. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32124. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32125. this._batchCache.mustReturn = true;
  32126. return this._batchCache;
  32127. }
  32128. if (currentRenderId !== selfRenderId) {
  32129. this._batchCache.renderSelf[subMeshId] = false;
  32130. }
  32131. }
  32132. this._renderIdForInstances[subMeshId] = currentRenderId;
  32133. }
  32134. return this._batchCache;
  32135. };
  32136. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32137. var visibleInstances = batch.visibleInstances[subMesh._id];
  32138. if (!visibleInstances) {
  32139. return this;
  32140. }
  32141. var matricesCount = visibleInstances.length + 1;
  32142. var bufferSize = matricesCount * 16 * 4;
  32143. var currentInstancesBufferSize = this._instancesBufferSize;
  32144. var instancesBuffer = this._instancesBuffer;
  32145. while (this._instancesBufferSize < bufferSize) {
  32146. this._instancesBufferSize *= 2;
  32147. }
  32148. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32149. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32150. }
  32151. var offset = 0;
  32152. var instancesCount = 0;
  32153. var world = this.getWorldMatrix();
  32154. if (batch.renderSelf[subMesh._id]) {
  32155. world.copyToArray(this._instancesData, offset);
  32156. offset += 16;
  32157. instancesCount++;
  32158. }
  32159. if (visibleInstances) {
  32160. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32161. var instance = visibleInstances[instanceIndex];
  32162. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32163. offset += 16;
  32164. instancesCount++;
  32165. }
  32166. }
  32167. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32168. if (instancesBuffer) {
  32169. instancesBuffer.dispose();
  32170. }
  32171. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32172. this._instancesBuffer = instancesBuffer;
  32173. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32174. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32175. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32176. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32177. }
  32178. else {
  32179. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32180. }
  32181. this._bind(subMesh, effect, fillMode);
  32182. this._draw(subMesh, fillMode, instancesCount);
  32183. engine.unbindInstanceAttributes();
  32184. return this;
  32185. };
  32186. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32187. var scene = this.getScene();
  32188. var engine = scene.getEngine();
  32189. if (hardwareInstancedRendering) {
  32190. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32191. }
  32192. else {
  32193. if (batch.renderSelf[subMesh._id]) {
  32194. // Draw
  32195. if (onBeforeDraw) {
  32196. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32197. }
  32198. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32199. }
  32200. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32201. if (visibleInstancesForSubMesh) {
  32202. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32203. var instance = visibleInstancesForSubMesh[instanceIndex];
  32204. // World
  32205. var world = instance.getWorldMatrix();
  32206. if (onBeforeDraw) {
  32207. onBeforeDraw(true, world, effectiveMaterial);
  32208. }
  32209. // Draw
  32210. this._draw(subMesh, fillMode);
  32211. }
  32212. }
  32213. }
  32214. return this;
  32215. };
  32216. /**
  32217. * Triggers the draw call for the mesh.
  32218. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32219. * Returns the Mesh.
  32220. */
  32221. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32222. this._checkOcclusionQuery();
  32223. if (this._isOccluded) {
  32224. return this;
  32225. }
  32226. var scene = this.getScene();
  32227. // Managing instances
  32228. var batch = this._getInstancesRenderList(subMesh._id);
  32229. if (batch.mustReturn) {
  32230. return this;
  32231. }
  32232. // Checking geometry state
  32233. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32234. return this;
  32235. }
  32236. this.onBeforeRenderObservable.notifyObservers(this);
  32237. var engine = scene.getEngine();
  32238. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32239. // Material
  32240. var material = subMesh.getMaterial();
  32241. if (!material) {
  32242. return this;
  32243. }
  32244. this._effectiveMaterial = material;
  32245. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32246. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32247. return this;
  32248. }
  32249. }
  32250. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32251. return this;
  32252. }
  32253. // Alpha mode
  32254. if (enableAlphaMode) {
  32255. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32256. }
  32257. // Outline - step 1
  32258. var savedDepthWrite = engine.getDepthWrite();
  32259. if (this.renderOutline) {
  32260. engine.setDepthWrite(false);
  32261. scene.getOutlineRenderer().render(subMesh, batch);
  32262. engine.setDepthWrite(savedDepthWrite);
  32263. }
  32264. var effect;
  32265. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32266. effect = subMesh.effect;
  32267. }
  32268. else {
  32269. effect = this._effectiveMaterial.getEffect();
  32270. }
  32271. if (!effect) {
  32272. return this;
  32273. }
  32274. var sideOrientation = this.overrideMaterialSideOrientation;
  32275. if (sideOrientation == null) {
  32276. sideOrientation = this._effectiveMaterial.sideOrientation;
  32277. if (this._getWorldMatrixDeterminant() < 0) {
  32278. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32279. }
  32280. }
  32281. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32282. if (this._effectiveMaterial.forceDepthWrite) {
  32283. engine.setDepthWrite(true);
  32284. }
  32285. // Bind
  32286. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32287. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32288. this._bind(subMesh, effect, fillMode);
  32289. }
  32290. var world = this.getWorldMatrix();
  32291. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32292. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32293. }
  32294. else {
  32295. this._effectiveMaterial.bind(world, this);
  32296. }
  32297. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32298. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32299. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32300. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32301. }
  32302. // Draw
  32303. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32304. // Unbind
  32305. this._effectiveMaterial.unbind();
  32306. // Outline - step 2
  32307. if (this.renderOutline && savedDepthWrite) {
  32308. engine.setDepthWrite(true);
  32309. engine.setColorWrite(false);
  32310. scene.getOutlineRenderer().render(subMesh, batch);
  32311. engine.setColorWrite(true);
  32312. }
  32313. // Overlay
  32314. if (this.renderOverlay) {
  32315. var currentMode = engine.getAlphaMode();
  32316. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32317. scene.getOutlineRenderer().render(subMesh, batch, true);
  32318. engine.setAlphaMode(currentMode);
  32319. }
  32320. this.onAfterRenderObservable.notifyObservers(this);
  32321. return this;
  32322. };
  32323. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32324. if (isInstance && effectiveMaterial) {
  32325. effectiveMaterial.bindOnlyWorldMatrix(world);
  32326. }
  32327. };
  32328. /**
  32329. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32330. */
  32331. Mesh.prototype.getEmittedParticleSystems = function () {
  32332. var results = new Array();
  32333. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32334. var particleSystem = this.getScene().particleSystems[index];
  32335. if (particleSystem.emitter === this) {
  32336. results.push(particleSystem);
  32337. }
  32338. }
  32339. return results;
  32340. };
  32341. /**
  32342. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32343. */
  32344. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32345. var results = new Array();
  32346. var descendants = this.getDescendants();
  32347. descendants.push(this);
  32348. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32349. var particleSystem = this.getScene().particleSystems[index];
  32350. var emitter = particleSystem.emitter;
  32351. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32352. results.push(particleSystem);
  32353. }
  32354. }
  32355. return results;
  32356. };
  32357. /**
  32358. * Normalize matrix weights so that all vertices have a total weight set to 1
  32359. */
  32360. Mesh.prototype.cleanMatrixWeights = function () {
  32361. var epsilon = 1e-3;
  32362. var noInfluenceBoneIndex = 0.0;
  32363. if (this.skeleton) {
  32364. noInfluenceBoneIndex = this.skeleton.bones.length;
  32365. }
  32366. else {
  32367. return;
  32368. }
  32369. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32370. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32371. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32372. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32373. var influencers = this.numBoneInfluencers;
  32374. var size = matricesWeights.length;
  32375. for (var i = 0; i < size; i += 4) {
  32376. var weight = 0.0;
  32377. var firstZeroWeight = -1;
  32378. for (var j = 0; j < 4; j++) {
  32379. var w = matricesWeights[i + j];
  32380. weight += w;
  32381. if (w < epsilon && firstZeroWeight < 0) {
  32382. firstZeroWeight = j;
  32383. }
  32384. }
  32385. if (matricesWeightsExtra) {
  32386. for (var j = 0; j < 4; j++) {
  32387. var w = matricesWeightsExtra[i + j];
  32388. weight += w;
  32389. if (w < epsilon && firstZeroWeight < 0) {
  32390. firstZeroWeight = j + 4;
  32391. }
  32392. }
  32393. }
  32394. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32395. firstZeroWeight = influencers - 1;
  32396. }
  32397. if (weight > epsilon) {
  32398. var mweight = 1.0 / weight;
  32399. for (var j = 0; j < 4; j++) {
  32400. matricesWeights[i + j] *= mweight;
  32401. }
  32402. if (matricesWeightsExtra) {
  32403. for (var j = 0; j < 4; j++) {
  32404. matricesWeightsExtra[i + j] *= mweight;
  32405. }
  32406. }
  32407. }
  32408. else {
  32409. if (firstZeroWeight >= 4) {
  32410. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32411. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32412. }
  32413. else {
  32414. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32415. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32416. }
  32417. }
  32418. }
  32419. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32420. if (matricesIndicesExtra) {
  32421. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32422. }
  32423. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32424. if (matricesWeightsExtra) {
  32425. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32426. }
  32427. };
  32428. Mesh.prototype._checkDelayState = function () {
  32429. var scene = this.getScene();
  32430. if (this._geometry) {
  32431. this._geometry.load(scene);
  32432. }
  32433. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32434. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32435. this._queueLoad(scene);
  32436. }
  32437. return this;
  32438. };
  32439. Mesh.prototype._queueLoad = function (scene) {
  32440. var _this = this;
  32441. scene._addPendingData(this);
  32442. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32443. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32444. if (data instanceof ArrayBuffer) {
  32445. _this._delayLoadingFunction(data, _this);
  32446. }
  32447. else {
  32448. _this._delayLoadingFunction(JSON.parse(data), _this);
  32449. }
  32450. _this.instances.forEach(function (instance) {
  32451. instance._syncSubMeshes();
  32452. });
  32453. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32454. scene._removePendingData(_this);
  32455. }, function () { }, scene.database, getBinaryData);
  32456. return this;
  32457. };
  32458. /**
  32459. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32460. */
  32461. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32462. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32463. return false;
  32464. }
  32465. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32466. return false;
  32467. }
  32468. this._checkDelayState();
  32469. return true;
  32470. };
  32471. /**
  32472. * Sets the mesh material by the material or multiMaterial `id` property.
  32473. * The material `id` is a string identifying the material or the multiMaterial.
  32474. * This method returns the Mesh.
  32475. */
  32476. Mesh.prototype.setMaterialByID = function (id) {
  32477. var materials = this.getScene().materials;
  32478. var index;
  32479. for (index = materials.length - 1; index > -1; index--) {
  32480. if (materials[index].id === id) {
  32481. this.material = materials[index];
  32482. return this;
  32483. }
  32484. }
  32485. // Multi
  32486. var multiMaterials = this.getScene().multiMaterials;
  32487. for (index = multiMaterials.length - 1; index > -1; index--) {
  32488. if (multiMaterials[index].id === id) {
  32489. this.material = multiMaterials[index];
  32490. return this;
  32491. }
  32492. }
  32493. return this;
  32494. };
  32495. /**
  32496. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32497. */
  32498. Mesh.prototype.getAnimatables = function () {
  32499. var results = new Array();
  32500. if (this.material) {
  32501. results.push(this.material);
  32502. }
  32503. if (this.skeleton) {
  32504. results.push(this.skeleton);
  32505. }
  32506. return results;
  32507. };
  32508. /**
  32509. * Modifies the mesh geometry according to the passed transformation matrix.
  32510. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32511. * The mesh normals are modified accordingly the same transformation.
  32512. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32513. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32514. * Returns the Mesh.
  32515. */
  32516. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32517. // Position
  32518. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32519. return this;
  32520. }
  32521. var submeshes = this.subMeshes.splice(0);
  32522. this._resetPointsArrayCache();
  32523. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32524. var temp = new Array();
  32525. var index;
  32526. for (index = 0; index < data.length; index += 3) {
  32527. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32528. }
  32529. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32530. // Normals
  32531. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32532. return this;
  32533. }
  32534. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32535. temp = [];
  32536. for (index = 0; index < data.length; index += 3) {
  32537. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32538. }
  32539. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32540. // flip faces?
  32541. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32542. this.flipFaces();
  32543. }
  32544. // Restore submeshes
  32545. this.releaseSubMeshes();
  32546. this.subMeshes = submeshes;
  32547. return this;
  32548. };
  32549. /**
  32550. * Modifies the mesh geometry according to its own current World Matrix.
  32551. * The mesh World Matrix is then reset.
  32552. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32553. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32554. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32555. * Returns the Mesh.
  32556. */
  32557. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32558. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32559. this.scaling.copyFromFloats(1, 1, 1);
  32560. this.position.copyFromFloats(0, 0, 0);
  32561. this.rotation.copyFromFloats(0, 0, 0);
  32562. //only if quaternion is already set
  32563. if (this.rotationQuaternion) {
  32564. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32565. }
  32566. this._worldMatrix = BABYLON.Matrix.Identity();
  32567. return this;
  32568. };
  32569. Object.defineProperty(Mesh.prototype, "_positions", {
  32570. // Cache
  32571. get: function () {
  32572. if (this._geometry) {
  32573. return this._geometry._positions;
  32574. }
  32575. return null;
  32576. },
  32577. enumerable: true,
  32578. configurable: true
  32579. });
  32580. Mesh.prototype._resetPointsArrayCache = function () {
  32581. if (this._geometry) {
  32582. this._geometry._resetPointsArrayCache();
  32583. }
  32584. return this;
  32585. };
  32586. Mesh.prototype._generatePointsArray = function () {
  32587. if (this._geometry) {
  32588. return this._geometry._generatePointsArray();
  32589. }
  32590. return false;
  32591. };
  32592. /**
  32593. * Returns a new Mesh object generated from the current mesh properties.
  32594. * This method must not get confused with createInstance().
  32595. * The parameter `name` is a string, the name given to the new mesh.
  32596. * The optional parameter `newParent` can be any Node object (default `null`).
  32597. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32598. * 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.
  32599. */
  32600. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32601. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32602. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32603. };
  32604. /**
  32605. * Releases resources associated with this mesh.
  32606. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32607. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32608. */
  32609. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32610. var _this = this;
  32611. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32612. this.morphTargetManager = null;
  32613. if (this._geometry) {
  32614. this._geometry.releaseForMesh(this, true);
  32615. }
  32616. // Sources
  32617. var meshes = this.getScene().meshes;
  32618. meshes.forEach(function (abstractMesh) {
  32619. var mesh = abstractMesh;
  32620. if (mesh._source && mesh._source === _this) {
  32621. mesh._source = null;
  32622. }
  32623. });
  32624. this._source = null;
  32625. // Instances
  32626. if (this._instancesBuffer) {
  32627. this._instancesBuffer.dispose();
  32628. this._instancesBuffer = null;
  32629. }
  32630. while (this.instances.length) {
  32631. this.instances[0].dispose();
  32632. }
  32633. // Effect layers.
  32634. var effectLayers = this.getScene().effectLayers;
  32635. for (var i = 0; i < effectLayers.length; i++) {
  32636. var effectLayer = effectLayers[i];
  32637. if (effectLayer) {
  32638. effectLayer._disposeMesh(this);
  32639. }
  32640. }
  32641. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32642. };
  32643. /**
  32644. * Modifies the mesh geometry according to a displacement map.
  32645. * 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.
  32646. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32647. * This method returns nothing.
  32648. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32649. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32650. * 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.
  32651. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32652. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32653. *
  32654. * Returns the Mesh.
  32655. */
  32656. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32657. var _this = this;
  32658. var scene = this.getScene();
  32659. var onload = function (img) {
  32660. // Getting height map data
  32661. var canvas = document.createElement("canvas");
  32662. var context = canvas.getContext("2d");
  32663. var heightMapWidth = img.width;
  32664. var heightMapHeight = img.height;
  32665. canvas.width = heightMapWidth;
  32666. canvas.height = heightMapHeight;
  32667. context.drawImage(img, 0, 0);
  32668. // Create VertexData from map data
  32669. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32670. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32671. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32672. //execute success callback, if set
  32673. if (onSuccess) {
  32674. onSuccess(_this);
  32675. }
  32676. };
  32677. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32678. return this;
  32679. };
  32680. /**
  32681. * Modifies the mesh geometry according to a displacementMap buffer.
  32682. * 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.
  32683. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32684. * This method returns nothing.
  32685. * 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.
  32686. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32687. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32688. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32689. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32690. *
  32691. * Returns the Mesh.
  32692. */
  32693. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32694. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32695. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32696. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32697. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32698. return this;
  32699. }
  32700. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32701. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32702. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32703. var position = BABYLON.Vector3.Zero();
  32704. var normal = BABYLON.Vector3.Zero();
  32705. var uv = BABYLON.Vector2.Zero();
  32706. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32707. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32708. for (var index = 0; index < positions.length; index += 3) {
  32709. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32710. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32711. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32712. // Compute height
  32713. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32714. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32715. var pos = (u + v * heightMapWidth) * 4;
  32716. var r = buffer[pos] / 255.0;
  32717. var g = buffer[pos + 1] / 255.0;
  32718. var b = buffer[pos + 2] / 255.0;
  32719. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32720. normal.normalize();
  32721. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32722. position = position.add(normal);
  32723. position.toArray(positions, index);
  32724. }
  32725. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32726. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32727. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32728. return this;
  32729. };
  32730. /**
  32731. * Modify the mesh to get a flat shading rendering.
  32732. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32733. * This method returns the Mesh.
  32734. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32735. */
  32736. Mesh.prototype.convertToFlatShadedMesh = function () {
  32737. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32738. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32739. var kinds = this.getVerticesDataKinds();
  32740. var vbs = {};
  32741. var data = {};
  32742. var newdata = {};
  32743. var updatableNormals = false;
  32744. var kindIndex;
  32745. var kind;
  32746. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32747. kind = kinds[kindIndex];
  32748. var vertexBuffer = this.getVertexBuffer(kind);
  32749. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32750. updatableNormals = vertexBuffer.isUpdatable();
  32751. kinds.splice(kindIndex, 1);
  32752. kindIndex--;
  32753. continue;
  32754. }
  32755. vbs[kind] = vertexBuffer;
  32756. data[kind] = vbs[kind].getData();
  32757. newdata[kind] = [];
  32758. }
  32759. // Save previous submeshes
  32760. var previousSubmeshes = this.subMeshes.slice(0);
  32761. var indices = this.getIndices();
  32762. var totalIndices = this.getTotalIndices();
  32763. // Generating unique vertices per face
  32764. var index;
  32765. for (index = 0; index < totalIndices; index++) {
  32766. var vertexIndex = indices[index];
  32767. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32768. kind = kinds[kindIndex];
  32769. var stride = vbs[kind].getStrideSize();
  32770. for (var offset = 0; offset < stride; offset++) {
  32771. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32772. }
  32773. }
  32774. }
  32775. // Updating faces & normal
  32776. var normals = [];
  32777. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32778. for (index = 0; index < totalIndices; index += 3) {
  32779. indices[index] = index;
  32780. indices[index + 1] = index + 1;
  32781. indices[index + 2] = index + 2;
  32782. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32783. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32784. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32785. var p1p2 = p1.subtract(p2);
  32786. var p3p2 = p3.subtract(p2);
  32787. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32788. // Store same normals for every vertex
  32789. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32790. normals.push(normal.x);
  32791. normals.push(normal.y);
  32792. normals.push(normal.z);
  32793. }
  32794. }
  32795. this.setIndices(indices);
  32796. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32797. // Updating vertex buffers
  32798. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32799. kind = kinds[kindIndex];
  32800. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32801. }
  32802. // Updating submeshes
  32803. this.releaseSubMeshes();
  32804. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32805. var previousOne = previousSubmeshes[submeshIndex];
  32806. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32807. }
  32808. this.synchronizeInstances();
  32809. return this;
  32810. };
  32811. /**
  32812. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32813. * In other words, more vertices, no more indices and a single bigger VBO.
  32814. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32815. * Returns the Mesh.
  32816. */
  32817. Mesh.prototype.convertToUnIndexedMesh = function () {
  32818. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32819. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32820. var kinds = this.getVerticesDataKinds();
  32821. var vbs = {};
  32822. var data = {};
  32823. var newdata = {};
  32824. var kindIndex;
  32825. var kind;
  32826. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32827. kind = kinds[kindIndex];
  32828. var vertexBuffer = this.getVertexBuffer(kind);
  32829. vbs[kind] = vertexBuffer;
  32830. data[kind] = vbs[kind].getData();
  32831. newdata[kind] = [];
  32832. }
  32833. // Save previous submeshes
  32834. var previousSubmeshes = this.subMeshes.slice(0);
  32835. var indices = this.getIndices();
  32836. var totalIndices = this.getTotalIndices();
  32837. // Generating unique vertices per face
  32838. var index;
  32839. for (index = 0; index < totalIndices; index++) {
  32840. var vertexIndex = indices[index];
  32841. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32842. kind = kinds[kindIndex];
  32843. var stride = vbs[kind].getStrideSize();
  32844. for (var offset = 0; offset < stride; offset++) {
  32845. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32846. }
  32847. }
  32848. }
  32849. // Updating indices
  32850. for (index = 0; index < totalIndices; index += 3) {
  32851. indices[index] = index;
  32852. indices[index + 1] = index + 1;
  32853. indices[index + 2] = index + 2;
  32854. }
  32855. this.setIndices(indices);
  32856. // Updating vertex buffers
  32857. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32858. kind = kinds[kindIndex];
  32859. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32860. }
  32861. // Updating submeshes
  32862. this.releaseSubMeshes();
  32863. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32864. var previousOne = previousSubmeshes[submeshIndex];
  32865. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32866. }
  32867. this._unIndexed = true;
  32868. this.synchronizeInstances();
  32869. return this;
  32870. };
  32871. /**
  32872. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32873. * This method returns the Mesh.
  32874. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32875. */
  32876. Mesh.prototype.flipFaces = function (flipNormals) {
  32877. if (flipNormals === void 0) { flipNormals = false; }
  32878. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32879. var i;
  32880. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32881. for (i = 0; i < vertex_data.normals.length; i++) {
  32882. vertex_data.normals[i] *= -1;
  32883. }
  32884. }
  32885. if (vertex_data.indices) {
  32886. var temp;
  32887. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32888. // reassign indices
  32889. temp = vertex_data.indices[i + 1];
  32890. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32891. vertex_data.indices[i + 2] = temp;
  32892. }
  32893. }
  32894. vertex_data.applyToMesh(this);
  32895. return this;
  32896. };
  32897. // Instances
  32898. /**
  32899. * Creates a new InstancedMesh object from the mesh model.
  32900. * An instance shares the same properties and the same material than its model.
  32901. * Only these properties of each instance can then be set individually :
  32902. * - position
  32903. * - rotation
  32904. * - rotationQuaternion
  32905. * - setPivotMatrix
  32906. * - scaling
  32907. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32908. * Warning : this method is not supported for Line mesh and LineSystem
  32909. */
  32910. Mesh.prototype.createInstance = function (name) {
  32911. return new BABYLON.InstancedMesh(name, this);
  32912. };
  32913. /**
  32914. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32915. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32916. * This method returns the Mesh.
  32917. */
  32918. Mesh.prototype.synchronizeInstances = function () {
  32919. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32920. var instance = this.instances[instanceIndex];
  32921. instance._syncSubMeshes();
  32922. }
  32923. return this;
  32924. };
  32925. /**
  32926. * Simplify the mesh according to the given array of settings.
  32927. * Function will return immediately and will simplify async. It returns the Mesh.
  32928. * @param settings a collection of simplification settings.
  32929. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32930. * @param type the type of simplification to run.
  32931. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32932. */
  32933. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32934. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32935. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32936. this.getScene().simplificationQueue.addTask({
  32937. settings: settings,
  32938. parallelProcessing: parallelProcessing,
  32939. mesh: this,
  32940. simplificationType: simplificationType,
  32941. successCallback: successCallback
  32942. });
  32943. return this;
  32944. };
  32945. /**
  32946. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32947. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32948. * This should be used together with the simplification to avoid disappearing triangles.
  32949. * Returns the Mesh.
  32950. * @param successCallback an optional success callback to be called after the optimization finished.
  32951. */
  32952. Mesh.prototype.optimizeIndices = function (successCallback) {
  32953. var _this = this;
  32954. var indices = this.getIndices();
  32955. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32956. if (!positions || !indices) {
  32957. return this;
  32958. }
  32959. var vectorPositions = new Array();
  32960. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32961. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32962. }
  32963. var dupes = new Array();
  32964. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32965. var realPos = vectorPositions.length - 1 - iteration;
  32966. var testedPosition = vectorPositions[realPos];
  32967. for (var j = 0; j < realPos; ++j) {
  32968. var againstPosition = vectorPositions[j];
  32969. if (testedPosition.equals(againstPosition)) {
  32970. dupes[realPos] = j;
  32971. break;
  32972. }
  32973. }
  32974. }, function () {
  32975. for (var i = 0; i < indices.length; ++i) {
  32976. indices[i] = dupes[indices[i]] || indices[i];
  32977. }
  32978. //indices are now reordered
  32979. var originalSubMeshes = _this.subMeshes.slice(0);
  32980. _this.setIndices(indices);
  32981. _this.subMeshes = originalSubMeshes;
  32982. if (successCallback) {
  32983. successCallback(_this);
  32984. }
  32985. });
  32986. return this;
  32987. };
  32988. Mesh.prototype.serialize = function (serializationObject) {
  32989. serializationObject.name = this.name;
  32990. serializationObject.id = this.id;
  32991. serializationObject.type = this.getClassName();
  32992. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32993. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32994. }
  32995. serializationObject.position = this.position.asArray();
  32996. if (this.rotationQuaternion) {
  32997. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32998. }
  32999. else if (this.rotation) {
  33000. serializationObject.rotation = this.rotation.asArray();
  33001. }
  33002. serializationObject.scaling = this.scaling.asArray();
  33003. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33004. serializationObject.isEnabled = this.isEnabled(false);
  33005. serializationObject.isVisible = this.isVisible;
  33006. serializationObject.infiniteDistance = this.infiniteDistance;
  33007. serializationObject.pickable = this.isPickable;
  33008. serializationObject.receiveShadows = this.receiveShadows;
  33009. serializationObject.billboardMode = this.billboardMode;
  33010. serializationObject.visibility = this.visibility;
  33011. serializationObject.checkCollisions = this.checkCollisions;
  33012. serializationObject.isBlocker = this.isBlocker;
  33013. // Parent
  33014. if (this.parent) {
  33015. serializationObject.parentId = this.parent.id;
  33016. }
  33017. // Geometry
  33018. serializationObject.isUnIndexed = this.isUnIndexed;
  33019. var geometry = this._geometry;
  33020. if (geometry) {
  33021. var geometryId = geometry.id;
  33022. serializationObject.geometryId = geometryId;
  33023. // SubMeshes
  33024. serializationObject.subMeshes = [];
  33025. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33026. var subMesh = this.subMeshes[subIndex];
  33027. serializationObject.subMeshes.push({
  33028. materialIndex: subMesh.materialIndex,
  33029. verticesStart: subMesh.verticesStart,
  33030. verticesCount: subMesh.verticesCount,
  33031. indexStart: subMesh.indexStart,
  33032. indexCount: subMesh.indexCount
  33033. });
  33034. }
  33035. }
  33036. // Material
  33037. if (this.material) {
  33038. serializationObject.materialId = this.material.id;
  33039. }
  33040. else {
  33041. this.material = null;
  33042. }
  33043. // Morph targets
  33044. if (this.morphTargetManager) {
  33045. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33046. }
  33047. // Skeleton
  33048. if (this.skeleton) {
  33049. serializationObject.skeletonId = this.skeleton.id;
  33050. }
  33051. // Physics
  33052. //TODO implement correct serialization for physics impostors.
  33053. var impostor = this.getPhysicsImpostor();
  33054. if (impostor) {
  33055. serializationObject.physicsMass = impostor.getParam("mass");
  33056. serializationObject.physicsFriction = impostor.getParam("friction");
  33057. serializationObject.physicsRestitution = impostor.getParam("mass");
  33058. serializationObject.physicsImpostor = impostor.type;
  33059. }
  33060. // Metadata
  33061. if (this.metadata) {
  33062. serializationObject.metadata = this.metadata;
  33063. }
  33064. // Instances
  33065. serializationObject.instances = [];
  33066. for (var index = 0; index < this.instances.length; index++) {
  33067. var instance = this.instances[index];
  33068. var serializationInstance = {
  33069. name: instance.name,
  33070. id: instance.id,
  33071. position: instance.position.asArray(),
  33072. scaling: instance.scaling.asArray()
  33073. };
  33074. if (instance.rotationQuaternion) {
  33075. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33076. }
  33077. else if (instance.rotation) {
  33078. serializationInstance.rotation = instance.rotation.asArray();
  33079. }
  33080. serializationObject.instances.push(serializationInstance);
  33081. // Animations
  33082. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33083. serializationInstance.ranges = instance.serializeAnimationRanges();
  33084. }
  33085. //
  33086. // Animations
  33087. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33088. serializationObject.ranges = this.serializeAnimationRanges();
  33089. // Layer mask
  33090. serializationObject.layerMask = this.layerMask;
  33091. // Alpha
  33092. serializationObject.alphaIndex = this.alphaIndex;
  33093. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33094. // Overlay
  33095. serializationObject.overlayAlpha = this.overlayAlpha;
  33096. serializationObject.overlayColor = this.overlayColor.asArray();
  33097. serializationObject.renderOverlay = this.renderOverlay;
  33098. // Fog
  33099. serializationObject.applyFog = this.applyFog;
  33100. // Action Manager
  33101. if (this.actionManager) {
  33102. serializationObject.actions = this.actionManager.serialize(this.name);
  33103. }
  33104. };
  33105. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33106. if (!this.geometry) {
  33107. return;
  33108. }
  33109. this._markSubMeshesAsAttributesDirty();
  33110. var morphTargetManager = this._morphTargetManager;
  33111. if (morphTargetManager && morphTargetManager.vertexCount) {
  33112. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33113. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33114. this.morphTargetManager = null;
  33115. return;
  33116. }
  33117. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33118. var morphTarget = morphTargetManager.getActiveTarget(index);
  33119. var positions = morphTarget.getPositions();
  33120. if (!positions) {
  33121. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33122. return;
  33123. }
  33124. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33125. var normals = morphTarget.getNormals();
  33126. if (normals) {
  33127. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33128. }
  33129. var tangents = morphTarget.getTangents();
  33130. if (tangents) {
  33131. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33132. }
  33133. }
  33134. }
  33135. else {
  33136. var index = 0;
  33137. // Positions
  33138. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33139. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33140. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33141. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33142. }
  33143. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33144. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33145. }
  33146. index++;
  33147. }
  33148. }
  33149. };
  33150. // Statics
  33151. /**
  33152. * Returns a new Mesh object parsed from the source provided.
  33153. * The parameter `parsedMesh` is the source.
  33154. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33155. */
  33156. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33157. var mesh;
  33158. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33159. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33160. }
  33161. else {
  33162. mesh = new Mesh(parsedMesh.name, scene);
  33163. }
  33164. mesh.id = parsedMesh.id;
  33165. if (BABYLON.Tags) {
  33166. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33167. }
  33168. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33169. if (parsedMesh.metadata !== undefined) {
  33170. mesh.metadata = parsedMesh.metadata;
  33171. }
  33172. if (parsedMesh.rotationQuaternion) {
  33173. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33174. }
  33175. else if (parsedMesh.rotation) {
  33176. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33177. }
  33178. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33179. if (parsedMesh.localMatrix) {
  33180. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33181. }
  33182. else if (parsedMesh.pivotMatrix) {
  33183. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33184. }
  33185. mesh.setEnabled(parsedMesh.isEnabled);
  33186. mesh.isVisible = parsedMesh.isVisible;
  33187. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33188. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33189. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33190. if (parsedMesh.applyFog !== undefined) {
  33191. mesh.applyFog = parsedMesh.applyFog;
  33192. }
  33193. if (parsedMesh.pickable !== undefined) {
  33194. mesh.isPickable = parsedMesh.pickable;
  33195. }
  33196. if (parsedMesh.alphaIndex !== undefined) {
  33197. mesh.alphaIndex = parsedMesh.alphaIndex;
  33198. }
  33199. mesh.receiveShadows = parsedMesh.receiveShadows;
  33200. mesh.billboardMode = parsedMesh.billboardMode;
  33201. if (parsedMesh.visibility !== undefined) {
  33202. mesh.visibility = parsedMesh.visibility;
  33203. }
  33204. mesh.checkCollisions = parsedMesh.checkCollisions;
  33205. if (parsedMesh.isBlocker !== undefined) {
  33206. mesh.isBlocker = parsedMesh.isBlocker;
  33207. }
  33208. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33209. // freezeWorldMatrix
  33210. if (parsedMesh.freezeWorldMatrix) {
  33211. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33212. }
  33213. // Parent
  33214. if (parsedMesh.parentId) {
  33215. mesh._waitingParentId = parsedMesh.parentId;
  33216. }
  33217. // Actions
  33218. if (parsedMesh.actions !== undefined) {
  33219. mesh._waitingActions = parsedMesh.actions;
  33220. }
  33221. // Overlay
  33222. if (parsedMesh.overlayAlpha !== undefined) {
  33223. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33224. }
  33225. if (parsedMesh.overlayColor !== undefined) {
  33226. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33227. }
  33228. if (parsedMesh.renderOverlay !== undefined) {
  33229. mesh.renderOverlay = parsedMesh.renderOverlay;
  33230. }
  33231. // Geometry
  33232. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33233. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33234. if (parsedMesh.delayLoadingFile) {
  33235. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33236. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33237. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33238. if (parsedMesh._binaryInfo) {
  33239. mesh._binaryInfo = parsedMesh._binaryInfo;
  33240. }
  33241. mesh._delayInfo = [];
  33242. if (parsedMesh.hasUVs) {
  33243. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33244. }
  33245. if (parsedMesh.hasUVs2) {
  33246. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33247. }
  33248. if (parsedMesh.hasUVs3) {
  33249. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33250. }
  33251. if (parsedMesh.hasUVs4) {
  33252. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33253. }
  33254. if (parsedMesh.hasUVs5) {
  33255. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33256. }
  33257. if (parsedMesh.hasUVs6) {
  33258. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33259. }
  33260. if (parsedMesh.hasColors) {
  33261. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33262. }
  33263. if (parsedMesh.hasMatricesIndices) {
  33264. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33265. }
  33266. if (parsedMesh.hasMatricesWeights) {
  33267. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33268. }
  33269. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33270. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33271. mesh._checkDelayState();
  33272. }
  33273. }
  33274. else {
  33275. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33276. }
  33277. // Material
  33278. if (parsedMesh.materialId) {
  33279. mesh.setMaterialByID(parsedMesh.materialId);
  33280. }
  33281. else {
  33282. mesh.material = null;
  33283. }
  33284. // Morph targets
  33285. if (parsedMesh.morphTargetManagerId > -1) {
  33286. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33287. }
  33288. // Skeleton
  33289. if (parsedMesh.skeletonId > -1) {
  33290. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33291. if (parsedMesh.numBoneInfluencers) {
  33292. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33293. }
  33294. }
  33295. // Animations
  33296. if (parsedMesh.animations) {
  33297. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33298. var parsedAnimation = parsedMesh.animations[animationIndex];
  33299. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33300. }
  33301. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33302. }
  33303. if (parsedMesh.autoAnimate) {
  33304. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33305. }
  33306. // Layer Mask
  33307. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33308. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33309. }
  33310. else {
  33311. mesh.layerMask = 0x0FFFFFFF;
  33312. }
  33313. // Physics
  33314. if (parsedMesh.physicsImpostor) {
  33315. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33316. mass: parsedMesh.physicsMass,
  33317. friction: parsedMesh.physicsFriction,
  33318. restitution: parsedMesh.physicsRestitution
  33319. }, scene);
  33320. }
  33321. // Instances
  33322. if (parsedMesh.instances) {
  33323. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33324. var parsedInstance = parsedMesh.instances[index];
  33325. var instance = mesh.createInstance(parsedInstance.name);
  33326. if (parsedInstance.id) {
  33327. instance.id = parsedInstance.id;
  33328. }
  33329. if (BABYLON.Tags) {
  33330. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33331. }
  33332. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33333. if (parsedInstance.parentId) {
  33334. instance._waitingParentId = parsedInstance.parentId;
  33335. }
  33336. if (parsedInstance.rotationQuaternion) {
  33337. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33338. }
  33339. else if (parsedInstance.rotation) {
  33340. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33341. }
  33342. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33343. instance.checkCollisions = mesh.checkCollisions;
  33344. if (parsedMesh.animations) {
  33345. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33346. parsedAnimation = parsedMesh.animations[animationIndex];
  33347. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33348. }
  33349. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33350. }
  33351. }
  33352. }
  33353. return mesh;
  33354. };
  33355. /**
  33356. * Creates a ribbon mesh.
  33357. * Please consider using the same method from the MeshBuilder class instead.
  33358. * 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.
  33359. *
  33360. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33361. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33362. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33363. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33364. * 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.
  33365. * 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.
  33366. * 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
  33367. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33368. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33369. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33370. */
  33371. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33372. if (closeArray === void 0) { closeArray = false; }
  33373. if (updatable === void 0) { updatable = false; }
  33374. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33375. pathArray: pathArray,
  33376. closeArray: closeArray,
  33377. closePath: closePath,
  33378. offset: offset,
  33379. updatable: updatable,
  33380. sideOrientation: sideOrientation,
  33381. instance: instance
  33382. }, scene);
  33383. };
  33384. /**
  33385. * Creates a plane polygonal mesh. By default, this is a disc.
  33386. * Please consider using the same method from the MeshBuilder class instead.
  33387. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33388. * 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.
  33389. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33390. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33391. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33392. */
  33393. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33394. if (scene === void 0) { scene = null; }
  33395. var options = {
  33396. radius: radius,
  33397. tessellation: tessellation,
  33398. sideOrientation: sideOrientation,
  33399. updatable: updatable
  33400. };
  33401. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33402. };
  33403. /**
  33404. * Creates a box mesh.
  33405. * Please consider using the same method from the MeshBuilder class instead.
  33406. * The parameter `size` sets the size (float) of each box side (default 1).
  33407. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33408. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33409. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33410. */
  33411. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33412. if (scene === void 0) { scene = null; }
  33413. var options = {
  33414. size: size,
  33415. sideOrientation: sideOrientation,
  33416. updatable: updatable
  33417. };
  33418. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33419. };
  33420. /**
  33421. * Creates a sphere mesh.
  33422. * Please consider using the same method from the MeshBuilder class instead.
  33423. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33424. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33425. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33426. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33427. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33428. */
  33429. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33430. var options = {
  33431. segments: segments,
  33432. diameterX: diameter,
  33433. diameterY: diameter,
  33434. diameterZ: diameter,
  33435. sideOrientation: sideOrientation,
  33436. updatable: updatable
  33437. };
  33438. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33439. };
  33440. /**
  33441. * Creates a cylinder or a cone mesh.
  33442. * Please consider using the same method from the MeshBuilder class instead.
  33443. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33444. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33445. * 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.
  33446. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33447. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33448. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33449. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33450. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33451. */
  33452. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33453. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33454. if (scene !== undefined) {
  33455. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33456. updatable = scene;
  33457. }
  33458. scene = subdivisions;
  33459. subdivisions = 1;
  33460. }
  33461. var options = {
  33462. height: height,
  33463. diameterTop: diameterTop,
  33464. diameterBottom: diameterBottom,
  33465. tessellation: tessellation,
  33466. subdivisions: subdivisions,
  33467. sideOrientation: sideOrientation,
  33468. updatable: updatable
  33469. };
  33470. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33471. };
  33472. // Torus (Code from SharpDX.org)
  33473. /**
  33474. * Creates a torus mesh.
  33475. * Please consider using the same method from the MeshBuilder class instead.
  33476. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33477. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33478. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33479. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33480. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33481. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33482. */
  33483. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33484. var options = {
  33485. diameter: diameter,
  33486. thickness: thickness,
  33487. tessellation: tessellation,
  33488. sideOrientation: sideOrientation,
  33489. updatable: updatable
  33490. };
  33491. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33492. };
  33493. /**
  33494. * Creates a torus knot mesh.
  33495. * Please consider using the same method from the MeshBuilder class instead.
  33496. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33497. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33498. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33499. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33500. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33501. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33502. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33503. */
  33504. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33505. var options = {
  33506. radius: radius,
  33507. tube: tube,
  33508. radialSegments: radialSegments,
  33509. tubularSegments: tubularSegments,
  33510. p: p,
  33511. q: q,
  33512. sideOrientation: sideOrientation,
  33513. updatable: updatable
  33514. };
  33515. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33516. };
  33517. /**
  33518. * Creates a line mesh.
  33519. * Please consider using the same method from the MeshBuilder class instead.
  33520. * 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.
  33521. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33522. * The parameter `points` is an array successive Vector3.
  33523. * 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
  33524. * When updating an instance, remember that only point positions can change, not the number of points.
  33525. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33526. */
  33527. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33528. if (scene === void 0) { scene = null; }
  33529. if (updatable === void 0) { updatable = false; }
  33530. if (instance === void 0) { instance = null; }
  33531. var options = {
  33532. points: points,
  33533. updatable: updatable,
  33534. instance: instance
  33535. };
  33536. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33537. };
  33538. /**
  33539. * Creates a dashed line mesh.
  33540. * Please consider using the same method from the MeshBuilder class instead.
  33541. * 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.
  33542. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33543. * The parameter `points` is an array successive Vector3.
  33544. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33545. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33546. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33547. * 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
  33548. * When updating an instance, remember that only point positions can change, not the number of points.
  33549. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33550. */
  33551. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33552. if (scene === void 0) { scene = null; }
  33553. var options = {
  33554. points: points,
  33555. dashSize: dashSize,
  33556. gapSize: gapSize,
  33557. dashNb: dashNb,
  33558. updatable: updatable,
  33559. instance: instance
  33560. };
  33561. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33562. };
  33563. /**
  33564. * Creates a polygon mesh.
  33565. * Please consider using the same method from the MeshBuilder class instead.
  33566. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33567. * 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.
  33568. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33569. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33570. * Remember you can only change the shape positions, not their number when updating a polygon.
  33571. */
  33572. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33573. var options = {
  33574. shape: shape,
  33575. holes: holes,
  33576. updatable: updatable,
  33577. sideOrientation: sideOrientation
  33578. };
  33579. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33580. };
  33581. /**
  33582. * Creates an extruded polygon mesh, with depth in the Y direction.
  33583. * Please consider using the same method from the MeshBuilder class instead.
  33584. */
  33585. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33586. var options = {
  33587. shape: shape,
  33588. holes: holes,
  33589. depth: depth,
  33590. updatable: updatable,
  33591. sideOrientation: sideOrientation
  33592. };
  33593. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33594. };
  33595. /**
  33596. * Creates an extruded shape mesh.
  33597. * 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.
  33598. * Please consider using the same method from the MeshBuilder class instead.
  33599. *
  33600. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33601. * 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
  33602. * extruded along the Z axis.
  33603. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33604. * 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.
  33605. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33606. * 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
  33607. * 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
  33608. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33609. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33610. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33611. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33612. */
  33613. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33614. if (scene === void 0) { scene = null; }
  33615. var options = {
  33616. shape: shape,
  33617. path: path,
  33618. scale: scale,
  33619. rotation: rotation,
  33620. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33621. sideOrientation: sideOrientation,
  33622. instance: instance,
  33623. updatable: updatable
  33624. };
  33625. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33626. };
  33627. /**
  33628. * Creates an custom extruded shape mesh.
  33629. * 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.
  33630. * Please consider using the same method from the MeshBuilder class instead.
  33631. *
  33632. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33633. * 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
  33634. * extruded along the Z axis.
  33635. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33636. * 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
  33637. * and the distance of this point from the begining of the path :
  33638. * ```javascript
  33639. * var rotationFunction = function(i, distance) {
  33640. * // do things
  33641. * return rotationValue; }
  33642. * ```
  33643. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33644. * 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
  33645. * and the distance of this point from the begining of the path :
  33646. * ```javascript
  33647. * var scaleFunction = function(i, distance) {
  33648. * // do things
  33649. * return scaleValue;}
  33650. * ```
  33651. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33652. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33653. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33654. * 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
  33655. * 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
  33656. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33657. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33658. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33659. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33660. */
  33661. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33662. var options = {
  33663. shape: shape,
  33664. path: path,
  33665. scaleFunction: scaleFunction,
  33666. rotationFunction: rotationFunction,
  33667. ribbonCloseArray: ribbonCloseArray,
  33668. ribbonClosePath: ribbonClosePath,
  33669. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33670. sideOrientation: sideOrientation,
  33671. instance: instance,
  33672. updatable: updatable
  33673. };
  33674. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33675. };
  33676. /**
  33677. * Creates lathe mesh.
  33678. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33679. * Please consider using the same method from the MeshBuilder class instead.
  33680. * 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
  33681. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33682. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33683. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33684. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33685. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33686. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33687. */
  33688. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33689. var options = {
  33690. shape: shape,
  33691. radius: radius,
  33692. tessellation: tessellation,
  33693. sideOrientation: sideOrientation,
  33694. updatable: updatable
  33695. };
  33696. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33697. };
  33698. /**
  33699. * Creates a plane mesh.
  33700. * Please consider using the same method from the MeshBuilder class instead.
  33701. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33702. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33703. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33704. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33705. */
  33706. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33707. var options = {
  33708. size: size,
  33709. width: size,
  33710. height: size,
  33711. sideOrientation: sideOrientation,
  33712. updatable: updatable
  33713. };
  33714. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33715. };
  33716. /**
  33717. * Creates a ground mesh.
  33718. * Please consider using the same method from the MeshBuilder class instead.
  33719. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33720. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33721. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33722. */
  33723. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33724. var options = {
  33725. width: width,
  33726. height: height,
  33727. subdivisions: subdivisions,
  33728. updatable: updatable
  33729. };
  33730. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33731. };
  33732. /**
  33733. * Creates a tiled ground mesh.
  33734. * Please consider using the same method from the MeshBuilder class instead.
  33735. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33736. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33737. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33738. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33739. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33740. * numbers of subdivisions on the ground width and height of each tile.
  33741. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33742. */
  33743. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33744. var options = {
  33745. xmin: xmin,
  33746. zmin: zmin,
  33747. xmax: xmax,
  33748. zmax: zmax,
  33749. subdivisions: subdivisions,
  33750. precision: precision,
  33751. updatable: updatable
  33752. };
  33753. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33754. };
  33755. /**
  33756. * Creates a ground mesh from a height map.
  33757. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33758. * Please consider using the same method from the MeshBuilder class instead.
  33759. * The parameter `url` sets the URL of the height map image resource.
  33760. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33761. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33762. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33763. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33764. * 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).
  33765. * This function is passed the newly built mesh :
  33766. * ```javascript
  33767. * function(mesh) { // do things
  33768. * return; }
  33769. * ```
  33770. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33771. */
  33772. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33773. var options = {
  33774. width: width,
  33775. height: height,
  33776. subdivisions: subdivisions,
  33777. minHeight: minHeight,
  33778. maxHeight: maxHeight,
  33779. updatable: updatable,
  33780. onReady: onReady
  33781. };
  33782. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33783. };
  33784. /**
  33785. * Creates a tube mesh.
  33786. * 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.
  33787. * Please consider using the same method from the MeshBuilder class instead.
  33788. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33789. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33790. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33791. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33792. * 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.
  33793. * It must return a radius value (positive float) :
  33794. * ```javascript
  33795. * var radiusFunction = function(i, distance) {
  33796. * // do things
  33797. * return radius; }
  33798. * ```
  33799. * 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
  33800. * 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
  33801. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33802. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33803. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33804. */
  33805. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33806. var options = {
  33807. path: path,
  33808. radius: radius,
  33809. tessellation: tessellation,
  33810. radiusFunction: radiusFunction,
  33811. arc: 1,
  33812. cap: cap,
  33813. updatable: updatable,
  33814. sideOrientation: sideOrientation,
  33815. instance: instance
  33816. };
  33817. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33818. };
  33819. /**
  33820. * Creates a polyhedron mesh.
  33821. * Please consider using the same method from the MeshBuilder class instead.
  33822. * 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
  33823. * to choose the wanted type.
  33824. * The parameter `size` (positive float, default 1) sets the polygon size.
  33825. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33826. * 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`.
  33827. * 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
  33828. * 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)`).
  33829. * 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
  33830. * 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.
  33831. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33832. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33833. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33834. */
  33835. Mesh.CreatePolyhedron = function (name, options, scene) {
  33836. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33837. };
  33838. /**
  33839. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33840. * Please consider using the same method from the MeshBuilder class instead.
  33841. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33842. * 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`).
  33843. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33844. * 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.
  33845. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33846. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33847. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33848. */
  33849. Mesh.CreateIcoSphere = function (name, options, scene) {
  33850. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33851. };
  33852. /**
  33853. * Creates a decal mesh.
  33854. * Please consider using the same method from the MeshBuilder class instead.
  33855. * 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.
  33856. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33857. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33858. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33859. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33860. */
  33861. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33862. var options = {
  33863. position: position,
  33864. normal: normal,
  33865. size: size,
  33866. angle: angle
  33867. };
  33868. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33869. };
  33870. // Skeletons
  33871. /**
  33872. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33873. */
  33874. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33875. if (!this._sourcePositions) {
  33876. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33877. if (!source) {
  33878. return this._sourcePositions;
  33879. }
  33880. this._sourcePositions = new Float32Array(source);
  33881. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33882. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33883. }
  33884. }
  33885. return this._sourcePositions;
  33886. };
  33887. /**
  33888. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33889. */
  33890. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33891. if (!this._sourceNormals) {
  33892. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33893. if (!source) {
  33894. return this._sourceNormals;
  33895. }
  33896. this._sourceNormals = new Float32Array(source);
  33897. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33898. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33899. }
  33900. }
  33901. return this._sourceNormals;
  33902. };
  33903. /**
  33904. * Updates the vertex buffer by applying transformation from the bones.
  33905. * Returns the Mesh.
  33906. *
  33907. * @param {skeleton} skeleton to apply
  33908. */
  33909. Mesh.prototype.applySkeleton = function (skeleton) {
  33910. if (!this.geometry) {
  33911. return this;
  33912. }
  33913. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33914. return this;
  33915. }
  33916. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33917. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33918. return this;
  33919. }
  33920. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33921. return this;
  33922. }
  33923. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33924. return this;
  33925. }
  33926. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33927. return this;
  33928. }
  33929. if (!this._sourcePositions) {
  33930. var submeshes = this.subMeshes.slice();
  33931. this.setPositionsForCPUSkinning();
  33932. this.subMeshes = submeshes;
  33933. }
  33934. if (!this._sourceNormals) {
  33935. this.setNormalsForCPUSkinning();
  33936. }
  33937. // positionsData checks for not being Float32Array will only pass at most once
  33938. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33939. if (!positionsData) {
  33940. return this;
  33941. }
  33942. if (!(positionsData instanceof Float32Array)) {
  33943. positionsData = new Float32Array(positionsData);
  33944. }
  33945. // normalsData checks for not being Float32Array will only pass at most once
  33946. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33947. if (!normalsData) {
  33948. return this;
  33949. }
  33950. if (!(normalsData instanceof Float32Array)) {
  33951. normalsData = new Float32Array(normalsData);
  33952. }
  33953. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33954. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33955. if (!matricesWeightsData || !matricesIndicesData) {
  33956. return this;
  33957. }
  33958. var needExtras = this.numBoneInfluencers > 4;
  33959. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33960. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33961. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33962. var tempVector3 = BABYLON.Vector3.Zero();
  33963. var finalMatrix = new BABYLON.Matrix();
  33964. var tempMatrix = new BABYLON.Matrix();
  33965. var matWeightIdx = 0;
  33966. var inf;
  33967. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33968. var weight;
  33969. for (inf = 0; inf < 4; inf++) {
  33970. weight = matricesWeightsData[matWeightIdx + inf];
  33971. if (weight > 0) {
  33972. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33973. finalMatrix.addToSelf(tempMatrix);
  33974. }
  33975. else
  33976. break;
  33977. }
  33978. if (needExtras) {
  33979. for (inf = 0; inf < 4; inf++) {
  33980. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33981. if (weight > 0) {
  33982. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33983. finalMatrix.addToSelf(tempMatrix);
  33984. }
  33985. else
  33986. break;
  33987. }
  33988. }
  33989. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33990. tempVector3.toArray(positionsData, index);
  33991. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33992. tempVector3.toArray(normalsData, index);
  33993. finalMatrix.reset();
  33994. }
  33995. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33996. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33997. return this;
  33998. };
  33999. // Tools
  34000. /**
  34001. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34002. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34003. */
  34004. Mesh.MinMax = function (meshes) {
  34005. var minVector = null;
  34006. var maxVector = null;
  34007. meshes.forEach(function (mesh, index, array) {
  34008. var boundingInfo = mesh.getBoundingInfo();
  34009. var boundingBox = boundingInfo.boundingBox;
  34010. if (!minVector || !maxVector) {
  34011. minVector = boundingBox.minimumWorld;
  34012. maxVector = boundingBox.maximumWorld;
  34013. }
  34014. else {
  34015. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34016. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34017. }
  34018. });
  34019. if (!minVector || !maxVector) {
  34020. return {
  34021. min: BABYLON.Vector3.Zero(),
  34022. max: BABYLON.Vector3.Zero()
  34023. };
  34024. }
  34025. return {
  34026. min: minVector,
  34027. max: maxVector
  34028. };
  34029. };
  34030. /**
  34031. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34032. */
  34033. Mesh.Center = function (meshesOrMinMaxVector) {
  34034. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34035. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34036. };
  34037. /**
  34038. * Merge the array of meshes into a single mesh for performance reasons.
  34039. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34040. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34041. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34042. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34043. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34044. */
  34045. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34046. if (disposeSource === void 0) { disposeSource = true; }
  34047. var index;
  34048. if (!allow32BitsIndices) {
  34049. var totalVertices = 0;
  34050. // Counting vertices
  34051. for (index = 0; index < meshes.length; index++) {
  34052. if (meshes[index]) {
  34053. totalVertices += meshes[index].getTotalVertices();
  34054. if (totalVertices > 65536) {
  34055. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34056. return null;
  34057. }
  34058. }
  34059. }
  34060. }
  34061. // Merge
  34062. var vertexData = null;
  34063. var otherVertexData;
  34064. var indiceArray = new Array();
  34065. var source = null;
  34066. for (index = 0; index < meshes.length; index++) {
  34067. if (meshes[index]) {
  34068. meshes[index].computeWorldMatrix(true);
  34069. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  34070. otherVertexData.transform(meshes[index].getWorldMatrix());
  34071. if (vertexData) {
  34072. vertexData.merge(otherVertexData);
  34073. }
  34074. else {
  34075. vertexData = otherVertexData;
  34076. source = meshes[index];
  34077. }
  34078. if (subdivideWithSubMeshes) {
  34079. indiceArray.push(meshes[index].getTotalIndices());
  34080. }
  34081. }
  34082. }
  34083. source = source;
  34084. if (!meshSubclass) {
  34085. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34086. }
  34087. vertexData.applyToMesh(meshSubclass);
  34088. // Setting properties
  34089. meshSubclass.material = source.material;
  34090. meshSubclass.checkCollisions = source.checkCollisions;
  34091. // Cleaning
  34092. if (disposeSource) {
  34093. for (index = 0; index < meshes.length; index++) {
  34094. if (meshes[index]) {
  34095. meshes[index].dispose();
  34096. }
  34097. }
  34098. }
  34099. // Subdivide
  34100. if (subdivideWithSubMeshes) {
  34101. //-- Suppresions du submesh global
  34102. meshSubclass.releaseSubMeshes();
  34103. index = 0;
  34104. var offset = 0;
  34105. //-- aplique la subdivision en fonction du tableau d'indices
  34106. while (index < indiceArray.length) {
  34107. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34108. offset += indiceArray[index];
  34109. index++;
  34110. }
  34111. }
  34112. return meshSubclass;
  34113. };
  34114. // Consts
  34115. Mesh._FRONTSIDE = 0;
  34116. Mesh._BACKSIDE = 1;
  34117. Mesh._DOUBLESIDE = 2;
  34118. Mesh._DEFAULTSIDE = 0;
  34119. Mesh._NO_CAP = 0;
  34120. Mesh._CAP_START = 1;
  34121. Mesh._CAP_END = 2;
  34122. Mesh._CAP_ALL = 3;
  34123. return Mesh;
  34124. }(BABYLON.AbstractMesh));
  34125. BABYLON.Mesh = Mesh;
  34126. })(BABYLON || (BABYLON = {}));
  34127. //# sourceMappingURL=babylon.mesh.js.map
  34128. var BABYLON;
  34129. (function (BABYLON) {
  34130. var BaseSubMesh = /** @class */ (function () {
  34131. function BaseSubMesh() {
  34132. }
  34133. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34134. get: function () {
  34135. return this._materialEffect;
  34136. },
  34137. enumerable: true,
  34138. configurable: true
  34139. });
  34140. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34141. if (defines === void 0) { defines = null; }
  34142. if (this._materialEffect === effect) {
  34143. if (!effect) {
  34144. this._materialDefines = null;
  34145. }
  34146. return;
  34147. }
  34148. this._materialDefines = defines;
  34149. this._materialEffect = effect;
  34150. };
  34151. return BaseSubMesh;
  34152. }());
  34153. BABYLON.BaseSubMesh = BaseSubMesh;
  34154. var SubMesh = /** @class */ (function (_super) {
  34155. __extends(SubMesh, _super);
  34156. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34157. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34158. var _this = _super.call(this) || this;
  34159. _this.materialIndex = materialIndex;
  34160. _this.verticesStart = verticesStart;
  34161. _this.verticesCount = verticesCount;
  34162. _this.indexStart = indexStart;
  34163. _this.indexCount = indexCount;
  34164. _this._renderId = 0;
  34165. _this._mesh = mesh;
  34166. _this._renderingMesh = renderingMesh || mesh;
  34167. mesh.subMeshes.push(_this);
  34168. _this._trianglePlanes = [];
  34169. _this._id = mesh.subMeshes.length - 1;
  34170. if (createBoundingBox) {
  34171. _this.refreshBoundingInfo();
  34172. mesh.computeWorldMatrix(true);
  34173. }
  34174. return _this;
  34175. }
  34176. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34177. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34178. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34179. };
  34180. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34181. get: function () {
  34182. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34183. },
  34184. enumerable: true,
  34185. configurable: true
  34186. });
  34187. /**
  34188. * Returns the submesh BoudingInfo object.
  34189. */
  34190. SubMesh.prototype.getBoundingInfo = function () {
  34191. if (this.IsGlobal) {
  34192. return this._mesh.getBoundingInfo();
  34193. }
  34194. return this._boundingInfo;
  34195. };
  34196. /**
  34197. * Sets the submesh BoundingInfo.
  34198. * Return the SubMesh.
  34199. */
  34200. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34201. this._boundingInfo = boundingInfo;
  34202. return this;
  34203. };
  34204. /**
  34205. * Returns the mesh of the current submesh.
  34206. */
  34207. SubMesh.prototype.getMesh = function () {
  34208. return this._mesh;
  34209. };
  34210. /**
  34211. * Returns the rendering mesh of the submesh.
  34212. */
  34213. SubMesh.prototype.getRenderingMesh = function () {
  34214. return this._renderingMesh;
  34215. };
  34216. /**
  34217. * Returns the submesh material.
  34218. */
  34219. SubMesh.prototype.getMaterial = function () {
  34220. var rootMaterial = this._renderingMesh.material;
  34221. if (rootMaterial === null || rootMaterial === undefined) {
  34222. return this._mesh.getScene().defaultMaterial;
  34223. }
  34224. else if (rootMaterial.getSubMaterial) {
  34225. var multiMaterial = rootMaterial;
  34226. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34227. if (this._currentMaterial !== effectiveMaterial) {
  34228. this._currentMaterial = effectiveMaterial;
  34229. this._materialDefines = null;
  34230. }
  34231. return effectiveMaterial;
  34232. }
  34233. return rootMaterial;
  34234. };
  34235. // Methods
  34236. /**
  34237. * Sets a new updated BoundingInfo object to the submesh.
  34238. * Returns the SubMesh.
  34239. */
  34240. SubMesh.prototype.refreshBoundingInfo = function () {
  34241. this._lastColliderWorldVertices = null;
  34242. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34243. return this;
  34244. }
  34245. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34246. if (!data) {
  34247. this._boundingInfo = this._mesh.getBoundingInfo();
  34248. return this;
  34249. }
  34250. var indices = this._renderingMesh.getIndices();
  34251. var extend;
  34252. //is this the only submesh?
  34253. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34254. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34255. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34256. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34257. }
  34258. else {
  34259. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34260. }
  34261. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34262. return this;
  34263. };
  34264. SubMesh.prototype._checkCollision = function (collider) {
  34265. var boundingInfo = this.getBoundingInfo();
  34266. return boundingInfo._checkCollision(collider);
  34267. };
  34268. /**
  34269. * Updates the submesh BoundingInfo.
  34270. * Returns the Submesh.
  34271. */
  34272. SubMesh.prototype.updateBoundingInfo = function (world) {
  34273. var boundingInfo = this.getBoundingInfo();
  34274. if (!boundingInfo) {
  34275. this.refreshBoundingInfo();
  34276. boundingInfo = this.getBoundingInfo();
  34277. }
  34278. boundingInfo.update(world);
  34279. return this;
  34280. };
  34281. /**
  34282. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34283. * Boolean returned.
  34284. */
  34285. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34286. var boundingInfo = this.getBoundingInfo();
  34287. if (!boundingInfo) {
  34288. return false;
  34289. }
  34290. return boundingInfo.isInFrustum(frustumPlanes);
  34291. };
  34292. /**
  34293. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34294. * Boolean returned.
  34295. */
  34296. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34297. var boundingInfo = this.getBoundingInfo();
  34298. if (!boundingInfo) {
  34299. return false;
  34300. }
  34301. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34302. };
  34303. /**
  34304. * Renders the submesh.
  34305. * Returns it.
  34306. */
  34307. SubMesh.prototype.render = function (enableAlphaMode) {
  34308. this._renderingMesh.render(this, enableAlphaMode);
  34309. return this;
  34310. };
  34311. /**
  34312. * Returns a new Index Buffer.
  34313. * Type returned : WebGLBuffer.
  34314. */
  34315. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34316. if (!this._linesIndexBuffer) {
  34317. var linesIndices = [];
  34318. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34319. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34320. }
  34321. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34322. this.linesIndexCount = linesIndices.length;
  34323. }
  34324. return this._linesIndexBuffer;
  34325. };
  34326. /**
  34327. * True is the passed Ray intersects the submesh bounding box.
  34328. * Boolean returned.
  34329. */
  34330. SubMesh.prototype.canIntersects = function (ray) {
  34331. var boundingInfo = this.getBoundingInfo();
  34332. if (!boundingInfo) {
  34333. return false;
  34334. }
  34335. return ray.intersectsBox(boundingInfo.boundingBox);
  34336. };
  34337. /**
  34338. * Returns an object IntersectionInfo.
  34339. */
  34340. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34341. var intersectInfo = null;
  34342. var material = this.getMaterial();
  34343. if (!material) {
  34344. return null;
  34345. }
  34346. switch (material.fillMode) {
  34347. case BABYLON.Material.PointListDrawMode:
  34348. case BABYLON.Material.LineListDrawMode:
  34349. case BABYLON.Material.LineLoopDrawMode:
  34350. case BABYLON.Material.LineStripDrawMode:
  34351. case BABYLON.Material.TriangleFanDrawMode:
  34352. case BABYLON.Material.TriangleStripDrawMode:
  34353. return null;
  34354. }
  34355. // LineMesh first as it's also a Mesh...
  34356. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34357. var lineMesh = this._mesh;
  34358. // Line test
  34359. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34360. var p0 = positions[indices[index]];
  34361. var p1 = positions[indices[index + 1]];
  34362. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34363. if (length < 0) {
  34364. continue;
  34365. }
  34366. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34367. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34368. if (fastCheck) {
  34369. break;
  34370. }
  34371. }
  34372. }
  34373. }
  34374. else {
  34375. // Triangles test
  34376. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34377. var p0 = positions[indices[index]];
  34378. var p1 = positions[indices[index + 1]];
  34379. var p2 = positions[indices[index + 2]];
  34380. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34381. if (currentIntersectInfo) {
  34382. if (currentIntersectInfo.distance < 0) {
  34383. continue;
  34384. }
  34385. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34386. intersectInfo = currentIntersectInfo;
  34387. intersectInfo.faceId = index / 3;
  34388. if (fastCheck) {
  34389. break;
  34390. }
  34391. }
  34392. }
  34393. }
  34394. }
  34395. return intersectInfo;
  34396. };
  34397. SubMesh.prototype._rebuild = function () {
  34398. if (this._linesIndexBuffer) {
  34399. this._linesIndexBuffer = null;
  34400. }
  34401. };
  34402. // Clone
  34403. /**
  34404. * Creates a new Submesh from the passed Mesh.
  34405. */
  34406. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34407. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34408. if (!this.IsGlobal) {
  34409. var boundingInfo = this.getBoundingInfo();
  34410. if (!boundingInfo) {
  34411. return result;
  34412. }
  34413. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34414. }
  34415. return result;
  34416. };
  34417. // Dispose
  34418. /**
  34419. * Disposes the Submesh.
  34420. * Returns nothing.
  34421. */
  34422. SubMesh.prototype.dispose = function () {
  34423. if (this._linesIndexBuffer) {
  34424. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34425. this._linesIndexBuffer = null;
  34426. }
  34427. // Remove from mesh
  34428. var index = this._mesh.subMeshes.indexOf(this);
  34429. this._mesh.subMeshes.splice(index, 1);
  34430. };
  34431. // Statics
  34432. /**
  34433. * Creates a new Submesh from the passed parameters :
  34434. * - materialIndex (integer) : the index of the main mesh material.
  34435. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34436. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34437. * - mesh (Mesh) : the main mesh to create the submesh from.
  34438. * - renderingMesh (optional Mesh) : rendering mesh.
  34439. */
  34440. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34441. var minVertexIndex = Number.MAX_VALUE;
  34442. var maxVertexIndex = -Number.MAX_VALUE;
  34443. renderingMesh = (renderingMesh || mesh);
  34444. var indices = renderingMesh.getIndices();
  34445. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34446. var vertexIndex = indices[index];
  34447. if (vertexIndex < minVertexIndex)
  34448. minVertexIndex = vertexIndex;
  34449. if (vertexIndex > maxVertexIndex)
  34450. maxVertexIndex = vertexIndex;
  34451. }
  34452. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34453. };
  34454. return SubMesh;
  34455. }(BaseSubMesh));
  34456. BABYLON.SubMesh = SubMesh;
  34457. })(BABYLON || (BABYLON = {}));
  34458. //# sourceMappingURL=babylon.subMesh.js.map
  34459. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34460. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34461. s = arguments[i];
  34462. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34463. t[p] = s[p];
  34464. }
  34465. return t;
  34466. };
  34467. var BABYLON;
  34468. (function (BABYLON) {
  34469. /**
  34470. * Manages the defines for the Material
  34471. */
  34472. var MaterialDefines = /** @class */ (function () {
  34473. function MaterialDefines() {
  34474. this._isDirty = true;
  34475. /** @hidden */
  34476. this._areLightsDirty = true;
  34477. /** @hidden */
  34478. this._areAttributesDirty = true;
  34479. /** @hidden */
  34480. this._areTexturesDirty = true;
  34481. /** @hidden */
  34482. this._areFresnelDirty = true;
  34483. /** @hidden */
  34484. this._areMiscDirty = true;
  34485. /** @hidden */
  34486. this._areImageProcessingDirty = true;
  34487. /** @hidden */
  34488. this._normals = false;
  34489. /** @hidden */
  34490. this._uvs = false;
  34491. /** @hidden */
  34492. this._needNormals = false;
  34493. /** @hidden */
  34494. this._needUVs = false;
  34495. }
  34496. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34497. /**
  34498. * Specifies if the material needs to be re-calculated
  34499. */
  34500. get: function () {
  34501. return this._isDirty;
  34502. },
  34503. enumerable: true,
  34504. configurable: true
  34505. });
  34506. /**
  34507. * Marks the material to indicate that it has been re-calculated
  34508. */
  34509. MaterialDefines.prototype.markAsProcessed = function () {
  34510. this._isDirty = false;
  34511. this._areAttributesDirty = false;
  34512. this._areTexturesDirty = false;
  34513. this._areFresnelDirty = false;
  34514. this._areLightsDirty = false;
  34515. this._areMiscDirty = false;
  34516. this._areImageProcessingDirty = false;
  34517. };
  34518. /**
  34519. * Marks the material to indicate that it needs to be re-calculated
  34520. */
  34521. MaterialDefines.prototype.markAsUnprocessed = function () {
  34522. this._isDirty = true;
  34523. };
  34524. /**
  34525. * Marks the material to indicate all of its defines need to be re-calculated
  34526. */
  34527. MaterialDefines.prototype.markAllAsDirty = function () {
  34528. this._areTexturesDirty = true;
  34529. this._areAttributesDirty = true;
  34530. this._areLightsDirty = true;
  34531. this._areFresnelDirty = true;
  34532. this._areMiscDirty = true;
  34533. this._areImageProcessingDirty = true;
  34534. this._isDirty = true;
  34535. };
  34536. /**
  34537. * Marks the material to indicate that image processing needs to be re-calculated
  34538. */
  34539. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34540. this._areImageProcessingDirty = true;
  34541. this._isDirty = true;
  34542. };
  34543. /**
  34544. * Marks the material to indicate the lights need to be re-calculated
  34545. */
  34546. MaterialDefines.prototype.markAsLightDirty = function () {
  34547. this._areLightsDirty = true;
  34548. this._isDirty = true;
  34549. };
  34550. /**
  34551. * Marks the attribute state as changed
  34552. */
  34553. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34554. this._areAttributesDirty = true;
  34555. this._isDirty = true;
  34556. };
  34557. /**
  34558. * Marks the texture state as changed
  34559. */
  34560. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34561. this._areTexturesDirty = true;
  34562. this._isDirty = true;
  34563. };
  34564. /**
  34565. * Marks the fresnel state as changed
  34566. */
  34567. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34568. this._areFresnelDirty = true;
  34569. this._isDirty = true;
  34570. };
  34571. /**
  34572. * Marks the misc state as changed
  34573. */
  34574. MaterialDefines.prototype.markAsMiscDirty = function () {
  34575. this._areMiscDirty = true;
  34576. this._isDirty = true;
  34577. };
  34578. /**
  34579. * Rebuilds the material defines
  34580. */
  34581. MaterialDefines.prototype.rebuild = function () {
  34582. if (this._keys) {
  34583. delete this._keys;
  34584. }
  34585. this._keys = [];
  34586. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34587. var key = _a[_i];
  34588. if (key[0] === "_") {
  34589. continue;
  34590. }
  34591. this._keys.push(key);
  34592. }
  34593. };
  34594. /**
  34595. * Specifies if two material defines are equal
  34596. * @param other - A material define instance to compare to
  34597. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34598. */
  34599. MaterialDefines.prototype.isEqual = function (other) {
  34600. if (this._keys.length !== other._keys.length) {
  34601. return false;
  34602. }
  34603. for (var index = 0; index < this._keys.length; index++) {
  34604. var prop = this._keys[index];
  34605. if (this[prop] !== other[prop]) {
  34606. return false;
  34607. }
  34608. }
  34609. return true;
  34610. };
  34611. /**
  34612. * Clones this instance's defines to another instance
  34613. * @param other - material defines to clone values to
  34614. */
  34615. MaterialDefines.prototype.cloneTo = function (other) {
  34616. if (this._keys.length !== other._keys.length) {
  34617. other._keys = this._keys.slice(0);
  34618. }
  34619. for (var index = 0; index < this._keys.length; index++) {
  34620. var prop = this._keys[index];
  34621. other[prop] = this[prop];
  34622. }
  34623. };
  34624. /**
  34625. * Resets the material define values
  34626. */
  34627. MaterialDefines.prototype.reset = function () {
  34628. for (var index = 0; index < this._keys.length; index++) {
  34629. var prop = this._keys[index];
  34630. var type = typeof this[prop];
  34631. switch (type) {
  34632. case "number":
  34633. this[prop] = 0;
  34634. break;
  34635. case "string":
  34636. this[prop] = "";
  34637. break;
  34638. default:
  34639. this[prop] = false;
  34640. break;
  34641. }
  34642. }
  34643. };
  34644. /**
  34645. * Converts the material define values to a string
  34646. * @returns - String of material define information
  34647. */
  34648. MaterialDefines.prototype.toString = function () {
  34649. var result = "";
  34650. for (var index = 0; index < this._keys.length; index++) {
  34651. var prop = this._keys[index];
  34652. var value = this[prop];
  34653. var type = typeof value;
  34654. switch (type) {
  34655. case "number":
  34656. case "string":
  34657. result += "#define " + prop + " " + value + "\n";
  34658. break;
  34659. default:
  34660. if (value) {
  34661. result += "#define " + prop + "\n";
  34662. }
  34663. break;
  34664. }
  34665. }
  34666. return result;
  34667. };
  34668. return MaterialDefines;
  34669. }());
  34670. BABYLON.MaterialDefines = MaterialDefines;
  34671. /**
  34672. * Base class for the main features of a material in Babylon.js
  34673. */
  34674. var Material = /** @class */ (function () {
  34675. /**
  34676. * Creates a material instance
  34677. * @param name defines the name of the material
  34678. * @param scene defines the scene to reference
  34679. * @param doNotAdd specifies if the material should be added to the scene
  34680. */
  34681. function Material(name, scene, doNotAdd) {
  34682. /**
  34683. * Specifies if the ready state should be checked on each call
  34684. */
  34685. this.checkReadyOnEveryCall = false;
  34686. /**
  34687. * Specifies if the ready state should be checked once
  34688. */
  34689. this.checkReadyOnlyOnce = false;
  34690. /**
  34691. * The state of the material
  34692. */
  34693. this.state = "";
  34694. /**
  34695. * The alpha value of the material
  34696. */
  34697. this._alpha = 1.0;
  34698. /**
  34699. * Specifies if back face culling is enabled
  34700. */
  34701. this._backFaceCulling = true;
  34702. /**
  34703. * Specifies if the material should be serialized
  34704. */
  34705. this.doNotSerialize = false;
  34706. /**
  34707. * Specifies if the effect should be stored on sub meshes
  34708. */
  34709. this.storeEffectOnSubMeshes = false;
  34710. /**
  34711. * An event triggered when the material is disposed
  34712. */
  34713. this.onDisposeObservable = new BABYLON.Observable();
  34714. /**
  34715. * An event triggered when the material is bound
  34716. */
  34717. this.onBindObservable = new BABYLON.Observable();
  34718. /**
  34719. * An event triggered when the material is unbound
  34720. */
  34721. this.onUnBindObservable = new BABYLON.Observable();
  34722. /**
  34723. * Stores the value of the alpha mode
  34724. */
  34725. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34726. /**
  34727. * Stores the state of the need depth pre-pass value
  34728. */
  34729. this._needDepthPrePass = false;
  34730. /**
  34731. * Specifies if depth writing should be disabled
  34732. */
  34733. this.disableDepthWrite = false;
  34734. /**
  34735. * Specifies if depth writing should be forced
  34736. */
  34737. this.forceDepthWrite = false;
  34738. /**
  34739. * Specifies if there should be a separate pass for culling
  34740. */
  34741. this.separateCullingPass = false;
  34742. /**
  34743. * Stores the state specifing if fog should be enabled
  34744. */
  34745. this._fogEnabled = true;
  34746. /**
  34747. * Stores the size of points
  34748. */
  34749. this.pointSize = 1.0;
  34750. /**
  34751. * Stores the z offset value
  34752. */
  34753. this.zOffset = 0;
  34754. /**
  34755. * Specifies if the material was previously ready
  34756. */
  34757. this._wasPreviouslyReady = false;
  34758. /**
  34759. * Stores the fill mode state
  34760. */
  34761. this._fillMode = Material.TriangleFillMode;
  34762. this.name = name;
  34763. this.id = name || BABYLON.Tools.RandomId();
  34764. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34765. if (this._scene.useRightHandedSystem) {
  34766. this.sideOrientation = Material.ClockWiseSideOrientation;
  34767. }
  34768. else {
  34769. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34770. }
  34771. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34772. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34773. if (!doNotAdd) {
  34774. this._scene.materials.push(this);
  34775. }
  34776. }
  34777. Object.defineProperty(Material, "TriangleFillMode", {
  34778. /**
  34779. * Returns the triangle fill mode
  34780. */
  34781. get: function () {
  34782. return Material._TriangleFillMode;
  34783. },
  34784. enumerable: true,
  34785. configurable: true
  34786. });
  34787. Object.defineProperty(Material, "WireFrameFillMode", {
  34788. /**
  34789. * Returns the wireframe mode
  34790. */
  34791. get: function () {
  34792. return Material._WireFrameFillMode;
  34793. },
  34794. enumerable: true,
  34795. configurable: true
  34796. });
  34797. Object.defineProperty(Material, "PointFillMode", {
  34798. /**
  34799. * Returns the point fill mode
  34800. */
  34801. get: function () {
  34802. return Material._PointFillMode;
  34803. },
  34804. enumerable: true,
  34805. configurable: true
  34806. });
  34807. Object.defineProperty(Material, "PointListDrawMode", {
  34808. /**
  34809. * Returns the point list draw mode
  34810. */
  34811. get: function () {
  34812. return Material._PointListDrawMode;
  34813. },
  34814. enumerable: true,
  34815. configurable: true
  34816. });
  34817. Object.defineProperty(Material, "LineListDrawMode", {
  34818. /**
  34819. * Returns the line list draw mode
  34820. */
  34821. get: function () {
  34822. return Material._LineListDrawMode;
  34823. },
  34824. enumerable: true,
  34825. configurable: true
  34826. });
  34827. Object.defineProperty(Material, "LineLoopDrawMode", {
  34828. /**
  34829. * Returns the line loop draw mode
  34830. */
  34831. get: function () {
  34832. return Material._LineLoopDrawMode;
  34833. },
  34834. enumerable: true,
  34835. configurable: true
  34836. });
  34837. Object.defineProperty(Material, "LineStripDrawMode", {
  34838. /**
  34839. * Returns the line strip draw mode
  34840. */
  34841. get: function () {
  34842. return Material._LineStripDrawMode;
  34843. },
  34844. enumerable: true,
  34845. configurable: true
  34846. });
  34847. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34848. /**
  34849. * Returns the triangle strip draw mode
  34850. */
  34851. get: function () {
  34852. return Material._TriangleStripDrawMode;
  34853. },
  34854. enumerable: true,
  34855. configurable: true
  34856. });
  34857. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34858. /**
  34859. * Returns the triangle fan draw mode
  34860. */
  34861. get: function () {
  34862. return Material._TriangleFanDrawMode;
  34863. },
  34864. enumerable: true,
  34865. configurable: true
  34866. });
  34867. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34868. /**
  34869. * Returns the clock-wise side orientation
  34870. */
  34871. get: function () {
  34872. return Material._ClockWiseSideOrientation;
  34873. },
  34874. enumerable: true,
  34875. configurable: true
  34876. });
  34877. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34878. /**
  34879. * Returns the counter clock-wise side orientation
  34880. */
  34881. get: function () {
  34882. return Material._CounterClockWiseSideOrientation;
  34883. },
  34884. enumerable: true,
  34885. configurable: true
  34886. });
  34887. Object.defineProperty(Material, "TextureDirtyFlag", {
  34888. /**
  34889. * Returns the dirty texture flag value
  34890. */
  34891. get: function () {
  34892. return Material._TextureDirtyFlag;
  34893. },
  34894. enumerable: true,
  34895. configurable: true
  34896. });
  34897. Object.defineProperty(Material, "LightDirtyFlag", {
  34898. /**
  34899. * Returns the dirty light flag value
  34900. */
  34901. get: function () {
  34902. return Material._LightDirtyFlag;
  34903. },
  34904. enumerable: true,
  34905. configurable: true
  34906. });
  34907. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34908. /**
  34909. * Returns the dirty fresnel flag value
  34910. */
  34911. get: function () {
  34912. return Material._FresnelDirtyFlag;
  34913. },
  34914. enumerable: true,
  34915. configurable: true
  34916. });
  34917. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34918. /**
  34919. * Returns the dirty attributes flag value
  34920. */
  34921. get: function () {
  34922. return Material._AttributesDirtyFlag;
  34923. },
  34924. enumerable: true,
  34925. configurable: true
  34926. });
  34927. Object.defineProperty(Material, "MiscDirtyFlag", {
  34928. /**
  34929. * Returns the dirty misc flag value
  34930. */
  34931. get: function () {
  34932. return Material._MiscDirtyFlag;
  34933. },
  34934. enumerable: true,
  34935. configurable: true
  34936. });
  34937. Object.defineProperty(Material.prototype, "alpha", {
  34938. /**
  34939. * Gets the alpha value of the material
  34940. */
  34941. get: function () {
  34942. return this._alpha;
  34943. },
  34944. /**
  34945. * Sets the alpha value of the material
  34946. */
  34947. set: function (value) {
  34948. if (this._alpha === value) {
  34949. return;
  34950. }
  34951. this._alpha = value;
  34952. this.markAsDirty(Material.MiscDirtyFlag);
  34953. },
  34954. enumerable: true,
  34955. configurable: true
  34956. });
  34957. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34958. /**
  34959. * Gets the back-face culling state
  34960. */
  34961. get: function () {
  34962. return this._backFaceCulling;
  34963. },
  34964. /**
  34965. * Sets the back-face culling state
  34966. */
  34967. set: function (value) {
  34968. if (this._backFaceCulling === value) {
  34969. return;
  34970. }
  34971. this._backFaceCulling = value;
  34972. this.markAsDirty(Material.TextureDirtyFlag);
  34973. },
  34974. enumerable: true,
  34975. configurable: true
  34976. });
  34977. Object.defineProperty(Material.prototype, "onDispose", {
  34978. /**
  34979. * Called during a dispose event
  34980. */
  34981. set: function (callback) {
  34982. if (this._onDisposeObserver) {
  34983. this.onDisposeObservable.remove(this._onDisposeObserver);
  34984. }
  34985. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34986. },
  34987. enumerable: true,
  34988. configurable: true
  34989. });
  34990. Object.defineProperty(Material.prototype, "onBind", {
  34991. /**
  34992. * Called during a bind event
  34993. */
  34994. set: function (callback) {
  34995. if (this._onBindObserver) {
  34996. this.onBindObservable.remove(this._onBindObserver);
  34997. }
  34998. this._onBindObserver = this.onBindObservable.add(callback);
  34999. },
  35000. enumerable: true,
  35001. configurable: true
  35002. });
  35003. Object.defineProperty(Material.prototype, "alphaMode", {
  35004. /**
  35005. * Gets the value of the alpha mode
  35006. */
  35007. get: function () {
  35008. return this._alphaMode;
  35009. },
  35010. /**
  35011. * Sets the value of the alpha mode.
  35012. *
  35013. * | Value | Type | Description |
  35014. * | --- | --- | --- |
  35015. * | 0 | ALPHA_DISABLE | |
  35016. * | 1 | ALPHA_ADD | |
  35017. * | 2 | ALPHA_COMBINE | |
  35018. * | 3 | ALPHA_SUBTRACT | |
  35019. * | 4 | ALPHA_MULTIPLY | |
  35020. * | 5 | ALPHA_MAXIMIZED | |
  35021. * | 6 | ALPHA_ONEONE | |
  35022. * | 7 | ALPHA_PREMULTIPLIED | |
  35023. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35024. * | 9 | ALPHA_INTERPOLATE | |
  35025. * | 10 | ALPHA_SCREENMODE | |
  35026. *
  35027. */
  35028. set: function (value) {
  35029. if (this._alphaMode === value) {
  35030. return;
  35031. }
  35032. this._alphaMode = value;
  35033. this.markAsDirty(Material.TextureDirtyFlag);
  35034. },
  35035. enumerable: true,
  35036. configurable: true
  35037. });
  35038. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35039. /**
  35040. * Gets the depth pre-pass value
  35041. */
  35042. get: function () {
  35043. return this._needDepthPrePass;
  35044. },
  35045. /**
  35046. * Sets the need depth pre-pass value
  35047. */
  35048. set: function (value) {
  35049. if (this._needDepthPrePass === value) {
  35050. return;
  35051. }
  35052. this._needDepthPrePass = value;
  35053. if (this._needDepthPrePass) {
  35054. this.checkReadyOnEveryCall = true;
  35055. }
  35056. },
  35057. enumerable: true,
  35058. configurable: true
  35059. });
  35060. Object.defineProperty(Material.prototype, "fogEnabled", {
  35061. /**
  35062. * Gets the value of the fog enabled state
  35063. */
  35064. get: function () {
  35065. return this._fogEnabled;
  35066. },
  35067. /**
  35068. * Sets the state for enabling fog
  35069. */
  35070. set: function (value) {
  35071. if (this._fogEnabled === value) {
  35072. return;
  35073. }
  35074. this._fogEnabled = value;
  35075. this.markAsDirty(Material.MiscDirtyFlag);
  35076. },
  35077. enumerable: true,
  35078. configurable: true
  35079. });
  35080. Object.defineProperty(Material.prototype, "wireframe", {
  35081. /**
  35082. * Gets a value specifying if wireframe mode is enabled
  35083. */
  35084. get: function () {
  35085. switch (this._fillMode) {
  35086. case Material.WireFrameFillMode:
  35087. case Material.LineListDrawMode:
  35088. case Material.LineLoopDrawMode:
  35089. case Material.LineStripDrawMode:
  35090. return true;
  35091. }
  35092. return this._scene.forceWireframe;
  35093. },
  35094. /**
  35095. * Sets the state of wireframe mode
  35096. */
  35097. set: function (value) {
  35098. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35099. },
  35100. enumerable: true,
  35101. configurable: true
  35102. });
  35103. Object.defineProperty(Material.prototype, "pointsCloud", {
  35104. /**
  35105. * Gets the value specifying if point clouds are enabled
  35106. */
  35107. get: function () {
  35108. switch (this._fillMode) {
  35109. case Material.PointFillMode:
  35110. case Material.PointListDrawMode:
  35111. return true;
  35112. }
  35113. return this._scene.forcePointsCloud;
  35114. },
  35115. /**
  35116. * Sets the state of point cloud mode
  35117. */
  35118. set: function (value) {
  35119. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35120. },
  35121. enumerable: true,
  35122. configurable: true
  35123. });
  35124. Object.defineProperty(Material.prototype, "fillMode", {
  35125. /**
  35126. * Gets the material fill mode
  35127. */
  35128. get: function () {
  35129. return this._fillMode;
  35130. },
  35131. /**
  35132. * Sets the material fill mode
  35133. */
  35134. set: function (value) {
  35135. if (this._fillMode === value) {
  35136. return;
  35137. }
  35138. this._fillMode = value;
  35139. this.markAsDirty(Material.MiscDirtyFlag);
  35140. },
  35141. enumerable: true,
  35142. configurable: true
  35143. });
  35144. /**
  35145. * Returns a string representation of the current material
  35146. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35147. * @returns a string with material information
  35148. */
  35149. Material.prototype.toString = function (fullDetails) {
  35150. var ret = "Name: " + this.name;
  35151. if (fullDetails) {
  35152. }
  35153. return ret;
  35154. };
  35155. /**
  35156. * Gets the class name of the material
  35157. * @returns a string with the class name of the material
  35158. */
  35159. Material.prototype.getClassName = function () {
  35160. return "Material";
  35161. };
  35162. Object.defineProperty(Material.prototype, "isFrozen", {
  35163. /**
  35164. * Specifies if updates for the material been locked
  35165. */
  35166. get: function () {
  35167. return this.checkReadyOnlyOnce;
  35168. },
  35169. enumerable: true,
  35170. configurable: true
  35171. });
  35172. /**
  35173. * Locks updates for the material
  35174. */
  35175. Material.prototype.freeze = function () {
  35176. this.checkReadyOnlyOnce = true;
  35177. };
  35178. /**
  35179. * Unlocks updates for the material
  35180. */
  35181. Material.prototype.unfreeze = function () {
  35182. this.checkReadyOnlyOnce = false;
  35183. };
  35184. /**
  35185. * Specifies if the material is ready to be used
  35186. * @param mesh defines the mesh to check
  35187. * @param useInstances specifies if instances should be used
  35188. * @returns a boolean indicating if the material is ready to be used
  35189. */
  35190. Material.prototype.isReady = function (mesh, useInstances) {
  35191. return true;
  35192. };
  35193. /**
  35194. * Specifies that the submesh is ready to be used
  35195. * @param mesh defines the mesh to check
  35196. * @param subMesh defines which submesh to check
  35197. * @param useInstances specifies that instances should be used
  35198. * @returns a boolean indicating that the submesh is ready or not
  35199. */
  35200. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35201. return false;
  35202. };
  35203. /**
  35204. * Returns the material effect
  35205. * @returns the effect associated with the material
  35206. */
  35207. Material.prototype.getEffect = function () {
  35208. return this._effect;
  35209. };
  35210. /**
  35211. * Returns the current scene
  35212. * @returns a Scene
  35213. */
  35214. Material.prototype.getScene = function () {
  35215. return this._scene;
  35216. };
  35217. /**
  35218. * Specifies if the material will require alpha blending
  35219. * @returns a boolean specifying if alpha blending is needed
  35220. */
  35221. Material.prototype.needAlphaBlending = function () {
  35222. return (this.alpha < 1.0);
  35223. };
  35224. /**
  35225. * Specifies if the mesh will require alpha blending
  35226. * @param mesh defines the mesh to check
  35227. * @returns a boolean specifying if alpha blending is needed for the mesh
  35228. */
  35229. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35230. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35231. };
  35232. /**
  35233. * Specifies if this material should be rendered in alpha test mode
  35234. * @returns a boolean specifying if an alpha test is needed.
  35235. */
  35236. Material.prototype.needAlphaTesting = function () {
  35237. return false;
  35238. };
  35239. /**
  35240. * Gets the texture used for the alpha test
  35241. * @returns the texture to use for alpha testing
  35242. */
  35243. Material.prototype.getAlphaTestTexture = function () {
  35244. return null;
  35245. };
  35246. /**
  35247. * Marks the material to indicate that it needs to be re-calculated
  35248. */
  35249. Material.prototype.markDirty = function () {
  35250. this._wasPreviouslyReady = false;
  35251. };
  35252. /** @hidden */
  35253. Material.prototype._preBind = function (effect, overrideOrientation) {
  35254. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35255. var engine = this._scene.getEngine();
  35256. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35257. var reverse = orientation === Material.ClockWiseSideOrientation;
  35258. engine.enableEffect(effect ? effect : this._effect);
  35259. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35260. return reverse;
  35261. };
  35262. /**
  35263. * Binds the material to the mesh
  35264. * @param world defines the world transformation matrix
  35265. * @param mesh defines the mesh to bind the material to
  35266. */
  35267. Material.prototype.bind = function (world, mesh) {
  35268. };
  35269. /**
  35270. * Binds the submesh to the material
  35271. * @param world defines the world transformation matrix
  35272. * @param mesh defines the mesh containing the submesh
  35273. * @param subMesh defines the submesh to bind the material to
  35274. */
  35275. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35276. };
  35277. /**
  35278. * Binds the world matrix to the material
  35279. * @param world defines the world transformation matrix
  35280. */
  35281. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35282. };
  35283. /**
  35284. * Binds the scene's uniform buffer to the effect.
  35285. * @param effect defines the effect to bind to the scene uniform buffer
  35286. * @param sceneUbo defines the uniform buffer storing scene data
  35287. */
  35288. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35289. sceneUbo.bindToEffect(effect, "Scene");
  35290. };
  35291. /**
  35292. * Binds the view matrix to the effect
  35293. * @param effect defines the effect to bind the view matrix to
  35294. */
  35295. Material.prototype.bindView = function (effect) {
  35296. if (!this._useUBO) {
  35297. effect.setMatrix("view", this.getScene().getViewMatrix());
  35298. }
  35299. else {
  35300. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35301. }
  35302. };
  35303. /**
  35304. * Binds the view projection matrix to the effect
  35305. * @param effect defines the effect to bind the view projection matrix to
  35306. */
  35307. Material.prototype.bindViewProjection = function (effect) {
  35308. if (!this._useUBO) {
  35309. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35310. }
  35311. else {
  35312. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35313. }
  35314. };
  35315. /**
  35316. * Specifies if material alpha testing should be turned on for the mesh
  35317. * @param mesh defines the mesh to check
  35318. */
  35319. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35320. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35321. };
  35322. /**
  35323. * Processes to execute after binding the material to a mesh
  35324. * @param mesh defines the rendered mesh
  35325. */
  35326. Material.prototype._afterBind = function (mesh) {
  35327. this._scene._cachedMaterial = this;
  35328. if (mesh) {
  35329. this._scene._cachedVisibility = mesh.visibility;
  35330. }
  35331. else {
  35332. this._scene._cachedVisibility = 1;
  35333. }
  35334. if (mesh) {
  35335. this.onBindObservable.notifyObservers(mesh);
  35336. }
  35337. if (this.disableDepthWrite) {
  35338. var engine = this._scene.getEngine();
  35339. this._cachedDepthWriteState = engine.getDepthWrite();
  35340. engine.setDepthWrite(false);
  35341. }
  35342. };
  35343. /**
  35344. * Unbinds the material from the mesh
  35345. */
  35346. Material.prototype.unbind = function () {
  35347. this.onUnBindObservable.notifyObservers(this);
  35348. if (this.disableDepthWrite) {
  35349. var engine = this._scene.getEngine();
  35350. engine.setDepthWrite(this._cachedDepthWriteState);
  35351. }
  35352. };
  35353. /**
  35354. * Gets the active textures from the material
  35355. * @returns an array of textures
  35356. */
  35357. Material.prototype.getActiveTextures = function () {
  35358. return [];
  35359. };
  35360. /**
  35361. * Specifies if the material uses a texture
  35362. * @param texture defines the texture to check against the material
  35363. * @returns a boolean specifying if the material uses the texture
  35364. */
  35365. Material.prototype.hasTexture = function (texture) {
  35366. return false;
  35367. };
  35368. /**
  35369. * Makes a duplicate of the material, and gives it a new name
  35370. * @param name defines the new name for the duplicated material
  35371. * @returns the cloned material
  35372. */
  35373. Material.prototype.clone = function (name) {
  35374. return null;
  35375. };
  35376. /**
  35377. * Gets the meshes bound to the material
  35378. * @returns an array of meshes bound to the material
  35379. */
  35380. Material.prototype.getBindedMeshes = function () {
  35381. var result = new Array();
  35382. for (var index = 0; index < this._scene.meshes.length; index++) {
  35383. var mesh = this._scene.meshes[index];
  35384. if (mesh.material === this) {
  35385. result.push(mesh);
  35386. }
  35387. }
  35388. return result;
  35389. };
  35390. /**
  35391. * Force shader compilation
  35392. * @param mesh defines the mesh associated with this material
  35393. * @param onCompiled defines a function to execute once the material is compiled
  35394. * @param options defines the options to configure the compilation
  35395. */
  35396. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35397. var _this = this;
  35398. var localOptions = __assign({ clipPlane: false }, options);
  35399. var subMesh = new BABYLON.BaseSubMesh();
  35400. var scene = this.getScene();
  35401. var checkReady = function () {
  35402. if (!_this._scene || !_this._scene.getEngine()) {
  35403. return;
  35404. }
  35405. if (subMesh._materialDefines) {
  35406. subMesh._materialDefines._renderId = -1;
  35407. }
  35408. var clipPlaneState = scene.clipPlane;
  35409. if (localOptions.clipPlane) {
  35410. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35411. }
  35412. if (_this.storeEffectOnSubMeshes) {
  35413. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35414. if (onCompiled) {
  35415. onCompiled(_this);
  35416. }
  35417. }
  35418. else {
  35419. setTimeout(checkReady, 16);
  35420. }
  35421. }
  35422. else {
  35423. if (_this.isReady(mesh)) {
  35424. if (onCompiled) {
  35425. onCompiled(_this);
  35426. }
  35427. }
  35428. else {
  35429. setTimeout(checkReady, 16);
  35430. }
  35431. }
  35432. if (localOptions.clipPlane) {
  35433. scene.clipPlane = clipPlaneState;
  35434. }
  35435. };
  35436. checkReady();
  35437. };
  35438. /**
  35439. * Force shader compilation
  35440. * @param mesh defines the mesh that will use this material
  35441. * @param options defines additional options for compiling the shaders
  35442. * @returns a promise that resolves when the compilation completes
  35443. */
  35444. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35445. var _this = this;
  35446. return new Promise(function (resolve) {
  35447. _this.forceCompilation(mesh, function () {
  35448. resolve();
  35449. }, options);
  35450. });
  35451. };
  35452. /**
  35453. * Marks a define in the material to indicate that it needs to be re-computed
  35454. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35455. */
  35456. Material.prototype.markAsDirty = function (flag) {
  35457. if (flag & Material.TextureDirtyFlag) {
  35458. this._markAllSubMeshesAsTexturesDirty();
  35459. }
  35460. if (flag & Material.LightDirtyFlag) {
  35461. this._markAllSubMeshesAsLightsDirty();
  35462. }
  35463. if (flag & Material.FresnelDirtyFlag) {
  35464. this._markAllSubMeshesAsFresnelDirty();
  35465. }
  35466. if (flag & Material.AttributesDirtyFlag) {
  35467. this._markAllSubMeshesAsAttributesDirty();
  35468. }
  35469. if (flag & Material.MiscDirtyFlag) {
  35470. this._markAllSubMeshesAsMiscDirty();
  35471. }
  35472. this.getScene().resetCachedMaterial();
  35473. };
  35474. /**
  35475. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35476. * @param func defines a function which checks material defines against the submeshes
  35477. */
  35478. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35479. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35480. var mesh = _a[_i];
  35481. if (!mesh.subMeshes) {
  35482. continue;
  35483. }
  35484. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35485. var subMesh = _c[_b];
  35486. if (subMesh.getMaterial() !== this) {
  35487. continue;
  35488. }
  35489. if (!subMesh._materialDefines) {
  35490. continue;
  35491. }
  35492. func(subMesh._materialDefines);
  35493. }
  35494. }
  35495. };
  35496. /**
  35497. * Indicates that image processing needs to be re-calculated for all submeshes
  35498. */
  35499. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35500. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35501. };
  35502. /**
  35503. * Indicates that textures need to be re-calculated for all submeshes
  35504. */
  35505. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35506. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35507. };
  35508. /**
  35509. * Indicates that fresnel needs to be re-calculated for all submeshes
  35510. */
  35511. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35512. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35513. };
  35514. /**
  35515. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35516. */
  35517. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35518. this._markAllSubMeshesAsDirty(function (defines) {
  35519. defines.markAsFresnelDirty();
  35520. defines.markAsMiscDirty();
  35521. });
  35522. };
  35523. /**
  35524. * Indicates that lights need to be re-calculated for all submeshes
  35525. */
  35526. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35527. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35528. };
  35529. /**
  35530. * Indicates that attributes need to be re-calculated for all submeshes
  35531. */
  35532. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35533. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35534. };
  35535. /**
  35536. * Indicates that misc needs to be re-calculated for all submeshes
  35537. */
  35538. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35539. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35540. };
  35541. /**
  35542. * Indicates that textures and misc need to be re-calculated for all submeshes
  35543. */
  35544. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35545. this._markAllSubMeshesAsDirty(function (defines) {
  35546. defines.markAsTexturesDirty();
  35547. defines.markAsMiscDirty();
  35548. });
  35549. };
  35550. /**
  35551. * Disposes the material
  35552. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35553. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35554. */
  35555. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35556. // Animations
  35557. this.getScene().stopAnimation(this);
  35558. this.getScene().freeProcessedMaterials();
  35559. // Remove from scene
  35560. var index = this._scene.materials.indexOf(this);
  35561. if (index >= 0) {
  35562. this._scene.materials.splice(index, 1);
  35563. }
  35564. // Remove from meshes
  35565. for (index = 0; index < this._scene.meshes.length; index++) {
  35566. var mesh = this._scene.meshes[index];
  35567. if (mesh.material === this) {
  35568. mesh.material = null;
  35569. if (mesh.geometry) {
  35570. var geometry = (mesh.geometry);
  35571. if (this.storeEffectOnSubMeshes) {
  35572. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35573. var subMesh = _a[_i];
  35574. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35575. if (forceDisposeEffect && subMesh._materialEffect) {
  35576. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35577. }
  35578. }
  35579. }
  35580. else {
  35581. geometry._releaseVertexArrayObject(this._effect);
  35582. }
  35583. }
  35584. }
  35585. }
  35586. this._uniformBuffer.dispose();
  35587. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35588. if (forceDisposeEffect && this._effect) {
  35589. if (!this.storeEffectOnSubMeshes) {
  35590. this._scene.getEngine()._releaseEffect(this._effect);
  35591. }
  35592. this._effect = null;
  35593. }
  35594. // Callback
  35595. this.onDisposeObservable.notifyObservers(this);
  35596. this.onDisposeObservable.clear();
  35597. this.onBindObservable.clear();
  35598. this.onUnBindObservable.clear();
  35599. };
  35600. /**
  35601. * Serializes this material
  35602. * @returns the serialized material object
  35603. */
  35604. Material.prototype.serialize = function () {
  35605. return BABYLON.SerializationHelper.Serialize(this);
  35606. };
  35607. /**
  35608. * Creates a MultiMaterial from parsed MultiMaterial data.
  35609. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35610. * @param scene defines the hosting scene
  35611. * @returns a new MultiMaterial
  35612. */
  35613. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35614. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35615. multiMaterial.id = parsedMultiMaterial.id;
  35616. if (BABYLON.Tags) {
  35617. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35618. }
  35619. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35620. var subMatId = parsedMultiMaterial.materials[matIndex];
  35621. if (subMatId) {
  35622. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35623. }
  35624. else {
  35625. multiMaterial.subMaterials.push(null);
  35626. }
  35627. }
  35628. return multiMaterial;
  35629. };
  35630. /**
  35631. * Creates a material from parsed material data
  35632. * @param parsedMaterial defines parsed material data
  35633. * @param scene defines the hosting scene
  35634. * @param rootUrl defines the root URL to use to load textures
  35635. * @returns a new material
  35636. */
  35637. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35638. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35639. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35640. }
  35641. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35642. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35643. if (!BABYLON.LegacyPBRMaterial) {
  35644. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35645. return;
  35646. }
  35647. }
  35648. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35649. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35650. };
  35651. // Triangle views
  35652. Material._TriangleFillMode = 0;
  35653. Material._WireFrameFillMode = 1;
  35654. Material._PointFillMode = 2;
  35655. // Draw modes
  35656. Material._PointListDrawMode = 3;
  35657. Material._LineListDrawMode = 4;
  35658. Material._LineLoopDrawMode = 5;
  35659. Material._LineStripDrawMode = 6;
  35660. Material._TriangleStripDrawMode = 7;
  35661. Material._TriangleFanDrawMode = 8;
  35662. /**
  35663. * Stores the clock-wise side orientation
  35664. */
  35665. Material._ClockWiseSideOrientation = 0;
  35666. /**
  35667. * Stores the counter clock-wise side orientation
  35668. */
  35669. Material._CounterClockWiseSideOrientation = 1;
  35670. /**
  35671. * The dirty texture flag value
  35672. */
  35673. Material._TextureDirtyFlag = 1;
  35674. /**
  35675. * The dirty light flag value
  35676. */
  35677. Material._LightDirtyFlag = 2;
  35678. /**
  35679. * The dirty fresnel flag value
  35680. */
  35681. Material._FresnelDirtyFlag = 4;
  35682. /**
  35683. * The dirty attribute flag value
  35684. */
  35685. Material._AttributesDirtyFlag = 8;
  35686. /**
  35687. * The dirty misc flag value
  35688. */
  35689. Material._MiscDirtyFlag = 16;
  35690. __decorate([
  35691. BABYLON.serialize()
  35692. ], Material.prototype, "id", void 0);
  35693. __decorate([
  35694. BABYLON.serialize()
  35695. ], Material.prototype, "name", void 0);
  35696. __decorate([
  35697. BABYLON.serialize()
  35698. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35699. __decorate([
  35700. BABYLON.serialize()
  35701. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35702. __decorate([
  35703. BABYLON.serialize()
  35704. ], Material.prototype, "state", void 0);
  35705. __decorate([
  35706. BABYLON.serialize("alpha")
  35707. ], Material.prototype, "_alpha", void 0);
  35708. __decorate([
  35709. BABYLON.serialize("backFaceCulling")
  35710. ], Material.prototype, "_backFaceCulling", void 0);
  35711. __decorate([
  35712. BABYLON.serialize()
  35713. ], Material.prototype, "sideOrientation", void 0);
  35714. __decorate([
  35715. BABYLON.serialize("alphaMode")
  35716. ], Material.prototype, "_alphaMode", void 0);
  35717. __decorate([
  35718. BABYLON.serialize()
  35719. ], Material.prototype, "_needDepthPrePass", void 0);
  35720. __decorate([
  35721. BABYLON.serialize()
  35722. ], Material.prototype, "disableDepthWrite", void 0);
  35723. __decorate([
  35724. BABYLON.serialize()
  35725. ], Material.prototype, "forceDepthWrite", void 0);
  35726. __decorate([
  35727. BABYLON.serialize()
  35728. ], Material.prototype, "separateCullingPass", void 0);
  35729. __decorate([
  35730. BABYLON.serialize("fogEnabled")
  35731. ], Material.prototype, "_fogEnabled", void 0);
  35732. __decorate([
  35733. BABYLON.serialize()
  35734. ], Material.prototype, "pointSize", void 0);
  35735. __decorate([
  35736. BABYLON.serialize()
  35737. ], Material.prototype, "zOffset", void 0);
  35738. __decorate([
  35739. BABYLON.serialize()
  35740. ], Material.prototype, "wireframe", null);
  35741. __decorate([
  35742. BABYLON.serialize()
  35743. ], Material.prototype, "pointsCloud", null);
  35744. __decorate([
  35745. BABYLON.serialize()
  35746. ], Material.prototype, "fillMode", null);
  35747. return Material;
  35748. }());
  35749. BABYLON.Material = Material;
  35750. })(BABYLON || (BABYLON = {}));
  35751. //# sourceMappingURL=babylon.material.js.map
  35752. var BABYLON;
  35753. (function (BABYLON) {
  35754. var UniformBuffer = /** @class */ (function () {
  35755. /**
  35756. * Uniform buffer objects.
  35757. *
  35758. * Handles blocks of uniform on the GPU.
  35759. *
  35760. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35761. *
  35762. * For more information, please refer to :
  35763. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35764. */
  35765. function UniformBuffer(engine, data, dynamic) {
  35766. this._engine = engine;
  35767. this._noUBO = !engine.supportsUniformBuffers;
  35768. this._dynamic = dynamic;
  35769. this._data = data || [];
  35770. this._uniformLocations = {};
  35771. this._uniformSizes = {};
  35772. this._uniformLocationPointer = 0;
  35773. this._needSync = false;
  35774. if (this._noUBO) {
  35775. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35776. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35777. this.updateFloat = this._updateFloatForEffect;
  35778. this.updateFloat2 = this._updateFloat2ForEffect;
  35779. this.updateFloat3 = this._updateFloat3ForEffect;
  35780. this.updateFloat4 = this._updateFloat4ForEffect;
  35781. this.updateMatrix = this._updateMatrixForEffect;
  35782. this.updateVector3 = this._updateVector3ForEffect;
  35783. this.updateVector4 = this._updateVector4ForEffect;
  35784. this.updateColor3 = this._updateColor3ForEffect;
  35785. this.updateColor4 = this._updateColor4ForEffect;
  35786. }
  35787. else {
  35788. this._engine._uniformBuffers.push(this);
  35789. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35790. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35791. this.updateFloat = this._updateFloatForUniform;
  35792. this.updateFloat2 = this._updateFloat2ForUniform;
  35793. this.updateFloat3 = this._updateFloat3ForUniform;
  35794. this.updateFloat4 = this._updateFloat4ForUniform;
  35795. this.updateMatrix = this._updateMatrixForUniform;
  35796. this.updateVector3 = this._updateVector3ForUniform;
  35797. this.updateVector4 = this._updateVector4ForUniform;
  35798. this.updateColor3 = this._updateColor3ForUniform;
  35799. this.updateColor4 = this._updateColor4ForUniform;
  35800. }
  35801. }
  35802. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35803. // Properties
  35804. /**
  35805. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35806. * or just falling back on setUniformXXX calls.
  35807. */
  35808. get: function () {
  35809. return !this._noUBO;
  35810. },
  35811. enumerable: true,
  35812. configurable: true
  35813. });
  35814. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35815. /**
  35816. * Indicates if the WebGL underlying uniform buffer is in sync
  35817. * with the javascript cache data.
  35818. */
  35819. get: function () {
  35820. return !this._needSync;
  35821. },
  35822. enumerable: true,
  35823. configurable: true
  35824. });
  35825. /**
  35826. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35827. * Also, a dynamic UniformBuffer will disable cache verification and always
  35828. * update the underlying WebGL uniform buffer to the GPU.
  35829. */
  35830. UniformBuffer.prototype.isDynamic = function () {
  35831. return this._dynamic !== undefined;
  35832. };
  35833. /**
  35834. * The data cache on JS side.
  35835. */
  35836. UniformBuffer.prototype.getData = function () {
  35837. return this._bufferData;
  35838. };
  35839. /**
  35840. * The underlying WebGL Uniform buffer.
  35841. */
  35842. UniformBuffer.prototype.getBuffer = function () {
  35843. return this._buffer;
  35844. };
  35845. /**
  35846. * std140 layout specifies how to align data within an UBO structure.
  35847. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35848. * for specs.
  35849. */
  35850. UniformBuffer.prototype._fillAlignment = function (size) {
  35851. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35852. // and 4x4 matrices
  35853. // TODO : change if other types are used
  35854. var alignment;
  35855. if (size <= 2) {
  35856. alignment = size;
  35857. }
  35858. else {
  35859. alignment = 4;
  35860. }
  35861. if ((this._uniformLocationPointer % alignment) !== 0) {
  35862. var oldPointer = this._uniformLocationPointer;
  35863. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35864. var diff = this._uniformLocationPointer - oldPointer;
  35865. for (var i = 0; i < diff; i++) {
  35866. this._data.push(0);
  35867. }
  35868. }
  35869. };
  35870. /**
  35871. * Adds an uniform in the buffer.
  35872. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35873. * for the layout to be correct !
  35874. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35875. * @param {number|number[]} size Data size, or data directly.
  35876. */
  35877. UniformBuffer.prototype.addUniform = function (name, size) {
  35878. if (this._noUBO) {
  35879. return;
  35880. }
  35881. if (this._uniformLocations[name] !== undefined) {
  35882. // Already existing uniform
  35883. return;
  35884. }
  35885. // This function must be called in the order of the shader layout !
  35886. // size can be the size of the uniform, or data directly
  35887. var data;
  35888. if (size instanceof Array) {
  35889. data = size;
  35890. size = data.length;
  35891. }
  35892. else {
  35893. size = size;
  35894. data = [];
  35895. // Fill with zeros
  35896. for (var i = 0; i < size; i++) {
  35897. data.push(0);
  35898. }
  35899. }
  35900. this._fillAlignment(size);
  35901. this._uniformSizes[name] = size;
  35902. this._uniformLocations[name] = this._uniformLocationPointer;
  35903. this._uniformLocationPointer += size;
  35904. for (var i = 0; i < size; i++) {
  35905. this._data.push(data[i]);
  35906. }
  35907. this._needSync = true;
  35908. };
  35909. /**
  35910. * Wrapper for addUniform.
  35911. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35912. * @param {Matrix} mat A 4x4 matrix.
  35913. */
  35914. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35915. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35916. };
  35917. /**
  35918. * Wrapper for addUniform.
  35919. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35920. * @param {number} x
  35921. * @param {number} y
  35922. */
  35923. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35924. var temp = [x, y];
  35925. this.addUniform(name, temp);
  35926. };
  35927. /**
  35928. * Wrapper for addUniform.
  35929. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35930. * @param {number} x
  35931. * @param {number} y
  35932. * @param {number} z
  35933. */
  35934. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35935. var temp = [x, y, z];
  35936. this.addUniform(name, temp);
  35937. };
  35938. /**
  35939. * Wrapper for addUniform.
  35940. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35941. * @param {Color3} color
  35942. */
  35943. UniformBuffer.prototype.addColor3 = function (name, color) {
  35944. var temp = new Array();
  35945. color.toArray(temp);
  35946. this.addUniform(name, temp);
  35947. };
  35948. /**
  35949. * Wrapper for addUniform.
  35950. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35951. * @param {Color3} color
  35952. * @param {number} alpha
  35953. */
  35954. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35955. var temp = new Array();
  35956. color.toArray(temp);
  35957. temp.push(alpha);
  35958. this.addUniform(name, temp);
  35959. };
  35960. /**
  35961. * Wrapper for addUniform.
  35962. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35963. * @param {Vector3} vector
  35964. */
  35965. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35966. var temp = new Array();
  35967. vector.toArray(temp);
  35968. this.addUniform(name, temp);
  35969. };
  35970. /**
  35971. * Wrapper for addUniform.
  35972. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35973. */
  35974. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35975. this.addUniform(name, 12);
  35976. };
  35977. /**
  35978. * Wrapper for addUniform.
  35979. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35980. */
  35981. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35982. this.addUniform(name, 8);
  35983. };
  35984. /**
  35985. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35986. */
  35987. UniformBuffer.prototype.create = function () {
  35988. if (this._noUBO) {
  35989. return;
  35990. }
  35991. if (this._buffer) {
  35992. return; // nothing to do
  35993. }
  35994. // See spec, alignment must be filled as a vec4
  35995. this._fillAlignment(4);
  35996. this._bufferData = new Float32Array(this._data);
  35997. this._rebuild();
  35998. this._needSync = true;
  35999. };
  36000. UniformBuffer.prototype._rebuild = function () {
  36001. if (this._noUBO) {
  36002. return;
  36003. }
  36004. if (this._dynamic) {
  36005. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36006. }
  36007. else {
  36008. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36009. }
  36010. };
  36011. /**
  36012. * Updates the WebGL Uniform Buffer on the GPU.
  36013. * If the `dynamic` flag is set to true, no cache comparison is done.
  36014. * Otherwise, the buffer will be updated only if the cache differs.
  36015. */
  36016. UniformBuffer.prototype.update = function () {
  36017. if (!this._buffer) {
  36018. this.create();
  36019. return;
  36020. }
  36021. if (!this._dynamic && !this._needSync) {
  36022. return;
  36023. }
  36024. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36025. this._needSync = false;
  36026. };
  36027. /**
  36028. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36029. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36030. * @param {number[]|Float32Array} data Flattened data
  36031. * @param {number} size Size of the data.
  36032. */
  36033. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36034. var location = this._uniformLocations[uniformName];
  36035. if (location === undefined) {
  36036. if (this._buffer) {
  36037. // Cannot add an uniform if the buffer is already created
  36038. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36039. return;
  36040. }
  36041. this.addUniform(uniformName, size);
  36042. location = this._uniformLocations[uniformName];
  36043. }
  36044. if (!this._buffer) {
  36045. this.create();
  36046. }
  36047. if (!this._dynamic) {
  36048. // Cache for static uniform buffers
  36049. var changed = false;
  36050. for (var i = 0; i < size; i++) {
  36051. if (this._bufferData[location + i] !== data[i]) {
  36052. changed = true;
  36053. this._bufferData[location + i] = data[i];
  36054. }
  36055. }
  36056. this._needSync = this._needSync || changed;
  36057. }
  36058. else {
  36059. // No cache for dynamic
  36060. for (var i = 0; i < size; i++) {
  36061. this._bufferData[location + i] = data[i];
  36062. }
  36063. }
  36064. };
  36065. // Update methods
  36066. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36067. // To match std140, matrix must be realigned
  36068. for (var i = 0; i < 3; i++) {
  36069. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36070. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36071. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36072. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36073. }
  36074. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36075. };
  36076. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36077. this._currentEffect.setMatrix3x3(name, matrix);
  36078. };
  36079. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36080. this._currentEffect.setMatrix2x2(name, matrix);
  36081. };
  36082. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36083. // To match std140, matrix must be realigned
  36084. for (var i = 0; i < 2; i++) {
  36085. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36086. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36087. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36088. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36089. }
  36090. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36091. };
  36092. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36093. this._currentEffect.setFloat(name, x);
  36094. };
  36095. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36096. UniformBuffer._tempBuffer[0] = x;
  36097. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36098. };
  36099. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36100. if (suffix === void 0) { suffix = ""; }
  36101. this._currentEffect.setFloat2(name + suffix, x, y);
  36102. };
  36103. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36104. if (suffix === void 0) { suffix = ""; }
  36105. UniformBuffer._tempBuffer[0] = x;
  36106. UniformBuffer._tempBuffer[1] = y;
  36107. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36108. };
  36109. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36110. if (suffix === void 0) { suffix = ""; }
  36111. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36112. };
  36113. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36114. if (suffix === void 0) { suffix = ""; }
  36115. UniformBuffer._tempBuffer[0] = x;
  36116. UniformBuffer._tempBuffer[1] = y;
  36117. UniformBuffer._tempBuffer[2] = z;
  36118. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36119. };
  36120. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36121. if (suffix === void 0) { suffix = ""; }
  36122. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36123. };
  36124. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36125. if (suffix === void 0) { suffix = ""; }
  36126. UniformBuffer._tempBuffer[0] = x;
  36127. UniformBuffer._tempBuffer[1] = y;
  36128. UniformBuffer._tempBuffer[2] = z;
  36129. UniformBuffer._tempBuffer[3] = w;
  36130. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36131. };
  36132. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36133. this._currentEffect.setMatrix(name, mat);
  36134. };
  36135. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36136. this.updateUniform(name, mat.toArray(), 16);
  36137. };
  36138. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36139. this._currentEffect.setVector3(name, vector);
  36140. };
  36141. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36142. vector.toArray(UniformBuffer._tempBuffer);
  36143. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36144. };
  36145. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36146. this._currentEffect.setVector4(name, vector);
  36147. };
  36148. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36149. vector.toArray(UniformBuffer._tempBuffer);
  36150. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36151. };
  36152. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36153. if (suffix === void 0) { suffix = ""; }
  36154. this._currentEffect.setColor3(name + suffix, color);
  36155. };
  36156. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36157. if (suffix === void 0) { suffix = ""; }
  36158. color.toArray(UniformBuffer._tempBuffer);
  36159. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36160. };
  36161. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36162. if (suffix === void 0) { suffix = ""; }
  36163. this._currentEffect.setColor4(name + suffix, color, alpha);
  36164. };
  36165. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36166. if (suffix === void 0) { suffix = ""; }
  36167. color.toArray(UniformBuffer._tempBuffer);
  36168. UniformBuffer._tempBuffer[3] = alpha;
  36169. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36170. };
  36171. /**
  36172. * Sets a sampler uniform on the effect.
  36173. * @param {string} name Name of the sampler.
  36174. * @param {Texture} texture
  36175. */
  36176. UniformBuffer.prototype.setTexture = function (name, texture) {
  36177. this._currentEffect.setTexture(name, texture);
  36178. };
  36179. /**
  36180. * Directly updates the value of the uniform in the cache AND on the GPU.
  36181. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36182. * @param {number[]|Float32Array} data Flattened data
  36183. */
  36184. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36185. this.updateUniform(uniformName, data, data.length);
  36186. this.update();
  36187. };
  36188. /**
  36189. * Binds this uniform buffer to an effect.
  36190. * @param {Effect} effect
  36191. * @param {string} name Name of the uniform block in the shader.
  36192. */
  36193. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36194. this._currentEffect = effect;
  36195. if (this._noUBO || !this._buffer) {
  36196. return;
  36197. }
  36198. effect.bindUniformBuffer(this._buffer, name);
  36199. };
  36200. /**
  36201. * Disposes the uniform buffer.
  36202. */
  36203. UniformBuffer.prototype.dispose = function () {
  36204. if (this._noUBO) {
  36205. return;
  36206. }
  36207. var index = this._engine._uniformBuffers.indexOf(this);
  36208. if (index !== -1) {
  36209. this._engine._uniformBuffers.splice(index, 1);
  36210. }
  36211. if (!this._buffer) {
  36212. return;
  36213. }
  36214. if (this._engine._releaseBuffer(this._buffer)) {
  36215. this._buffer = null;
  36216. }
  36217. };
  36218. // Pool for avoiding memory leaks
  36219. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36220. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36221. return UniformBuffer;
  36222. }());
  36223. BABYLON.UniformBuffer = UniformBuffer;
  36224. })(BABYLON || (BABYLON = {}));
  36225. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36226. var BABYLON;
  36227. (function (BABYLON) {
  36228. /**
  36229. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36230. */
  36231. var VertexData = /** @class */ (function () {
  36232. function VertexData() {
  36233. }
  36234. /**
  36235. * Uses the passed data array to set the set the values for the specified kind of data
  36236. * @param data a linear array of floating numbers
  36237. * @param kind the type of data that is being set, eg positions, colors etc
  36238. */
  36239. VertexData.prototype.set = function (data, kind) {
  36240. switch (kind) {
  36241. case BABYLON.VertexBuffer.PositionKind:
  36242. this.positions = data;
  36243. break;
  36244. case BABYLON.VertexBuffer.NormalKind:
  36245. this.normals = data;
  36246. break;
  36247. case BABYLON.VertexBuffer.TangentKind:
  36248. this.tangents = data;
  36249. break;
  36250. case BABYLON.VertexBuffer.UVKind:
  36251. this.uvs = data;
  36252. break;
  36253. case BABYLON.VertexBuffer.UV2Kind:
  36254. this.uvs2 = data;
  36255. break;
  36256. case BABYLON.VertexBuffer.UV3Kind:
  36257. this.uvs3 = data;
  36258. break;
  36259. case BABYLON.VertexBuffer.UV4Kind:
  36260. this.uvs4 = data;
  36261. break;
  36262. case BABYLON.VertexBuffer.UV5Kind:
  36263. this.uvs5 = data;
  36264. break;
  36265. case BABYLON.VertexBuffer.UV6Kind:
  36266. this.uvs6 = data;
  36267. break;
  36268. case BABYLON.VertexBuffer.ColorKind:
  36269. this.colors = data;
  36270. break;
  36271. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36272. this.matricesIndices = data;
  36273. break;
  36274. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36275. this.matricesWeights = data;
  36276. break;
  36277. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36278. this.matricesIndicesExtra = data;
  36279. break;
  36280. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36281. this.matricesWeightsExtra = data;
  36282. break;
  36283. }
  36284. };
  36285. /**
  36286. * Associates the vertexData to the passed Mesh.
  36287. * Sets it as updatable or not (default `false`)
  36288. * @param mesh the mesh the vertexData is applied to
  36289. * @param updatable when used and having the value true allows new data to update the vertexData
  36290. * @returns the VertexData
  36291. */
  36292. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36293. this._applyTo(mesh, updatable);
  36294. return this;
  36295. };
  36296. /**
  36297. * Associates the vertexData to the passed Geometry.
  36298. * Sets it as updatable or not (default `false`)
  36299. * @param geometry the geometry the vertexData is applied to
  36300. * @param updatable when used and having the value true allows new data to update the vertexData
  36301. * @returns VertexData
  36302. */
  36303. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36304. this._applyTo(geometry, updatable);
  36305. return this;
  36306. };
  36307. /**
  36308. * Updates the associated mesh
  36309. * @param mesh the mesh to be updated
  36310. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36311. * @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
  36312. * @returns VertexData
  36313. */
  36314. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36315. this._update(mesh);
  36316. return this;
  36317. };
  36318. /**
  36319. * Updates the associated geometry
  36320. * @param geometry the geometry to be updated
  36321. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36322. * @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
  36323. * @returns VertexData.
  36324. */
  36325. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36326. this._update(geometry);
  36327. return this;
  36328. };
  36329. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36330. if (updatable === void 0) { updatable = false; }
  36331. if (this.positions) {
  36332. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36333. }
  36334. if (this.normals) {
  36335. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36336. }
  36337. if (this.tangents) {
  36338. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36339. }
  36340. if (this.uvs) {
  36341. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36342. }
  36343. if (this.uvs2) {
  36344. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36345. }
  36346. if (this.uvs3) {
  36347. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36348. }
  36349. if (this.uvs4) {
  36350. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36351. }
  36352. if (this.uvs5) {
  36353. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36354. }
  36355. if (this.uvs6) {
  36356. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36357. }
  36358. if (this.colors) {
  36359. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36360. }
  36361. if (this.matricesIndices) {
  36362. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36363. }
  36364. if (this.matricesWeights) {
  36365. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36366. }
  36367. if (this.matricesIndicesExtra) {
  36368. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36369. }
  36370. if (this.matricesWeightsExtra) {
  36371. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36372. }
  36373. if (this.indices) {
  36374. meshOrGeometry.setIndices(this.indices, null, updatable);
  36375. }
  36376. return this;
  36377. };
  36378. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36379. if (this.positions) {
  36380. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36381. }
  36382. if (this.normals) {
  36383. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36384. }
  36385. if (this.tangents) {
  36386. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36387. }
  36388. if (this.uvs) {
  36389. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36390. }
  36391. if (this.uvs2) {
  36392. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36393. }
  36394. if (this.uvs3) {
  36395. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36396. }
  36397. if (this.uvs4) {
  36398. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36399. }
  36400. if (this.uvs5) {
  36401. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36402. }
  36403. if (this.uvs6) {
  36404. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36405. }
  36406. if (this.colors) {
  36407. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36408. }
  36409. if (this.matricesIndices) {
  36410. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36411. }
  36412. if (this.matricesWeights) {
  36413. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36414. }
  36415. if (this.matricesIndicesExtra) {
  36416. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36417. }
  36418. if (this.matricesWeightsExtra) {
  36419. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36420. }
  36421. if (this.indices) {
  36422. meshOrGeometry.setIndices(this.indices, null);
  36423. }
  36424. return this;
  36425. };
  36426. /**
  36427. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36428. * @param matrix the transforming matrix
  36429. * @returns the VertexData
  36430. */
  36431. VertexData.prototype.transform = function (matrix) {
  36432. var transformed = BABYLON.Vector3.Zero();
  36433. var index;
  36434. if (this.positions) {
  36435. var position = BABYLON.Vector3.Zero();
  36436. for (index = 0; index < this.positions.length; index += 3) {
  36437. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36438. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36439. this.positions[index] = transformed.x;
  36440. this.positions[index + 1] = transformed.y;
  36441. this.positions[index + 2] = transformed.z;
  36442. }
  36443. }
  36444. if (this.normals) {
  36445. var normal = BABYLON.Vector3.Zero();
  36446. for (index = 0; index < this.normals.length; index += 3) {
  36447. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36448. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36449. this.normals[index] = transformed.x;
  36450. this.normals[index + 1] = transformed.y;
  36451. this.normals[index + 2] = transformed.z;
  36452. }
  36453. }
  36454. if (this.tangents) {
  36455. var tangent = BABYLON.Vector4.Zero();
  36456. var tangentTransformed = BABYLON.Vector4.Zero();
  36457. for (index = 0; index < this.tangents.length; index += 4) {
  36458. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36459. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36460. this.tangents[index] = tangentTransformed.x;
  36461. this.tangents[index + 1] = tangentTransformed.y;
  36462. this.tangents[index + 2] = tangentTransformed.z;
  36463. this.tangents[index + 3] = tangentTransformed.w;
  36464. }
  36465. }
  36466. return this;
  36467. };
  36468. /**
  36469. * Merges the passed VertexData into the current one
  36470. * @param other the VertexData to be merged into the current one
  36471. * @returns the modified VertexData
  36472. */
  36473. VertexData.prototype.merge = function (other) {
  36474. this._validate();
  36475. other._validate();
  36476. if (!this.normals !== !other.normals ||
  36477. !this.tangents !== !other.tangents ||
  36478. !this.uvs !== !other.uvs ||
  36479. !this.uvs2 !== !other.uvs2 ||
  36480. !this.uvs3 !== !other.uvs3 ||
  36481. !this.uvs4 !== !other.uvs4 ||
  36482. !this.uvs5 !== !other.uvs5 ||
  36483. !this.uvs6 !== !other.uvs6 ||
  36484. !this.colors !== !other.colors ||
  36485. !this.matricesIndices !== !other.matricesIndices ||
  36486. !this.matricesWeights !== !other.matricesWeights ||
  36487. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36488. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36489. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36490. }
  36491. if (other.indices) {
  36492. if (!this.indices) {
  36493. this.indices = [];
  36494. }
  36495. var offset = this.positions ? this.positions.length / 3 : 0;
  36496. for (var index = 0; index < other.indices.length; index++) {
  36497. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36498. this.indices.push(other.indices[index] + offset);
  36499. }
  36500. }
  36501. this.positions = this._mergeElement(this.positions, other.positions);
  36502. this.normals = this._mergeElement(this.normals, other.normals);
  36503. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36504. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36505. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36506. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36507. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36508. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36509. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36510. this.colors = this._mergeElement(this.colors, other.colors);
  36511. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36512. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36513. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36514. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36515. return this;
  36516. };
  36517. VertexData.prototype._mergeElement = function (source, other) {
  36518. if (!source) {
  36519. return other;
  36520. }
  36521. if (!other) {
  36522. return source;
  36523. }
  36524. var len = other.length + source.length;
  36525. var isSrcTypedArray = source instanceof Float32Array;
  36526. var isOthTypedArray = other instanceof Float32Array;
  36527. // use non-loop method when the source is Float32Array
  36528. if (isSrcTypedArray) {
  36529. var ret32 = new Float32Array(len);
  36530. ret32.set(source);
  36531. ret32.set(other, source.length);
  36532. return ret32;
  36533. // source is number[], when other is also use concat
  36534. }
  36535. else if (!isOthTypedArray) {
  36536. return source.concat(other);
  36537. // source is a number[], but other is a Float32Array, loop required
  36538. }
  36539. else {
  36540. var ret = source.slice(0); // copy source to a separate array
  36541. for (var i = 0, len = other.length; i < len; i++) {
  36542. ret.push(other[i]);
  36543. }
  36544. return ret;
  36545. }
  36546. };
  36547. VertexData.prototype._validate = function () {
  36548. if (!this.positions) {
  36549. throw new Error("Positions are required");
  36550. }
  36551. var getElementCount = function (kind, values) {
  36552. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36553. if ((values.length % stride) !== 0) {
  36554. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36555. }
  36556. return values.length / stride;
  36557. };
  36558. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36559. var validateElementCount = function (kind, values) {
  36560. var elementCount = getElementCount(kind, values);
  36561. if (elementCount !== positionsElementCount) {
  36562. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36563. }
  36564. };
  36565. if (this.normals)
  36566. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36567. if (this.tangents)
  36568. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36569. if (this.uvs)
  36570. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36571. if (this.uvs2)
  36572. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36573. if (this.uvs3)
  36574. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36575. if (this.uvs4)
  36576. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36577. if (this.uvs5)
  36578. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36579. if (this.uvs6)
  36580. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36581. if (this.colors)
  36582. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36583. if (this.matricesIndices)
  36584. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36585. if (this.matricesWeights)
  36586. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36587. if (this.matricesIndicesExtra)
  36588. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36589. if (this.matricesWeightsExtra)
  36590. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36591. };
  36592. /**
  36593. * Serializes the VertexData
  36594. * @returns a serialized object
  36595. */
  36596. VertexData.prototype.serialize = function () {
  36597. var serializationObject = this.serialize();
  36598. if (this.positions) {
  36599. serializationObject.positions = this.positions;
  36600. }
  36601. if (this.normals) {
  36602. serializationObject.normals = this.normals;
  36603. }
  36604. if (this.tangents) {
  36605. serializationObject.tangents = this.tangents;
  36606. }
  36607. if (this.uvs) {
  36608. serializationObject.uvs = this.uvs;
  36609. }
  36610. if (this.uvs2) {
  36611. serializationObject.uvs2 = this.uvs2;
  36612. }
  36613. if (this.uvs3) {
  36614. serializationObject.uvs3 = this.uvs3;
  36615. }
  36616. if (this.uvs4) {
  36617. serializationObject.uvs4 = this.uvs4;
  36618. }
  36619. if (this.uvs5) {
  36620. serializationObject.uvs5 = this.uvs5;
  36621. }
  36622. if (this.uvs6) {
  36623. serializationObject.uvs6 = this.uvs6;
  36624. }
  36625. if (this.colors) {
  36626. serializationObject.colors = this.colors;
  36627. }
  36628. if (this.matricesIndices) {
  36629. serializationObject.matricesIndices = this.matricesIndices;
  36630. serializationObject.matricesIndices._isExpanded = true;
  36631. }
  36632. if (this.matricesWeights) {
  36633. serializationObject.matricesWeights = this.matricesWeights;
  36634. }
  36635. if (this.matricesIndicesExtra) {
  36636. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36637. serializationObject.matricesIndicesExtra._isExpanded = true;
  36638. }
  36639. if (this.matricesWeightsExtra) {
  36640. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36641. }
  36642. serializationObject.indices = this.indices;
  36643. return serializationObject;
  36644. };
  36645. // Statics
  36646. /**
  36647. * Extracts the vertexData from a mesh
  36648. * @param mesh the mesh from which to extract the VertexData
  36649. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36650. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36651. * @returns the object VertexData associated to the passed mesh
  36652. */
  36653. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36654. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36655. };
  36656. /**
  36657. * Extracts the vertexData from the geometry
  36658. * @param geometry the geometry from which to extract the VertexData
  36659. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36660. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36661. * @returns the object VertexData associated to the passed mesh
  36662. */
  36663. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36664. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36665. };
  36666. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36667. var result = new VertexData();
  36668. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36669. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36670. }
  36671. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36672. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36673. }
  36674. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36675. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36676. }
  36677. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36678. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36679. }
  36680. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36681. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36682. }
  36683. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36684. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36685. }
  36686. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36687. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36688. }
  36689. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36690. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36691. }
  36692. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36693. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36694. }
  36695. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36696. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36697. }
  36698. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36699. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36700. }
  36701. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36702. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36703. }
  36704. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36705. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36706. }
  36707. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36708. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36709. }
  36710. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36711. return result;
  36712. };
  36713. /**
  36714. * Creates the VertexData for a Ribbon
  36715. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36716. * * pathArray array of paths, each of which an array of successive Vector3
  36717. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36718. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36719. * * 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
  36720. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36721. * * 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)
  36722. * * 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)
  36723. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36724. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36725. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36726. * @returns the VertexData of the ribbon
  36727. */
  36728. VertexData.CreateRibbon = function (options) {
  36729. var pathArray = options.pathArray;
  36730. var closeArray = options.closeArray || false;
  36731. var closePath = options.closePath || false;
  36732. var invertUV = options.invertUV || false;
  36733. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36734. var offset = options.offset || defaultOffset;
  36735. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36736. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36737. var customUV = options.uvs;
  36738. var customColors = options.colors;
  36739. var positions = [];
  36740. var indices = [];
  36741. var normals = [];
  36742. var uvs = [];
  36743. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36744. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36745. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36746. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36747. var minlg; // minimal length among all paths from pathArray
  36748. var lg = []; // array of path lengths : nb of vertex per path
  36749. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36750. var p; // path iterator
  36751. var i; // point iterator
  36752. var j; // point iterator
  36753. // if single path in pathArray
  36754. if (pathArray.length < 2) {
  36755. var ar1 = [];
  36756. var ar2 = [];
  36757. for (i = 0; i < pathArray[0].length - offset; i++) {
  36758. ar1.push(pathArray[0][i]);
  36759. ar2.push(pathArray[0][i + offset]);
  36760. }
  36761. pathArray = [ar1, ar2];
  36762. }
  36763. // positions and horizontal distances (u)
  36764. var idc = 0;
  36765. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36766. var path;
  36767. var l;
  36768. minlg = pathArray[0].length;
  36769. var vectlg;
  36770. var dist;
  36771. for (p = 0; p < pathArray.length; p++) {
  36772. uTotalDistance[p] = 0;
  36773. us[p] = [0];
  36774. path = pathArray[p];
  36775. l = path.length;
  36776. minlg = (minlg < l) ? minlg : l;
  36777. j = 0;
  36778. while (j < l) {
  36779. positions.push(path[j].x, path[j].y, path[j].z);
  36780. if (j > 0) {
  36781. vectlg = path[j].subtract(path[j - 1]).length();
  36782. dist = vectlg + uTotalDistance[p];
  36783. us[p].push(dist);
  36784. uTotalDistance[p] = dist;
  36785. }
  36786. j++;
  36787. }
  36788. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36789. j--;
  36790. positions.push(path[0].x, path[0].y, path[0].z);
  36791. vectlg = path[j].subtract(path[0]).length();
  36792. dist = vectlg + uTotalDistance[p];
  36793. us[p].push(dist);
  36794. uTotalDistance[p] = dist;
  36795. }
  36796. lg[p] = l + closePathCorr;
  36797. idx[p] = idc;
  36798. idc += (l + closePathCorr);
  36799. }
  36800. // vertical distances (v)
  36801. var path1;
  36802. var path2;
  36803. var vertex1 = null;
  36804. var vertex2 = null;
  36805. for (i = 0; i < minlg + closePathCorr; i++) {
  36806. vTotalDistance[i] = 0;
  36807. vs[i] = [0];
  36808. for (p = 0; p < pathArray.length - 1; p++) {
  36809. path1 = pathArray[p];
  36810. path2 = pathArray[p + 1];
  36811. if (i === minlg) { // closePath
  36812. vertex1 = path1[0];
  36813. vertex2 = path2[0];
  36814. }
  36815. else {
  36816. vertex1 = path1[i];
  36817. vertex2 = path2[i];
  36818. }
  36819. vectlg = vertex2.subtract(vertex1).length();
  36820. dist = vectlg + vTotalDistance[i];
  36821. vs[i].push(dist);
  36822. vTotalDistance[i] = dist;
  36823. }
  36824. if (closeArray && vertex2 && vertex1) {
  36825. path1 = pathArray[p];
  36826. path2 = pathArray[0];
  36827. if (i === minlg) { // closePath
  36828. vertex2 = path2[0];
  36829. }
  36830. vectlg = vertex2.subtract(vertex1).length();
  36831. dist = vectlg + vTotalDistance[i];
  36832. vTotalDistance[i] = dist;
  36833. }
  36834. }
  36835. // uvs
  36836. var u;
  36837. var v;
  36838. if (customUV) {
  36839. for (p = 0; p < customUV.length; p++) {
  36840. uvs.push(customUV[p].x, customUV[p].y);
  36841. }
  36842. }
  36843. else {
  36844. for (p = 0; p < pathArray.length; p++) {
  36845. for (i = 0; i < minlg + closePathCorr; i++) {
  36846. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36847. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36848. if (invertUV) {
  36849. uvs.push(v, u);
  36850. }
  36851. else {
  36852. uvs.push(u, v);
  36853. }
  36854. }
  36855. }
  36856. }
  36857. // indices
  36858. p = 0; // path index
  36859. var pi = 0; // positions array index
  36860. var l1 = lg[p] - 1; // path1 length
  36861. var l2 = lg[p + 1] - 1; // path2 length
  36862. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36863. var shft = idx[1] - idx[0]; // shift
  36864. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36865. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36866. // 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
  36867. indices.push(pi, pi + shft, pi + 1);
  36868. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36869. pi += 1;
  36870. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36871. p++;
  36872. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36873. shft = idx[0] - idx[p];
  36874. l1 = lg[p] - 1;
  36875. l2 = lg[0] - 1;
  36876. }
  36877. else {
  36878. shft = idx[p + 1] - idx[p];
  36879. l1 = lg[p] - 1;
  36880. l2 = lg[p + 1] - 1;
  36881. }
  36882. pi = idx[p];
  36883. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36884. }
  36885. }
  36886. // normals
  36887. VertexData.ComputeNormals(positions, indices, normals);
  36888. if (closePath) { // update both the first and last vertex normals to their average value
  36889. var indexFirst = 0;
  36890. var indexLast = 0;
  36891. for (p = 0; p < pathArray.length; p++) {
  36892. indexFirst = idx[p] * 3;
  36893. if (p + 1 < pathArray.length) {
  36894. indexLast = (idx[p + 1] - 1) * 3;
  36895. }
  36896. else {
  36897. indexLast = normals.length - 3;
  36898. }
  36899. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36900. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36901. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36902. normals[indexLast] = normals[indexFirst];
  36903. normals[indexLast + 1] = normals[indexFirst + 1];
  36904. normals[indexLast + 2] = normals[indexFirst + 2];
  36905. }
  36906. }
  36907. // sides
  36908. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36909. // Colors
  36910. var colors = null;
  36911. if (customColors) {
  36912. colors = new Float32Array(customColors.length * 4);
  36913. for (var c = 0; c < customColors.length; c++) {
  36914. colors[c * 4] = customColors[c].r;
  36915. colors[c * 4 + 1] = customColors[c].g;
  36916. colors[c * 4 + 2] = customColors[c].b;
  36917. colors[c * 4 + 3] = customColors[c].a;
  36918. }
  36919. }
  36920. // Result
  36921. var vertexData = new VertexData();
  36922. var positions32 = new Float32Array(positions);
  36923. var normals32 = new Float32Array(normals);
  36924. var uvs32 = new Float32Array(uvs);
  36925. vertexData.indices = indices;
  36926. vertexData.positions = positions32;
  36927. vertexData.normals = normals32;
  36928. vertexData.uvs = uvs32;
  36929. if (colors) {
  36930. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36931. }
  36932. if (closePath) {
  36933. vertexData._idx = idx;
  36934. }
  36935. return vertexData;
  36936. };
  36937. /**
  36938. * Creates the VertexData for a box
  36939. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36940. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36941. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36942. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36943. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36944. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36945. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36946. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36947. * * 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)
  36948. * * 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)
  36949. * @returns the VertexData of the box
  36950. */
  36951. VertexData.CreateBox = function (options) {
  36952. var normalsSource = [
  36953. new BABYLON.Vector3(0, 0, 1),
  36954. new BABYLON.Vector3(0, 0, -1),
  36955. new BABYLON.Vector3(1, 0, 0),
  36956. new BABYLON.Vector3(-1, 0, 0),
  36957. new BABYLON.Vector3(0, 1, 0),
  36958. new BABYLON.Vector3(0, -1, 0)
  36959. ];
  36960. var indices = [];
  36961. var positions = [];
  36962. var normals = [];
  36963. var uvs = [];
  36964. var width = options.width || options.size || 1;
  36965. var height = options.height || options.size || 1;
  36966. var depth = options.depth || options.size || 1;
  36967. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36968. var faceUV = options.faceUV || new Array(6);
  36969. var faceColors = options.faceColors;
  36970. var colors = [];
  36971. // default face colors and UV if undefined
  36972. for (var f = 0; f < 6; f++) {
  36973. if (faceUV[f] === undefined) {
  36974. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36975. }
  36976. if (faceColors && faceColors[f] === undefined) {
  36977. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36978. }
  36979. }
  36980. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36981. // Create each face in turn.
  36982. for (var index = 0; index < normalsSource.length; index++) {
  36983. var normal = normalsSource[index];
  36984. // Get two vectors perpendicular to the face normal and to each other.
  36985. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36986. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36987. // Six indices (two triangles) per face.
  36988. var verticesLength = positions.length / 3;
  36989. indices.push(verticesLength);
  36990. indices.push(verticesLength + 1);
  36991. indices.push(verticesLength + 2);
  36992. indices.push(verticesLength);
  36993. indices.push(verticesLength + 2);
  36994. indices.push(verticesLength + 3);
  36995. // Four vertices per face.
  36996. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36997. positions.push(vertex.x, vertex.y, vertex.z);
  36998. normals.push(normal.x, normal.y, normal.z);
  36999. uvs.push(faceUV[index].z, faceUV[index].w);
  37000. if (faceColors) {
  37001. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37002. }
  37003. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37004. positions.push(vertex.x, vertex.y, vertex.z);
  37005. normals.push(normal.x, normal.y, normal.z);
  37006. uvs.push(faceUV[index].x, faceUV[index].w);
  37007. if (faceColors) {
  37008. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37009. }
  37010. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37011. positions.push(vertex.x, vertex.y, vertex.z);
  37012. normals.push(normal.x, normal.y, normal.z);
  37013. uvs.push(faceUV[index].x, faceUV[index].y);
  37014. if (faceColors) {
  37015. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37016. }
  37017. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37018. positions.push(vertex.x, vertex.y, vertex.z);
  37019. normals.push(normal.x, normal.y, normal.z);
  37020. uvs.push(faceUV[index].z, faceUV[index].y);
  37021. if (faceColors) {
  37022. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37023. }
  37024. }
  37025. // sides
  37026. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37027. // Result
  37028. var vertexData = new VertexData();
  37029. vertexData.indices = indices;
  37030. vertexData.positions = positions;
  37031. vertexData.normals = normals;
  37032. vertexData.uvs = uvs;
  37033. if (faceColors) {
  37034. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37035. vertexData.colors = totalColors;
  37036. }
  37037. return vertexData;
  37038. };
  37039. /**
  37040. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37041. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37042. * * segments sets the number of horizontal strips optional, default 32
  37043. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37044. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37045. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37046. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37047. * * 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
  37048. * * 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
  37049. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37050. * * 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)
  37051. * * 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)
  37052. * @returns the VertexData of the ellipsoid
  37053. */
  37054. VertexData.CreateSphere = function (options) {
  37055. var segments = options.segments || 32;
  37056. var diameterX = options.diameterX || options.diameter || 1;
  37057. var diameterY = options.diameterY || options.diameter || 1;
  37058. var diameterZ = options.diameterZ || options.diameter || 1;
  37059. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37060. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37061. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37062. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37063. var totalZRotationSteps = 2 + segments;
  37064. var totalYRotationSteps = 2 * totalZRotationSteps;
  37065. var indices = [];
  37066. var positions = [];
  37067. var normals = [];
  37068. var uvs = [];
  37069. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37070. var normalizedZ = zRotationStep / totalZRotationSteps;
  37071. var angleZ = normalizedZ * Math.PI * slice;
  37072. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37073. var normalizedY = yRotationStep / totalYRotationSteps;
  37074. var angleY = normalizedY * Math.PI * 2 * arc;
  37075. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37076. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37077. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37078. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37079. var vertex = complete.multiply(radius);
  37080. var normal = complete.divide(radius).normalize();
  37081. positions.push(vertex.x, vertex.y, vertex.z);
  37082. normals.push(normal.x, normal.y, normal.z);
  37083. uvs.push(normalizedY, normalizedZ);
  37084. }
  37085. if (zRotationStep > 0) {
  37086. var verticesCount = positions.length / 3;
  37087. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37088. indices.push((firstIndex));
  37089. indices.push((firstIndex + 1));
  37090. indices.push(firstIndex + totalYRotationSteps + 1);
  37091. indices.push((firstIndex + totalYRotationSteps + 1));
  37092. indices.push((firstIndex + 1));
  37093. indices.push((firstIndex + totalYRotationSteps + 2));
  37094. }
  37095. }
  37096. }
  37097. // Sides
  37098. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37099. // Result
  37100. var vertexData = new VertexData();
  37101. vertexData.indices = indices;
  37102. vertexData.positions = positions;
  37103. vertexData.normals = normals;
  37104. vertexData.uvs = uvs;
  37105. return vertexData;
  37106. };
  37107. /**
  37108. * Creates the VertexData for a cylinder, cone or prism
  37109. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37110. * * height sets the height (y direction) of the cylinder, optional, default 2
  37111. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37112. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37113. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37114. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37115. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37116. * * 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
  37117. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37118. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37119. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37120. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37121. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37122. * * 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)
  37123. * * 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)
  37124. * @returns the VertexData of the cylinder, cone or prism
  37125. */
  37126. VertexData.CreateCylinder = function (options) {
  37127. var height = options.height || 2;
  37128. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37129. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37130. var tessellation = options.tessellation || 24;
  37131. var subdivisions = options.subdivisions || 1;
  37132. var hasRings = options.hasRings ? true : false;
  37133. var enclose = options.enclose ? true : false;
  37134. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37135. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37136. var faceUV = options.faceUV || new Array(3);
  37137. var faceColors = options.faceColors;
  37138. // default face colors and UV if undefined
  37139. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37140. var ringNb = (hasRings) ? subdivisions : 1;
  37141. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37142. var f;
  37143. for (f = 0; f < surfaceNb; f++) {
  37144. if (faceColors && faceColors[f] === undefined) {
  37145. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37146. }
  37147. }
  37148. for (f = 0; f < surfaceNb; f++) {
  37149. if (faceUV && faceUV[f] === undefined) {
  37150. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37151. }
  37152. }
  37153. var indices = new Array();
  37154. var positions = new Array();
  37155. var normals = new Array();
  37156. var uvs = new Array();
  37157. var colors = new Array();
  37158. var angle_step = Math.PI * 2 * arc / tessellation;
  37159. var angle;
  37160. var h;
  37161. var radius;
  37162. var tan = (diameterBottom - diameterTop) / 2 / height;
  37163. var ringVertex = BABYLON.Vector3.Zero();
  37164. var ringNormal = BABYLON.Vector3.Zero();
  37165. var ringFirstVertex = BABYLON.Vector3.Zero();
  37166. var ringFirstNormal = BABYLON.Vector3.Zero();
  37167. var quadNormal = BABYLON.Vector3.Zero();
  37168. var Y = BABYLON.Axis.Y;
  37169. // positions, normals, uvs
  37170. var i;
  37171. var j;
  37172. var r;
  37173. var ringIdx = 1;
  37174. var s = 1; // surface index
  37175. var cs = 0;
  37176. var v = 0;
  37177. for (i = 0; i <= subdivisions; i++) {
  37178. h = i / subdivisions;
  37179. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37180. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37181. for (r = 0; r < ringIdx; r++) {
  37182. if (hasRings) {
  37183. s += r;
  37184. }
  37185. if (enclose) {
  37186. s += 2 * r;
  37187. }
  37188. for (j = 0; j <= tessellation; j++) {
  37189. angle = j * angle_step;
  37190. // position
  37191. ringVertex.x = Math.cos(-angle) * radius;
  37192. ringVertex.y = -height / 2 + h * height;
  37193. ringVertex.z = Math.sin(-angle) * radius;
  37194. // normal
  37195. if (diameterTop === 0 && i === subdivisions) {
  37196. // if no top cap, reuse former normals
  37197. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37198. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37199. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37200. }
  37201. else {
  37202. ringNormal.x = ringVertex.x;
  37203. ringNormal.z = ringVertex.z;
  37204. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37205. ringNormal.normalize();
  37206. }
  37207. // keep first ring vertex values for enclose
  37208. if (j === 0) {
  37209. ringFirstVertex.copyFrom(ringVertex);
  37210. ringFirstNormal.copyFrom(ringNormal);
  37211. }
  37212. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37213. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37214. if (hasRings) {
  37215. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37216. }
  37217. else {
  37218. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37219. }
  37220. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37221. if (faceColors) {
  37222. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37223. }
  37224. }
  37225. // if enclose, add four vertices and their dedicated normals
  37226. if (arc !== 1 && enclose) {
  37227. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37228. positions.push(0, ringVertex.y, 0);
  37229. positions.push(0, ringVertex.y, 0);
  37230. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37231. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37232. quadNormal.normalize();
  37233. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37234. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37235. quadNormal.normalize();
  37236. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37237. if (hasRings) {
  37238. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37239. }
  37240. else {
  37241. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37242. }
  37243. uvs.push(faceUV[s + 1].x, v);
  37244. uvs.push(faceUV[s + 1].z, v);
  37245. if (hasRings) {
  37246. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37247. }
  37248. else {
  37249. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37250. }
  37251. uvs.push(faceUV[s + 2].x, v);
  37252. uvs.push(faceUV[s + 2].z, v);
  37253. if (faceColors) {
  37254. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37255. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37256. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37257. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37258. }
  37259. }
  37260. if (cs !== s) {
  37261. cs = s;
  37262. }
  37263. }
  37264. }
  37265. // indices
  37266. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37267. var s;
  37268. i = 0;
  37269. for (s = 0; s < subdivisions; s++) {
  37270. var i0 = 0;
  37271. var i1 = 0;
  37272. var i2 = 0;
  37273. var i3 = 0;
  37274. for (j = 0; j < tessellation; j++) {
  37275. i0 = i * (e + 1) + j;
  37276. i1 = (i + 1) * (e + 1) + j;
  37277. i2 = i * (e + 1) + (j + 1);
  37278. i3 = (i + 1) * (e + 1) + (j + 1);
  37279. indices.push(i0, i1, i2);
  37280. indices.push(i3, i2, i1);
  37281. }
  37282. if (arc !== 1 && enclose) { // if enclose, add two quads
  37283. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37284. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37285. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37286. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37287. }
  37288. i = (hasRings) ? (i + 2) : (i + 1);
  37289. }
  37290. // Caps
  37291. var createCylinderCap = function (isTop) {
  37292. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37293. if (radius === 0) {
  37294. return;
  37295. }
  37296. // Cap positions, normals & uvs
  37297. var angle;
  37298. var circleVector;
  37299. var i;
  37300. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37301. var c = null;
  37302. if (faceColors) {
  37303. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37304. }
  37305. // cap center
  37306. var vbase = positions.length / 3;
  37307. var offset = isTop ? height / 2 : -height / 2;
  37308. var center = new BABYLON.Vector3(0, offset, 0);
  37309. positions.push(center.x, center.y, center.z);
  37310. normals.push(0, isTop ? 1 : -1, 0);
  37311. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37312. if (c) {
  37313. colors.push(c.r, c.g, c.b, c.a);
  37314. }
  37315. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37316. for (i = 0; i <= tessellation; i++) {
  37317. angle = Math.PI * 2 * i * arc / tessellation;
  37318. var cos = Math.cos(-angle);
  37319. var sin = Math.sin(-angle);
  37320. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37321. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37322. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37323. normals.push(0, isTop ? 1 : -1, 0);
  37324. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37325. if (c) {
  37326. colors.push(c.r, c.g, c.b, c.a);
  37327. }
  37328. }
  37329. // Cap indices
  37330. for (i = 0; i < tessellation; i++) {
  37331. if (!isTop) {
  37332. indices.push(vbase);
  37333. indices.push(vbase + (i + 1));
  37334. indices.push(vbase + (i + 2));
  37335. }
  37336. else {
  37337. indices.push(vbase);
  37338. indices.push(vbase + (i + 2));
  37339. indices.push(vbase + (i + 1));
  37340. }
  37341. }
  37342. };
  37343. // add caps to geometry
  37344. createCylinderCap(false);
  37345. createCylinderCap(true);
  37346. // Sides
  37347. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37348. var vertexData = new VertexData();
  37349. vertexData.indices = indices;
  37350. vertexData.positions = positions;
  37351. vertexData.normals = normals;
  37352. vertexData.uvs = uvs;
  37353. if (faceColors) {
  37354. vertexData.colors = colors;
  37355. }
  37356. return vertexData;
  37357. };
  37358. /**
  37359. * Creates the VertexData for a torus
  37360. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37361. * * diameter the diameter of the torus, optional default 1
  37362. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37363. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37364. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37365. * * 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)
  37366. * * 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)
  37367. * @returns the VertexData of the torus
  37368. */
  37369. VertexData.CreateTorus = function (options) {
  37370. var indices = [];
  37371. var positions = [];
  37372. var normals = [];
  37373. var uvs = [];
  37374. var diameter = options.diameter || 1;
  37375. var thickness = options.thickness || 0.5;
  37376. var tessellation = options.tessellation || 16;
  37377. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37378. var stride = tessellation + 1;
  37379. for (var i = 0; i <= tessellation; i++) {
  37380. var u = i / tessellation;
  37381. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37382. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37383. for (var j = 0; j <= tessellation; j++) {
  37384. var v = 1 - j / tessellation;
  37385. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37386. var dx = Math.cos(innerAngle);
  37387. var dy = Math.sin(innerAngle);
  37388. // Create a vertex.
  37389. var normal = new BABYLON.Vector3(dx, dy, 0);
  37390. var position = normal.scale(thickness / 2);
  37391. var textureCoordinate = new BABYLON.Vector2(u, v);
  37392. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37393. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37394. positions.push(position.x, position.y, position.z);
  37395. normals.push(normal.x, normal.y, normal.z);
  37396. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37397. // And create indices for two triangles.
  37398. var nextI = (i + 1) % stride;
  37399. var nextJ = (j + 1) % stride;
  37400. indices.push(i * stride + j);
  37401. indices.push(i * stride + nextJ);
  37402. indices.push(nextI * stride + j);
  37403. indices.push(i * stride + nextJ);
  37404. indices.push(nextI * stride + nextJ);
  37405. indices.push(nextI * stride + j);
  37406. }
  37407. }
  37408. // Sides
  37409. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37410. // Result
  37411. var vertexData = new VertexData();
  37412. vertexData.indices = indices;
  37413. vertexData.positions = positions;
  37414. vertexData.normals = normals;
  37415. vertexData.uvs = uvs;
  37416. return vertexData;
  37417. };
  37418. /**
  37419. * Creates the VertexData of the LineSystem
  37420. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37421. * - lines an array of lines, each line being an array of successive Vector3
  37422. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37423. * @returns the VertexData of the LineSystem
  37424. */
  37425. VertexData.CreateLineSystem = function (options) {
  37426. var indices = [];
  37427. var positions = [];
  37428. var lines = options.lines;
  37429. var colors = options.colors;
  37430. var vertexColors = [];
  37431. var idx = 0;
  37432. for (var l = 0; l < lines.length; l++) {
  37433. var points = lines[l];
  37434. for (var index = 0; index < points.length; index++) {
  37435. positions.push(points[index].x, points[index].y, points[index].z);
  37436. if (colors) {
  37437. var color = colors[l];
  37438. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37439. }
  37440. if (index > 0) {
  37441. indices.push(idx - 1);
  37442. indices.push(idx);
  37443. }
  37444. idx++;
  37445. }
  37446. }
  37447. var vertexData = new VertexData();
  37448. vertexData.indices = indices;
  37449. vertexData.positions = positions;
  37450. if (colors) {
  37451. vertexData.colors = vertexColors;
  37452. }
  37453. return vertexData;
  37454. };
  37455. /**
  37456. * Create the VertexData for a DashedLines
  37457. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37458. * - points an array successive Vector3
  37459. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37460. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37461. * - dashNb the intended total number of dashes, optional, default 200
  37462. * @returns the VertexData for the DashedLines
  37463. */
  37464. VertexData.CreateDashedLines = function (options) {
  37465. var dashSize = options.dashSize || 3;
  37466. var gapSize = options.gapSize || 1;
  37467. var dashNb = options.dashNb || 200;
  37468. var points = options.points;
  37469. var positions = new Array();
  37470. var indices = new Array();
  37471. var curvect = BABYLON.Vector3.Zero();
  37472. var lg = 0;
  37473. var nb = 0;
  37474. var shft = 0;
  37475. var dashshft = 0;
  37476. var curshft = 0;
  37477. var idx = 0;
  37478. var i = 0;
  37479. for (i = 0; i < points.length - 1; i++) {
  37480. points[i + 1].subtractToRef(points[i], curvect);
  37481. lg += curvect.length();
  37482. }
  37483. shft = lg / dashNb;
  37484. dashshft = dashSize * shft / (dashSize + gapSize);
  37485. for (i = 0; i < points.length - 1; i++) {
  37486. points[i + 1].subtractToRef(points[i], curvect);
  37487. nb = Math.floor(curvect.length() / shft);
  37488. curvect.normalize();
  37489. for (var j = 0; j < nb; j++) {
  37490. curshft = shft * j;
  37491. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37492. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37493. indices.push(idx, idx + 1);
  37494. idx += 2;
  37495. }
  37496. }
  37497. // Result
  37498. var vertexData = new VertexData();
  37499. vertexData.positions = positions;
  37500. vertexData.indices = indices;
  37501. return vertexData;
  37502. };
  37503. /**
  37504. * Creates the VertexData for a Ground
  37505. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37506. * - width the width (x direction) of the ground, optional, default 1
  37507. * - height the height (z direction) of the ground, optional, default 1
  37508. * - subdivisions the number of subdivisions per side, optional, default 1
  37509. * @returns the VertexData of the Ground
  37510. */
  37511. VertexData.CreateGround = function (options) {
  37512. var indices = [];
  37513. var positions = [];
  37514. var normals = [];
  37515. var uvs = [];
  37516. var row, col;
  37517. var width = options.width || 1;
  37518. var height = options.height || 1;
  37519. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37520. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37521. for (row = 0; row <= subdivisionsY; row++) {
  37522. for (col = 0; col <= subdivisionsX; col++) {
  37523. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37524. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37525. positions.push(position.x, position.y, position.z);
  37526. normals.push(normal.x, normal.y, normal.z);
  37527. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37528. }
  37529. }
  37530. for (row = 0; row < subdivisionsY; row++) {
  37531. for (col = 0; col < subdivisionsX; col++) {
  37532. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37533. indices.push(col + 1 + row * (subdivisionsX + 1));
  37534. indices.push(col + row * (subdivisionsX + 1));
  37535. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37536. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37537. indices.push(col + row * (subdivisionsX + 1));
  37538. }
  37539. }
  37540. // Result
  37541. var vertexData = new VertexData();
  37542. vertexData.indices = indices;
  37543. vertexData.positions = positions;
  37544. vertexData.normals = normals;
  37545. vertexData.uvs = uvs;
  37546. return vertexData;
  37547. };
  37548. /**
  37549. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37550. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37551. * * xmin the ground minimum X coordinate, optional, default -1
  37552. * * zmin the ground minimum Z coordinate, optional, default -1
  37553. * * xmax the ground maximum X coordinate, optional, default 1
  37554. * * zmax the ground maximum Z coordinate, optional, default 1
  37555. * * 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}
  37556. * * 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}
  37557. * @returns the VertexData of the TiledGround
  37558. */
  37559. VertexData.CreateTiledGround = function (options) {
  37560. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37561. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37562. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37563. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37564. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37565. var precision = options.precision || { w: 1, h: 1 };
  37566. var indices = new Array();
  37567. var positions = new Array();
  37568. var normals = new Array();
  37569. var uvs = new Array();
  37570. var row, col, tileRow, tileCol;
  37571. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37572. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37573. precision.w = (precision.w < 1) ? 1 : precision.w;
  37574. precision.h = (precision.h < 1) ? 1 : precision.h;
  37575. var tileSize = {
  37576. 'w': (xmax - xmin) / subdivisions.w,
  37577. 'h': (zmax - zmin) / subdivisions.h
  37578. };
  37579. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37580. // Indices
  37581. var base = positions.length / 3;
  37582. var rowLength = precision.w + 1;
  37583. for (row = 0; row < precision.h; row++) {
  37584. for (col = 0; col < precision.w; col++) {
  37585. var square = [
  37586. base + col + row * rowLength,
  37587. base + (col + 1) + row * rowLength,
  37588. base + (col + 1) + (row + 1) * rowLength,
  37589. base + col + (row + 1) * rowLength
  37590. ];
  37591. indices.push(square[1]);
  37592. indices.push(square[2]);
  37593. indices.push(square[3]);
  37594. indices.push(square[0]);
  37595. indices.push(square[1]);
  37596. indices.push(square[3]);
  37597. }
  37598. }
  37599. // Position, normals and uvs
  37600. var position = BABYLON.Vector3.Zero();
  37601. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37602. for (row = 0; row <= precision.h; row++) {
  37603. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37604. for (col = 0; col <= precision.w; col++) {
  37605. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37606. position.y = 0;
  37607. positions.push(position.x, position.y, position.z);
  37608. normals.push(normal.x, normal.y, normal.z);
  37609. uvs.push(col / precision.w, row / precision.h);
  37610. }
  37611. }
  37612. }
  37613. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37614. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37615. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37616. }
  37617. }
  37618. // Result
  37619. var vertexData = new VertexData();
  37620. vertexData.indices = indices;
  37621. vertexData.positions = positions;
  37622. vertexData.normals = normals;
  37623. vertexData.uvs = uvs;
  37624. return vertexData;
  37625. };
  37626. /**
  37627. * Creates the VertexData of the Ground designed from a heightmap
  37628. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37629. * * width the width (x direction) of the ground
  37630. * * height the height (z direction) of the ground
  37631. * * subdivisions the number of subdivisions per side
  37632. * * minHeight the minimum altitude on the ground, optional, default 0
  37633. * * maxHeight the maximum altitude on the ground, optional default 1
  37634. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37635. * * buffer the array holding the image color data
  37636. * * bufferWidth the width of image
  37637. * * bufferHeight the height of image
  37638. * @returns the VertexData of the Ground designed from a heightmap
  37639. */
  37640. VertexData.CreateGroundFromHeightMap = function (options) {
  37641. var indices = [];
  37642. var positions = [];
  37643. var normals = [];
  37644. var uvs = [];
  37645. var row, col;
  37646. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37647. // Vertices
  37648. for (row = 0; row <= options.subdivisions; row++) {
  37649. for (col = 0; col <= options.subdivisions; col++) {
  37650. 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));
  37651. // Compute height
  37652. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37653. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37654. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37655. var r = options.buffer[pos] / 255.0;
  37656. var g = options.buffer[pos + 1] / 255.0;
  37657. var b = options.buffer[pos + 2] / 255.0;
  37658. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37659. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37660. // Add vertex
  37661. positions.push(position.x, position.y, position.z);
  37662. normals.push(0, 0, 0);
  37663. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37664. }
  37665. }
  37666. // Indices
  37667. for (row = 0; row < options.subdivisions; row++) {
  37668. for (col = 0; col < options.subdivisions; col++) {
  37669. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37670. indices.push(col + 1 + row * (options.subdivisions + 1));
  37671. indices.push(col + row * (options.subdivisions + 1));
  37672. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37673. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37674. indices.push(col + row * (options.subdivisions + 1));
  37675. }
  37676. }
  37677. // Normals
  37678. VertexData.ComputeNormals(positions, indices, normals);
  37679. // Result
  37680. var vertexData = new VertexData();
  37681. vertexData.indices = indices;
  37682. vertexData.positions = positions;
  37683. vertexData.normals = normals;
  37684. vertexData.uvs = uvs;
  37685. return vertexData;
  37686. };
  37687. /**
  37688. * Creates the VertexData for a Plane
  37689. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37690. * * size sets the width and height of the plane to the value of size, optional default 1
  37691. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37692. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37693. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37694. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37695. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37696. * @returns the VertexData of the box
  37697. */
  37698. VertexData.CreatePlane = function (options) {
  37699. var indices = [];
  37700. var positions = [];
  37701. var normals = [];
  37702. var uvs = [];
  37703. var width = options.width || options.size || 1;
  37704. var height = options.height || options.size || 1;
  37705. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37706. // Vertices
  37707. var halfWidth = width / 2.0;
  37708. var halfHeight = height / 2.0;
  37709. positions.push(-halfWidth, -halfHeight, 0);
  37710. normals.push(0, 0, -1.0);
  37711. uvs.push(0.0, 0.0);
  37712. positions.push(halfWidth, -halfHeight, 0);
  37713. normals.push(0, 0, -1.0);
  37714. uvs.push(1.0, 0.0);
  37715. positions.push(halfWidth, halfHeight, 0);
  37716. normals.push(0, 0, -1.0);
  37717. uvs.push(1.0, 1.0);
  37718. positions.push(-halfWidth, halfHeight, 0);
  37719. normals.push(0, 0, -1.0);
  37720. uvs.push(0.0, 1.0);
  37721. // Indices
  37722. indices.push(0);
  37723. indices.push(1);
  37724. indices.push(2);
  37725. indices.push(0);
  37726. indices.push(2);
  37727. indices.push(3);
  37728. // Sides
  37729. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37730. // Result
  37731. var vertexData = new VertexData();
  37732. vertexData.indices = indices;
  37733. vertexData.positions = positions;
  37734. vertexData.normals = normals;
  37735. vertexData.uvs = uvs;
  37736. return vertexData;
  37737. };
  37738. /**
  37739. * Creates the VertexData of the Disc or regular Polygon
  37740. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37741. * * radius the radius of the disc, optional default 0.5
  37742. * * tessellation the number of polygon sides, optional, default 64
  37743. * * 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
  37744. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37745. * * 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)
  37746. * * 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)
  37747. * @returns the VertexData of the box
  37748. */
  37749. VertexData.CreateDisc = function (options) {
  37750. var positions = new Array();
  37751. var indices = new Array();
  37752. var normals = new Array();
  37753. var uvs = new Array();
  37754. var radius = options.radius || 0.5;
  37755. var tessellation = options.tessellation || 64;
  37756. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37757. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37758. // positions and uvs
  37759. positions.push(0, 0, 0); // disc center first
  37760. uvs.push(0.5, 0.5);
  37761. var theta = Math.PI * 2 * arc;
  37762. var step = theta / tessellation;
  37763. for (var a = 0; a < theta; a += step) {
  37764. var x = Math.cos(a);
  37765. var y = Math.sin(a);
  37766. var u = (x + 1) / 2;
  37767. var v = (1 - y) / 2;
  37768. positions.push(radius * x, radius * y, 0);
  37769. uvs.push(u, v);
  37770. }
  37771. if (arc === 1) {
  37772. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37773. uvs.push(uvs[2], uvs[3]);
  37774. }
  37775. //indices
  37776. var vertexNb = positions.length / 3;
  37777. for (var i = 1; i < vertexNb - 1; i++) {
  37778. indices.push(i + 1, 0, i);
  37779. }
  37780. // result
  37781. VertexData.ComputeNormals(positions, indices, normals);
  37782. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37783. var vertexData = new VertexData();
  37784. vertexData.indices = indices;
  37785. vertexData.positions = positions;
  37786. vertexData.normals = normals;
  37787. vertexData.uvs = uvs;
  37788. return vertexData;
  37789. };
  37790. /**
  37791. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37792. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37793. * @param polygon a mesh built from polygonTriangulation.build()
  37794. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37795. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37796. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37797. * @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)
  37798. * @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)
  37799. * @returns the VertexData of the Polygon
  37800. */
  37801. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37802. var faceUV = fUV || new Array(3);
  37803. var faceColors = fColors;
  37804. var colors = [];
  37805. // default face colors and UV if undefined
  37806. for (var f = 0; f < 3; f++) {
  37807. if (faceUV[f] === undefined) {
  37808. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37809. }
  37810. if (faceColors && faceColors[f] === undefined) {
  37811. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37812. }
  37813. }
  37814. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37815. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37816. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37817. var indices = polygon.getIndices();
  37818. // set face colours and textures
  37819. var idx = 0;
  37820. var face = 0;
  37821. for (var index = 0; index < normals.length; index += 3) {
  37822. //Edge Face no. 1
  37823. if (Math.abs(normals[index + 1]) < 0.001) {
  37824. face = 1;
  37825. }
  37826. //Top Face no. 0
  37827. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37828. face = 0;
  37829. }
  37830. //Bottom Face no. 2
  37831. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37832. face = 2;
  37833. }
  37834. idx = index / 3;
  37835. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37836. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37837. if (faceColors) {
  37838. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37839. }
  37840. }
  37841. // sides
  37842. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37843. // Result
  37844. var vertexData = new VertexData();
  37845. vertexData.indices = indices;
  37846. vertexData.positions = positions;
  37847. vertexData.normals = normals;
  37848. vertexData.uvs = uvs;
  37849. if (faceColors) {
  37850. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37851. vertexData.colors = totalColors;
  37852. }
  37853. return vertexData;
  37854. };
  37855. /**
  37856. * Creates the VertexData of the IcoSphere
  37857. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37858. * * radius the radius of the IcoSphere, optional default 1
  37859. * * radiusX allows stretching in the x direction, optional, default radius
  37860. * * radiusY allows stretching in the y direction, optional, default radius
  37861. * * radiusZ allows stretching in the z direction, optional, default radius
  37862. * * flat when true creates a flat shaded mesh, optional, default true
  37863. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37864. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37865. * * 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)
  37866. * * 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)
  37867. * @returns the VertexData of the IcoSphere
  37868. */
  37869. VertexData.CreateIcoSphere = function (options) {
  37870. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37871. var radius = options.radius || 1;
  37872. var flat = (options.flat === undefined) ? true : options.flat;
  37873. var subdivisions = options.subdivisions || 4;
  37874. var radiusX = options.radiusX || radius;
  37875. var radiusY = options.radiusY || radius;
  37876. var radiusZ = options.radiusZ || radius;
  37877. var t = (1 + Math.sqrt(5)) / 2;
  37878. // 12 vertex x,y,z
  37879. var ico_vertices = [
  37880. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37881. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37882. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37883. ];
  37884. // index of 3 vertex makes a face of icopshere
  37885. var ico_indices = [
  37886. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37887. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37888. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37889. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37890. ];
  37891. // vertex for uv have aliased position, not for UV
  37892. var vertices_unalias_id = [
  37893. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37894. // vertex alias
  37895. 0,
  37896. 2,
  37897. 3,
  37898. 3,
  37899. 3,
  37900. 4,
  37901. 7,
  37902. 8,
  37903. 9,
  37904. 9,
  37905. 10,
  37906. 11 // 23: B + 12
  37907. ];
  37908. // uv as integer step (not pixels !)
  37909. var ico_vertexuv = [
  37910. 5, 1, 3, 1, 6, 4, 0, 0,
  37911. 5, 3, 4, 2, 2, 2, 4, 0,
  37912. 2, 0, 1, 1, 6, 0, 6, 2,
  37913. // vertex alias (for same vertex on different faces)
  37914. 0, 4,
  37915. 3, 3,
  37916. 4, 4,
  37917. 3, 1,
  37918. 4, 2,
  37919. 4, 4,
  37920. 0, 2,
  37921. 1, 1,
  37922. 2, 2,
  37923. 3, 3,
  37924. 1, 3,
  37925. 2, 4 // 23: B + 12
  37926. ];
  37927. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37928. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37929. // First island of uv mapping
  37930. // v = 4h 3+ 2
  37931. // v = 3h 9+ 4
  37932. // v = 2h 9+ 5 B
  37933. // v = 1h 9 1 0
  37934. // v = 0h 3 8 7 A
  37935. // u = 0 1 2 3 4 5 6 *a
  37936. // Second island of uv mapping
  37937. // v = 4h 0+ B+ 4+
  37938. // v = 3h A+ 2+
  37939. // v = 2h 7+ 6 3+
  37940. // v = 1h 8+ 3+
  37941. // v = 0h
  37942. // u = 0 1 2 3 4 5 6 *a
  37943. // Face layout on texture UV mapping
  37944. // ============
  37945. // \ 4 /\ 16 / ======
  37946. // \ / \ / /\ 11 /
  37947. // \/ 7 \/ / \ /
  37948. // ======= / 10 \/
  37949. // /\ 17 /\ =======
  37950. // / \ / \ \ 15 /\
  37951. // / 8 \/ 12 \ \ / \
  37952. // ============ \/ 6 \
  37953. // \ 18 /\ ============
  37954. // \ / \ \ 5 /\ 0 /
  37955. // \/ 13 \ \ / \ /
  37956. // ======= \/ 1 \/
  37957. // =============
  37958. // /\ 19 /\ 2 /\
  37959. // / \ / \ / \
  37960. // / 14 \/ 9 \/ 3 \
  37961. // ===================
  37962. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37963. var ustep = 138 / 1024;
  37964. var vstep = 239 / 1024;
  37965. var uoffset = 60 / 1024;
  37966. var voffset = 26 / 1024;
  37967. // Second island should have margin, not to touch the first island
  37968. // avoid any borderline artefact in pixel rounding
  37969. var island_u_offset = -40 / 1024;
  37970. var island_v_offset = +20 / 1024;
  37971. // face is either island 0 or 1 :
  37972. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37973. var island = [
  37974. 0, 0, 0, 0, 1,
  37975. 0, 0, 1, 1, 0,
  37976. 0, 0, 1, 1, 0,
  37977. 0, 1, 1, 1, 0 // 15 - 19
  37978. ];
  37979. var indices = new Array();
  37980. var positions = new Array();
  37981. var normals = new Array();
  37982. var uvs = new Array();
  37983. var current_indice = 0;
  37984. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37985. var face_vertex_pos = new Array(3);
  37986. var face_vertex_uv = new Array(3);
  37987. var v012;
  37988. for (v012 = 0; v012 < 3; v012++) {
  37989. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37990. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37991. }
  37992. // create all with normals
  37993. for (var face = 0; face < 20; face++) {
  37994. // 3 vertex per face
  37995. for (v012 = 0; v012 < 3; v012++) {
  37996. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37997. var v_id = ico_indices[3 * face + v012];
  37998. // vertex have 3D position (x,y,z)
  37999. 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]);
  38000. // Normalize to get normal, then scale to radius
  38001. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38002. // uv Coordinates from vertex ID
  38003. 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);
  38004. }
  38005. // Subdivide the face (interpolate pos, norm, uv)
  38006. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38007. // - norm is linear interpolation of vertex corner normal
  38008. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38009. // - uv is linear interpolation
  38010. //
  38011. // Topology is as below for sub-divide by 2
  38012. // vertex shown as v0,v1,v2
  38013. // interp index is i1 to progress in range [v0,v1[
  38014. // interp index is i2 to progress in range [v0,v2[
  38015. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38016. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38017. //
  38018. //
  38019. // i2 v2
  38020. // ^ ^
  38021. // / / \
  38022. // / / \
  38023. // / / \
  38024. // / / (0,1) \
  38025. // / #---------\
  38026. // / / \ (0,0)'/ \
  38027. // / / \ / \
  38028. // / / \ / \
  38029. // / / (0,0) \ / (1,0) \
  38030. // / #---------#---------\
  38031. // v0 v1
  38032. //
  38033. // --------------------> i1
  38034. //
  38035. // interp of (i1,i2):
  38036. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38037. // along i1 : lerp(x0,x1, i1/(S-i2))
  38038. //
  38039. // centroid of triangle is needed to get help normal computation
  38040. // (c1,c2) are used for centroid location
  38041. var interp_vertex = function (i1, i2, c1, c2) {
  38042. // vertex is interpolated from
  38043. // - face_vertex_pos[0..2]
  38044. // - face_vertex_uv[0..2]
  38045. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38046. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38047. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38048. pos_interp.normalize();
  38049. var vertex_normal;
  38050. if (flat) {
  38051. // in flat mode, recalculate normal as face centroid normal
  38052. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38053. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38054. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38055. }
  38056. else {
  38057. // in smooth mode, recalculate normal from each single vertex position
  38058. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38059. }
  38060. // Vertex normal need correction due to X,Y,Z radius scaling
  38061. vertex_normal.x /= radiusX;
  38062. vertex_normal.y /= radiusY;
  38063. vertex_normal.z /= radiusZ;
  38064. vertex_normal.normalize();
  38065. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38066. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38067. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38068. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38069. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38070. uvs.push(uv_interp.x, uv_interp.y);
  38071. // push each vertex has member of a face
  38072. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38073. indices.push(current_indice);
  38074. current_indice++;
  38075. };
  38076. for (var i2 = 0; i2 < subdivisions; i2++) {
  38077. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38078. // face : (i1,i2) for /\ :
  38079. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38080. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38081. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38082. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38083. if (i1 + i2 + 1 < subdivisions) {
  38084. // face : (i1,i2)' for \/ :
  38085. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38086. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38087. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38088. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38089. }
  38090. }
  38091. }
  38092. }
  38093. // Sides
  38094. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38095. // Result
  38096. var vertexData = new VertexData();
  38097. vertexData.indices = indices;
  38098. vertexData.positions = positions;
  38099. vertexData.normals = normals;
  38100. vertexData.uvs = uvs;
  38101. return vertexData;
  38102. };
  38103. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38104. /**
  38105. * Creates the VertexData for a Polyhedron
  38106. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38107. * * type provided types are:
  38108. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38109. * * 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)
  38110. * * size the size of the IcoSphere, optional default 1
  38111. * * sizeX allows stretching in the x direction, optional, default size
  38112. * * sizeY allows stretching in the y direction, optional, default size
  38113. * * sizeZ allows stretching in the z direction, optional, default size
  38114. * * 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
  38115. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38116. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38117. * * flat when true creates a flat shaded mesh, optional, default true
  38118. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38119. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38120. * * 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)
  38121. * * 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)
  38122. * @returns the VertexData of the Polyhedron
  38123. */
  38124. VertexData.CreatePolyhedron = function (options) {
  38125. // provided polyhedron types :
  38126. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38127. // 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)
  38128. var polyhedra = [];
  38129. 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]] };
  38130. 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]] };
  38131. polyhedra[2] = {
  38132. 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]],
  38133. 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]]
  38134. };
  38135. polyhedra[3] = {
  38136. 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]],
  38137. 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]]
  38138. };
  38139. polyhedra[4] = {
  38140. 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]],
  38141. 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]]
  38142. };
  38143. 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]] };
  38144. 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]] };
  38145. 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]] };
  38146. 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]] };
  38147. 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]] };
  38148. 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]] };
  38149. 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]] };
  38150. 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]] };
  38151. 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]] };
  38152. polyhedra[14] = {
  38153. 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]],
  38154. 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]]
  38155. };
  38156. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38157. var size = options.size;
  38158. var sizeX = options.sizeX || size || 1;
  38159. var sizeY = options.sizeY || size || 1;
  38160. var sizeZ = options.sizeZ || size || 1;
  38161. var data = options.custom || polyhedra[type];
  38162. var nbfaces = data.face.length;
  38163. var faceUV = options.faceUV || new Array(nbfaces);
  38164. var faceColors = options.faceColors;
  38165. var flat = (options.flat === undefined) ? true : options.flat;
  38166. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38167. var positions = new Array();
  38168. var indices = new Array();
  38169. var normals = new Array();
  38170. var uvs = new Array();
  38171. var colors = new Array();
  38172. var index = 0;
  38173. var faceIdx = 0; // face cursor in the array "indexes"
  38174. var indexes = new Array();
  38175. var i = 0;
  38176. var f = 0;
  38177. var u, v, ang, x, y, tmp;
  38178. // default face colors and UV if undefined
  38179. if (flat) {
  38180. for (f = 0; f < nbfaces; f++) {
  38181. if (faceColors && faceColors[f] === undefined) {
  38182. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38183. }
  38184. if (faceUV && faceUV[f] === undefined) {
  38185. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38186. }
  38187. }
  38188. }
  38189. if (!flat) {
  38190. for (i = 0; i < data.vertex.length; i++) {
  38191. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38192. uvs.push(0, 0);
  38193. }
  38194. for (f = 0; f < nbfaces; f++) {
  38195. for (i = 0; i < data.face[f].length - 2; i++) {
  38196. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38197. }
  38198. }
  38199. }
  38200. else {
  38201. for (f = 0; f < nbfaces; f++) {
  38202. var fl = data.face[f].length; // number of vertices of the current face
  38203. ang = 2 * Math.PI / fl;
  38204. x = 0.5 * Math.tan(ang / 2);
  38205. y = 0.5;
  38206. // positions, uvs, colors
  38207. for (i = 0; i < fl; i++) {
  38208. // positions
  38209. 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);
  38210. indexes.push(index);
  38211. index++;
  38212. // uvs
  38213. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38214. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38215. uvs.push(u, v);
  38216. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38217. y = x * Math.sin(ang) + y * Math.cos(ang);
  38218. x = tmp;
  38219. // colors
  38220. if (faceColors) {
  38221. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38222. }
  38223. }
  38224. // indices from indexes
  38225. for (i = 0; i < fl - 2; i++) {
  38226. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38227. }
  38228. faceIdx += fl;
  38229. }
  38230. }
  38231. VertexData.ComputeNormals(positions, indices, normals);
  38232. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38233. var vertexData = new VertexData();
  38234. vertexData.positions = positions;
  38235. vertexData.indices = indices;
  38236. vertexData.normals = normals;
  38237. vertexData.uvs = uvs;
  38238. if (faceColors && flat) {
  38239. vertexData.colors = colors;
  38240. }
  38241. return vertexData;
  38242. };
  38243. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38244. /**
  38245. * Creates the VertexData for a TorusKnot
  38246. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38247. * * radius the radius of the torus knot, optional, default 2
  38248. * * tube the thickness of the tube, optional, default 0.5
  38249. * * radialSegments the number of sides on each tube segments, optional, default 32
  38250. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38251. * * p the number of windings around the z axis, optional, default 2
  38252. * * q the number of windings around the x axis, optional, default 3
  38253. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38254. * * 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)
  38255. * * 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)
  38256. * @returns the VertexData of the Torus Knot
  38257. */
  38258. VertexData.CreateTorusKnot = function (options) {
  38259. var indices = new Array();
  38260. var positions = new Array();
  38261. var normals = new Array();
  38262. var uvs = new Array();
  38263. var radius = options.radius || 2;
  38264. var tube = options.tube || 0.5;
  38265. var radialSegments = options.radialSegments || 32;
  38266. var tubularSegments = options.tubularSegments || 32;
  38267. var p = options.p || 2;
  38268. var q = options.q || 3;
  38269. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38270. // Helper
  38271. var getPos = function (angle) {
  38272. var cu = Math.cos(angle);
  38273. var su = Math.sin(angle);
  38274. var quOverP = q / p * angle;
  38275. var cs = Math.cos(quOverP);
  38276. var tx = radius * (2 + cs) * 0.5 * cu;
  38277. var ty = radius * (2 + cs) * su * 0.5;
  38278. var tz = radius * Math.sin(quOverP) * 0.5;
  38279. return new BABYLON.Vector3(tx, ty, tz);
  38280. };
  38281. // Vertices
  38282. var i;
  38283. var j;
  38284. for (i = 0; i <= radialSegments; i++) {
  38285. var modI = i % radialSegments;
  38286. var u = modI / radialSegments * 2 * p * Math.PI;
  38287. var p1 = getPos(u);
  38288. var p2 = getPos(u + 0.01);
  38289. var tang = p2.subtract(p1);
  38290. var n = p2.add(p1);
  38291. var bitan = BABYLON.Vector3.Cross(tang, n);
  38292. n = BABYLON.Vector3.Cross(bitan, tang);
  38293. bitan.normalize();
  38294. n.normalize();
  38295. for (j = 0; j < tubularSegments; j++) {
  38296. var modJ = j % tubularSegments;
  38297. var v = modJ / tubularSegments * 2 * Math.PI;
  38298. var cx = -tube * Math.cos(v);
  38299. var cy = tube * Math.sin(v);
  38300. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38301. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38302. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38303. uvs.push(i / radialSegments);
  38304. uvs.push(j / tubularSegments);
  38305. }
  38306. }
  38307. for (i = 0; i < radialSegments; i++) {
  38308. for (j = 0; j < tubularSegments; j++) {
  38309. var jNext = (j + 1) % tubularSegments;
  38310. var a = i * tubularSegments + j;
  38311. var b = (i + 1) * tubularSegments + j;
  38312. var c = (i + 1) * tubularSegments + jNext;
  38313. var d = i * tubularSegments + jNext;
  38314. indices.push(d);
  38315. indices.push(b);
  38316. indices.push(a);
  38317. indices.push(d);
  38318. indices.push(c);
  38319. indices.push(b);
  38320. }
  38321. }
  38322. // Normals
  38323. VertexData.ComputeNormals(positions, indices, normals);
  38324. // Sides
  38325. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38326. // Result
  38327. var vertexData = new VertexData();
  38328. vertexData.indices = indices;
  38329. vertexData.positions = positions;
  38330. vertexData.normals = normals;
  38331. vertexData.uvs = uvs;
  38332. return vertexData;
  38333. };
  38334. // Tools
  38335. /**
  38336. * Compute normals for given positions and indices
  38337. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38338. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38339. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38340. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38341. * * facetNormals : optional array of facet normals (vector3)
  38342. * * facetPositions : optional array of facet positions (vector3)
  38343. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38344. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38345. * * bInfo : optional bounding info, required for facetPartitioning computation
  38346. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38347. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38348. * * useRightHandedSystem: optional boolean to for right handed system computation
  38349. * * depthSort : optional boolean to enable the facet depth sort computation
  38350. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38351. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38352. */
  38353. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38354. // temporary scalar variables
  38355. var index = 0; // facet index
  38356. var p1p2x = 0.0; // p1p2 vector x coordinate
  38357. var p1p2y = 0.0; // p1p2 vector y coordinate
  38358. var p1p2z = 0.0; // p1p2 vector z coordinate
  38359. var p3p2x = 0.0; // p3p2 vector x coordinate
  38360. var p3p2y = 0.0; // p3p2 vector y coordinate
  38361. var p3p2z = 0.0; // p3p2 vector z coordinate
  38362. var faceNormalx = 0.0; // facet normal x coordinate
  38363. var faceNormaly = 0.0; // facet normal y coordinate
  38364. var faceNormalz = 0.0; // facet normal z coordinate
  38365. var length = 0.0; // facet normal length before normalization
  38366. var v1x = 0; // vector1 x index in the positions array
  38367. var v1y = 0; // vector1 y index in the positions array
  38368. var v1z = 0; // vector1 z index in the positions array
  38369. var v2x = 0; // vector2 x index in the positions array
  38370. var v2y = 0; // vector2 y index in the positions array
  38371. var v2z = 0; // vector2 z index in the positions array
  38372. var v3x = 0; // vector3 x index in the positions array
  38373. var v3y = 0; // vector3 y index in the positions array
  38374. var v3z = 0; // vector3 z index in the positions array
  38375. var computeFacetNormals = false;
  38376. var computeFacetPositions = false;
  38377. var computeFacetPartitioning = false;
  38378. var computeDepthSort = false;
  38379. var faceNormalSign = 1;
  38380. var ratio = 0;
  38381. var distanceTo = null;
  38382. if (options) {
  38383. computeFacetNormals = (options.facetNormals) ? true : false;
  38384. computeFacetPositions = (options.facetPositions) ? true : false;
  38385. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38386. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38387. ratio = options.ratio || 0;
  38388. computeDepthSort = (options.depthSort) ? true : false;
  38389. distanceTo = (options.distanceTo);
  38390. if (computeDepthSort) {
  38391. if (distanceTo === undefined) {
  38392. distanceTo = BABYLON.Vector3.Zero();
  38393. }
  38394. var depthSortedFacets = options.depthSortedFacets;
  38395. }
  38396. }
  38397. // facetPartitioning reinit if needed
  38398. var xSubRatio = 0;
  38399. var ySubRatio = 0;
  38400. var zSubRatio = 0;
  38401. var subSq = 0;
  38402. if (computeFacetPartitioning && options && options.bbSize) {
  38403. var ox = 0; // X partitioning index for facet position
  38404. var oy = 0; // Y partinioning index for facet position
  38405. var oz = 0; // Z partinioning index for facet position
  38406. var b1x = 0; // X partitioning index for facet v1 vertex
  38407. var b1y = 0; // Y partitioning index for facet v1 vertex
  38408. var b1z = 0; // z partitioning index for facet v1 vertex
  38409. var b2x = 0; // X partitioning index for facet v2 vertex
  38410. var b2y = 0; // Y partitioning index for facet v2 vertex
  38411. var b2z = 0; // Z partitioning index for facet v2 vertex
  38412. var b3x = 0; // X partitioning index for facet v3 vertex
  38413. var b3y = 0; // Y partitioning index for facet v3 vertex
  38414. var b3z = 0; // Z partitioning index for facet v3 vertex
  38415. var block_idx_o = 0; // facet barycenter block index
  38416. var block_idx_v1 = 0; // v1 vertex block index
  38417. var block_idx_v2 = 0; // v2 vertex block index
  38418. var block_idx_v3 = 0; // v3 vertex block index
  38419. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38420. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38421. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38422. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38423. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38424. subSq = options.subDiv.max * options.subDiv.max;
  38425. options.facetPartitioning.length = 0;
  38426. }
  38427. // reset the normals
  38428. for (index = 0; index < positions.length; index++) {
  38429. normals[index] = 0.0;
  38430. }
  38431. // Loop : 1 indice triplet = 1 facet
  38432. var nbFaces = (indices.length / 3) | 0;
  38433. for (index = 0; index < nbFaces; index++) {
  38434. // get the indexes of the coordinates of each vertex of the facet
  38435. v1x = indices[index * 3] * 3;
  38436. v1y = v1x + 1;
  38437. v1z = v1x + 2;
  38438. v2x = indices[index * 3 + 1] * 3;
  38439. v2y = v2x + 1;
  38440. v2z = v2x + 2;
  38441. v3x = indices[index * 3 + 2] * 3;
  38442. v3y = v3x + 1;
  38443. v3z = v3x + 2;
  38444. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38445. p1p2y = positions[v1y] - positions[v2y];
  38446. p1p2z = positions[v1z] - positions[v2z];
  38447. p3p2x = positions[v3x] - positions[v2x];
  38448. p3p2y = positions[v3y] - positions[v2y];
  38449. p3p2z = positions[v3z] - positions[v2z];
  38450. // compute the face normal with the cross product
  38451. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38452. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38453. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38454. // normalize this normal and store it in the array facetData
  38455. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38456. length = (length === 0) ? 1.0 : length;
  38457. faceNormalx /= length;
  38458. faceNormaly /= length;
  38459. faceNormalz /= length;
  38460. if (computeFacetNormals && options) {
  38461. options.facetNormals[index].x = faceNormalx;
  38462. options.facetNormals[index].y = faceNormaly;
  38463. options.facetNormals[index].z = faceNormalz;
  38464. }
  38465. if (computeFacetPositions && options) {
  38466. // compute and the facet barycenter coordinates in the array facetPositions
  38467. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38468. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38469. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38470. }
  38471. if (computeFacetPartitioning && options) {
  38472. // store the facet indexes in arrays in the main facetPartitioning array :
  38473. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38474. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38475. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38476. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38477. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38478. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38479. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38480. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38481. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38482. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38483. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38484. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38485. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38486. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38487. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38488. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38489. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38490. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38491. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38492. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38493. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38494. // push each facet index in each block containing the vertex
  38495. options.facetPartitioning[block_idx_v1].push(index);
  38496. if (block_idx_v2 != block_idx_v1) {
  38497. options.facetPartitioning[block_idx_v2].push(index);
  38498. }
  38499. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38500. options.facetPartitioning[block_idx_v3].push(index);
  38501. }
  38502. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38503. options.facetPartitioning[block_idx_o].push(index);
  38504. }
  38505. }
  38506. if (computeDepthSort && options && options.facetPositions) {
  38507. var dsf = depthSortedFacets[index];
  38508. dsf.ind = index * 3;
  38509. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38510. }
  38511. // compute the normals anyway
  38512. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38513. normals[v1y] += faceNormaly;
  38514. normals[v1z] += faceNormalz;
  38515. normals[v2x] += faceNormalx;
  38516. normals[v2y] += faceNormaly;
  38517. normals[v2z] += faceNormalz;
  38518. normals[v3x] += faceNormalx;
  38519. normals[v3y] += faceNormaly;
  38520. normals[v3z] += faceNormalz;
  38521. }
  38522. // last normalization of each normal
  38523. for (index = 0; index < normals.length / 3; index++) {
  38524. faceNormalx = normals[index * 3];
  38525. faceNormaly = normals[index * 3 + 1];
  38526. faceNormalz = normals[index * 3 + 2];
  38527. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38528. length = (length === 0) ? 1.0 : length;
  38529. faceNormalx /= length;
  38530. faceNormaly /= length;
  38531. faceNormalz /= length;
  38532. normals[index * 3] = faceNormalx;
  38533. normals[index * 3 + 1] = faceNormaly;
  38534. normals[index * 3 + 2] = faceNormalz;
  38535. }
  38536. };
  38537. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38538. var li = indices.length;
  38539. var ln = normals.length;
  38540. var i;
  38541. var n;
  38542. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38543. switch (sideOrientation) {
  38544. case BABYLON.Mesh.FRONTSIDE:
  38545. // nothing changed
  38546. break;
  38547. case BABYLON.Mesh.BACKSIDE:
  38548. var tmp;
  38549. // indices
  38550. for (i = 0; i < li; i += 3) {
  38551. tmp = indices[i];
  38552. indices[i] = indices[i + 2];
  38553. indices[i + 2] = tmp;
  38554. }
  38555. // normals
  38556. for (n = 0; n < ln; n++) {
  38557. normals[n] = -normals[n];
  38558. }
  38559. break;
  38560. case BABYLON.Mesh.DOUBLESIDE:
  38561. // positions
  38562. var lp = positions.length;
  38563. var l = lp / 3;
  38564. for (var p = 0; p < lp; p++) {
  38565. positions[lp + p] = positions[p];
  38566. }
  38567. // indices
  38568. for (i = 0; i < li; i += 3) {
  38569. indices[i + li] = indices[i + 2] + l;
  38570. indices[i + 1 + li] = indices[i + 1] + l;
  38571. indices[i + 2 + li] = indices[i] + l;
  38572. }
  38573. // normals
  38574. for (n = 0; n < ln; n++) {
  38575. normals[ln + n] = -normals[n];
  38576. }
  38577. // uvs
  38578. var lu = uvs.length;
  38579. var u = 0;
  38580. for (u = 0; u < lu; u++) {
  38581. uvs[u + lu] = uvs[u];
  38582. }
  38583. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38584. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38585. u = 0;
  38586. for (i = 0; i < lu / 2; i++) {
  38587. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38588. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38589. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38590. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38591. u += 2;
  38592. }
  38593. break;
  38594. }
  38595. };
  38596. /**
  38597. * Applies VertexData created from the imported parameters to the geometry
  38598. * @param parsedVertexData the parsed data from an imported file
  38599. * @param geometry the geometry to apply the VertexData to
  38600. */
  38601. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38602. var vertexData = new VertexData();
  38603. // positions
  38604. var positions = parsedVertexData.positions;
  38605. if (positions) {
  38606. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38607. }
  38608. // normals
  38609. var normals = parsedVertexData.normals;
  38610. if (normals) {
  38611. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38612. }
  38613. // tangents
  38614. var tangents = parsedVertexData.tangents;
  38615. if (tangents) {
  38616. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38617. }
  38618. // uvs
  38619. var uvs = parsedVertexData.uvs;
  38620. if (uvs) {
  38621. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38622. }
  38623. // uv2s
  38624. var uv2s = parsedVertexData.uv2s;
  38625. if (uv2s) {
  38626. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38627. }
  38628. // uv3s
  38629. var uv3s = parsedVertexData.uv3s;
  38630. if (uv3s) {
  38631. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38632. }
  38633. // uv4s
  38634. var uv4s = parsedVertexData.uv4s;
  38635. if (uv4s) {
  38636. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38637. }
  38638. // uv5s
  38639. var uv5s = parsedVertexData.uv5s;
  38640. if (uv5s) {
  38641. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38642. }
  38643. // uv6s
  38644. var uv6s = parsedVertexData.uv6s;
  38645. if (uv6s) {
  38646. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38647. }
  38648. // colors
  38649. var colors = parsedVertexData.colors;
  38650. if (colors) {
  38651. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38652. }
  38653. // matricesIndices
  38654. var matricesIndices = parsedVertexData.matricesIndices;
  38655. if (matricesIndices) {
  38656. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38657. }
  38658. // matricesWeights
  38659. var matricesWeights = parsedVertexData.matricesWeights;
  38660. if (matricesWeights) {
  38661. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38662. }
  38663. // indices
  38664. var indices = parsedVertexData.indices;
  38665. if (indices) {
  38666. vertexData.indices = indices;
  38667. }
  38668. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38669. };
  38670. return VertexData;
  38671. }());
  38672. BABYLON.VertexData = VertexData;
  38673. })(BABYLON || (BABYLON = {}));
  38674. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38675. var BABYLON;
  38676. (function (BABYLON) {
  38677. /**
  38678. * Class used to store geometry data (vertex buffers + index buffer)
  38679. */
  38680. var Geometry = /** @class */ (function () {
  38681. /**
  38682. * Creates a new geometry
  38683. * @param id defines the unique ID
  38684. * @param scene defines the hosting scene
  38685. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38686. * @param updatable defines if geometry must be updatable (false by default)
  38687. * @param mesh defines the mesh that will be associated with the geometry
  38688. */
  38689. function Geometry(id, scene, vertexData, updatable, mesh) {
  38690. if (updatable === void 0) { updatable = false; }
  38691. if (mesh === void 0) { mesh = null; }
  38692. /**
  38693. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38694. */
  38695. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38696. this._totalVertices = 0;
  38697. this._isDisposed = false;
  38698. this._indexBufferIsUpdatable = false;
  38699. this.id = id;
  38700. this._engine = scene.getEngine();
  38701. this._meshes = [];
  38702. this._scene = scene;
  38703. //Init vertex buffer cache
  38704. this._vertexBuffers = {};
  38705. this._indices = [];
  38706. this._updatable = updatable;
  38707. // vertexData
  38708. if (vertexData) {
  38709. this.setAllVerticesData(vertexData, updatable);
  38710. }
  38711. else {
  38712. this._totalVertices = 0;
  38713. this._indices = [];
  38714. }
  38715. if (this._engine.getCaps().vertexArrayObject) {
  38716. this._vertexArrayObjects = {};
  38717. }
  38718. // applyToMesh
  38719. if (mesh) {
  38720. if (mesh.getClassName() === "LinesMesh") {
  38721. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38722. this._updateExtend();
  38723. }
  38724. this.applyToMesh(mesh);
  38725. mesh.computeWorldMatrix(true);
  38726. }
  38727. }
  38728. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38729. /**
  38730. * 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
  38731. */
  38732. get: function () {
  38733. return this._boundingBias;
  38734. },
  38735. /**
  38736. * 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
  38737. */
  38738. set: function (value) {
  38739. if (this._boundingBias && this._boundingBias.equals(value)) {
  38740. return;
  38741. }
  38742. this._boundingBias = value.clone();
  38743. this._updateBoundingInfo(true, null);
  38744. },
  38745. enumerable: true,
  38746. configurable: true
  38747. });
  38748. /**
  38749. * Static function used to attach a new empty geometry to a mesh
  38750. * @param mesh defines the mesh to attach the geometry to
  38751. * @returns the new {BABYLON.Geometry}
  38752. */
  38753. Geometry.CreateGeometryForMesh = function (mesh) {
  38754. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38755. geometry.applyToMesh(mesh);
  38756. return geometry;
  38757. };
  38758. Object.defineProperty(Geometry.prototype, "extend", {
  38759. /**
  38760. * Gets the current extend of the geometry
  38761. */
  38762. get: function () {
  38763. return this._extend;
  38764. },
  38765. enumerable: true,
  38766. configurable: true
  38767. });
  38768. /**
  38769. * Gets the hosting scene
  38770. * @returns the hosting {BABYLON.Scene}
  38771. */
  38772. Geometry.prototype.getScene = function () {
  38773. return this._scene;
  38774. };
  38775. /**
  38776. * Gets the hosting engine
  38777. * @returns the hosting {BABYLON.Engine}
  38778. */
  38779. Geometry.prototype.getEngine = function () {
  38780. return this._engine;
  38781. };
  38782. /**
  38783. * Defines if the geometry is ready to use
  38784. * @returns true if the geometry is ready to be used
  38785. */
  38786. Geometry.prototype.isReady = function () {
  38787. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38788. };
  38789. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38790. /**
  38791. * Gets a value indicating that the geometry should not be serialized
  38792. */
  38793. get: function () {
  38794. for (var index = 0; index < this._meshes.length; index++) {
  38795. if (!this._meshes[index].doNotSerialize) {
  38796. return false;
  38797. }
  38798. }
  38799. return true;
  38800. },
  38801. enumerable: true,
  38802. configurable: true
  38803. });
  38804. /** @hidden */
  38805. Geometry.prototype._rebuild = function () {
  38806. if (this._vertexArrayObjects) {
  38807. this._vertexArrayObjects = {};
  38808. }
  38809. // Index buffer
  38810. if (this._meshes.length !== 0 && this._indices) {
  38811. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38812. }
  38813. // Vertex buffers
  38814. for (var key in this._vertexBuffers) {
  38815. var vertexBuffer = this._vertexBuffers[key];
  38816. vertexBuffer._rebuild();
  38817. }
  38818. };
  38819. /**
  38820. * Affects all gemetry data in one call
  38821. * @param vertexData defines the geometry data
  38822. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38823. */
  38824. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38825. vertexData.applyToGeometry(this, updatable);
  38826. this.notifyUpdate();
  38827. };
  38828. /**
  38829. * Set specific vertex data
  38830. * @param kind defines the data kind (Position, normal, etc...)
  38831. * @param data defines the vertex data to use
  38832. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38833. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38834. */
  38835. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38836. if (updatable === void 0) { updatable = false; }
  38837. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38838. this.setVerticesBuffer(buffer);
  38839. };
  38840. /**
  38841. * Removes a specific vertex data
  38842. * @param kind defines the data kind (Position, normal, etc...)
  38843. */
  38844. Geometry.prototype.removeVerticesData = function (kind) {
  38845. if (this._vertexBuffers[kind]) {
  38846. this._vertexBuffers[kind].dispose();
  38847. delete this._vertexBuffers[kind];
  38848. }
  38849. };
  38850. /**
  38851. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38852. * @param buffer defines the vertex buffer to use
  38853. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38854. */
  38855. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38856. if (totalVertices === void 0) { totalVertices = null; }
  38857. var kind = buffer.getKind();
  38858. if (this._vertexBuffers[kind]) {
  38859. this._vertexBuffers[kind].dispose();
  38860. }
  38861. this._vertexBuffers[kind] = buffer;
  38862. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38863. var data = buffer.getData();
  38864. if (totalVertices != null) {
  38865. this._totalVertices = totalVertices;
  38866. }
  38867. else {
  38868. if (data != null) {
  38869. this._totalVertices = data.length / (buffer.byteStride / 4);
  38870. }
  38871. }
  38872. this._updateExtend(data);
  38873. this._resetPointsArrayCache();
  38874. var meshes = this._meshes;
  38875. var numOfMeshes = meshes.length;
  38876. for (var index = 0; index < numOfMeshes; index++) {
  38877. var mesh = meshes[index];
  38878. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38879. mesh._createGlobalSubMesh(false);
  38880. mesh.computeWorldMatrix(true);
  38881. }
  38882. }
  38883. this.notifyUpdate(kind);
  38884. if (this._vertexArrayObjects) {
  38885. this._disposeVertexArrayObjects();
  38886. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38887. }
  38888. };
  38889. /**
  38890. * Update a specific vertex buffer
  38891. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38892. * It will do nothing if the buffer is not updatable
  38893. * @param kind defines the data kind (Position, normal, etc...)
  38894. * @param data defines the data to use
  38895. * @param offset defines the offset in the target buffer where to store the data
  38896. * @param useBytes set to true if the offset is in bytes
  38897. */
  38898. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38899. if (useBytes === void 0) { useBytes = false; }
  38900. var vertexBuffer = this.getVertexBuffer(kind);
  38901. if (!vertexBuffer) {
  38902. return;
  38903. }
  38904. vertexBuffer.updateDirectly(data, offset, useBytes);
  38905. this.notifyUpdate(kind);
  38906. };
  38907. /**
  38908. * Update a specific vertex buffer
  38909. * This function will create a new buffer if the current one is not updatable
  38910. * @param kind defines the data kind (Position, normal, etc...)
  38911. * @param data defines the data to use
  38912. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38913. */
  38914. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38915. if (updateExtends === void 0) { updateExtends = false; }
  38916. var vertexBuffer = this.getVertexBuffer(kind);
  38917. if (!vertexBuffer) {
  38918. return;
  38919. }
  38920. vertexBuffer.update(data);
  38921. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38922. this._updateBoundingInfo(updateExtends, data);
  38923. }
  38924. this.notifyUpdate(kind);
  38925. };
  38926. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38927. if (updateExtends) {
  38928. this._updateExtend(data);
  38929. }
  38930. var meshes = this._meshes;
  38931. var numOfMeshes = meshes.length;
  38932. this._resetPointsArrayCache();
  38933. for (var index = 0; index < numOfMeshes; index++) {
  38934. var mesh = meshes[index];
  38935. if (updateExtends) {
  38936. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38937. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38938. var subMesh = mesh.subMeshes[subIndex];
  38939. subMesh.refreshBoundingInfo();
  38940. }
  38941. }
  38942. }
  38943. };
  38944. /** @hidden */
  38945. Geometry.prototype._bind = function (effect, indexToBind) {
  38946. if (!effect) {
  38947. return;
  38948. }
  38949. if (indexToBind === undefined) {
  38950. indexToBind = this._indexBuffer;
  38951. }
  38952. var vbs = this.getVertexBuffers();
  38953. if (!vbs) {
  38954. return;
  38955. }
  38956. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38957. this._engine.bindBuffers(vbs, indexToBind, effect);
  38958. return;
  38959. }
  38960. // Using VAO
  38961. if (!this._vertexArrayObjects[effect.key]) {
  38962. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38963. }
  38964. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38965. };
  38966. /**
  38967. * Gets total number of vertices
  38968. * @returns the total number of vertices
  38969. */
  38970. Geometry.prototype.getTotalVertices = function () {
  38971. if (!this.isReady()) {
  38972. return 0;
  38973. }
  38974. return this._totalVertices;
  38975. };
  38976. /**
  38977. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38978. * @param kind defines the data kind (Position, normal, etc...)
  38979. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38980. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38981. * @returns a float array containing vertex data
  38982. */
  38983. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38984. var vertexBuffer = this.getVertexBuffer(kind);
  38985. if (!vertexBuffer) {
  38986. return null;
  38987. }
  38988. var data = vertexBuffer.getData();
  38989. if (!data) {
  38990. return null;
  38991. }
  38992. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38993. var count = this._totalVertices * vertexBuffer.getSize();
  38994. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38995. var copy_1 = new Array(count);
  38996. vertexBuffer.forEach(count, function (value, index) {
  38997. copy_1[index] = value;
  38998. });
  38999. return copy_1;
  39000. }
  39001. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39002. if (data instanceof Array) {
  39003. var offset = vertexBuffer.byteOffset / 4;
  39004. return BABYLON.Tools.Slice(data, offset, offset + count);
  39005. }
  39006. else if (data instanceof ArrayBuffer) {
  39007. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39008. }
  39009. else {
  39010. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39011. }
  39012. }
  39013. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39014. return BABYLON.Tools.Slice(data);
  39015. }
  39016. return data;
  39017. };
  39018. /**
  39019. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39020. * @param kind defines the data kind (Position, normal, etc...)
  39021. * @returns true if the vertex buffer with the specified kind is updatable
  39022. */
  39023. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39024. var vb = this._vertexBuffers[kind];
  39025. if (!vb) {
  39026. return false;
  39027. }
  39028. return vb.isUpdatable();
  39029. };
  39030. /**
  39031. * Gets a specific vertex buffer
  39032. * @param kind defines the data kind (Position, normal, etc...)
  39033. * @returns a {BABYLON.VertexBuffer}
  39034. */
  39035. Geometry.prototype.getVertexBuffer = function (kind) {
  39036. if (!this.isReady()) {
  39037. return null;
  39038. }
  39039. return this._vertexBuffers[kind];
  39040. };
  39041. /**
  39042. * Returns all vertex buffers
  39043. * @return an object holding all vertex buffers indexed by kind
  39044. */
  39045. Geometry.prototype.getVertexBuffers = function () {
  39046. if (!this.isReady()) {
  39047. return null;
  39048. }
  39049. return this._vertexBuffers;
  39050. };
  39051. /**
  39052. * Gets a boolean indicating if specific vertex buffer is present
  39053. * @param kind defines the data kind (Position, normal, etc...)
  39054. * @returns true if data is present
  39055. */
  39056. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39057. if (!this._vertexBuffers) {
  39058. if (this._delayInfo) {
  39059. return this._delayInfo.indexOf(kind) !== -1;
  39060. }
  39061. return false;
  39062. }
  39063. return this._vertexBuffers[kind] !== undefined;
  39064. };
  39065. /**
  39066. * Gets a list of all attached data kinds (Position, normal, etc...)
  39067. * @returns a list of string containing all kinds
  39068. */
  39069. Geometry.prototype.getVerticesDataKinds = function () {
  39070. var result = [];
  39071. var kind;
  39072. if (!this._vertexBuffers && this._delayInfo) {
  39073. for (kind in this._delayInfo) {
  39074. result.push(kind);
  39075. }
  39076. }
  39077. else {
  39078. for (kind in this._vertexBuffers) {
  39079. result.push(kind);
  39080. }
  39081. }
  39082. return result;
  39083. };
  39084. /**
  39085. * Update index buffer
  39086. * @param indices defines the indices to store in the index buffer
  39087. * @param offset defines the offset in the target buffer where to store the data
  39088. */
  39089. Geometry.prototype.updateIndices = function (indices, offset) {
  39090. if (!this._indexBuffer) {
  39091. return;
  39092. }
  39093. if (!this._indexBufferIsUpdatable) {
  39094. this.setIndices(indices, null, true);
  39095. }
  39096. else {
  39097. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39098. }
  39099. };
  39100. /**
  39101. * Creates a new index buffer
  39102. * @param indices defines the indices to store in the index buffer
  39103. * @param totalVertices defines the total number of vertices (could be null)
  39104. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39105. */
  39106. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39107. if (totalVertices === void 0) { totalVertices = null; }
  39108. if (updatable === void 0) { updatable = false; }
  39109. if (this._indexBuffer) {
  39110. this._engine._releaseBuffer(this._indexBuffer);
  39111. }
  39112. this._disposeVertexArrayObjects();
  39113. this._indices = indices;
  39114. this._indexBufferIsUpdatable = updatable;
  39115. if (this._meshes.length !== 0 && this._indices) {
  39116. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39117. }
  39118. if (totalVertices != undefined) { // including null and undefined
  39119. this._totalVertices = totalVertices;
  39120. }
  39121. var meshes = this._meshes;
  39122. var numOfMeshes = meshes.length;
  39123. for (var index = 0; index < numOfMeshes; index++) {
  39124. meshes[index]._createGlobalSubMesh(true);
  39125. }
  39126. this.notifyUpdate();
  39127. };
  39128. /**
  39129. * Return the total number of indices
  39130. * @returns the total number of indices
  39131. */
  39132. Geometry.prototype.getTotalIndices = function () {
  39133. if (!this.isReady()) {
  39134. return 0;
  39135. }
  39136. return this._indices.length;
  39137. };
  39138. /**
  39139. * Gets the index buffer array
  39140. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39141. * @returns the index buffer array
  39142. */
  39143. Geometry.prototype.getIndices = function (copyWhenShared) {
  39144. if (!this.isReady()) {
  39145. return null;
  39146. }
  39147. var orig = this._indices;
  39148. if (!copyWhenShared || this._meshes.length === 1) {
  39149. return orig;
  39150. }
  39151. else {
  39152. var len = orig.length;
  39153. var copy = [];
  39154. for (var i = 0; i < len; i++) {
  39155. copy.push(orig[i]);
  39156. }
  39157. return copy;
  39158. }
  39159. };
  39160. /**
  39161. * Gets the index buffer
  39162. * @return the index buffer
  39163. */
  39164. Geometry.prototype.getIndexBuffer = function () {
  39165. if (!this.isReady()) {
  39166. return null;
  39167. }
  39168. return this._indexBuffer;
  39169. };
  39170. /** @hidden */
  39171. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39172. if (effect === void 0) { effect = null; }
  39173. if (!effect || !this._vertexArrayObjects) {
  39174. return;
  39175. }
  39176. if (this._vertexArrayObjects[effect.key]) {
  39177. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39178. delete this._vertexArrayObjects[effect.key];
  39179. }
  39180. };
  39181. /**
  39182. * Release the associated resources for a specific mesh
  39183. * @param mesh defines the source mesh
  39184. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39185. */
  39186. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39187. var meshes = this._meshes;
  39188. var index = meshes.indexOf(mesh);
  39189. if (index === -1) {
  39190. return;
  39191. }
  39192. meshes.splice(index, 1);
  39193. mesh._geometry = null;
  39194. if (meshes.length === 0 && shouldDispose) {
  39195. this.dispose();
  39196. }
  39197. };
  39198. /**
  39199. * Apply current geometry to a given mesh
  39200. * @param mesh defines the mesh to apply geometry to
  39201. */
  39202. Geometry.prototype.applyToMesh = function (mesh) {
  39203. if (mesh._geometry === this) {
  39204. return;
  39205. }
  39206. var previousGeometry = mesh._geometry;
  39207. if (previousGeometry) {
  39208. previousGeometry.releaseForMesh(mesh);
  39209. }
  39210. var meshes = this._meshes;
  39211. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39212. mesh._geometry = this;
  39213. this._scene.pushGeometry(this);
  39214. meshes.push(mesh);
  39215. if (this.isReady()) {
  39216. this._applyToMesh(mesh);
  39217. }
  39218. else {
  39219. mesh._boundingInfo = this._boundingInfo;
  39220. }
  39221. };
  39222. Geometry.prototype._updateExtend = function (data) {
  39223. if (data === void 0) { data = null; }
  39224. if (!data) {
  39225. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39226. }
  39227. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39228. };
  39229. Geometry.prototype._applyToMesh = function (mesh) {
  39230. var numOfMeshes = this._meshes.length;
  39231. // vertexBuffers
  39232. for (var kind in this._vertexBuffers) {
  39233. if (numOfMeshes === 1) {
  39234. this._vertexBuffers[kind].create();
  39235. }
  39236. var buffer = this._vertexBuffers[kind].getBuffer();
  39237. if (buffer)
  39238. buffer.references = numOfMeshes;
  39239. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39240. if (!this._extend) {
  39241. this._updateExtend();
  39242. }
  39243. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39244. mesh._createGlobalSubMesh(false);
  39245. //bounding info was just created again, world matrix should be applied again.
  39246. mesh._updateBoundingInfo();
  39247. }
  39248. }
  39249. // indexBuffer
  39250. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39251. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39252. }
  39253. if (this._indexBuffer) {
  39254. this._indexBuffer.references = numOfMeshes;
  39255. }
  39256. };
  39257. Geometry.prototype.notifyUpdate = function (kind) {
  39258. if (this.onGeometryUpdated) {
  39259. this.onGeometryUpdated(this, kind);
  39260. }
  39261. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39262. var mesh = _a[_i];
  39263. mesh._markSubMeshesAsAttributesDirty();
  39264. }
  39265. };
  39266. /**
  39267. * Load the geometry if it was flagged as delay loaded
  39268. * @param scene defines the hosting scene
  39269. * @param onLoaded defines a callback called when the geometry is loaded
  39270. */
  39271. Geometry.prototype.load = function (scene, onLoaded) {
  39272. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39273. return;
  39274. }
  39275. if (this.isReady()) {
  39276. if (onLoaded) {
  39277. onLoaded();
  39278. }
  39279. return;
  39280. }
  39281. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39282. this._queueLoad(scene, onLoaded);
  39283. };
  39284. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39285. var _this = this;
  39286. if (!this.delayLoadingFile) {
  39287. return;
  39288. }
  39289. scene._addPendingData(this);
  39290. scene._loadFile(this.delayLoadingFile, function (data) {
  39291. if (!_this._delayLoadingFunction) {
  39292. return;
  39293. }
  39294. _this._delayLoadingFunction(JSON.parse(data), _this);
  39295. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39296. _this._delayInfo = [];
  39297. scene._removePendingData(_this);
  39298. var meshes = _this._meshes;
  39299. var numOfMeshes = meshes.length;
  39300. for (var index = 0; index < numOfMeshes; index++) {
  39301. _this._applyToMesh(meshes[index]);
  39302. }
  39303. if (onLoaded) {
  39304. onLoaded();
  39305. }
  39306. }, undefined, true);
  39307. };
  39308. /**
  39309. * Invert the geometry to move from a right handed system to a left handed one.
  39310. */
  39311. Geometry.prototype.toLeftHanded = function () {
  39312. // Flip faces
  39313. var tIndices = this.getIndices(false);
  39314. if (tIndices != null && tIndices.length > 0) {
  39315. for (var i = 0; i < tIndices.length; i += 3) {
  39316. var tTemp = tIndices[i + 0];
  39317. tIndices[i + 0] = tIndices[i + 2];
  39318. tIndices[i + 2] = tTemp;
  39319. }
  39320. this.setIndices(tIndices);
  39321. }
  39322. // Negate position.z
  39323. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39324. if (tPositions != null && tPositions.length > 0) {
  39325. for (var i = 0; i < tPositions.length; i += 3) {
  39326. tPositions[i + 2] = -tPositions[i + 2];
  39327. }
  39328. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39329. }
  39330. // Negate normal.z
  39331. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39332. if (tNormals != null && tNormals.length > 0) {
  39333. for (var i = 0; i < tNormals.length; i += 3) {
  39334. tNormals[i + 2] = -tNormals[i + 2];
  39335. }
  39336. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39337. }
  39338. };
  39339. // Cache
  39340. /** @hidden */
  39341. Geometry.prototype._resetPointsArrayCache = function () {
  39342. this._positions = null;
  39343. };
  39344. /** @hidden */
  39345. Geometry.prototype._generatePointsArray = function () {
  39346. if (this._positions)
  39347. return true;
  39348. this._positions = [];
  39349. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39350. if (!data) {
  39351. return false;
  39352. }
  39353. for (var index = 0; index < data.length; index += 3) {
  39354. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39355. }
  39356. return true;
  39357. };
  39358. /**
  39359. * Gets a value indicating if the geometry is disposed
  39360. * @returns true if the geometry was disposed
  39361. */
  39362. Geometry.prototype.isDisposed = function () {
  39363. return this._isDisposed;
  39364. };
  39365. Geometry.prototype._disposeVertexArrayObjects = function () {
  39366. if (this._vertexArrayObjects) {
  39367. for (var kind in this._vertexArrayObjects) {
  39368. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39369. }
  39370. this._vertexArrayObjects = {};
  39371. }
  39372. };
  39373. /**
  39374. * Free all associated resources
  39375. */
  39376. Geometry.prototype.dispose = function () {
  39377. var meshes = this._meshes;
  39378. var numOfMeshes = meshes.length;
  39379. var index;
  39380. for (index = 0; index < numOfMeshes; index++) {
  39381. this.releaseForMesh(meshes[index]);
  39382. }
  39383. this._meshes = [];
  39384. this._disposeVertexArrayObjects();
  39385. for (var kind in this._vertexBuffers) {
  39386. this._vertexBuffers[kind].dispose();
  39387. }
  39388. this._vertexBuffers = {};
  39389. this._totalVertices = 0;
  39390. if (this._indexBuffer) {
  39391. this._engine._releaseBuffer(this._indexBuffer);
  39392. }
  39393. this._indexBuffer = null;
  39394. this._indices = [];
  39395. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39396. this.delayLoadingFile = null;
  39397. this._delayLoadingFunction = null;
  39398. this._delayInfo = [];
  39399. this._boundingInfo = null;
  39400. this._scene.removeGeometry(this);
  39401. this._isDisposed = true;
  39402. };
  39403. /**
  39404. * Clone the current geometry into a new geometry
  39405. * @param id defines the unique ID of the new geometry
  39406. * @returns a new geometry object
  39407. */
  39408. Geometry.prototype.copy = function (id) {
  39409. var vertexData = new BABYLON.VertexData();
  39410. vertexData.indices = [];
  39411. var indices = this.getIndices();
  39412. if (indices) {
  39413. for (var index = 0; index < indices.length; index++) {
  39414. vertexData.indices.push(indices[index]);
  39415. }
  39416. }
  39417. var updatable = false;
  39418. var stopChecking = false;
  39419. var kind;
  39420. for (kind in this._vertexBuffers) {
  39421. // using slice() to make a copy of the array and not just reference it
  39422. var data = this.getVerticesData(kind);
  39423. if (data instanceof Float32Array) {
  39424. vertexData.set(new Float32Array(data), kind);
  39425. }
  39426. else {
  39427. vertexData.set(data.slice(0), kind);
  39428. }
  39429. if (!stopChecking) {
  39430. var vb = this.getVertexBuffer(kind);
  39431. if (vb) {
  39432. updatable = vb.isUpdatable();
  39433. stopChecking = !updatable;
  39434. }
  39435. }
  39436. }
  39437. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39438. geometry.delayLoadState = this.delayLoadState;
  39439. geometry.delayLoadingFile = this.delayLoadingFile;
  39440. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39441. for (kind in this._delayInfo) {
  39442. geometry._delayInfo = geometry._delayInfo || [];
  39443. geometry._delayInfo.push(kind);
  39444. }
  39445. // Bounding info
  39446. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39447. return geometry;
  39448. };
  39449. /**
  39450. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39451. * @return a JSON representation of the current geometry data (without the vertices data)
  39452. */
  39453. Geometry.prototype.serialize = function () {
  39454. var serializationObject = {};
  39455. serializationObject.id = this.id;
  39456. serializationObject.updatable = this._updatable;
  39457. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39458. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39459. }
  39460. return serializationObject;
  39461. };
  39462. Geometry.prototype.toNumberArray = function (origin) {
  39463. if (Array.isArray(origin)) {
  39464. return origin;
  39465. }
  39466. else {
  39467. return Array.prototype.slice.call(origin);
  39468. }
  39469. };
  39470. /**
  39471. * Serialize all vertices data into a JSON oject
  39472. * @returns a JSON representation of the current geometry data
  39473. */
  39474. Geometry.prototype.serializeVerticeData = function () {
  39475. var serializationObject = this.serialize();
  39476. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39477. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39478. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39479. serializationObject.positions._updatable = true;
  39480. }
  39481. }
  39482. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39483. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39484. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39485. serializationObject.normals._updatable = true;
  39486. }
  39487. }
  39488. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39489. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39490. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39491. serializationObject.tangets._updatable = true;
  39492. }
  39493. }
  39494. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39495. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39496. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39497. serializationObject.uvs._updatable = true;
  39498. }
  39499. }
  39500. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39501. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39502. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39503. serializationObject.uv2s._updatable = true;
  39504. }
  39505. }
  39506. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39507. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39508. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39509. serializationObject.uv3s._updatable = true;
  39510. }
  39511. }
  39512. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39513. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39514. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39515. serializationObject.uv4s._updatable = true;
  39516. }
  39517. }
  39518. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39519. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39520. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39521. serializationObject.uv5s._updatable = true;
  39522. }
  39523. }
  39524. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39525. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39526. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39527. serializationObject.uv6s._updatable = true;
  39528. }
  39529. }
  39530. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39531. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39532. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39533. serializationObject.colors._updatable = true;
  39534. }
  39535. }
  39536. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39537. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39538. serializationObject.matricesIndices._isExpanded = true;
  39539. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39540. serializationObject.matricesIndices._updatable = true;
  39541. }
  39542. }
  39543. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39544. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39545. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39546. serializationObject.matricesWeights._updatable = true;
  39547. }
  39548. }
  39549. serializationObject.indices = this.toNumberArray(this.getIndices());
  39550. return serializationObject;
  39551. };
  39552. // Statics
  39553. /**
  39554. * Extracts a clone of a mesh geometry
  39555. * @param mesh defines the source mesh
  39556. * @param id defines the unique ID of the new geometry object
  39557. * @returns the new geometry object
  39558. */
  39559. Geometry.ExtractFromMesh = function (mesh, id) {
  39560. var geometry = mesh._geometry;
  39561. if (!geometry) {
  39562. return null;
  39563. }
  39564. return geometry.copy(id);
  39565. };
  39566. /**
  39567. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39568. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39569. * Be aware Math.random() could cause collisions, but:
  39570. * "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"
  39571. * @returns a string containing a new GUID
  39572. */
  39573. Geometry.RandomId = function () {
  39574. return BABYLON.Tools.RandomId();
  39575. };
  39576. /** @hidden */
  39577. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39578. var scene = mesh.getScene();
  39579. // Geometry
  39580. var geometryId = parsedGeometry.geometryId;
  39581. if (geometryId) {
  39582. var geometry = scene.getGeometryByID(geometryId);
  39583. if (geometry) {
  39584. geometry.applyToMesh(mesh);
  39585. }
  39586. }
  39587. else if (parsedGeometry instanceof ArrayBuffer) {
  39588. var binaryInfo = mesh._binaryInfo;
  39589. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39590. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39591. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39592. }
  39593. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39594. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39595. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39596. }
  39597. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39598. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39599. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39600. }
  39601. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39602. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39603. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39604. }
  39605. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39606. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39607. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39608. }
  39609. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39610. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39611. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39612. }
  39613. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39614. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39615. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39616. }
  39617. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39618. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39619. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39620. }
  39621. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39622. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39623. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39624. }
  39625. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39626. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39627. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39628. }
  39629. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39630. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39631. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39632. }
  39633. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39634. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39635. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39636. }
  39637. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39638. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39639. mesh.setIndices(indicesData, null);
  39640. }
  39641. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39642. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39643. mesh.subMeshes = [];
  39644. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39645. var materialIndex = subMeshesData[(i * 5) + 0];
  39646. var verticesStart = subMeshesData[(i * 5) + 1];
  39647. var verticesCount = subMeshesData[(i * 5) + 2];
  39648. var indexStart = subMeshesData[(i * 5) + 3];
  39649. var indexCount = subMeshesData[(i * 5) + 4];
  39650. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39651. }
  39652. }
  39653. }
  39654. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39655. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39656. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39657. if (parsedGeometry.tangents) {
  39658. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39659. }
  39660. if (parsedGeometry.uvs) {
  39661. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39662. }
  39663. if (parsedGeometry.uvs2) {
  39664. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39665. }
  39666. if (parsedGeometry.uvs3) {
  39667. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39668. }
  39669. if (parsedGeometry.uvs4) {
  39670. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39671. }
  39672. if (parsedGeometry.uvs5) {
  39673. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39674. }
  39675. if (parsedGeometry.uvs6) {
  39676. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39677. }
  39678. if (parsedGeometry.colors) {
  39679. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39680. }
  39681. if (parsedGeometry.matricesIndices) {
  39682. if (!parsedGeometry.matricesIndices._isExpanded) {
  39683. var floatIndices = [];
  39684. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39685. var matricesIndex = parsedGeometry.matricesIndices[i];
  39686. floatIndices.push(matricesIndex & 0x000000FF);
  39687. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39688. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39689. floatIndices.push(matricesIndex >> 24);
  39690. }
  39691. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39692. }
  39693. else {
  39694. delete parsedGeometry.matricesIndices._isExpanded;
  39695. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39696. }
  39697. }
  39698. if (parsedGeometry.matricesIndicesExtra) {
  39699. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39700. var floatIndices = [];
  39701. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39702. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39703. floatIndices.push(matricesIndex & 0x000000FF);
  39704. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39705. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39706. floatIndices.push(matricesIndex >> 24);
  39707. }
  39708. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39709. }
  39710. else {
  39711. delete parsedGeometry.matricesIndices._isExpanded;
  39712. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39713. }
  39714. }
  39715. if (parsedGeometry.matricesWeights) {
  39716. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39717. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39718. }
  39719. if (parsedGeometry.matricesWeightsExtra) {
  39720. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39721. }
  39722. mesh.setIndices(parsedGeometry.indices, null);
  39723. }
  39724. // SubMeshes
  39725. if (parsedGeometry.subMeshes) {
  39726. mesh.subMeshes = [];
  39727. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39728. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39729. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39730. }
  39731. }
  39732. // Flat shading
  39733. if (mesh._shouldGenerateFlatShading) {
  39734. mesh.convertToFlatShadedMesh();
  39735. delete mesh._shouldGenerateFlatShading;
  39736. }
  39737. // Update
  39738. mesh.computeWorldMatrix(true);
  39739. // Octree
  39740. var sceneOctree = scene.selectionOctree;
  39741. if (sceneOctree !== undefined && sceneOctree !== null) {
  39742. sceneOctree.addMesh(mesh);
  39743. }
  39744. };
  39745. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39746. var epsilon = 1e-3;
  39747. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39748. return;
  39749. }
  39750. var noInfluenceBoneIndex = 0.0;
  39751. if (parsedGeometry.skeletonId > -1) {
  39752. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39753. if (!skeleton) {
  39754. return;
  39755. }
  39756. noInfluenceBoneIndex = skeleton.bones.length;
  39757. }
  39758. else {
  39759. return;
  39760. }
  39761. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39762. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39763. var matricesWeights = parsedGeometry.matricesWeights;
  39764. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39765. var influencers = parsedGeometry.numBoneInfluencer;
  39766. var size = matricesWeights.length;
  39767. for (var i = 0; i < size; i += 4) {
  39768. var weight = 0.0;
  39769. var firstZeroWeight = -1;
  39770. for (var j = 0; j < 4; j++) {
  39771. var w = matricesWeights[i + j];
  39772. weight += w;
  39773. if (w < epsilon && firstZeroWeight < 0) {
  39774. firstZeroWeight = j;
  39775. }
  39776. }
  39777. if (matricesWeightsExtra) {
  39778. for (var j = 0; j < 4; j++) {
  39779. var w = matricesWeightsExtra[i + j];
  39780. weight += w;
  39781. if (w < epsilon && firstZeroWeight < 0) {
  39782. firstZeroWeight = j + 4;
  39783. }
  39784. }
  39785. }
  39786. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39787. firstZeroWeight = influencers - 1;
  39788. }
  39789. if (weight > epsilon) {
  39790. var mweight = 1.0 / weight;
  39791. for (var j = 0; j < 4; j++) {
  39792. matricesWeights[i + j] *= mweight;
  39793. }
  39794. if (matricesWeightsExtra) {
  39795. for (var j = 0; j < 4; j++) {
  39796. matricesWeightsExtra[i + j] *= mweight;
  39797. }
  39798. }
  39799. }
  39800. else {
  39801. if (firstZeroWeight >= 4) {
  39802. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39803. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39804. }
  39805. else {
  39806. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39807. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39808. }
  39809. }
  39810. }
  39811. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39812. if (parsedGeometry.matricesWeightsExtra) {
  39813. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39814. }
  39815. };
  39816. /**
  39817. * Create a new geometry from persisted data (Using .babylon file format)
  39818. * @param parsedVertexData defines the persisted data
  39819. * @param scene defines the hosting scene
  39820. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39821. * @returns the new geometry object
  39822. */
  39823. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39824. if (scene.getGeometryByID(parsedVertexData.id)) {
  39825. return null; // null since geometry could be something else than a box...
  39826. }
  39827. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39828. if (BABYLON.Tags) {
  39829. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39830. }
  39831. if (parsedVertexData.delayLoadingFile) {
  39832. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39833. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39834. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39835. geometry._delayInfo = [];
  39836. if (parsedVertexData.hasUVs) {
  39837. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39838. }
  39839. if (parsedVertexData.hasUVs2) {
  39840. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39841. }
  39842. if (parsedVertexData.hasUVs3) {
  39843. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39844. }
  39845. if (parsedVertexData.hasUVs4) {
  39846. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39847. }
  39848. if (parsedVertexData.hasUVs5) {
  39849. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39850. }
  39851. if (parsedVertexData.hasUVs6) {
  39852. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39853. }
  39854. if (parsedVertexData.hasColors) {
  39855. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39856. }
  39857. if (parsedVertexData.hasMatricesIndices) {
  39858. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39859. }
  39860. if (parsedVertexData.hasMatricesWeights) {
  39861. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39862. }
  39863. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39864. }
  39865. else {
  39866. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39867. }
  39868. scene.pushGeometry(geometry, true);
  39869. return geometry;
  39870. };
  39871. return Geometry;
  39872. }());
  39873. BABYLON.Geometry = Geometry;
  39874. // Primitives
  39875. /// Abstract class
  39876. /**
  39877. * Abstract class used to provide common services for all typed geometries
  39878. * @hidden
  39879. */
  39880. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39881. __extends(_PrimitiveGeometry, _super);
  39882. /**
  39883. * Creates a new typed geometry
  39884. * @param id defines the unique ID of the geometry
  39885. * @param scene defines the hosting scene
  39886. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39887. * @param mesh defines the hosting mesh (can be null)
  39888. */
  39889. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39890. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39891. if (mesh === void 0) { mesh = null; }
  39892. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39893. _this._canBeRegenerated = _canBeRegenerated;
  39894. _this._beingRegenerated = true;
  39895. _this.regenerate();
  39896. _this._beingRegenerated = false;
  39897. return _this;
  39898. }
  39899. /**
  39900. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39901. * @returns true if the geometry can be regenerated
  39902. */
  39903. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39904. return this._canBeRegenerated;
  39905. };
  39906. /**
  39907. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39908. */
  39909. _PrimitiveGeometry.prototype.regenerate = function () {
  39910. if (!this._canBeRegenerated) {
  39911. return;
  39912. }
  39913. this._beingRegenerated = true;
  39914. this.setAllVerticesData(this._regenerateVertexData(), false);
  39915. this._beingRegenerated = false;
  39916. };
  39917. /**
  39918. * Clone the geometry
  39919. * @param id defines the unique ID of the new geometry
  39920. * @returns the new geometry
  39921. */
  39922. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39923. return _super.prototype.copy.call(this, id);
  39924. };
  39925. // overrides
  39926. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39927. if (!this._beingRegenerated) {
  39928. return;
  39929. }
  39930. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39931. };
  39932. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39933. if (!this._beingRegenerated) {
  39934. return;
  39935. }
  39936. _super.prototype.setVerticesData.call(this, kind, data, false);
  39937. };
  39938. // to override
  39939. /** @hidden */
  39940. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39941. throw new Error("Abstract method");
  39942. };
  39943. _PrimitiveGeometry.prototype.copy = function (id) {
  39944. throw new Error("Must be overriden in sub-classes.");
  39945. };
  39946. _PrimitiveGeometry.prototype.serialize = function () {
  39947. var serializationObject = _super.prototype.serialize.call(this);
  39948. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39949. return serializationObject;
  39950. };
  39951. return _PrimitiveGeometry;
  39952. }(Geometry));
  39953. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39954. /**
  39955. * Creates a ribbon geometry
  39956. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39957. */
  39958. var RibbonGeometry = /** @class */ (function (_super) {
  39959. __extends(RibbonGeometry, _super);
  39960. /**
  39961. * Creates a ribbon geometry
  39962. * @param id defines the unique ID of the geometry
  39963. * @param scene defines the hosting scene
  39964. * @param pathArray defines the array of paths to use
  39965. * @param closeArray defines if the last path and the first path must be joined
  39966. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39967. * @param offset defines the offset between points
  39968. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39969. * @param mesh defines the hosting mesh (can be null)
  39970. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39971. */
  39972. function RibbonGeometry(id, scene,
  39973. /**
  39974. * Defines the array of paths to use
  39975. */
  39976. pathArray,
  39977. /**
  39978. * Defines if the last and first points of each path in your pathArray must be joined
  39979. */
  39980. closeArray,
  39981. /**
  39982. * Defines if the last and first points of each path in your pathArray must be joined
  39983. */
  39984. closePath,
  39985. /**
  39986. * Defines the offset between points
  39987. */
  39988. offset, canBeRegenerated, mesh,
  39989. /**
  39990. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39991. */
  39992. side) {
  39993. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39994. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39995. _this.pathArray = pathArray;
  39996. _this.closeArray = closeArray;
  39997. _this.closePath = closePath;
  39998. _this.offset = offset;
  39999. _this.side = side;
  40000. return _this;
  40001. }
  40002. /** @hidden */
  40003. RibbonGeometry.prototype._regenerateVertexData = function () {
  40004. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40005. };
  40006. RibbonGeometry.prototype.copy = function (id) {
  40007. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40008. };
  40009. return RibbonGeometry;
  40010. }(_PrimitiveGeometry));
  40011. BABYLON.RibbonGeometry = RibbonGeometry;
  40012. /**
  40013. * Creates a box geometry
  40014. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40015. */
  40016. var BoxGeometry = /** @class */ (function (_super) {
  40017. __extends(BoxGeometry, _super);
  40018. /**
  40019. * Creates a box geometry
  40020. * @param id defines the unique ID of the geometry
  40021. * @param scene defines the hosting scene
  40022. * @param size defines the zise of the box (width, height and depth are the same)
  40023. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40024. * @param mesh defines the hosting mesh (can be null)
  40025. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40026. */
  40027. function BoxGeometry(id, scene,
  40028. /**
  40029. * Defines the zise of the box (width, height and depth are the same)
  40030. */
  40031. size, canBeRegenerated, mesh,
  40032. /**
  40033. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40034. */
  40035. side) {
  40036. if (mesh === void 0) { mesh = null; }
  40037. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40038. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40039. _this.size = size;
  40040. _this.side = side;
  40041. return _this;
  40042. }
  40043. BoxGeometry.prototype._regenerateVertexData = function () {
  40044. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40045. };
  40046. BoxGeometry.prototype.copy = function (id) {
  40047. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40048. };
  40049. BoxGeometry.prototype.serialize = function () {
  40050. var serializationObject = _super.prototype.serialize.call(this);
  40051. serializationObject.size = this.size;
  40052. return serializationObject;
  40053. };
  40054. BoxGeometry.Parse = function (parsedBox, scene) {
  40055. if (scene.getGeometryByID(parsedBox.id)) {
  40056. return null; // null since geometry could be something else than a box...
  40057. }
  40058. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40059. if (BABYLON.Tags) {
  40060. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40061. }
  40062. scene.pushGeometry(box, true);
  40063. return box;
  40064. };
  40065. return BoxGeometry;
  40066. }(_PrimitiveGeometry));
  40067. BABYLON.BoxGeometry = BoxGeometry;
  40068. /**
  40069. * Creates a sphere geometry
  40070. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40071. */
  40072. var SphereGeometry = /** @class */ (function (_super) {
  40073. __extends(SphereGeometry, _super);
  40074. /**
  40075. * Create a new sphere geometry
  40076. * @param id defines the unique ID of the geometry
  40077. * @param scene defines the hosting scene
  40078. * @param segments defines the number of segments to use to create the sphere
  40079. * @param diameter defines the diameter of the sphere
  40080. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40081. * @param mesh defines the hosting mesh (can be null)
  40082. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40083. */
  40084. function SphereGeometry(id, scene,
  40085. /**
  40086. * Defines the number of segments to use to create the sphere
  40087. */
  40088. segments,
  40089. /**
  40090. * Defines the diameter of the sphere
  40091. */
  40092. diameter, canBeRegenerated, mesh,
  40093. /**
  40094. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40095. */
  40096. side) {
  40097. if (mesh === void 0) { mesh = null; }
  40098. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40099. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40100. _this.segments = segments;
  40101. _this.diameter = diameter;
  40102. _this.side = side;
  40103. return _this;
  40104. }
  40105. SphereGeometry.prototype._regenerateVertexData = function () {
  40106. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40107. };
  40108. SphereGeometry.prototype.copy = function (id) {
  40109. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40110. };
  40111. SphereGeometry.prototype.serialize = function () {
  40112. var serializationObject = _super.prototype.serialize.call(this);
  40113. serializationObject.segments = this.segments;
  40114. serializationObject.diameter = this.diameter;
  40115. return serializationObject;
  40116. };
  40117. SphereGeometry.Parse = function (parsedSphere, scene) {
  40118. if (scene.getGeometryByID(parsedSphere.id)) {
  40119. return null; // null since geometry could be something else than a sphere...
  40120. }
  40121. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40122. if (BABYLON.Tags) {
  40123. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40124. }
  40125. scene.pushGeometry(sphere, true);
  40126. return sphere;
  40127. };
  40128. return SphereGeometry;
  40129. }(_PrimitiveGeometry));
  40130. BABYLON.SphereGeometry = SphereGeometry;
  40131. /**
  40132. * Creates a disc geometry
  40133. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40134. */
  40135. var DiscGeometry = /** @class */ (function (_super) {
  40136. __extends(DiscGeometry, _super);
  40137. /**
  40138. * Creates a new disc geometry
  40139. * @param id defines the unique ID of the geometry
  40140. * @param scene defines the hosting scene
  40141. * @param radius defines the radius of the disc
  40142. * @param tessellation defines the tesselation factor to apply to the disc
  40143. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40144. * @param mesh defines the hosting mesh (can be null)
  40145. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40146. */
  40147. function DiscGeometry(id, scene,
  40148. /**
  40149. * Defines the radius of the disc
  40150. */
  40151. radius,
  40152. /**
  40153. * Defines the tesselation factor to apply to the disc
  40154. */
  40155. tessellation, canBeRegenerated, mesh,
  40156. /**
  40157. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40158. */
  40159. side) {
  40160. if (mesh === void 0) { mesh = null; }
  40161. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40162. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40163. _this.radius = radius;
  40164. _this.tessellation = tessellation;
  40165. _this.side = side;
  40166. return _this;
  40167. }
  40168. DiscGeometry.prototype._regenerateVertexData = function () {
  40169. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40170. };
  40171. DiscGeometry.prototype.copy = function (id) {
  40172. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40173. };
  40174. return DiscGeometry;
  40175. }(_PrimitiveGeometry));
  40176. BABYLON.DiscGeometry = DiscGeometry;
  40177. /**
  40178. * Creates a new cylinder geometry
  40179. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40180. */
  40181. var CylinderGeometry = /** @class */ (function (_super) {
  40182. __extends(CylinderGeometry, _super);
  40183. /**
  40184. * Creates a new cylinder geometry
  40185. * @param id defines the unique ID of the geometry
  40186. * @param scene defines the hosting scene
  40187. * @param height defines the height of the cylinder
  40188. * @param diameterTop defines the diameter of the cylinder's top cap
  40189. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40190. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40191. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40192. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40193. * @param mesh defines the hosting mesh (can be null)
  40194. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40195. */
  40196. function CylinderGeometry(id, scene,
  40197. /**
  40198. * Defines the height of the cylinder
  40199. */
  40200. height,
  40201. /**
  40202. * Defines the diameter of the cylinder's top cap
  40203. */
  40204. diameterTop,
  40205. /**
  40206. * Defines the diameter of the cylinder's bottom cap
  40207. */
  40208. diameterBottom,
  40209. /**
  40210. * Defines the tessellation factor to apply to the cylinder
  40211. */
  40212. tessellation,
  40213. /**
  40214. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40215. */
  40216. subdivisions, canBeRegenerated, mesh,
  40217. /**
  40218. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40219. */
  40220. side) {
  40221. if (subdivisions === void 0) { subdivisions = 1; }
  40222. if (mesh === void 0) { mesh = null; }
  40223. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40224. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40225. _this.height = height;
  40226. _this.diameterTop = diameterTop;
  40227. _this.diameterBottom = diameterBottom;
  40228. _this.tessellation = tessellation;
  40229. _this.subdivisions = subdivisions;
  40230. _this.side = side;
  40231. return _this;
  40232. }
  40233. CylinderGeometry.prototype._regenerateVertexData = function () {
  40234. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40235. };
  40236. CylinderGeometry.prototype.copy = function (id) {
  40237. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40238. };
  40239. CylinderGeometry.prototype.serialize = function () {
  40240. var serializationObject = _super.prototype.serialize.call(this);
  40241. serializationObject.height = this.height;
  40242. serializationObject.diameterTop = this.diameterTop;
  40243. serializationObject.diameterBottom = this.diameterBottom;
  40244. serializationObject.tessellation = this.tessellation;
  40245. return serializationObject;
  40246. };
  40247. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40248. if (scene.getGeometryByID(parsedCylinder.id)) {
  40249. return null; // null since geometry could be something else than a cylinder...
  40250. }
  40251. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40252. if (BABYLON.Tags) {
  40253. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40254. }
  40255. scene.pushGeometry(cylinder, true);
  40256. return cylinder;
  40257. };
  40258. return CylinderGeometry;
  40259. }(_PrimitiveGeometry));
  40260. BABYLON.CylinderGeometry = CylinderGeometry;
  40261. /**
  40262. * Creates a new torus geometry
  40263. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40264. */
  40265. var TorusGeometry = /** @class */ (function (_super) {
  40266. __extends(TorusGeometry, _super);
  40267. /**
  40268. * Creates a new torus geometry
  40269. * @param id defines the unique ID of the geometry
  40270. * @param scene defines the hosting scene
  40271. * @param diameter defines the diameter of the torus
  40272. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40273. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40274. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40275. * @param mesh defines the hosting mesh (can be null)
  40276. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40277. */
  40278. function TorusGeometry(id, scene,
  40279. /**
  40280. * Defines the diameter of the torus
  40281. */
  40282. diameter,
  40283. /**
  40284. * Defines the thickness of the torus (ie. internal diameter)
  40285. */
  40286. thickness,
  40287. /**
  40288. * Defines the tesselation factor to apply to the torus
  40289. */
  40290. tessellation, canBeRegenerated, mesh,
  40291. /**
  40292. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40293. */
  40294. side) {
  40295. if (mesh === void 0) { mesh = null; }
  40296. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40297. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40298. _this.diameter = diameter;
  40299. _this.thickness = thickness;
  40300. _this.tessellation = tessellation;
  40301. _this.side = side;
  40302. return _this;
  40303. }
  40304. TorusGeometry.prototype._regenerateVertexData = function () {
  40305. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40306. };
  40307. TorusGeometry.prototype.copy = function (id) {
  40308. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40309. };
  40310. TorusGeometry.prototype.serialize = function () {
  40311. var serializationObject = _super.prototype.serialize.call(this);
  40312. serializationObject.diameter = this.diameter;
  40313. serializationObject.thickness = this.thickness;
  40314. serializationObject.tessellation = this.tessellation;
  40315. return serializationObject;
  40316. };
  40317. TorusGeometry.Parse = function (parsedTorus, scene) {
  40318. if (scene.getGeometryByID(parsedTorus.id)) {
  40319. return null; // null since geometry could be something else than a torus...
  40320. }
  40321. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40322. if (BABYLON.Tags) {
  40323. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40324. }
  40325. scene.pushGeometry(torus, true);
  40326. return torus;
  40327. };
  40328. return TorusGeometry;
  40329. }(_PrimitiveGeometry));
  40330. BABYLON.TorusGeometry = TorusGeometry;
  40331. /**
  40332. * Creates a new ground geometry
  40333. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40334. */
  40335. var GroundGeometry = /** @class */ (function (_super) {
  40336. __extends(GroundGeometry, _super);
  40337. /**
  40338. * Creates a new ground geometry
  40339. * @param id defines the unique ID of the geometry
  40340. * @param scene defines the hosting scene
  40341. * @param width defines the width of the ground
  40342. * @param height defines the height of the ground
  40343. * @param subdivisions defines the subdivisions to apply to the ground
  40344. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40345. * @param mesh defines the hosting mesh (can be null)
  40346. */
  40347. function GroundGeometry(id, scene,
  40348. /**
  40349. * Defines the width of the ground
  40350. */
  40351. width,
  40352. /**
  40353. * Defines the height of the ground
  40354. */
  40355. height,
  40356. /**
  40357. * Defines the subdivisions to apply to the ground
  40358. */
  40359. subdivisions, canBeRegenerated, mesh) {
  40360. if (mesh === void 0) { mesh = null; }
  40361. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40362. _this.width = width;
  40363. _this.height = height;
  40364. _this.subdivisions = subdivisions;
  40365. return _this;
  40366. }
  40367. GroundGeometry.prototype._regenerateVertexData = function () {
  40368. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40369. };
  40370. GroundGeometry.prototype.copy = function (id) {
  40371. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40372. };
  40373. GroundGeometry.prototype.serialize = function () {
  40374. var serializationObject = _super.prototype.serialize.call(this);
  40375. serializationObject.width = this.width;
  40376. serializationObject.height = this.height;
  40377. serializationObject.subdivisions = this.subdivisions;
  40378. return serializationObject;
  40379. };
  40380. GroundGeometry.Parse = function (parsedGround, scene) {
  40381. if (scene.getGeometryByID(parsedGround.id)) {
  40382. return null; // null since geometry could be something else than a ground...
  40383. }
  40384. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40385. if (BABYLON.Tags) {
  40386. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40387. }
  40388. scene.pushGeometry(ground, true);
  40389. return ground;
  40390. };
  40391. return GroundGeometry;
  40392. }(_PrimitiveGeometry));
  40393. BABYLON.GroundGeometry = GroundGeometry;
  40394. /**
  40395. * Creates a tiled ground geometry
  40396. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40397. */
  40398. var TiledGroundGeometry = /** @class */ (function (_super) {
  40399. __extends(TiledGroundGeometry, _super);
  40400. /**
  40401. * Creates a tiled ground geometry
  40402. * @param id defines the unique ID of the geometry
  40403. * @param scene defines the hosting scene
  40404. * @param xmin defines the minimum value on X axis
  40405. * @param zmin defines the minimum value on Z axis
  40406. * @param xmax defines the maximum value on X axis
  40407. * @param zmax defines the maximum value on Z axis
  40408. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40409. * @param precision defines the precision to use when computing the tiles
  40410. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40411. * @param mesh defines the hosting mesh (can be null)
  40412. */
  40413. function TiledGroundGeometry(id, scene,
  40414. /**
  40415. * Defines the minimum value on X axis
  40416. */
  40417. xmin,
  40418. /**
  40419. * Defines the minimum value on Z axis
  40420. */
  40421. zmin,
  40422. /**
  40423. * Defines the maximum value on X axis
  40424. */
  40425. xmax,
  40426. /**
  40427. * Defines the maximum value on Z axis
  40428. */
  40429. zmax,
  40430. /**
  40431. * Defines the subdivisions to apply to the ground
  40432. */
  40433. subdivisions,
  40434. /**
  40435. * Defines the precision to use when computing the tiles
  40436. */
  40437. precision, canBeRegenerated, mesh) {
  40438. if (mesh === void 0) { mesh = null; }
  40439. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40440. _this.xmin = xmin;
  40441. _this.zmin = zmin;
  40442. _this.xmax = xmax;
  40443. _this.zmax = zmax;
  40444. _this.subdivisions = subdivisions;
  40445. _this.precision = precision;
  40446. return _this;
  40447. }
  40448. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40449. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40450. };
  40451. TiledGroundGeometry.prototype.copy = function (id) {
  40452. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40453. };
  40454. return TiledGroundGeometry;
  40455. }(_PrimitiveGeometry));
  40456. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40457. /**
  40458. * Creates a plane geometry
  40459. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40460. */
  40461. var PlaneGeometry = /** @class */ (function (_super) {
  40462. __extends(PlaneGeometry, _super);
  40463. /**
  40464. * Creates a plane geometry
  40465. * @param id defines the unique ID of the geometry
  40466. * @param scene defines the hosting scene
  40467. * @param size defines the size of the plane (width === height)
  40468. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40469. * @param mesh defines the hosting mesh (can be null)
  40470. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40471. */
  40472. function PlaneGeometry(id, scene,
  40473. /**
  40474. * Defines the size of the plane (width === height)
  40475. */
  40476. size, canBeRegenerated, mesh,
  40477. /**
  40478. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40479. */
  40480. side) {
  40481. if (mesh === void 0) { mesh = null; }
  40482. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40483. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40484. _this.size = size;
  40485. _this.side = side;
  40486. return _this;
  40487. }
  40488. PlaneGeometry.prototype._regenerateVertexData = function () {
  40489. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40490. };
  40491. PlaneGeometry.prototype.copy = function (id) {
  40492. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40493. };
  40494. PlaneGeometry.prototype.serialize = function () {
  40495. var serializationObject = _super.prototype.serialize.call(this);
  40496. serializationObject.size = this.size;
  40497. return serializationObject;
  40498. };
  40499. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40500. if (scene.getGeometryByID(parsedPlane.id)) {
  40501. return null; // null since geometry could be something else than a ground...
  40502. }
  40503. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40504. if (BABYLON.Tags) {
  40505. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40506. }
  40507. scene.pushGeometry(plane, true);
  40508. return plane;
  40509. };
  40510. return PlaneGeometry;
  40511. }(_PrimitiveGeometry));
  40512. BABYLON.PlaneGeometry = PlaneGeometry;
  40513. /**
  40514. * Creates a torus knot geometry
  40515. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40516. */
  40517. var TorusKnotGeometry = /** @class */ (function (_super) {
  40518. __extends(TorusKnotGeometry, _super);
  40519. /**
  40520. * Creates a torus knot geometry
  40521. * @param id defines the unique ID of the geometry
  40522. * @param scene defines the hosting scene
  40523. * @param radius defines the radius of the torus knot
  40524. * @param tube defines the thickness of the torus knot tube
  40525. * @param radialSegments defines the number of radial segments
  40526. * @param tubularSegments defines the number of tubular segments
  40527. * @param p defines the first number of windings
  40528. * @param q defines the second number of windings
  40529. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40530. * @param mesh defines the hosting mesh (can be null)
  40531. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40532. */
  40533. function TorusKnotGeometry(id, scene,
  40534. /**
  40535. * Defines the radius of the torus knot
  40536. */
  40537. radius,
  40538. /**
  40539. * Defines the thickness of the torus knot tube
  40540. */
  40541. tube,
  40542. /**
  40543. * Defines the number of radial segments
  40544. */
  40545. radialSegments,
  40546. /**
  40547. * Defines the number of tubular segments
  40548. */
  40549. tubularSegments,
  40550. /**
  40551. * Defines the first number of windings
  40552. */
  40553. p,
  40554. /**
  40555. * Defines the second number of windings
  40556. */
  40557. q, canBeRegenerated, mesh,
  40558. /**
  40559. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40560. */
  40561. side) {
  40562. if (mesh === void 0) { mesh = null; }
  40563. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40564. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40565. _this.radius = radius;
  40566. _this.tube = tube;
  40567. _this.radialSegments = radialSegments;
  40568. _this.tubularSegments = tubularSegments;
  40569. _this.p = p;
  40570. _this.q = q;
  40571. _this.side = side;
  40572. return _this;
  40573. }
  40574. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40575. 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 });
  40576. };
  40577. TorusKnotGeometry.prototype.copy = function (id) {
  40578. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40579. };
  40580. TorusKnotGeometry.prototype.serialize = function () {
  40581. var serializationObject = _super.prototype.serialize.call(this);
  40582. serializationObject.radius = this.radius;
  40583. serializationObject.tube = this.tube;
  40584. serializationObject.radialSegments = this.radialSegments;
  40585. serializationObject.tubularSegments = this.tubularSegments;
  40586. serializationObject.p = this.p;
  40587. serializationObject.q = this.q;
  40588. return serializationObject;
  40589. };
  40590. ;
  40591. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40592. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40593. return null; // null since geometry could be something else than a ground...
  40594. }
  40595. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40596. if (BABYLON.Tags) {
  40597. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40598. }
  40599. scene.pushGeometry(torusKnot, true);
  40600. return torusKnot;
  40601. };
  40602. return TorusKnotGeometry;
  40603. }(_PrimitiveGeometry));
  40604. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40605. //}
  40606. })(BABYLON || (BABYLON = {}));
  40607. //# sourceMappingURL=babylon.geometry.js.map
  40608. var BABYLON;
  40609. (function (BABYLON) {
  40610. /**
  40611. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40612. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40613. */
  40614. var PostProcessManager = /** @class */ (function () {
  40615. /**
  40616. * Creates a new instance PostProcess
  40617. * @param scene The scene that the post process is associated with.
  40618. */
  40619. function PostProcessManager(scene) {
  40620. this._vertexBuffers = {};
  40621. this._scene = scene;
  40622. }
  40623. PostProcessManager.prototype._prepareBuffers = function () {
  40624. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40625. return;
  40626. }
  40627. // VBO
  40628. var vertices = [];
  40629. vertices.push(1, 1);
  40630. vertices.push(-1, 1);
  40631. vertices.push(-1, -1);
  40632. vertices.push(1, -1);
  40633. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40634. this._buildIndexBuffer();
  40635. };
  40636. PostProcessManager.prototype._buildIndexBuffer = function () {
  40637. // Indices
  40638. var indices = [];
  40639. indices.push(0);
  40640. indices.push(1);
  40641. indices.push(2);
  40642. indices.push(0);
  40643. indices.push(2);
  40644. indices.push(3);
  40645. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40646. };
  40647. /**
  40648. * Rebuilds the vertex buffers of the manager.
  40649. */
  40650. PostProcessManager.prototype._rebuild = function () {
  40651. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40652. if (!vb) {
  40653. return;
  40654. }
  40655. vb._rebuild();
  40656. this._buildIndexBuffer();
  40657. };
  40658. // Methods
  40659. /**
  40660. * Prepares a frame to be run through a post process.
  40661. * @param sourceTexture The input texture to the post procesess. (default: null)
  40662. * @param postProcesses An array of post processes to be run. (default: null)
  40663. * @returns True if the post processes were able to be run.
  40664. */
  40665. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40666. if (sourceTexture === void 0) { sourceTexture = null; }
  40667. if (postProcesses === void 0) { postProcesses = null; }
  40668. var camera = this._scene.activeCamera;
  40669. if (!camera) {
  40670. return false;
  40671. }
  40672. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40673. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40674. return false;
  40675. }
  40676. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40677. return true;
  40678. };
  40679. /**
  40680. * Manually render a set of post processes to a texture.
  40681. * @param postProcesses An array of post processes to be run.
  40682. * @param targetTexture The target texture to render to.
  40683. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40684. */
  40685. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40686. if (targetTexture === void 0) { targetTexture = null; }
  40687. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40688. var engine = this._scene.getEngine();
  40689. for (var index = 0; index < postProcesses.length; index++) {
  40690. if (index < postProcesses.length - 1) {
  40691. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40692. }
  40693. else {
  40694. if (targetTexture) {
  40695. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40696. }
  40697. else {
  40698. engine.restoreDefaultFramebuffer();
  40699. }
  40700. }
  40701. var pp = postProcesses[index];
  40702. var effect = pp.apply();
  40703. if (effect) {
  40704. pp.onBeforeRenderObservable.notifyObservers(effect);
  40705. // VBOs
  40706. this._prepareBuffers();
  40707. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40708. // Draw order
  40709. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40710. pp.onAfterRenderObservable.notifyObservers(effect);
  40711. }
  40712. }
  40713. // Restore depth buffer
  40714. engine.setDepthBuffer(true);
  40715. engine.setDepthWrite(true);
  40716. };
  40717. /**
  40718. * Finalize the result of the output of the postprocesses.
  40719. * @param doNotPresent If true the result will not be displayed to the screen.
  40720. * @param targetTexture The target texture to render to.
  40721. * @param faceIndex The index of the face to bind the target texture to.
  40722. * @param postProcesses The array of post processes to render.
  40723. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40724. */
  40725. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40726. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40727. var camera = this._scene.activeCamera;
  40728. if (!camera) {
  40729. return;
  40730. }
  40731. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40732. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40733. return;
  40734. }
  40735. var engine = this._scene.getEngine();
  40736. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40737. var pp = postProcesses[index];
  40738. if (index < len - 1) {
  40739. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40740. }
  40741. else {
  40742. if (targetTexture) {
  40743. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40744. pp._outputTexture = targetTexture;
  40745. }
  40746. else {
  40747. engine.restoreDefaultFramebuffer();
  40748. pp._outputTexture = null;
  40749. }
  40750. }
  40751. if (doNotPresent) {
  40752. break;
  40753. }
  40754. var effect = pp.apply();
  40755. if (effect) {
  40756. pp.onBeforeRenderObservable.notifyObservers(effect);
  40757. // VBOs
  40758. this._prepareBuffers();
  40759. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40760. // Draw order
  40761. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40762. pp.onAfterRenderObservable.notifyObservers(effect);
  40763. }
  40764. }
  40765. // Restore states
  40766. engine.setDepthBuffer(true);
  40767. engine.setDepthWrite(true);
  40768. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40769. };
  40770. /**
  40771. * Disposes of the post process manager.
  40772. */
  40773. PostProcessManager.prototype.dispose = function () {
  40774. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40775. if (buffer) {
  40776. buffer.dispose();
  40777. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40778. }
  40779. if (this._indexBuffer) {
  40780. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40781. this._indexBuffer = null;
  40782. }
  40783. };
  40784. return PostProcessManager;
  40785. }());
  40786. BABYLON.PostProcessManager = PostProcessManager;
  40787. })(BABYLON || (BABYLON = {}));
  40788. //# sourceMappingURL=babylon.postProcessManager.js.map
  40789. var BABYLON;
  40790. (function (BABYLON) {
  40791. /**
  40792. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40793. */
  40794. var PerformanceMonitor = /** @class */ (function () {
  40795. /**
  40796. * constructor
  40797. * @param frameSampleSize The number of samples required to saturate the sliding window
  40798. */
  40799. function PerformanceMonitor(frameSampleSize) {
  40800. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40801. this._enabled = true;
  40802. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40803. }
  40804. /**
  40805. * Samples current frame
  40806. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40807. */
  40808. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40809. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40810. if (!this._enabled)
  40811. return;
  40812. if (this._lastFrameTimeMs != null) {
  40813. var dt = timeMs - this._lastFrameTimeMs;
  40814. this._rollingFrameTime.add(dt);
  40815. }
  40816. this._lastFrameTimeMs = timeMs;
  40817. };
  40818. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40819. /**
  40820. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40821. * @return Average frame time in milliseconds
  40822. */
  40823. get: function () {
  40824. return this._rollingFrameTime.average;
  40825. },
  40826. enumerable: true,
  40827. configurable: true
  40828. });
  40829. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40830. /**
  40831. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40832. * @return Frame time variance in milliseconds squared
  40833. */
  40834. get: function () {
  40835. return this._rollingFrameTime.variance;
  40836. },
  40837. enumerable: true,
  40838. configurable: true
  40839. });
  40840. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40841. /**
  40842. * Returns the frame time of the most recent frame
  40843. * @return Frame time in milliseconds
  40844. */
  40845. get: function () {
  40846. return this._rollingFrameTime.history(0);
  40847. },
  40848. enumerable: true,
  40849. configurable: true
  40850. });
  40851. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40852. /**
  40853. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40854. * @return Framerate in frames per second
  40855. */
  40856. get: function () {
  40857. return 1000.0 / this._rollingFrameTime.average;
  40858. },
  40859. enumerable: true,
  40860. configurable: true
  40861. });
  40862. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40863. /**
  40864. * Returns the average framerate in frames per second using the most recent frame time
  40865. * @return Framerate in frames per second
  40866. */
  40867. get: function () {
  40868. var history = this._rollingFrameTime.history(0);
  40869. if (history === 0) {
  40870. return 0;
  40871. }
  40872. return 1000.0 / history;
  40873. },
  40874. enumerable: true,
  40875. configurable: true
  40876. });
  40877. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40878. /**
  40879. * Returns true if enough samples have been taken to completely fill the sliding window
  40880. * @return true if saturated
  40881. */
  40882. get: function () {
  40883. return this._rollingFrameTime.isSaturated();
  40884. },
  40885. enumerable: true,
  40886. configurable: true
  40887. });
  40888. /**
  40889. * Enables contributions to the sliding window sample set
  40890. */
  40891. PerformanceMonitor.prototype.enable = function () {
  40892. this._enabled = true;
  40893. };
  40894. /**
  40895. * Disables contributions to the sliding window sample set
  40896. * Samples will not be interpolated over the disabled period
  40897. */
  40898. PerformanceMonitor.prototype.disable = function () {
  40899. this._enabled = false;
  40900. //clear last sample to avoid interpolating over the disabled period when next enabled
  40901. this._lastFrameTimeMs = null;
  40902. };
  40903. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40904. /**
  40905. * Returns true if sampling is enabled
  40906. * @return true if enabled
  40907. */
  40908. get: function () {
  40909. return this._enabled;
  40910. },
  40911. enumerable: true,
  40912. configurable: true
  40913. });
  40914. /**
  40915. * Resets performance monitor
  40916. */
  40917. PerformanceMonitor.prototype.reset = function () {
  40918. //clear last sample to avoid interpolating over the disabled period when next enabled
  40919. this._lastFrameTimeMs = null;
  40920. //wipe record
  40921. this._rollingFrameTime.reset();
  40922. };
  40923. return PerformanceMonitor;
  40924. }());
  40925. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40926. /**
  40927. * RollingAverage
  40928. *
  40929. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40930. */
  40931. var RollingAverage = /** @class */ (function () {
  40932. /**
  40933. * constructor
  40934. * @param length The number of samples required to saturate the sliding window
  40935. */
  40936. function RollingAverage(length) {
  40937. this._samples = new Array(length);
  40938. this.reset();
  40939. }
  40940. /**
  40941. * Adds a sample to the sample set
  40942. * @param v The sample value
  40943. */
  40944. RollingAverage.prototype.add = function (v) {
  40945. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40946. var delta;
  40947. //we need to check if we've already wrapped round
  40948. if (this.isSaturated()) {
  40949. //remove bottom of stack from mean
  40950. var bottomValue = this._samples[this._pos];
  40951. delta = bottomValue - this.average;
  40952. this.average -= delta / (this._sampleCount - 1);
  40953. this._m2 -= delta * (bottomValue - this.average);
  40954. }
  40955. else {
  40956. this._sampleCount++;
  40957. }
  40958. //add new value to mean
  40959. delta = v - this.average;
  40960. this.average += delta / (this._sampleCount);
  40961. this._m2 += delta * (v - this.average);
  40962. //set the new variance
  40963. this.variance = this._m2 / (this._sampleCount - 1);
  40964. this._samples[this._pos] = v;
  40965. this._pos++;
  40966. this._pos %= this._samples.length; //positive wrap around
  40967. };
  40968. /**
  40969. * Returns previously added values or null if outside of history or outside the sliding window domain
  40970. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40971. * @return Value previously recorded with add() or null if outside of range
  40972. */
  40973. RollingAverage.prototype.history = function (i) {
  40974. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40975. return 0;
  40976. }
  40977. var i0 = this._wrapPosition(this._pos - 1.0);
  40978. return this._samples[this._wrapPosition(i0 - i)];
  40979. };
  40980. /**
  40981. * Returns true if enough samples have been taken to completely fill the sliding window
  40982. * @return true if sample-set saturated
  40983. */
  40984. RollingAverage.prototype.isSaturated = function () {
  40985. return this._sampleCount >= this._samples.length;
  40986. };
  40987. /**
  40988. * Resets the rolling average (equivalent to 0 samples taken so far)
  40989. */
  40990. RollingAverage.prototype.reset = function () {
  40991. this.average = 0;
  40992. this.variance = 0;
  40993. this._sampleCount = 0;
  40994. this._pos = 0;
  40995. this._m2 = 0;
  40996. };
  40997. /**
  40998. * Wraps a value around the sample range boundaries
  40999. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41000. * @return Wrapped position in sample range
  41001. */
  41002. RollingAverage.prototype._wrapPosition = function (i) {
  41003. var max = this._samples.length;
  41004. return ((i % max) + max) % max;
  41005. };
  41006. return RollingAverage;
  41007. }());
  41008. BABYLON.RollingAverage = RollingAverage;
  41009. })(BABYLON || (BABYLON = {}));
  41010. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41011. var BABYLON;
  41012. (function (BABYLON) {
  41013. /**
  41014. * This groups together the common properties used for image processing either in direct forward pass
  41015. * or through post processing effect depending on the use of the image processing pipeline in your scene
  41016. * or not.
  41017. */
  41018. var ImageProcessingConfiguration = /** @class */ (function () {
  41019. function ImageProcessingConfiguration() {
  41020. /**
  41021. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  41022. */
  41023. this.colorCurves = new BABYLON.ColorCurves();
  41024. this._colorCurvesEnabled = false;
  41025. this._colorGradingEnabled = false;
  41026. this._colorGradingWithGreenDepth = true;
  41027. this._colorGradingBGR = true;
  41028. this._exposure = 1.0;
  41029. this._toneMappingEnabled = false;
  41030. this._contrast = 1.0;
  41031. /**
  41032. * Vignette stretch size.
  41033. */
  41034. this.vignetteStretch = 0;
  41035. /**
  41036. * Vignette centre X Offset.
  41037. */
  41038. this.vignetteCentreX = 0;
  41039. /**
  41040. * Vignette centre Y Offset.
  41041. */
  41042. this.vignetteCentreY = 0;
  41043. /**
  41044. * Vignette weight or intensity of the vignette effect.
  41045. */
  41046. this.vignetteWeight = 1.5;
  41047. /**
  41048. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41049. * if vignetteEnabled is set to true.
  41050. */
  41051. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  41052. /**
  41053. * Camera field of view used by the Vignette effect.
  41054. */
  41055. this.vignetteCameraFov = 0.5;
  41056. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  41057. this._vignetteEnabled = false;
  41058. this._applyByPostProcess = false;
  41059. this._isEnabled = true;
  41060. /**
  41061. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  41062. */
  41063. this.onUpdateParameters = new BABYLON.Observable();
  41064. }
  41065. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  41066. /**
  41067. * Gets wether the color curves effect is enabled.
  41068. */
  41069. get: function () {
  41070. return this._colorCurvesEnabled;
  41071. },
  41072. /**
  41073. * Sets wether the color curves effect is enabled.
  41074. */
  41075. set: function (value) {
  41076. if (this._colorCurvesEnabled === value) {
  41077. return;
  41078. }
  41079. this._colorCurvesEnabled = value;
  41080. this._updateParameters();
  41081. },
  41082. enumerable: true,
  41083. configurable: true
  41084. });
  41085. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  41086. /**
  41087. * Gets wether the color grading effect is enabled.
  41088. */
  41089. get: function () {
  41090. return this._colorGradingEnabled;
  41091. },
  41092. /**
  41093. * Sets wether the color grading effect is enabled.
  41094. */
  41095. set: function (value) {
  41096. if (this._colorGradingEnabled === value) {
  41097. return;
  41098. }
  41099. this._colorGradingEnabled = value;
  41100. this._updateParameters();
  41101. },
  41102. enumerable: true,
  41103. configurable: true
  41104. });
  41105. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  41106. /**
  41107. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  41108. */
  41109. get: function () {
  41110. return this._colorGradingWithGreenDepth;
  41111. },
  41112. /**
  41113. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  41114. */
  41115. set: function (value) {
  41116. if (this._colorGradingWithGreenDepth === value) {
  41117. return;
  41118. }
  41119. this._colorGradingWithGreenDepth = value;
  41120. this._updateParameters();
  41121. },
  41122. enumerable: true,
  41123. configurable: true
  41124. });
  41125. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  41126. /**
  41127. * Gets wether the color grading texture contains BGR values.
  41128. */
  41129. get: function () {
  41130. return this._colorGradingBGR;
  41131. },
  41132. /**
  41133. * Sets wether the color grading texture contains BGR values.
  41134. */
  41135. set: function (value) {
  41136. if (this._colorGradingBGR === value) {
  41137. return;
  41138. }
  41139. this._colorGradingBGR = value;
  41140. this._updateParameters();
  41141. },
  41142. enumerable: true,
  41143. configurable: true
  41144. });
  41145. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  41146. /**
  41147. * Gets the Exposure used in the effect.
  41148. */
  41149. get: function () {
  41150. return this._exposure;
  41151. },
  41152. /**
  41153. * Sets the Exposure used in the effect.
  41154. */
  41155. set: function (value) {
  41156. if (this._exposure === value) {
  41157. return;
  41158. }
  41159. this._exposure = value;
  41160. this._updateParameters();
  41161. },
  41162. enumerable: true,
  41163. configurable: true
  41164. });
  41165. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  41166. /**
  41167. * Gets wether the tone mapping effect is enabled.
  41168. */
  41169. get: function () {
  41170. return this._toneMappingEnabled;
  41171. },
  41172. /**
  41173. * Sets wether the tone mapping effect is enabled.
  41174. */
  41175. set: function (value) {
  41176. if (this._toneMappingEnabled === value) {
  41177. return;
  41178. }
  41179. this._toneMappingEnabled = value;
  41180. this._updateParameters();
  41181. },
  41182. enumerable: true,
  41183. configurable: true
  41184. });
  41185. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41186. /**
  41187. * Gets the contrast used in the effect.
  41188. */
  41189. get: function () {
  41190. return this._contrast;
  41191. },
  41192. /**
  41193. * Sets the contrast used in the effect.
  41194. */
  41195. set: function (value) {
  41196. if (this._contrast === value) {
  41197. return;
  41198. }
  41199. this._contrast = value;
  41200. this._updateParameters();
  41201. },
  41202. enumerable: true,
  41203. configurable: true
  41204. });
  41205. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41206. /**
  41207. * Gets the vignette blend mode allowing different kind of effect.
  41208. */
  41209. get: function () {
  41210. return this._vignetteBlendMode;
  41211. },
  41212. /**
  41213. * Sets the vignette blend mode allowing different kind of effect.
  41214. */
  41215. set: function (value) {
  41216. if (this._vignetteBlendMode === value) {
  41217. return;
  41218. }
  41219. this._vignetteBlendMode = value;
  41220. this._updateParameters();
  41221. },
  41222. enumerable: true,
  41223. configurable: true
  41224. });
  41225. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41226. /**
  41227. * Gets wether the vignette effect is enabled.
  41228. */
  41229. get: function () {
  41230. return this._vignetteEnabled;
  41231. },
  41232. /**
  41233. * Sets wether the vignette effect is enabled.
  41234. */
  41235. set: function (value) {
  41236. if (this._vignetteEnabled === value) {
  41237. return;
  41238. }
  41239. this._vignetteEnabled = value;
  41240. this._updateParameters();
  41241. },
  41242. enumerable: true,
  41243. configurable: true
  41244. });
  41245. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41246. /**
  41247. * Gets wether the image processing is applied through a post process or not.
  41248. */
  41249. get: function () {
  41250. return this._applyByPostProcess;
  41251. },
  41252. /**
  41253. * Sets wether the image processing is applied through a post process or not.
  41254. */
  41255. set: function (value) {
  41256. if (this._applyByPostProcess === value) {
  41257. return;
  41258. }
  41259. this._applyByPostProcess = value;
  41260. this._updateParameters();
  41261. },
  41262. enumerable: true,
  41263. configurable: true
  41264. });
  41265. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41266. /**
  41267. * Gets wether the image processing is enabled or not.
  41268. */
  41269. get: function () {
  41270. return this._isEnabled;
  41271. },
  41272. /**
  41273. * Sets wether the image processing is enabled or not.
  41274. */
  41275. set: function (value) {
  41276. if (this._isEnabled === value) {
  41277. return;
  41278. }
  41279. this._isEnabled = value;
  41280. this._updateParameters();
  41281. },
  41282. enumerable: true,
  41283. configurable: true
  41284. });
  41285. /**
  41286. * Method called each time the image processing information changes requires to recompile the effect.
  41287. */
  41288. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41289. this.onUpdateParameters.notifyObservers(this);
  41290. };
  41291. ImageProcessingConfiguration.prototype.getClassName = function () {
  41292. return "ImageProcessingConfiguration";
  41293. };
  41294. /**
  41295. * Prepare the list of uniforms associated with the Image Processing effects.
  41296. * @param uniformsList The list of uniforms used in the effect
  41297. * @param defines the list of defines currently in use
  41298. */
  41299. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41300. if (defines.EXPOSURE) {
  41301. uniforms.push("exposureLinear");
  41302. }
  41303. if (defines.CONTRAST) {
  41304. uniforms.push("contrast");
  41305. }
  41306. if (defines.COLORGRADING) {
  41307. uniforms.push("colorTransformSettings");
  41308. }
  41309. if (defines.VIGNETTE) {
  41310. uniforms.push("vInverseScreenSize");
  41311. uniforms.push("vignetteSettings1");
  41312. uniforms.push("vignetteSettings2");
  41313. }
  41314. if (defines.COLORCURVES) {
  41315. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41316. }
  41317. };
  41318. /**
  41319. * Prepare the list of samplers associated with the Image Processing effects.
  41320. * @param uniformsList The list of uniforms used in the effect
  41321. * @param defines the list of defines currently in use
  41322. */
  41323. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41324. if (defines.COLORGRADING) {
  41325. samplersList.push("txColorTransform");
  41326. }
  41327. };
  41328. /**
  41329. * Prepare the list of defines associated to the shader.
  41330. * @param defines the list of defines to complete
  41331. */
  41332. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41333. if (forPostProcess === void 0) { forPostProcess = false; }
  41334. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41335. defines.VIGNETTE = false;
  41336. defines.TONEMAPPING = false;
  41337. defines.CONTRAST = false;
  41338. defines.EXPOSURE = false;
  41339. defines.COLORCURVES = false;
  41340. defines.COLORGRADING = false;
  41341. defines.COLORGRADING3D = false;
  41342. defines.IMAGEPROCESSING = false;
  41343. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41344. return;
  41345. }
  41346. defines.VIGNETTE = this.vignetteEnabled;
  41347. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41348. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41349. defines.TONEMAPPING = this.toneMappingEnabled;
  41350. defines.CONTRAST = (this.contrast !== 1.0);
  41351. defines.EXPOSURE = (this.exposure !== 1.0);
  41352. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41353. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41354. if (defines.COLORGRADING) {
  41355. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41356. }
  41357. else {
  41358. defines.COLORGRADING3D = false;
  41359. }
  41360. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41361. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41362. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41363. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41364. };
  41365. /**
  41366. * Returns true if all the image processing information are ready.
  41367. */
  41368. ImageProcessingConfiguration.prototype.isReady = function () {
  41369. // Color Grading texure can not be none blocking.
  41370. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41371. };
  41372. /**
  41373. * Binds the image processing to the shader.
  41374. * @param effect The effect to bind to
  41375. */
  41376. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41377. if (aspectRatio === void 0) { aspectRatio = 1; }
  41378. // Color Curves
  41379. if (this._colorCurvesEnabled && this.colorCurves) {
  41380. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41381. }
  41382. // Vignette
  41383. if (this._vignetteEnabled) {
  41384. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41385. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41386. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41387. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41388. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41389. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41390. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41391. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41392. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41393. var vignettePower = -2.0 * this.vignetteWeight;
  41394. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41395. }
  41396. // Exposure
  41397. effect.setFloat("exposureLinear", this.exposure);
  41398. // Contrast
  41399. effect.setFloat("contrast", this.contrast);
  41400. // Color transform settings
  41401. if (this.colorGradingTexture) {
  41402. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41403. var textureSize = this.colorGradingTexture.getSize().height;
  41404. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41405. 0.5 / textureSize, // textureOffset
  41406. textureSize, // textureSize
  41407. this.colorGradingTexture.level // weight
  41408. );
  41409. }
  41410. };
  41411. /**
  41412. * Clones the current image processing instance.
  41413. * @return The cloned image processing
  41414. */
  41415. ImageProcessingConfiguration.prototype.clone = function () {
  41416. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41417. };
  41418. /**
  41419. * Serializes the current image processing instance to a json representation.
  41420. * @return a JSON representation
  41421. */
  41422. ImageProcessingConfiguration.prototype.serialize = function () {
  41423. return BABYLON.SerializationHelper.Serialize(this);
  41424. };
  41425. /**
  41426. * Parses the image processing from a json representation.
  41427. * @param source the JSON source to parse
  41428. * @return The parsed image processing
  41429. */
  41430. ImageProcessingConfiguration.Parse = function (source) {
  41431. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41432. };
  41433. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41434. /**
  41435. * Used to apply the vignette as a mix with the pixel color.
  41436. */
  41437. get: function () {
  41438. return this._VIGNETTEMODE_MULTIPLY;
  41439. },
  41440. enumerable: true,
  41441. configurable: true
  41442. });
  41443. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41444. /**
  41445. * Used to apply the vignette as a replacement of the pixel color.
  41446. */
  41447. get: function () {
  41448. return this._VIGNETTEMODE_OPAQUE;
  41449. },
  41450. enumerable: true,
  41451. configurable: true
  41452. });
  41453. // Static constants associated to the image processing.
  41454. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41455. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41456. __decorate([
  41457. BABYLON.serializeAsColorCurves()
  41458. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41459. __decorate([
  41460. BABYLON.serialize()
  41461. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41462. __decorate([
  41463. BABYLON.serializeAsTexture()
  41464. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41465. __decorate([
  41466. BABYLON.serialize()
  41467. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41468. __decorate([
  41469. BABYLON.serialize()
  41470. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41471. __decorate([
  41472. BABYLON.serialize()
  41473. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41474. __decorate([
  41475. BABYLON.serialize()
  41476. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41477. __decorate([
  41478. BABYLON.serialize()
  41479. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41480. __decorate([
  41481. BABYLON.serialize()
  41482. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41483. __decorate([
  41484. BABYLON.serialize()
  41485. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41486. __decorate([
  41487. BABYLON.serialize()
  41488. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41489. __decorate([
  41490. BABYLON.serialize()
  41491. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41492. __decorate([
  41493. BABYLON.serialize()
  41494. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41495. __decorate([
  41496. BABYLON.serializeAsColor4()
  41497. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41498. __decorate([
  41499. BABYLON.serialize()
  41500. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41501. __decorate([
  41502. BABYLON.serialize()
  41503. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41504. __decorate([
  41505. BABYLON.serialize()
  41506. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41507. __decorate([
  41508. BABYLON.serialize()
  41509. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41510. __decorate([
  41511. BABYLON.serialize()
  41512. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41513. return ImageProcessingConfiguration;
  41514. }());
  41515. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41516. })(BABYLON || (BABYLON = {}));
  41517. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41518. var BABYLON;
  41519. (function (BABYLON) {
  41520. /**
  41521. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41522. * It can help converting any input color in a desired output one. This can then be used to create effects
  41523. * from sepia, black and white to sixties or futuristic rendering...
  41524. *
  41525. * The only supported format is currently 3dl.
  41526. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41527. */
  41528. var ColorGradingTexture = /** @class */ (function (_super) {
  41529. __extends(ColorGradingTexture, _super);
  41530. /**
  41531. * Instantiates a ColorGradingTexture from the following parameters.
  41532. *
  41533. * @param url The location of the color gradind data (currently only supporting 3dl)
  41534. * @param scene The scene the texture will be used in
  41535. */
  41536. function ColorGradingTexture(url, scene) {
  41537. var _this = _super.call(this, scene) || this;
  41538. if (!url) {
  41539. return _this;
  41540. }
  41541. _this._engine = scene.getEngine();
  41542. _this._textureMatrix = BABYLON.Matrix.Identity();
  41543. _this.name = url;
  41544. _this.url = url;
  41545. _this.hasAlpha = false;
  41546. _this.isCube = false;
  41547. _this.is3D = _this._engine.webGLVersion > 1;
  41548. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41549. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41550. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41551. _this.anisotropicFilteringLevel = 1;
  41552. _this._texture = _this._getFromCache(url, true);
  41553. if (!_this._texture) {
  41554. if (!scene.useDelayedTextureLoading) {
  41555. _this.loadTexture();
  41556. }
  41557. else {
  41558. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41559. }
  41560. }
  41561. return _this;
  41562. }
  41563. /**
  41564. * Returns the texture matrix used in most of the material.
  41565. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41566. */
  41567. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41568. return this._textureMatrix;
  41569. };
  41570. /**
  41571. * Occurs when the file being loaded is a .3dl LUT file.
  41572. */
  41573. ColorGradingTexture.prototype.load3dlTexture = function () {
  41574. var engine = this._engine;
  41575. var texture;
  41576. if (engine.webGLVersion === 1) {
  41577. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41578. }
  41579. else {
  41580. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41581. }
  41582. this._texture = texture;
  41583. var callback = function (text) {
  41584. if (typeof text !== "string") {
  41585. return;
  41586. }
  41587. var data = null;
  41588. var tempData = null;
  41589. var line;
  41590. var lines = text.split('\n');
  41591. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41592. var maxColor = 0;
  41593. for (var i = 0; i < lines.length; i++) {
  41594. line = lines[i];
  41595. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41596. continue;
  41597. if (line.indexOf('#') === 0)
  41598. continue;
  41599. var words = line.split(" ");
  41600. if (size === 0) {
  41601. // Number of space + one
  41602. size = words.length;
  41603. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41604. tempData = new Float32Array(size * size * size * 4);
  41605. continue;
  41606. }
  41607. if (size != 0) {
  41608. var r = Math.max(parseInt(words[0]), 0);
  41609. var g = Math.max(parseInt(words[1]), 0);
  41610. var b = Math.max(parseInt(words[2]), 0);
  41611. maxColor = Math.max(r, maxColor);
  41612. maxColor = Math.max(g, maxColor);
  41613. maxColor = Math.max(b, maxColor);
  41614. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41615. if (tempData) {
  41616. tempData[pixelStorageIndex + 0] = r;
  41617. tempData[pixelStorageIndex + 1] = g;
  41618. tempData[pixelStorageIndex + 2] = b;
  41619. }
  41620. pixelIndexSlice++;
  41621. if (pixelIndexSlice % size == 0) {
  41622. pixelIndexH++;
  41623. pixelIndexSlice = 0;
  41624. if (pixelIndexH % size == 0) {
  41625. pixelIndexW++;
  41626. pixelIndexH = 0;
  41627. }
  41628. }
  41629. }
  41630. }
  41631. if (tempData && data) {
  41632. for (var i = 0; i < tempData.length; i++) {
  41633. if (i > 0 && (i + 1) % 4 === 0) {
  41634. data[i] = 255;
  41635. }
  41636. else {
  41637. var value = tempData[i];
  41638. data[i] = (value / maxColor * 255);
  41639. }
  41640. }
  41641. }
  41642. if (texture.is3D) {
  41643. texture.updateSize(size, size, size);
  41644. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41645. }
  41646. else {
  41647. texture.updateSize(size * size, size);
  41648. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41649. }
  41650. };
  41651. var scene = this.getScene();
  41652. if (scene) {
  41653. scene._loadFile(this.url, callback);
  41654. }
  41655. else {
  41656. this._engine._loadFile(this.url, callback);
  41657. }
  41658. return this._texture;
  41659. };
  41660. /**
  41661. * Starts the loading process of the texture.
  41662. */
  41663. ColorGradingTexture.prototype.loadTexture = function () {
  41664. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41665. this.load3dlTexture();
  41666. }
  41667. };
  41668. /**
  41669. * Clones the color gradind texture.
  41670. */
  41671. ColorGradingTexture.prototype.clone = function () {
  41672. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41673. // Base texture
  41674. newTexture.level = this.level;
  41675. return newTexture;
  41676. };
  41677. /**
  41678. * Called during delayed load for textures.
  41679. */
  41680. ColorGradingTexture.prototype.delayLoad = function () {
  41681. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41682. return;
  41683. }
  41684. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41685. this._texture = this._getFromCache(this.url, true);
  41686. if (!this._texture) {
  41687. this.loadTexture();
  41688. }
  41689. };
  41690. /**
  41691. * Parses a color grading texture serialized by Babylon.
  41692. * @param parsedTexture The texture information being parsedTexture
  41693. * @param scene The scene to load the texture in
  41694. * @param rootUrl The root url of the data assets to load
  41695. * @return A color gradind texture
  41696. */
  41697. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41698. var texture = null;
  41699. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41700. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41701. texture.name = parsedTexture.name;
  41702. texture.level = parsedTexture.level;
  41703. }
  41704. return texture;
  41705. };
  41706. /**
  41707. * Serializes the LUT texture to json format.
  41708. */
  41709. ColorGradingTexture.prototype.serialize = function () {
  41710. if (!this.name) {
  41711. return null;
  41712. }
  41713. var serializationObject = {};
  41714. serializationObject.name = this.name;
  41715. serializationObject.level = this.level;
  41716. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41717. return serializationObject;
  41718. };
  41719. /**
  41720. * Empty line regex stored for GC.
  41721. */
  41722. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41723. return ColorGradingTexture;
  41724. }(BABYLON.BaseTexture));
  41725. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41726. })(BABYLON || (BABYLON = {}));
  41727. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41728. var BABYLON;
  41729. (function (BABYLON) {
  41730. /**
  41731. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41732. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41733. * 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;
  41734. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41735. */
  41736. var ColorCurves = /** @class */ (function () {
  41737. function ColorCurves() {
  41738. this._dirty = true;
  41739. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41740. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41741. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41742. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41743. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41744. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41745. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41746. this._globalHue = 30;
  41747. this._globalDensity = 0;
  41748. this._globalSaturation = 0;
  41749. this._globalExposure = 0;
  41750. this._highlightsHue = 30;
  41751. this._highlightsDensity = 0;
  41752. this._highlightsSaturation = 0;
  41753. this._highlightsExposure = 0;
  41754. this._midtonesHue = 30;
  41755. this._midtonesDensity = 0;
  41756. this._midtonesSaturation = 0;
  41757. this._midtonesExposure = 0;
  41758. this._shadowsHue = 30;
  41759. this._shadowsDensity = 0;
  41760. this._shadowsSaturation = 0;
  41761. this._shadowsExposure = 0;
  41762. }
  41763. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41764. /**
  41765. * Gets the global Hue value.
  41766. * 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).
  41767. */
  41768. get: function () {
  41769. return this._globalHue;
  41770. },
  41771. /**
  41772. * Sets the global Hue value.
  41773. * 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).
  41774. */
  41775. set: function (value) {
  41776. this._globalHue = value;
  41777. this._dirty = true;
  41778. },
  41779. enumerable: true,
  41780. configurable: true
  41781. });
  41782. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41783. /**
  41784. * Gets the global Density value.
  41785. * 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.
  41786. * Values less than zero provide a filter of opposite hue.
  41787. */
  41788. get: function () {
  41789. return this._globalDensity;
  41790. },
  41791. /**
  41792. * Sets the global Density value.
  41793. * 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.
  41794. * Values less than zero provide a filter of opposite hue.
  41795. */
  41796. set: function (value) {
  41797. this._globalDensity = value;
  41798. this._dirty = true;
  41799. },
  41800. enumerable: true,
  41801. configurable: true
  41802. });
  41803. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41804. /**
  41805. * Gets the global Saturation value.
  41806. * 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.
  41807. */
  41808. get: function () {
  41809. return this._globalSaturation;
  41810. },
  41811. /**
  41812. * Sets the global Saturation value.
  41813. * 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.
  41814. */
  41815. set: function (value) {
  41816. this._globalSaturation = value;
  41817. this._dirty = true;
  41818. },
  41819. enumerable: true,
  41820. configurable: true
  41821. });
  41822. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  41823. /**
  41824. * Gets the global Exposure value.
  41825. * 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.
  41826. */
  41827. get: function () {
  41828. return this._globalExposure;
  41829. },
  41830. /**
  41831. * Sets the global Exposure value.
  41832. * 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.
  41833. */
  41834. set: function (value) {
  41835. this._globalExposure = value;
  41836. this._dirty = true;
  41837. },
  41838. enumerable: true,
  41839. configurable: true
  41840. });
  41841. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41842. /**
  41843. * Gets the highlights Hue value.
  41844. * 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).
  41845. */
  41846. get: function () {
  41847. return this._highlightsHue;
  41848. },
  41849. /**
  41850. * Sets the highlights Hue value.
  41851. * 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).
  41852. */
  41853. set: function (value) {
  41854. this._highlightsHue = value;
  41855. this._dirty = true;
  41856. },
  41857. enumerable: true,
  41858. configurable: true
  41859. });
  41860. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41861. /**
  41862. * Gets the highlights Density value.
  41863. * 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.
  41864. * Values less than zero provide a filter of opposite hue.
  41865. */
  41866. get: function () {
  41867. return this._highlightsDensity;
  41868. },
  41869. /**
  41870. * Sets the highlights Density value.
  41871. * 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.
  41872. * Values less than zero provide a filter of opposite hue.
  41873. */
  41874. set: function (value) {
  41875. this._highlightsDensity = value;
  41876. this._dirty = true;
  41877. },
  41878. enumerable: true,
  41879. configurable: true
  41880. });
  41881. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41882. /**
  41883. * Gets the highlights Saturation value.
  41884. * 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.
  41885. */
  41886. get: function () {
  41887. return this._highlightsSaturation;
  41888. },
  41889. /**
  41890. * Sets the highlights Saturation value.
  41891. * 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.
  41892. */
  41893. set: function (value) {
  41894. this._highlightsSaturation = value;
  41895. this._dirty = true;
  41896. },
  41897. enumerable: true,
  41898. configurable: true
  41899. });
  41900. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41901. /**
  41902. * Gets the highlights Exposure value.
  41903. * 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.
  41904. */
  41905. get: function () {
  41906. return this._highlightsExposure;
  41907. },
  41908. /**
  41909. * Sets the highlights Exposure value.
  41910. * 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.
  41911. */
  41912. set: function (value) {
  41913. this._highlightsExposure = value;
  41914. this._dirty = true;
  41915. },
  41916. enumerable: true,
  41917. configurable: true
  41918. });
  41919. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41920. /**
  41921. * Gets the midtones Hue value.
  41922. * 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).
  41923. */
  41924. get: function () {
  41925. return this._midtonesHue;
  41926. },
  41927. /**
  41928. * Sets the midtones Hue value.
  41929. * 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).
  41930. */
  41931. set: function (value) {
  41932. this._midtonesHue = value;
  41933. this._dirty = true;
  41934. },
  41935. enumerable: true,
  41936. configurable: true
  41937. });
  41938. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41939. /**
  41940. * Gets the midtones Density value.
  41941. * 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.
  41942. * Values less than zero provide a filter of opposite hue.
  41943. */
  41944. get: function () {
  41945. return this._midtonesDensity;
  41946. },
  41947. /**
  41948. * Sets the midtones Density value.
  41949. * 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.
  41950. * Values less than zero provide a filter of opposite hue.
  41951. */
  41952. set: function (value) {
  41953. this._midtonesDensity = value;
  41954. this._dirty = true;
  41955. },
  41956. enumerable: true,
  41957. configurable: true
  41958. });
  41959. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41960. /**
  41961. * Gets the midtones Saturation value.
  41962. * 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.
  41963. */
  41964. get: function () {
  41965. return this._midtonesSaturation;
  41966. },
  41967. /**
  41968. * Sets the midtones Saturation value.
  41969. * 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.
  41970. */
  41971. set: function (value) {
  41972. this._midtonesSaturation = value;
  41973. this._dirty = true;
  41974. },
  41975. enumerable: true,
  41976. configurable: true
  41977. });
  41978. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41979. /**
  41980. * Gets the midtones Exposure value.
  41981. * 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.
  41982. */
  41983. get: function () {
  41984. return this._midtonesExposure;
  41985. },
  41986. /**
  41987. * Sets the midtones Exposure value.
  41988. * 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.
  41989. */
  41990. set: function (value) {
  41991. this._midtonesExposure = value;
  41992. this._dirty = true;
  41993. },
  41994. enumerable: true,
  41995. configurable: true
  41996. });
  41997. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41998. /**
  41999. * Gets the shadows Hue value.
  42000. * 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).
  42001. */
  42002. get: function () {
  42003. return this._shadowsHue;
  42004. },
  42005. /**
  42006. * Sets the shadows Hue value.
  42007. * 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).
  42008. */
  42009. set: function (value) {
  42010. this._shadowsHue = value;
  42011. this._dirty = true;
  42012. },
  42013. enumerable: true,
  42014. configurable: true
  42015. });
  42016. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  42017. /**
  42018. * Gets the shadows Density value.
  42019. * 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.
  42020. * Values less than zero provide a filter of opposite hue.
  42021. */
  42022. get: function () {
  42023. return this._shadowsDensity;
  42024. },
  42025. /**
  42026. * Sets the shadows Density value.
  42027. * 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.
  42028. * Values less than zero provide a filter of opposite hue.
  42029. */
  42030. set: function (value) {
  42031. this._shadowsDensity = value;
  42032. this._dirty = true;
  42033. },
  42034. enumerable: true,
  42035. configurable: true
  42036. });
  42037. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  42038. /**
  42039. * Gets the shadows Saturation value.
  42040. * 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.
  42041. */
  42042. get: function () {
  42043. return this._shadowsSaturation;
  42044. },
  42045. /**
  42046. * Sets the shadows Saturation value.
  42047. * 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.
  42048. */
  42049. set: function (value) {
  42050. this._shadowsSaturation = value;
  42051. this._dirty = true;
  42052. },
  42053. enumerable: true,
  42054. configurable: true
  42055. });
  42056. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  42057. /**
  42058. * Gets the shadows Exposure value.
  42059. * 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.
  42060. */
  42061. get: function () {
  42062. return this._shadowsExposure;
  42063. },
  42064. /**
  42065. * Sets the shadows Exposure value.
  42066. * 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.
  42067. */
  42068. set: function (value) {
  42069. this._shadowsExposure = value;
  42070. this._dirty = true;
  42071. },
  42072. enumerable: true,
  42073. configurable: true
  42074. });
  42075. ColorCurves.prototype.getClassName = function () {
  42076. return "ColorCurves";
  42077. };
  42078. /**
  42079. * Binds the color curves to the shader.
  42080. * @param colorCurves The color curve to bind
  42081. * @param effect The effect to bind to
  42082. */
  42083. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42084. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42085. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42086. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42087. if (colorCurves._dirty) {
  42088. colorCurves._dirty = false;
  42089. // Fill in global info.
  42090. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42091. // Compute highlights info.
  42092. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42093. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42094. // Compute midtones info.
  42095. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42096. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42097. // Compute shadows info.
  42098. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42099. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42100. // Compute deltas (neutral is midtones).
  42101. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42102. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42103. }
  42104. if (effect) {
  42105. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42106. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42107. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42108. }
  42109. };
  42110. /**
  42111. * Prepare the list of uniforms associated with the ColorCurves effects.
  42112. * @param uniformsList The list of uniforms used in the effect
  42113. */
  42114. ColorCurves.PrepareUniforms = function (uniformsList) {
  42115. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42116. };
  42117. /**
  42118. * Returns color grading data based on a hue, density, saturation and exposure value.
  42119. * @param filterHue The hue of the color filter.
  42120. * @param filterDensity The density of the color filter.
  42121. * @param saturation The saturation.
  42122. * @param exposure The exposure.
  42123. * @param result The result data container.
  42124. */
  42125. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42126. if (hue == null) {
  42127. return;
  42128. }
  42129. hue = ColorCurves.clamp(hue, 0, 360);
  42130. density = ColorCurves.clamp(density, -100, 100);
  42131. saturation = ColorCurves.clamp(saturation, -100, 100);
  42132. exposure = ColorCurves.clamp(exposure, -100, 100);
  42133. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42134. // so that the maximum filter density is only 50% control. This provides fine control
  42135. // for small values and reasonable range.
  42136. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42137. density *= 0.5;
  42138. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42139. if (density < 0) {
  42140. density *= -1;
  42141. hue = (hue + 180) % 360;
  42142. }
  42143. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42144. result.scaleToRef(2, result);
  42145. result.a = 1 + 0.01 * saturation;
  42146. };
  42147. /**
  42148. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42149. * @param value The input slider value in range [-100,100].
  42150. * @returns Adjusted value.
  42151. */
  42152. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42153. value /= 100;
  42154. var x = Math.abs(value);
  42155. x = Math.pow(x, 2);
  42156. if (value < 0) {
  42157. x *= -1;
  42158. }
  42159. x *= 100;
  42160. return x;
  42161. };
  42162. /**
  42163. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42164. * @param hue The hue (H) input.
  42165. * @param saturation The saturation (S) input.
  42166. * @param brightness The brightness (B) input.
  42167. * @result An RGBA color represented as Vector4.
  42168. */
  42169. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42170. var h = ColorCurves.clamp(hue, 0, 360);
  42171. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42172. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42173. if (s === 0) {
  42174. result.r = v;
  42175. result.g = v;
  42176. result.b = v;
  42177. }
  42178. else {
  42179. // sector 0 to 5
  42180. h /= 60;
  42181. var i = Math.floor(h);
  42182. // fractional part of h
  42183. var f = h - i;
  42184. var p = v * (1 - s);
  42185. var q = v * (1 - s * f);
  42186. var t = v * (1 - s * (1 - f));
  42187. switch (i) {
  42188. case 0:
  42189. result.r = v;
  42190. result.g = t;
  42191. result.b = p;
  42192. break;
  42193. case 1:
  42194. result.r = q;
  42195. result.g = v;
  42196. result.b = p;
  42197. break;
  42198. case 2:
  42199. result.r = p;
  42200. result.g = v;
  42201. result.b = t;
  42202. break;
  42203. case 3:
  42204. result.r = p;
  42205. result.g = q;
  42206. result.b = v;
  42207. break;
  42208. case 4:
  42209. result.r = t;
  42210. result.g = p;
  42211. result.b = v;
  42212. break;
  42213. default: // case 5:
  42214. result.r = v;
  42215. result.g = p;
  42216. result.b = q;
  42217. break;
  42218. }
  42219. }
  42220. result.a = 1;
  42221. };
  42222. /**
  42223. * Returns a value clamped between min and max
  42224. * @param value The value to clamp
  42225. * @param min The minimum of value
  42226. * @param max The maximum of value
  42227. * @returns The clamped value.
  42228. */
  42229. ColorCurves.clamp = function (value, min, max) {
  42230. return Math.min(Math.max(value, min), max);
  42231. };
  42232. /**
  42233. * Clones the current color curve instance.
  42234. * @return The cloned curves
  42235. */
  42236. ColorCurves.prototype.clone = function () {
  42237. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42238. };
  42239. /**
  42240. * Serializes the current color curve instance to a json representation.
  42241. * @return a JSON representation
  42242. */
  42243. ColorCurves.prototype.serialize = function () {
  42244. return BABYLON.SerializationHelper.Serialize(this);
  42245. };
  42246. /**
  42247. * Parses the color curve from a json representation.
  42248. * @param source the JSON source to parse
  42249. * @return The parsed curves
  42250. */
  42251. ColorCurves.Parse = function (source) {
  42252. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42253. };
  42254. __decorate([
  42255. BABYLON.serialize()
  42256. ], ColorCurves.prototype, "_globalHue", void 0);
  42257. __decorate([
  42258. BABYLON.serialize()
  42259. ], ColorCurves.prototype, "_globalDensity", void 0);
  42260. __decorate([
  42261. BABYLON.serialize()
  42262. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42263. __decorate([
  42264. BABYLON.serialize()
  42265. ], ColorCurves.prototype, "_globalExposure", void 0);
  42266. __decorate([
  42267. BABYLON.serialize()
  42268. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42269. __decorate([
  42270. BABYLON.serialize()
  42271. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42272. __decorate([
  42273. BABYLON.serialize()
  42274. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42275. __decorate([
  42276. BABYLON.serialize()
  42277. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42278. __decorate([
  42279. BABYLON.serialize()
  42280. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42281. __decorate([
  42282. BABYLON.serialize()
  42283. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42284. __decorate([
  42285. BABYLON.serialize()
  42286. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42287. __decorate([
  42288. BABYLON.serialize()
  42289. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42290. return ColorCurves;
  42291. }());
  42292. BABYLON.ColorCurves = ColorCurves;
  42293. })(BABYLON || (BABYLON = {}));
  42294. //# sourceMappingURL=babylon.colorCurves.js.map
  42295. //# sourceMappingURL=babylon.behavior.js.map
  42296. var BABYLON;
  42297. (function (BABYLON) {
  42298. /**
  42299. * "Static Class" containing the most commonly used helper while dealing with material for
  42300. * rendering purpose.
  42301. *
  42302. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42303. *
  42304. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42305. */
  42306. var MaterialHelper = /** @class */ (function () {
  42307. function MaterialHelper() {
  42308. }
  42309. /**
  42310. * Bind the current view position to an effect.
  42311. * @param effect The effect to be bound
  42312. * @param scene The scene the eyes position is used from
  42313. */
  42314. MaterialHelper.BindEyePosition = function (effect, scene) {
  42315. if (scene._forcedViewPosition) {
  42316. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42317. return;
  42318. }
  42319. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42320. };
  42321. /**
  42322. * Helps preparing the defines values about the UVs in used in the effect.
  42323. * UVs are shared as much as we can accross chanels in the shaders.
  42324. * @param texture The texture we are preparing the UVs for
  42325. * @param defines The defines to update
  42326. * @param key The chanel key "diffuse", "specular"... used in the shader
  42327. */
  42328. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42329. defines._needUVs = true;
  42330. defines[key] = true;
  42331. if (texture.getTextureMatrix().isIdentity(true)) {
  42332. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42333. if (texture.coordinatesIndex === 0) {
  42334. defines["MAINUV1"] = true;
  42335. }
  42336. else {
  42337. defines["MAINUV2"] = true;
  42338. }
  42339. }
  42340. else {
  42341. defines[key + "DIRECTUV"] = 0;
  42342. }
  42343. };
  42344. /**
  42345. * Binds a texture matrix value to its corrsponding uniform
  42346. * @param texture The texture to bind the matrix for
  42347. * @param uniformBuffer The uniform buffer receivin the data
  42348. * @param key The chanel key "diffuse", "specular"... used in the shader
  42349. */
  42350. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42351. var matrix = texture.getTextureMatrix();
  42352. if (!matrix.isIdentity(true)) {
  42353. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42354. }
  42355. };
  42356. /**
  42357. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42358. * @param mesh defines the current mesh
  42359. * @param scene defines the current scene
  42360. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42361. * @param pointsCloud defines if point cloud rendering has to be turned on
  42362. * @param fogEnabled defines if fog has to be turned on
  42363. * @param alphaTest defines if alpha testing has to be turned on
  42364. * @param defines defines the current list of defines
  42365. */
  42366. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42367. if (defines._areMiscDirty) {
  42368. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42369. defines["POINTSIZE"] = pointsCloud;
  42370. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42371. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42372. defines["ALPHATEST"] = alphaTest;
  42373. }
  42374. };
  42375. /**
  42376. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42377. * @param scene defines the current scene
  42378. * @param engine defines the current engine
  42379. * @param defines specifies the list of active defines
  42380. * @param useInstances defines if instances have to be turned on
  42381. * @param useClipPlane defines if clip plane have to be turned on
  42382. */
  42383. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42384. if (useClipPlane === void 0) { useClipPlane = null; }
  42385. var changed = false;
  42386. if (useClipPlane == null) {
  42387. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42388. }
  42389. if (defines["CLIPPLANE"] !== useClipPlane) {
  42390. defines["CLIPPLANE"] = useClipPlane;
  42391. changed = true;
  42392. }
  42393. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42394. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42395. changed = true;
  42396. }
  42397. if (defines["INSTANCES"] !== useInstances) {
  42398. defines["INSTANCES"] = useInstances;
  42399. changed = true;
  42400. }
  42401. if (changed) {
  42402. defines.markAsUnprocessed();
  42403. }
  42404. };
  42405. /**
  42406. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42407. * @param mesh The mesh containing the geometry data we will draw
  42408. * @param defines The defines to update
  42409. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42410. * @param useBones Precise whether bones should be used or not (override mesh info)
  42411. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42412. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42413. * @returns false if defines are considered not dirty and have not been checked
  42414. */
  42415. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42416. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42417. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42418. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42419. return false;
  42420. }
  42421. defines._normals = defines._needNormals;
  42422. defines._uvs = defines._needUVs;
  42423. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42424. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42425. defines["TANGENT"] = true;
  42426. }
  42427. if (defines._needUVs) {
  42428. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42429. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42430. }
  42431. else {
  42432. defines["UV1"] = false;
  42433. defines["UV2"] = false;
  42434. }
  42435. if (useVertexColor) {
  42436. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42437. defines["VERTEXCOLOR"] = hasVertexColors;
  42438. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42439. }
  42440. if (useBones) {
  42441. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42442. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42443. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42444. }
  42445. else {
  42446. defines["NUM_BONE_INFLUENCERS"] = 0;
  42447. defines["BonesPerMesh"] = 0;
  42448. }
  42449. }
  42450. if (useMorphTargets) {
  42451. var manager = mesh.morphTargetManager;
  42452. if (manager) {
  42453. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42454. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42455. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42456. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42457. }
  42458. else {
  42459. defines["MORPHTARGETS_TANGENT"] = false;
  42460. defines["MORPHTARGETS_NORMAL"] = false;
  42461. defines["MORPHTARGETS"] = false;
  42462. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42463. }
  42464. }
  42465. return true;
  42466. };
  42467. /**
  42468. * Prepares the defines related to the light information passed in parameter
  42469. * @param scene The scene we are intending to draw
  42470. * @param mesh The mesh the effect is compiling for
  42471. * @param defines The defines to update
  42472. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42473. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42474. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42475. * @returns true if normals will be required for the rest of the effect
  42476. */
  42477. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42478. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42479. if (disableLighting === void 0) { disableLighting = false; }
  42480. if (!defines._areLightsDirty) {
  42481. return defines._needNormals;
  42482. }
  42483. var lightIndex = 0;
  42484. var needNormals = false;
  42485. var needRebuild = false;
  42486. var lightmapMode = false;
  42487. var shadowEnabled = false;
  42488. var specularEnabled = false;
  42489. if (scene.lightsEnabled && !disableLighting) {
  42490. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42491. var light = _a[_i];
  42492. needNormals = true;
  42493. if (defines["LIGHT" + lightIndex] === undefined) {
  42494. needRebuild = true;
  42495. }
  42496. defines["LIGHT" + lightIndex] = true;
  42497. defines["SPOTLIGHT" + lightIndex] = false;
  42498. defines["HEMILIGHT" + lightIndex] = false;
  42499. defines["POINTLIGHT" + lightIndex] = false;
  42500. defines["DIRLIGHT" + lightIndex] = false;
  42501. var type;
  42502. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42503. type = "SPOTLIGHT" + lightIndex;
  42504. var spotLight = light;
  42505. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42506. }
  42507. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42508. type = "HEMILIGHT" + lightIndex;
  42509. }
  42510. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42511. type = "POINTLIGHT" + lightIndex;
  42512. }
  42513. else {
  42514. type = "DIRLIGHT" + lightIndex;
  42515. }
  42516. defines[type] = true;
  42517. // Specular
  42518. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42519. specularEnabled = true;
  42520. }
  42521. // Shadows
  42522. defines["SHADOW" + lightIndex] = false;
  42523. defines["SHADOWPCF" + lightIndex] = false;
  42524. defines["SHADOWPCSS" + lightIndex] = false;
  42525. defines["SHADOWPOISSON" + lightIndex] = false;
  42526. defines["SHADOWESM" + lightIndex] = false;
  42527. defines["SHADOWCUBE" + lightIndex] = false;
  42528. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42529. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42530. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42531. var shadowGenerator = light.getShadowGenerator();
  42532. if (shadowGenerator) {
  42533. shadowEnabled = true;
  42534. shadowGenerator.prepareDefines(defines, lightIndex);
  42535. }
  42536. }
  42537. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42538. lightmapMode = true;
  42539. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42540. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42541. }
  42542. else {
  42543. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42544. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42545. }
  42546. lightIndex++;
  42547. if (lightIndex === maxSimultaneousLights)
  42548. break;
  42549. }
  42550. }
  42551. defines["SPECULARTERM"] = specularEnabled;
  42552. defines["SHADOWS"] = shadowEnabled;
  42553. // Resetting all other lights if any
  42554. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42555. if (defines["LIGHT" + index] !== undefined) {
  42556. defines["LIGHT" + index] = false;
  42557. defines["HEMILIGHT" + lightIndex] = false;
  42558. defines["POINTLIGHT" + lightIndex] = false;
  42559. defines["DIRLIGHT" + lightIndex] = false;
  42560. defines["SPOTLIGHT" + lightIndex] = false;
  42561. defines["SHADOW" + lightIndex] = false;
  42562. }
  42563. }
  42564. var caps = scene.getEngine().getCaps();
  42565. if (defines["SHADOWFLOAT"] === undefined) {
  42566. needRebuild = true;
  42567. }
  42568. defines["SHADOWFLOAT"] = shadowEnabled &&
  42569. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42570. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42571. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42572. if (needRebuild) {
  42573. defines.rebuild();
  42574. }
  42575. return needNormals;
  42576. };
  42577. /**
  42578. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42579. * that won t be acctive due to defines being turned off.
  42580. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42581. * @param samplersList The samplers list
  42582. * @param defines The defines helping in the list generation
  42583. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42584. */
  42585. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42586. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42587. var uniformsList;
  42588. var uniformBuffersList = null;
  42589. if (uniformsListOrOptions.uniformsNames) {
  42590. var options = uniformsListOrOptions;
  42591. uniformsList = options.uniformsNames;
  42592. uniformBuffersList = options.uniformBuffersNames;
  42593. samplersList = options.samplers;
  42594. defines = options.defines;
  42595. maxSimultaneousLights = options.maxSimultaneousLights;
  42596. }
  42597. else {
  42598. uniformsList = uniformsListOrOptions;
  42599. if (!samplersList) {
  42600. samplersList = [];
  42601. }
  42602. }
  42603. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42604. if (!defines["LIGHT" + lightIndex]) {
  42605. break;
  42606. }
  42607. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42608. if (uniformBuffersList) {
  42609. uniformBuffersList.push("Light" + lightIndex);
  42610. }
  42611. samplersList.push("shadowSampler" + lightIndex);
  42612. samplersList.push("depthSampler" + lightIndex);
  42613. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42614. samplersList.push("projectionLightSampler" + lightIndex);
  42615. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42616. }
  42617. }
  42618. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42619. uniformsList.push("morphTargetInfluences");
  42620. }
  42621. };
  42622. /**
  42623. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42624. * @param defines The defines to update while falling back
  42625. * @param fallbacks The authorized effect fallbacks
  42626. * @param maxSimultaneousLights The maximum number of lights allowed
  42627. * @param rank the current rank of the Effect
  42628. * @returns The newly affected rank
  42629. */
  42630. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42631. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42632. if (rank === void 0) { rank = 0; }
  42633. var lightFallbackRank = 0;
  42634. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42635. if (!defines["LIGHT" + lightIndex]) {
  42636. break;
  42637. }
  42638. if (lightIndex > 0) {
  42639. lightFallbackRank = rank + lightIndex;
  42640. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42641. }
  42642. if (!defines["SHADOWS"]) {
  42643. if (defines["SHADOW" + lightIndex]) {
  42644. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42645. }
  42646. if (defines["SHADOWPCF" + lightIndex]) {
  42647. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42648. }
  42649. if (defines["SHADOWPCSS" + lightIndex]) {
  42650. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42651. }
  42652. if (defines["SHADOWPOISSON" + lightIndex]) {
  42653. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42654. }
  42655. if (defines["SHADOWESM" + lightIndex]) {
  42656. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42657. }
  42658. }
  42659. }
  42660. return lightFallbackRank++;
  42661. };
  42662. /**
  42663. * Prepares the list of attributes required for morph targets according to the effect defines.
  42664. * @param attribs The current list of supported attribs
  42665. * @param mesh The mesh to prepare the morph targets attributes for
  42666. * @param defines The current Defines of the effect
  42667. */
  42668. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42669. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42670. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42671. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42672. var manager = mesh.morphTargetManager;
  42673. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42674. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42675. for (var index = 0; index < influencers; index++) {
  42676. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42677. if (normal) {
  42678. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42679. }
  42680. if (tangent) {
  42681. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42682. }
  42683. if (attribs.length > maxAttributesCount) {
  42684. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42685. }
  42686. }
  42687. }
  42688. };
  42689. /**
  42690. * Prepares the list of attributes required for bones according to the effect defines.
  42691. * @param attribs The current list of supported attribs
  42692. * @param mesh The mesh to prepare the bones attributes for
  42693. * @param defines The current Defines of the effect
  42694. * @param fallbacks The current efffect fallback strategy
  42695. */
  42696. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42697. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42698. fallbacks.addCPUSkinningFallback(0, mesh);
  42699. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42700. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42701. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42702. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42703. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42704. }
  42705. }
  42706. };
  42707. /**
  42708. * Prepares the list of attributes required for instances according to the effect defines.
  42709. * @param attribs The current list of supported attribs
  42710. * @param defines The current Defines of the effect
  42711. */
  42712. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42713. if (defines["INSTANCES"]) {
  42714. attribs.push("world0");
  42715. attribs.push("world1");
  42716. attribs.push("world2");
  42717. attribs.push("world3");
  42718. }
  42719. };
  42720. /**
  42721. * Binds the light shadow information to the effect for the given mesh.
  42722. * @param light The light containing the generator
  42723. * @param scene The scene the lights belongs to
  42724. * @param mesh The mesh we are binding the information to render
  42725. * @param lightIndex The light index in the effect used to render the mesh
  42726. * @param effect The effect we are binding the data to
  42727. */
  42728. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42729. if (light.shadowEnabled && mesh.receiveShadows) {
  42730. var shadowGenerator = light.getShadowGenerator();
  42731. if (shadowGenerator) {
  42732. shadowGenerator.bindShadowLight(lightIndex, effect);
  42733. }
  42734. }
  42735. };
  42736. /**
  42737. * Binds the light information to the effect.
  42738. * @param light The light containing the generator
  42739. * @param effect The effect we are binding the data to
  42740. * @param lightIndex The light index in the effect used to render
  42741. */
  42742. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42743. light.transferToEffect(effect, lightIndex + "");
  42744. };
  42745. /**
  42746. * Binds the lights information from the scene to the effect for the given mesh.
  42747. * @param scene The scene the lights belongs to
  42748. * @param mesh The mesh we are binding the information to render
  42749. * @param effect The effect we are binding the data to
  42750. * @param defines The generated defines for the effect
  42751. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42752. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42753. */
  42754. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42755. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42756. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42757. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42758. for (var i = 0; i < len; i++) {
  42759. var light = mesh._lightSources[i];
  42760. var iAsString = i.toString();
  42761. var scaledIntensity = light.getScaledIntensity();
  42762. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42763. MaterialHelper.BindLightProperties(light, effect, i);
  42764. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42765. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42766. if (defines["SPECULARTERM"]) {
  42767. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42768. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42769. }
  42770. // Shadows
  42771. if (scene.shadowsEnabled) {
  42772. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42773. }
  42774. light._uniformBuffer.update();
  42775. }
  42776. };
  42777. /**
  42778. * Binds the fog information from the scene to the effect for the given mesh.
  42779. * @param scene The scene the lights belongs to
  42780. * @param mesh The mesh we are binding the information to render
  42781. * @param effect The effect we are binding the data to
  42782. */
  42783. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42784. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42785. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42786. effect.setColor3("vFogColor", scene.fogColor);
  42787. }
  42788. };
  42789. /**
  42790. * Binds the bones information from the mesh to the effect.
  42791. * @param mesh The mesh we are binding the information to render
  42792. * @param effect The effect we are binding the data to
  42793. */
  42794. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42795. if (!effect || !mesh) {
  42796. return;
  42797. }
  42798. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42799. mesh.computeBonesUsingShaders = false;
  42800. }
  42801. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42802. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42803. if (matrices) {
  42804. effect.setMatrices("mBones", matrices);
  42805. }
  42806. }
  42807. };
  42808. /**
  42809. * Binds the morph targets information from the mesh to the effect.
  42810. * @param abstractMesh The mesh we are binding the information to render
  42811. * @param effect The effect we are binding the data to
  42812. */
  42813. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42814. var manager = abstractMesh.morphTargetManager;
  42815. if (!abstractMesh || !manager) {
  42816. return;
  42817. }
  42818. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42819. };
  42820. /**
  42821. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42822. * @param defines The generated defines used in the effect
  42823. * @param effect The effect we are binding the data to
  42824. * @param scene The scene we are willing to render with logarithmic scale for
  42825. */
  42826. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42827. if (defines["LOGARITHMICDEPTH"]) {
  42828. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42829. }
  42830. };
  42831. /**
  42832. * Binds the clip plane information from the scene to the effect.
  42833. * @param scene The scene the clip plane information are extracted from
  42834. * @param effect The effect we are binding the data to
  42835. */
  42836. MaterialHelper.BindClipPlane = function (effect, scene) {
  42837. if (scene.clipPlane) {
  42838. var clipPlane = scene.clipPlane;
  42839. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42840. }
  42841. };
  42842. return MaterialHelper;
  42843. }());
  42844. BABYLON.MaterialHelper = MaterialHelper;
  42845. })(BABYLON || (BABYLON = {}));
  42846. //# sourceMappingURL=babylon.materialHelper.js.map
  42847. var BABYLON;
  42848. (function (BABYLON) {
  42849. var PushMaterial = /** @class */ (function (_super) {
  42850. __extends(PushMaterial, _super);
  42851. function PushMaterial(name, scene) {
  42852. var _this = _super.call(this, name, scene) || this;
  42853. _this._normalMatrix = new BABYLON.Matrix();
  42854. _this.storeEffectOnSubMeshes = true;
  42855. return _this;
  42856. }
  42857. PushMaterial.prototype.getEffect = function () {
  42858. return this._activeEffect;
  42859. };
  42860. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42861. if (!mesh) {
  42862. return false;
  42863. }
  42864. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42865. return true;
  42866. }
  42867. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42868. };
  42869. /**
  42870. * Binds the given world matrix to the active effect
  42871. *
  42872. * @param world the matrix to bind
  42873. */
  42874. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42875. this._activeEffect.setMatrix("world", world);
  42876. };
  42877. /**
  42878. * Binds the given normal matrix to the active effect
  42879. *
  42880. * @param normalMatrix the matrix to bind
  42881. */
  42882. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42883. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42884. };
  42885. PushMaterial.prototype.bind = function (world, mesh) {
  42886. if (!mesh) {
  42887. return;
  42888. }
  42889. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42890. };
  42891. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42892. if (effect === void 0) { effect = null; }
  42893. _super.prototype._afterBind.call(this, mesh);
  42894. this.getScene()._cachedEffect = effect;
  42895. };
  42896. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42897. if (visibility === void 0) { visibility = 1; }
  42898. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42899. };
  42900. return PushMaterial;
  42901. }(BABYLON.Material));
  42902. BABYLON.PushMaterial = PushMaterial;
  42903. })(BABYLON || (BABYLON = {}));
  42904. //# sourceMappingURL=babylon.pushMaterial.js.map
  42905. var BABYLON;
  42906. (function (BABYLON) {
  42907. /** @hidden */
  42908. var StandardMaterialDefines = /** @class */ (function (_super) {
  42909. __extends(StandardMaterialDefines, _super);
  42910. function StandardMaterialDefines() {
  42911. var _this = _super.call(this) || this;
  42912. _this.MAINUV1 = false;
  42913. _this.MAINUV2 = false;
  42914. _this.DIFFUSE = false;
  42915. _this.DIFFUSEDIRECTUV = 0;
  42916. _this.AMBIENT = false;
  42917. _this.AMBIENTDIRECTUV = 0;
  42918. _this.OPACITY = false;
  42919. _this.OPACITYDIRECTUV = 0;
  42920. _this.OPACITYRGB = false;
  42921. _this.REFLECTION = false;
  42922. _this.EMISSIVE = false;
  42923. _this.EMISSIVEDIRECTUV = 0;
  42924. _this.SPECULAR = false;
  42925. _this.SPECULARDIRECTUV = 0;
  42926. _this.BUMP = false;
  42927. _this.BUMPDIRECTUV = 0;
  42928. _this.PARALLAX = false;
  42929. _this.PARALLAXOCCLUSION = false;
  42930. _this.SPECULAROVERALPHA = false;
  42931. _this.CLIPPLANE = false;
  42932. _this.ALPHATEST = false;
  42933. _this.DEPTHPREPASS = false;
  42934. _this.ALPHAFROMDIFFUSE = false;
  42935. _this.POINTSIZE = false;
  42936. _this.FOG = false;
  42937. _this.SPECULARTERM = false;
  42938. _this.DIFFUSEFRESNEL = false;
  42939. _this.OPACITYFRESNEL = false;
  42940. _this.REFLECTIONFRESNEL = false;
  42941. _this.REFRACTIONFRESNEL = false;
  42942. _this.EMISSIVEFRESNEL = false;
  42943. _this.FRESNEL = false;
  42944. _this.NORMAL = false;
  42945. _this.UV1 = false;
  42946. _this.UV2 = false;
  42947. _this.VERTEXCOLOR = false;
  42948. _this.VERTEXALPHA = false;
  42949. _this.NUM_BONE_INFLUENCERS = 0;
  42950. _this.BonesPerMesh = 0;
  42951. _this.INSTANCES = false;
  42952. _this.GLOSSINESS = false;
  42953. _this.ROUGHNESS = false;
  42954. _this.EMISSIVEASILLUMINATION = false;
  42955. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42956. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42957. _this.LIGHTMAP = false;
  42958. _this.LIGHTMAPDIRECTUV = 0;
  42959. _this.OBJECTSPACE_NORMALMAP = false;
  42960. _this.USELIGHTMAPASSHADOWMAP = false;
  42961. _this.REFLECTIONMAP_3D = false;
  42962. _this.REFLECTIONMAP_SPHERICAL = false;
  42963. _this.REFLECTIONMAP_PLANAR = false;
  42964. _this.REFLECTIONMAP_CUBIC = false;
  42965. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42966. _this.REFLECTIONMAP_PROJECTION = false;
  42967. _this.REFLECTIONMAP_SKYBOX = false;
  42968. _this.REFLECTIONMAP_EXPLICIT = false;
  42969. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42970. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42971. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42972. _this.INVERTCUBICMAP = false;
  42973. _this.LOGARITHMICDEPTH = false;
  42974. _this.REFRACTION = false;
  42975. _this.REFRACTIONMAP_3D = false;
  42976. _this.REFLECTIONOVERALPHA = false;
  42977. _this.TWOSIDEDLIGHTING = false;
  42978. _this.SHADOWFLOAT = false;
  42979. _this.MORPHTARGETS = false;
  42980. _this.MORPHTARGETS_NORMAL = false;
  42981. _this.MORPHTARGETS_TANGENT = false;
  42982. _this.NUM_MORPH_INFLUENCERS = 0;
  42983. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42984. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42985. _this.IMAGEPROCESSING = false;
  42986. _this.VIGNETTE = false;
  42987. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42988. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42989. _this.TONEMAPPING = false;
  42990. _this.CONTRAST = false;
  42991. _this.COLORCURVES = false;
  42992. _this.COLORGRADING = false;
  42993. _this.COLORGRADING3D = false;
  42994. _this.SAMPLER3DGREENDEPTH = false;
  42995. _this.SAMPLER3DBGRMAP = false;
  42996. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42997. /**
  42998. * If the reflection texture on this material is in linear color space
  42999. * @hidden
  43000. */
  43001. _this.IS_REFLECTION_LINEAR = false;
  43002. /**
  43003. * If the refraction texture on this material is in linear color space
  43004. * @hidden
  43005. */
  43006. _this.IS_REFRACTION_LINEAR = false;
  43007. _this.EXPOSURE = false;
  43008. _this.rebuild();
  43009. return _this;
  43010. }
  43011. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43012. var modes = [
  43013. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43014. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43015. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43016. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43017. ];
  43018. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43019. var mode = modes_1[_i];
  43020. this[mode] = (mode === modeToEnable);
  43021. }
  43022. };
  43023. return StandardMaterialDefines;
  43024. }(BABYLON.MaterialDefines));
  43025. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43026. var StandardMaterial = /** @class */ (function (_super) {
  43027. __extends(StandardMaterial, _super);
  43028. function StandardMaterial(name, scene) {
  43029. var _this = _super.call(this, name, scene) || this;
  43030. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43031. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43032. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43033. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43034. _this.specularPower = 64;
  43035. _this._useAlphaFromDiffuseTexture = false;
  43036. _this._useEmissiveAsIllumination = false;
  43037. _this._linkEmissiveWithDiffuse = false;
  43038. _this._useSpecularOverAlpha = false;
  43039. _this._useReflectionOverAlpha = false;
  43040. _this._disableLighting = false;
  43041. _this._useObjectSpaceNormalMap = false;
  43042. _this._useParallax = false;
  43043. _this._useParallaxOcclusion = false;
  43044. _this.parallaxScaleBias = 0.05;
  43045. _this._roughness = 0;
  43046. _this.indexOfRefraction = 0.98;
  43047. _this.invertRefractionY = true;
  43048. /**
  43049. * Defines the alpha limits in alpha test mode
  43050. */
  43051. _this.alphaCutOff = 0.4;
  43052. _this._useLightmapAsShadowmap = false;
  43053. _this._useReflectionFresnelFromSpecular = false;
  43054. _this._useGlossinessFromSpecularMapAlpha = false;
  43055. _this._maxSimultaneousLights = 4;
  43056. /**
  43057. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43058. */
  43059. _this._invertNormalMapX = false;
  43060. /**
  43061. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43062. */
  43063. _this._invertNormalMapY = false;
  43064. /**
  43065. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43066. */
  43067. _this._twoSidedLighting = false;
  43068. _this._renderTargets = new BABYLON.SmartArray(16);
  43069. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43070. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43071. // Setup the default processing configuration to the scene.
  43072. _this._attachImageProcessingConfiguration(null);
  43073. _this.getRenderTargetTextures = function () {
  43074. _this._renderTargets.reset();
  43075. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43076. _this._renderTargets.push(_this._reflectionTexture);
  43077. }
  43078. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43079. _this._renderTargets.push(_this._refractionTexture);
  43080. }
  43081. return _this._renderTargets;
  43082. };
  43083. return _this;
  43084. }
  43085. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43086. /**
  43087. * Gets the image processing configuration used either in this material.
  43088. */
  43089. get: function () {
  43090. return this._imageProcessingConfiguration;
  43091. },
  43092. /**
  43093. * Sets the Default image processing configuration used either in the this material.
  43094. *
  43095. * If sets to null, the scene one is in use.
  43096. */
  43097. set: function (value) {
  43098. this._attachImageProcessingConfiguration(value);
  43099. // Ensure the effect will be rebuilt.
  43100. this._markAllSubMeshesAsTexturesDirty();
  43101. },
  43102. enumerable: true,
  43103. configurable: true
  43104. });
  43105. /**
  43106. * Attaches a new image processing configuration to the Standard Material.
  43107. * @param configuration
  43108. */
  43109. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43110. var _this = this;
  43111. if (configuration === this._imageProcessingConfiguration) {
  43112. return;
  43113. }
  43114. // Detaches observer.
  43115. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43116. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43117. }
  43118. // Pick the scene configuration if needed.
  43119. if (!configuration) {
  43120. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43121. }
  43122. else {
  43123. this._imageProcessingConfiguration = configuration;
  43124. }
  43125. // Attaches observer.
  43126. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43127. _this._markAllSubMeshesAsImageProcessingDirty();
  43128. });
  43129. };
  43130. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43131. /**
  43132. * Gets wether the color curves effect is enabled.
  43133. */
  43134. get: function () {
  43135. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43136. },
  43137. /**
  43138. * Sets wether the color curves effect is enabled.
  43139. */
  43140. set: function (value) {
  43141. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43142. },
  43143. enumerable: true,
  43144. configurable: true
  43145. });
  43146. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43147. /**
  43148. * Gets wether the color grading effect is enabled.
  43149. */
  43150. get: function () {
  43151. return this.imageProcessingConfiguration.colorGradingEnabled;
  43152. },
  43153. /**
  43154. * Gets wether the color grading effect is enabled.
  43155. */
  43156. set: function (value) {
  43157. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43158. },
  43159. enumerable: true,
  43160. configurable: true
  43161. });
  43162. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43163. /**
  43164. * Gets wether tonemapping is enabled or not.
  43165. */
  43166. get: function () {
  43167. return this._imageProcessingConfiguration.toneMappingEnabled;
  43168. },
  43169. /**
  43170. * Sets wether tonemapping is enabled or not
  43171. */
  43172. set: function (value) {
  43173. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43174. },
  43175. enumerable: true,
  43176. configurable: true
  43177. });
  43178. ;
  43179. ;
  43180. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43181. /**
  43182. * The camera exposure used on this material.
  43183. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43184. * This corresponds to a photographic exposure.
  43185. */
  43186. get: function () {
  43187. return this._imageProcessingConfiguration.exposure;
  43188. },
  43189. /**
  43190. * The camera exposure used on this material.
  43191. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43192. * This corresponds to a photographic exposure.
  43193. */
  43194. set: function (value) {
  43195. this._imageProcessingConfiguration.exposure = value;
  43196. },
  43197. enumerable: true,
  43198. configurable: true
  43199. });
  43200. ;
  43201. ;
  43202. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43203. /**
  43204. * Gets The camera contrast used on this material.
  43205. */
  43206. get: function () {
  43207. return this._imageProcessingConfiguration.contrast;
  43208. },
  43209. /**
  43210. * Sets The camera contrast used on this material.
  43211. */
  43212. set: function (value) {
  43213. this._imageProcessingConfiguration.contrast = value;
  43214. },
  43215. enumerable: true,
  43216. configurable: true
  43217. });
  43218. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43219. /**
  43220. * Gets the Color Grading 2D Lookup Texture.
  43221. */
  43222. get: function () {
  43223. return this._imageProcessingConfiguration.colorGradingTexture;
  43224. },
  43225. /**
  43226. * Sets the Color Grading 2D Lookup Texture.
  43227. */
  43228. set: function (value) {
  43229. this._imageProcessingConfiguration.colorGradingTexture = value;
  43230. },
  43231. enumerable: true,
  43232. configurable: true
  43233. });
  43234. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43235. /**
  43236. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43237. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43238. * 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;
  43239. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43240. */
  43241. get: function () {
  43242. return this._imageProcessingConfiguration.colorCurves;
  43243. },
  43244. /**
  43245. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43246. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43247. * 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;
  43248. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43249. */
  43250. set: function (value) {
  43251. this._imageProcessingConfiguration.colorCurves = value;
  43252. },
  43253. enumerable: true,
  43254. configurable: true
  43255. });
  43256. StandardMaterial.prototype.getClassName = function () {
  43257. return "StandardMaterial";
  43258. };
  43259. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43260. get: function () {
  43261. return this._useLogarithmicDepth;
  43262. },
  43263. set: function (value) {
  43264. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43265. this._markAllSubMeshesAsMiscDirty();
  43266. },
  43267. enumerable: true,
  43268. configurable: true
  43269. });
  43270. StandardMaterial.prototype.needAlphaBlending = function () {
  43271. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43272. };
  43273. StandardMaterial.prototype.needAlphaTesting = function () {
  43274. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43275. };
  43276. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43277. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43278. };
  43279. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43280. return this._diffuseTexture;
  43281. };
  43282. /**
  43283. * Child classes can use it to update shaders
  43284. */
  43285. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43286. if (useInstances === void 0) { useInstances = false; }
  43287. if (subMesh.effect && this.isFrozen) {
  43288. if (this._wasPreviouslyReady && subMesh.effect) {
  43289. return true;
  43290. }
  43291. }
  43292. if (!subMesh._materialDefines) {
  43293. subMesh._materialDefines = new StandardMaterialDefines();
  43294. }
  43295. var scene = this.getScene();
  43296. var defines = subMesh._materialDefines;
  43297. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43298. if (defines._renderId === scene.getRenderId()) {
  43299. return true;
  43300. }
  43301. }
  43302. var engine = scene.getEngine();
  43303. // Lights
  43304. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43305. // Textures
  43306. if (defines._areTexturesDirty) {
  43307. defines._needUVs = false;
  43308. defines.MAINUV1 = false;
  43309. defines.MAINUV2 = false;
  43310. if (scene.texturesEnabled) {
  43311. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43312. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43313. return false;
  43314. }
  43315. else {
  43316. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43317. }
  43318. }
  43319. else {
  43320. defines.DIFFUSE = false;
  43321. }
  43322. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43323. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43324. return false;
  43325. }
  43326. else {
  43327. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43328. }
  43329. }
  43330. else {
  43331. defines.AMBIENT = false;
  43332. }
  43333. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43334. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43335. return false;
  43336. }
  43337. else {
  43338. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43339. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43340. }
  43341. }
  43342. else {
  43343. defines.OPACITY = false;
  43344. }
  43345. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43346. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43347. return false;
  43348. }
  43349. else {
  43350. defines._needNormals = true;
  43351. defines.REFLECTION = true;
  43352. defines.ROUGHNESS = (this._roughness > 0);
  43353. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43354. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43355. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43356. switch (this._reflectionTexture.coordinatesMode) {
  43357. case BABYLON.Texture.EXPLICIT_MODE:
  43358. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43359. break;
  43360. case BABYLON.Texture.PLANAR_MODE:
  43361. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43362. break;
  43363. case BABYLON.Texture.PROJECTION_MODE:
  43364. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43365. break;
  43366. case BABYLON.Texture.SKYBOX_MODE:
  43367. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43368. break;
  43369. case BABYLON.Texture.SPHERICAL_MODE:
  43370. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43371. break;
  43372. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43373. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43374. break;
  43375. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43376. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43377. break;
  43378. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43379. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43380. break;
  43381. case BABYLON.Texture.CUBIC_MODE:
  43382. case BABYLON.Texture.INVCUBIC_MODE:
  43383. default:
  43384. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43385. break;
  43386. }
  43387. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43388. }
  43389. }
  43390. else {
  43391. defines.REFLECTION = false;
  43392. }
  43393. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43394. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43395. return false;
  43396. }
  43397. else {
  43398. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43399. }
  43400. }
  43401. else {
  43402. defines.EMISSIVE = false;
  43403. }
  43404. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43405. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43406. return false;
  43407. }
  43408. else {
  43409. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43410. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43411. }
  43412. }
  43413. else {
  43414. defines.LIGHTMAP = false;
  43415. }
  43416. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43417. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43418. return false;
  43419. }
  43420. else {
  43421. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43422. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43423. }
  43424. }
  43425. else {
  43426. defines.SPECULAR = false;
  43427. }
  43428. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43429. // Bump texure can not be not blocking.
  43430. if (!this._bumpTexture.isReady()) {
  43431. return false;
  43432. }
  43433. else {
  43434. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43435. defines.PARALLAX = this._useParallax;
  43436. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43437. }
  43438. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43439. }
  43440. else {
  43441. defines.BUMP = false;
  43442. }
  43443. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43444. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43445. return false;
  43446. }
  43447. else {
  43448. defines._needUVs = true;
  43449. defines.REFRACTION = true;
  43450. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43451. }
  43452. }
  43453. else {
  43454. defines.REFRACTION = false;
  43455. }
  43456. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43457. }
  43458. else {
  43459. defines.DIFFUSE = false;
  43460. defines.AMBIENT = false;
  43461. defines.OPACITY = false;
  43462. defines.REFLECTION = false;
  43463. defines.EMISSIVE = false;
  43464. defines.LIGHTMAP = false;
  43465. defines.BUMP = false;
  43466. defines.REFRACTION = false;
  43467. }
  43468. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43469. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43470. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43471. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43472. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43473. }
  43474. if (defines._areImageProcessingDirty) {
  43475. if (!this._imageProcessingConfiguration.isReady()) {
  43476. return false;
  43477. }
  43478. this._imageProcessingConfiguration.prepareDefines(defines);
  43479. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43480. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43481. }
  43482. if (defines._areFresnelDirty) {
  43483. if (StandardMaterial.FresnelEnabled) {
  43484. // Fresnel
  43485. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43486. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43487. this._reflectionFresnelParameters) {
  43488. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43489. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43490. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43491. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43492. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43493. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43494. defines._needNormals = true;
  43495. defines.FRESNEL = true;
  43496. }
  43497. }
  43498. else {
  43499. defines.FRESNEL = false;
  43500. }
  43501. }
  43502. // Misc.
  43503. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43504. // Attribs
  43505. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43506. // Values that need to be evaluated on every frame
  43507. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43508. // Get correct effect
  43509. if (defines.isDirty) {
  43510. defines.markAsProcessed();
  43511. scene.resetCachedMaterial();
  43512. // Fallbacks
  43513. var fallbacks = new BABYLON.EffectFallbacks();
  43514. if (defines.REFLECTION) {
  43515. fallbacks.addFallback(0, "REFLECTION");
  43516. }
  43517. if (defines.SPECULAR) {
  43518. fallbacks.addFallback(0, "SPECULAR");
  43519. }
  43520. if (defines.BUMP) {
  43521. fallbacks.addFallback(0, "BUMP");
  43522. }
  43523. if (defines.PARALLAX) {
  43524. fallbacks.addFallback(1, "PARALLAX");
  43525. }
  43526. if (defines.PARALLAXOCCLUSION) {
  43527. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43528. }
  43529. if (defines.SPECULAROVERALPHA) {
  43530. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43531. }
  43532. if (defines.FOG) {
  43533. fallbacks.addFallback(1, "FOG");
  43534. }
  43535. if (defines.POINTSIZE) {
  43536. fallbacks.addFallback(0, "POINTSIZE");
  43537. }
  43538. if (defines.LOGARITHMICDEPTH) {
  43539. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43540. }
  43541. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43542. if (defines.SPECULARTERM) {
  43543. fallbacks.addFallback(0, "SPECULARTERM");
  43544. }
  43545. if (defines.DIFFUSEFRESNEL) {
  43546. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43547. }
  43548. if (defines.OPACITYFRESNEL) {
  43549. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43550. }
  43551. if (defines.REFLECTIONFRESNEL) {
  43552. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43553. }
  43554. if (defines.EMISSIVEFRESNEL) {
  43555. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43556. }
  43557. if (defines.FRESNEL) {
  43558. fallbacks.addFallback(4, "FRESNEL");
  43559. }
  43560. //Attributes
  43561. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43562. if (defines.NORMAL) {
  43563. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43564. }
  43565. if (defines.UV1) {
  43566. attribs.push(BABYLON.VertexBuffer.UVKind);
  43567. }
  43568. if (defines.UV2) {
  43569. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43570. }
  43571. if (defines.VERTEXCOLOR) {
  43572. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43573. }
  43574. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43575. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43576. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43577. var shaderName = "default";
  43578. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43579. "vFogInfos", "vFogColor", "pointSize",
  43580. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43581. "mBones",
  43582. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43583. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43584. "vReflectionPosition", "vReflectionSize",
  43585. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43586. ];
  43587. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43588. var uniformBuffers = ["Material", "Scene"];
  43589. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43590. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43591. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43592. uniformsNames: uniforms,
  43593. uniformBuffersNames: uniformBuffers,
  43594. samplers: samplers,
  43595. defines: defines,
  43596. maxSimultaneousLights: this._maxSimultaneousLights
  43597. });
  43598. if (this.customShaderNameResolve) {
  43599. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43600. }
  43601. var join = defines.toString();
  43602. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43603. attributes: attribs,
  43604. uniformsNames: uniforms,
  43605. uniformBuffersNames: uniformBuffers,
  43606. samplers: samplers,
  43607. defines: join,
  43608. fallbacks: fallbacks,
  43609. onCompiled: this.onCompiled,
  43610. onError: this.onError,
  43611. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43612. }, engine), defines);
  43613. this.buildUniformLayout();
  43614. }
  43615. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43616. return false;
  43617. }
  43618. defines._renderId = scene.getRenderId();
  43619. this._wasPreviouslyReady = true;
  43620. return true;
  43621. };
  43622. StandardMaterial.prototype.buildUniformLayout = function () {
  43623. // Order is important !
  43624. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43625. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43626. this._uniformBuffer.addUniform("opacityParts", 4);
  43627. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43628. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43629. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43630. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43631. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43632. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43633. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43634. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43635. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43636. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43637. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43638. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43639. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43640. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43641. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43642. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43643. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43644. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43645. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43646. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43647. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43648. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43649. this._uniformBuffer.addUniform("specularMatrix", 16);
  43650. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43651. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43652. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43653. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43654. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43655. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43656. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43657. this._uniformBuffer.addUniform("pointSize", 1);
  43658. this._uniformBuffer.create();
  43659. };
  43660. StandardMaterial.prototype.unbind = function () {
  43661. if (this._activeEffect) {
  43662. var needFlag = false;
  43663. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43664. this._activeEffect.setTexture("reflection2DSampler", null);
  43665. needFlag = true;
  43666. }
  43667. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43668. this._activeEffect.setTexture("refraction2DSampler", null);
  43669. needFlag = true;
  43670. }
  43671. if (needFlag) {
  43672. this._markAllSubMeshesAsTexturesDirty();
  43673. }
  43674. }
  43675. _super.prototype.unbind.call(this);
  43676. };
  43677. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43678. var scene = this.getScene();
  43679. var defines = subMesh._materialDefines;
  43680. if (!defines) {
  43681. return;
  43682. }
  43683. var effect = subMesh.effect;
  43684. if (!effect) {
  43685. return;
  43686. }
  43687. this._activeEffect = effect;
  43688. // Matrices
  43689. this.bindOnlyWorldMatrix(world);
  43690. // Normal Matrix
  43691. if (defines.OBJECTSPACE_NORMALMAP) {
  43692. world.toNormalMatrix(this._normalMatrix);
  43693. this.bindOnlyNormalMatrix(this._normalMatrix);
  43694. }
  43695. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43696. // Bones
  43697. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43698. if (mustRebind) {
  43699. this._uniformBuffer.bindToEffect(effect, "Material");
  43700. this.bindViewProjection(effect);
  43701. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43702. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43703. // Fresnel
  43704. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43705. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43706. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43707. }
  43708. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43709. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43710. }
  43711. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43712. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43713. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43714. }
  43715. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43716. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43717. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43718. }
  43719. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43720. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43721. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43722. }
  43723. }
  43724. // Textures
  43725. if (scene.texturesEnabled) {
  43726. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43727. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43728. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43729. if (this._diffuseTexture.hasAlpha) {
  43730. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43731. }
  43732. }
  43733. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43734. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43735. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43736. }
  43737. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43738. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43739. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43740. }
  43741. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43742. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43743. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43744. if (this._reflectionTexture.boundingBoxSize) {
  43745. var cubeTexture = this._reflectionTexture;
  43746. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43747. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43748. }
  43749. }
  43750. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43751. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43752. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43753. }
  43754. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43755. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43756. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43757. }
  43758. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43759. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43760. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43761. }
  43762. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43763. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43764. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43765. if (scene._mirroredCameraPosition) {
  43766. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43767. }
  43768. else {
  43769. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43770. }
  43771. }
  43772. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43773. var depth = 1.0;
  43774. if (!this._refractionTexture.isCube) {
  43775. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43776. if (this._refractionTexture.depth) {
  43777. depth = this._refractionTexture.depth;
  43778. }
  43779. }
  43780. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43781. }
  43782. }
  43783. // Point size
  43784. if (this.pointsCloud) {
  43785. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43786. }
  43787. if (defines.SPECULARTERM) {
  43788. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43789. }
  43790. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43791. // Diffuse
  43792. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43793. }
  43794. // Textures
  43795. if (scene.texturesEnabled) {
  43796. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43797. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43798. }
  43799. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43800. effect.setTexture("ambientSampler", this._ambientTexture);
  43801. }
  43802. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43803. effect.setTexture("opacitySampler", this._opacityTexture);
  43804. }
  43805. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43806. if (this._reflectionTexture.isCube) {
  43807. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43808. }
  43809. else {
  43810. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43811. }
  43812. }
  43813. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43814. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43815. }
  43816. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43817. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43818. }
  43819. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43820. effect.setTexture("specularSampler", this._specularTexture);
  43821. }
  43822. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43823. effect.setTexture("bumpSampler", this._bumpTexture);
  43824. }
  43825. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43826. var depth = 1.0;
  43827. if (this._refractionTexture.isCube) {
  43828. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43829. }
  43830. else {
  43831. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43832. }
  43833. }
  43834. }
  43835. // Clip plane
  43836. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43837. // Colors
  43838. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43839. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43840. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43841. }
  43842. if (mustRebind || !this.isFrozen) {
  43843. // Lights
  43844. if (scene.lightsEnabled && !this._disableLighting) {
  43845. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43846. }
  43847. // View
  43848. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43849. this.bindView(effect);
  43850. }
  43851. // Fog
  43852. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43853. // Morph targets
  43854. if (defines.NUM_MORPH_INFLUENCERS) {
  43855. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43856. }
  43857. // Log. depth
  43858. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43859. // image processing
  43860. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43861. this._imageProcessingConfiguration.bind(this._activeEffect);
  43862. }
  43863. }
  43864. this._uniformBuffer.update();
  43865. this._afterBind(mesh, this._activeEffect);
  43866. };
  43867. StandardMaterial.prototype.getAnimatables = function () {
  43868. var results = [];
  43869. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43870. results.push(this._diffuseTexture);
  43871. }
  43872. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43873. results.push(this._ambientTexture);
  43874. }
  43875. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43876. results.push(this._opacityTexture);
  43877. }
  43878. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43879. results.push(this._reflectionTexture);
  43880. }
  43881. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43882. results.push(this._emissiveTexture);
  43883. }
  43884. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43885. results.push(this._specularTexture);
  43886. }
  43887. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43888. results.push(this._bumpTexture);
  43889. }
  43890. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43891. results.push(this._lightmapTexture);
  43892. }
  43893. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43894. results.push(this._refractionTexture);
  43895. }
  43896. return results;
  43897. };
  43898. StandardMaterial.prototype.getActiveTextures = function () {
  43899. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43900. if (this._diffuseTexture) {
  43901. activeTextures.push(this._diffuseTexture);
  43902. }
  43903. if (this._ambientTexture) {
  43904. activeTextures.push(this._ambientTexture);
  43905. }
  43906. if (this._opacityTexture) {
  43907. activeTextures.push(this._opacityTexture);
  43908. }
  43909. if (this._reflectionTexture) {
  43910. activeTextures.push(this._reflectionTexture);
  43911. }
  43912. if (this._emissiveTexture) {
  43913. activeTextures.push(this._emissiveTexture);
  43914. }
  43915. if (this._specularTexture) {
  43916. activeTextures.push(this._specularTexture);
  43917. }
  43918. if (this._bumpTexture) {
  43919. activeTextures.push(this._bumpTexture);
  43920. }
  43921. if (this._lightmapTexture) {
  43922. activeTextures.push(this._lightmapTexture);
  43923. }
  43924. if (this._refractionTexture) {
  43925. activeTextures.push(this._refractionTexture);
  43926. }
  43927. return activeTextures;
  43928. };
  43929. StandardMaterial.prototype.hasTexture = function (texture) {
  43930. if (_super.prototype.hasTexture.call(this, texture)) {
  43931. return true;
  43932. }
  43933. if (this._diffuseTexture === texture) {
  43934. return true;
  43935. }
  43936. if (this._ambientTexture === texture) {
  43937. return true;
  43938. }
  43939. if (this._opacityTexture === texture) {
  43940. return true;
  43941. }
  43942. if (this._reflectionTexture === texture) {
  43943. return true;
  43944. }
  43945. if (this._emissiveTexture === texture) {
  43946. return true;
  43947. }
  43948. if (this._specularTexture === texture) {
  43949. return true;
  43950. }
  43951. if (this._bumpTexture === texture) {
  43952. return true;
  43953. }
  43954. if (this._lightmapTexture === texture) {
  43955. return true;
  43956. }
  43957. if (this._refractionTexture === texture) {
  43958. return true;
  43959. }
  43960. return false;
  43961. };
  43962. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43963. if (forceDisposeTextures) {
  43964. if (this._diffuseTexture) {
  43965. this._diffuseTexture.dispose();
  43966. }
  43967. if (this._ambientTexture) {
  43968. this._ambientTexture.dispose();
  43969. }
  43970. if (this._opacityTexture) {
  43971. this._opacityTexture.dispose();
  43972. }
  43973. if (this._reflectionTexture) {
  43974. this._reflectionTexture.dispose();
  43975. }
  43976. if (this._emissiveTexture) {
  43977. this._emissiveTexture.dispose();
  43978. }
  43979. if (this._specularTexture) {
  43980. this._specularTexture.dispose();
  43981. }
  43982. if (this._bumpTexture) {
  43983. this._bumpTexture.dispose();
  43984. }
  43985. if (this._lightmapTexture) {
  43986. this._lightmapTexture.dispose();
  43987. }
  43988. if (this._refractionTexture) {
  43989. this._refractionTexture.dispose();
  43990. }
  43991. }
  43992. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43993. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43994. }
  43995. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43996. };
  43997. StandardMaterial.prototype.clone = function (name) {
  43998. var _this = this;
  43999. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44000. result.name = name;
  44001. result.id = name;
  44002. return result;
  44003. };
  44004. StandardMaterial.prototype.serialize = function () {
  44005. return BABYLON.SerializationHelper.Serialize(this);
  44006. };
  44007. // Statics
  44008. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44009. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44010. };
  44011. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44012. get: function () {
  44013. return StandardMaterial._DiffuseTextureEnabled;
  44014. },
  44015. set: function (value) {
  44016. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44017. return;
  44018. }
  44019. StandardMaterial._DiffuseTextureEnabled = value;
  44020. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44021. },
  44022. enumerable: true,
  44023. configurable: true
  44024. });
  44025. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44026. get: function () {
  44027. return StandardMaterial._AmbientTextureEnabled;
  44028. },
  44029. set: function (value) {
  44030. if (StandardMaterial._AmbientTextureEnabled === value) {
  44031. return;
  44032. }
  44033. StandardMaterial._AmbientTextureEnabled = value;
  44034. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44035. },
  44036. enumerable: true,
  44037. configurable: true
  44038. });
  44039. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44040. get: function () {
  44041. return StandardMaterial._OpacityTextureEnabled;
  44042. },
  44043. set: function (value) {
  44044. if (StandardMaterial._OpacityTextureEnabled === value) {
  44045. return;
  44046. }
  44047. StandardMaterial._OpacityTextureEnabled = value;
  44048. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44049. },
  44050. enumerable: true,
  44051. configurable: true
  44052. });
  44053. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44054. get: function () {
  44055. return StandardMaterial._ReflectionTextureEnabled;
  44056. },
  44057. set: function (value) {
  44058. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44059. return;
  44060. }
  44061. StandardMaterial._ReflectionTextureEnabled = value;
  44062. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44063. },
  44064. enumerable: true,
  44065. configurable: true
  44066. });
  44067. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44068. get: function () {
  44069. return StandardMaterial._EmissiveTextureEnabled;
  44070. },
  44071. set: function (value) {
  44072. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44073. return;
  44074. }
  44075. StandardMaterial._EmissiveTextureEnabled = value;
  44076. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44077. },
  44078. enumerable: true,
  44079. configurable: true
  44080. });
  44081. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44082. get: function () {
  44083. return StandardMaterial._SpecularTextureEnabled;
  44084. },
  44085. set: function (value) {
  44086. if (StandardMaterial._SpecularTextureEnabled === value) {
  44087. return;
  44088. }
  44089. StandardMaterial._SpecularTextureEnabled = value;
  44090. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44091. },
  44092. enumerable: true,
  44093. configurable: true
  44094. });
  44095. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44096. get: function () {
  44097. return StandardMaterial._BumpTextureEnabled;
  44098. },
  44099. set: function (value) {
  44100. if (StandardMaterial._BumpTextureEnabled === value) {
  44101. return;
  44102. }
  44103. StandardMaterial._BumpTextureEnabled = value;
  44104. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44105. },
  44106. enumerable: true,
  44107. configurable: true
  44108. });
  44109. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44110. get: function () {
  44111. return StandardMaterial._LightmapTextureEnabled;
  44112. },
  44113. set: function (value) {
  44114. if (StandardMaterial._LightmapTextureEnabled === value) {
  44115. return;
  44116. }
  44117. StandardMaterial._LightmapTextureEnabled = value;
  44118. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44119. },
  44120. enumerable: true,
  44121. configurable: true
  44122. });
  44123. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44124. get: function () {
  44125. return StandardMaterial._RefractionTextureEnabled;
  44126. },
  44127. set: function (value) {
  44128. if (StandardMaterial._RefractionTextureEnabled === value) {
  44129. return;
  44130. }
  44131. StandardMaterial._RefractionTextureEnabled = value;
  44132. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44133. },
  44134. enumerable: true,
  44135. configurable: true
  44136. });
  44137. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44138. get: function () {
  44139. return StandardMaterial._ColorGradingTextureEnabled;
  44140. },
  44141. set: function (value) {
  44142. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44143. return;
  44144. }
  44145. StandardMaterial._ColorGradingTextureEnabled = value;
  44146. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44147. },
  44148. enumerable: true,
  44149. configurable: true
  44150. });
  44151. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44152. get: function () {
  44153. return StandardMaterial._FresnelEnabled;
  44154. },
  44155. set: function (value) {
  44156. if (StandardMaterial._FresnelEnabled === value) {
  44157. return;
  44158. }
  44159. StandardMaterial._FresnelEnabled = value;
  44160. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44161. },
  44162. enumerable: true,
  44163. configurable: true
  44164. });
  44165. // Flags used to enable or disable a type of texture for all Standard Materials
  44166. StandardMaterial._DiffuseTextureEnabled = true;
  44167. StandardMaterial._AmbientTextureEnabled = true;
  44168. StandardMaterial._OpacityTextureEnabled = true;
  44169. StandardMaterial._ReflectionTextureEnabled = true;
  44170. StandardMaterial._EmissiveTextureEnabled = true;
  44171. StandardMaterial._SpecularTextureEnabled = true;
  44172. StandardMaterial._BumpTextureEnabled = true;
  44173. StandardMaterial._LightmapTextureEnabled = true;
  44174. StandardMaterial._RefractionTextureEnabled = true;
  44175. StandardMaterial._ColorGradingTextureEnabled = true;
  44176. StandardMaterial._FresnelEnabled = true;
  44177. __decorate([
  44178. BABYLON.serializeAsTexture("diffuseTexture")
  44179. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44180. __decorate([
  44181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44182. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44183. __decorate([
  44184. BABYLON.serializeAsTexture("ambientTexture")
  44185. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44186. __decorate([
  44187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44188. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44189. __decorate([
  44190. BABYLON.serializeAsTexture("opacityTexture")
  44191. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44192. __decorate([
  44193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44194. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44195. __decorate([
  44196. BABYLON.serializeAsTexture("reflectionTexture")
  44197. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44198. __decorate([
  44199. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44200. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44201. __decorate([
  44202. BABYLON.serializeAsTexture("emissiveTexture")
  44203. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44204. __decorate([
  44205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44206. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44207. __decorate([
  44208. BABYLON.serializeAsTexture("specularTexture")
  44209. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44210. __decorate([
  44211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44212. ], StandardMaterial.prototype, "specularTexture", void 0);
  44213. __decorate([
  44214. BABYLON.serializeAsTexture("bumpTexture")
  44215. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44216. __decorate([
  44217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44218. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44219. __decorate([
  44220. BABYLON.serializeAsTexture("lightmapTexture")
  44221. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44222. __decorate([
  44223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44224. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44225. __decorate([
  44226. BABYLON.serializeAsTexture("refractionTexture")
  44227. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44228. __decorate([
  44229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44230. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44231. __decorate([
  44232. BABYLON.serializeAsColor3("ambient")
  44233. ], StandardMaterial.prototype, "ambientColor", void 0);
  44234. __decorate([
  44235. BABYLON.serializeAsColor3("diffuse")
  44236. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44237. __decorate([
  44238. BABYLON.serializeAsColor3("specular")
  44239. ], StandardMaterial.prototype, "specularColor", void 0);
  44240. __decorate([
  44241. BABYLON.serializeAsColor3("emissive")
  44242. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44243. __decorate([
  44244. BABYLON.serialize()
  44245. ], StandardMaterial.prototype, "specularPower", void 0);
  44246. __decorate([
  44247. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44248. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44249. __decorate([
  44250. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44251. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44252. __decorate([
  44253. BABYLON.serialize("useEmissiveAsIllumination")
  44254. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44255. __decorate([
  44256. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44257. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44258. __decorate([
  44259. BABYLON.serialize("linkEmissiveWithDiffuse")
  44260. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44261. __decorate([
  44262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44263. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44264. __decorate([
  44265. BABYLON.serialize("useSpecularOverAlpha")
  44266. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44267. __decorate([
  44268. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44269. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44270. __decorate([
  44271. BABYLON.serialize("useReflectionOverAlpha")
  44272. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44273. __decorate([
  44274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44275. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44276. __decorate([
  44277. BABYLON.serialize("disableLighting")
  44278. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44279. __decorate([
  44280. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44281. ], StandardMaterial.prototype, "disableLighting", void 0);
  44282. __decorate([
  44283. BABYLON.serialize("useObjectSpaceNormalMap")
  44284. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44285. __decorate([
  44286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44287. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44288. __decorate([
  44289. BABYLON.serialize("useParallax")
  44290. ], StandardMaterial.prototype, "_useParallax", void 0);
  44291. __decorate([
  44292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44293. ], StandardMaterial.prototype, "useParallax", void 0);
  44294. __decorate([
  44295. BABYLON.serialize("useParallaxOcclusion")
  44296. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44297. __decorate([
  44298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44299. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44300. __decorate([
  44301. BABYLON.serialize()
  44302. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44303. __decorate([
  44304. BABYLON.serialize("roughness")
  44305. ], StandardMaterial.prototype, "_roughness", void 0);
  44306. __decorate([
  44307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44308. ], StandardMaterial.prototype, "roughness", void 0);
  44309. __decorate([
  44310. BABYLON.serialize()
  44311. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44312. __decorate([
  44313. BABYLON.serialize()
  44314. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44315. __decorate([
  44316. BABYLON.serialize()
  44317. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44318. __decorate([
  44319. BABYLON.serialize("useLightmapAsShadowmap")
  44320. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44321. __decorate([
  44322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44323. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44324. __decorate([
  44325. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44326. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44327. __decorate([
  44328. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44329. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44330. __decorate([
  44331. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44332. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44333. __decorate([
  44334. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44335. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44336. __decorate([
  44337. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44338. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44339. __decorate([
  44340. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44341. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44342. __decorate([
  44343. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44344. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44345. __decorate([
  44346. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44347. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44348. __decorate([
  44349. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44350. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44351. __decorate([
  44352. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44353. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44354. __decorate([
  44355. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44356. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44357. __decorate([
  44358. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44359. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44360. __decorate([
  44361. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44362. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44363. __decorate([
  44364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44365. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44366. __decorate([
  44367. BABYLON.serialize("maxSimultaneousLights")
  44368. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44369. __decorate([
  44370. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44371. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44372. __decorate([
  44373. BABYLON.serialize("invertNormalMapX")
  44374. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44375. __decorate([
  44376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44377. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44378. __decorate([
  44379. BABYLON.serialize("invertNormalMapY")
  44380. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44381. __decorate([
  44382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44383. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44384. __decorate([
  44385. BABYLON.serialize("twoSidedLighting")
  44386. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44387. __decorate([
  44388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44389. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44390. __decorate([
  44391. BABYLON.serialize()
  44392. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44393. return StandardMaterial;
  44394. }(BABYLON.PushMaterial));
  44395. BABYLON.StandardMaterial = StandardMaterial;
  44396. })(BABYLON || (BABYLON = {}));
  44397. //# sourceMappingURL=babylon.standardMaterial.js.map
  44398. var BABYLON;
  44399. (function (BABYLON) {
  44400. /**
  44401. * Manages the defines for the PBR Material.
  44402. * @hiddenChildren
  44403. */
  44404. var PBRMaterialDefines = /** @class */ (function (_super) {
  44405. __extends(PBRMaterialDefines, _super);
  44406. /**
  44407. * Initializes the PBR Material defines.
  44408. */
  44409. function PBRMaterialDefines() {
  44410. var _this = _super.call(this) || this;
  44411. _this.PBR = true;
  44412. _this.MAINUV1 = false;
  44413. _this.MAINUV2 = false;
  44414. _this.UV1 = false;
  44415. _this.UV2 = false;
  44416. _this.ALBEDO = false;
  44417. _this.ALBEDODIRECTUV = 0;
  44418. _this.VERTEXCOLOR = false;
  44419. _this.AMBIENT = false;
  44420. _this.AMBIENTDIRECTUV = 0;
  44421. _this.AMBIENTINGRAYSCALE = false;
  44422. _this.OPACITY = false;
  44423. _this.VERTEXALPHA = false;
  44424. _this.OPACITYDIRECTUV = 0;
  44425. _this.OPACITYRGB = false;
  44426. _this.ALPHATEST = false;
  44427. _this.DEPTHPREPASS = false;
  44428. _this.ALPHABLEND = false;
  44429. _this.ALPHAFROMALBEDO = false;
  44430. _this.ALPHATESTVALUE = "0.5";
  44431. _this.SPECULAROVERALPHA = false;
  44432. _this.RADIANCEOVERALPHA = false;
  44433. _this.ALPHAFRESNEL = false;
  44434. _this.LINEARALPHAFRESNEL = false;
  44435. _this.PREMULTIPLYALPHA = false;
  44436. _this.EMISSIVE = false;
  44437. _this.EMISSIVEDIRECTUV = 0;
  44438. _this.REFLECTIVITY = false;
  44439. _this.REFLECTIVITYDIRECTUV = 0;
  44440. _this.SPECULARTERM = false;
  44441. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44442. _this.MICROSURFACEAUTOMATIC = false;
  44443. _this.LODBASEDMICROSFURACE = false;
  44444. _this.MICROSURFACEMAP = false;
  44445. _this.MICROSURFACEMAPDIRECTUV = 0;
  44446. _this.METALLICWORKFLOW = false;
  44447. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44448. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44449. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44450. _this.AOSTOREINMETALMAPRED = false;
  44451. _this.ENVIRONMENTBRDF = false;
  44452. _this.NORMAL = false;
  44453. _this.TANGENT = false;
  44454. _this.BUMP = false;
  44455. _this.BUMPDIRECTUV = 0;
  44456. _this.OBJECTSPACE_NORMALMAP = false;
  44457. _this.PARALLAX = false;
  44458. _this.PARALLAXOCCLUSION = false;
  44459. _this.NORMALXYSCALE = true;
  44460. _this.LIGHTMAP = false;
  44461. _this.LIGHTMAPDIRECTUV = 0;
  44462. _this.USELIGHTMAPASSHADOWMAP = false;
  44463. _this.GAMMALIGHTMAP = false;
  44464. _this.REFLECTION = false;
  44465. _this.REFLECTIONMAP_3D = false;
  44466. _this.REFLECTIONMAP_SPHERICAL = false;
  44467. _this.REFLECTIONMAP_PLANAR = false;
  44468. _this.REFLECTIONMAP_CUBIC = false;
  44469. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44470. _this.REFLECTIONMAP_PROJECTION = false;
  44471. _this.REFLECTIONMAP_SKYBOX = false;
  44472. _this.REFLECTIONMAP_EXPLICIT = false;
  44473. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44474. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44475. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44476. _this.INVERTCUBICMAP = false;
  44477. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44478. _this.USESPHERICALINVERTEX = false;
  44479. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44480. _this.LODINREFLECTIONALPHA = false;
  44481. _this.GAMMAREFLECTION = false;
  44482. _this.RADIANCEOCCLUSION = false;
  44483. _this.HORIZONOCCLUSION = false;
  44484. _this.REFRACTION = false;
  44485. _this.REFRACTIONMAP_3D = false;
  44486. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44487. _this.LODINREFRACTIONALPHA = false;
  44488. _this.GAMMAREFRACTION = false;
  44489. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44490. _this.INSTANCES = false;
  44491. _this.NUM_BONE_INFLUENCERS = 0;
  44492. _this.BonesPerMesh = 0;
  44493. _this.NONUNIFORMSCALING = false;
  44494. _this.MORPHTARGETS = false;
  44495. _this.MORPHTARGETS_NORMAL = false;
  44496. _this.MORPHTARGETS_TANGENT = false;
  44497. _this.NUM_MORPH_INFLUENCERS = 0;
  44498. _this.IMAGEPROCESSING = false;
  44499. _this.VIGNETTE = false;
  44500. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44501. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44502. _this.TONEMAPPING = false;
  44503. _this.CONTRAST = false;
  44504. _this.COLORCURVES = false;
  44505. _this.COLORGRADING = false;
  44506. _this.COLORGRADING3D = false;
  44507. _this.SAMPLER3DGREENDEPTH = false;
  44508. _this.SAMPLER3DBGRMAP = false;
  44509. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44510. _this.EXPOSURE = false;
  44511. _this.USEPHYSICALLIGHTFALLOFF = false;
  44512. _this.TWOSIDEDLIGHTING = false;
  44513. _this.SHADOWFLOAT = false;
  44514. _this.CLIPPLANE = false;
  44515. _this.POINTSIZE = false;
  44516. _this.FOG = false;
  44517. _this.LOGARITHMICDEPTH = false;
  44518. _this.FORCENORMALFORWARD = false;
  44519. _this.SPECULARAA = false;
  44520. _this.UNLIT = false;
  44521. _this.rebuild();
  44522. return _this;
  44523. }
  44524. /**
  44525. * Resets the PBR Material defines.
  44526. */
  44527. PBRMaterialDefines.prototype.reset = function () {
  44528. _super.prototype.reset.call(this);
  44529. this.ALPHATESTVALUE = "0.5";
  44530. this.PBR = true;
  44531. };
  44532. return PBRMaterialDefines;
  44533. }(BABYLON.MaterialDefines));
  44534. /**
  44535. * The Physically based material base class of BJS.
  44536. *
  44537. * This offers the main features of a standard PBR material.
  44538. * For more information, please refer to the documentation :
  44539. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44540. */
  44541. var PBRBaseMaterial = /** @class */ (function (_super) {
  44542. __extends(PBRBaseMaterial, _super);
  44543. /**
  44544. * Instantiates a new PBRMaterial instance.
  44545. *
  44546. * @param name The material name
  44547. * @param scene The scene the material will be use in.
  44548. */
  44549. function PBRBaseMaterial(name, scene) {
  44550. var _this = _super.call(this, name, scene) || this;
  44551. /**
  44552. * Intensity of the direct lights e.g. the four lights available in your scene.
  44553. * This impacts both the direct diffuse and specular highlights.
  44554. */
  44555. _this._directIntensity = 1.0;
  44556. /**
  44557. * Intensity of the emissive part of the material.
  44558. * This helps controlling the emissive effect without modifying the emissive color.
  44559. */
  44560. _this._emissiveIntensity = 1.0;
  44561. /**
  44562. * Intensity of the environment e.g. how much the environment will light the object
  44563. * either through harmonics for rough material or through the refelction for shiny ones.
  44564. */
  44565. _this._environmentIntensity = 1.0;
  44566. /**
  44567. * This is a special control allowing the reduction of the specular highlights coming from the
  44568. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44569. */
  44570. _this._specularIntensity = 1.0;
  44571. /**
  44572. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44573. */
  44574. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44575. /**
  44576. * Debug Control allowing disabling the bump map on this material.
  44577. */
  44578. _this._disableBumpMap = false;
  44579. /**
  44580. * AKA Occlusion Texture Intensity in other nomenclature.
  44581. */
  44582. _this._ambientTextureStrength = 1.0;
  44583. /**
  44584. * The color of a material in ambient lighting.
  44585. */
  44586. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44587. /**
  44588. * AKA Diffuse Color in other nomenclature.
  44589. */
  44590. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44591. /**
  44592. * AKA Specular Color in other nomenclature.
  44593. */
  44594. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44595. /**
  44596. * The color applied when light is reflected from a material.
  44597. */
  44598. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44599. /**
  44600. * The color applied when light is emitted from a material.
  44601. */
  44602. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44603. /**
  44604. * AKA Glossiness in other nomenclature.
  44605. */
  44606. _this._microSurface = 0.9;
  44607. /**
  44608. * source material index of refraction (IOR)' / 'destination material IOR.
  44609. */
  44610. _this._indexOfRefraction = 0.66;
  44611. /**
  44612. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44613. */
  44614. _this._invertRefractionY = false;
  44615. /**
  44616. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44617. * Materials half opaque for instance using refraction could benefit from this control.
  44618. */
  44619. _this._linkRefractionWithTransparency = false;
  44620. /**
  44621. * Specifies that the material will use the light map as a show map.
  44622. */
  44623. _this._useLightmapAsShadowmap = false;
  44624. /**
  44625. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44626. * makes the reflect vector face the model (under horizon).
  44627. */
  44628. _this._useHorizonOcclusion = true;
  44629. /**
  44630. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44631. * too much the area relying on ambient texture to define their ambient occlusion.
  44632. */
  44633. _this._useRadianceOcclusion = true;
  44634. /**
  44635. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44636. */
  44637. _this._useAlphaFromAlbedoTexture = false;
  44638. /**
  44639. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44640. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44641. */
  44642. _this._useSpecularOverAlpha = true;
  44643. /**
  44644. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44645. */
  44646. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44647. /**
  44648. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44649. */
  44650. _this._useRoughnessFromMetallicTextureAlpha = true;
  44651. /**
  44652. * Specifies if the metallic texture contains the roughness information in its green channel.
  44653. */
  44654. _this._useRoughnessFromMetallicTextureGreen = false;
  44655. /**
  44656. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44657. */
  44658. _this._useMetallnessFromMetallicTextureBlue = false;
  44659. /**
  44660. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44661. */
  44662. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44663. /**
  44664. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44665. */
  44666. _this._useAmbientInGrayScale = false;
  44667. /**
  44668. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44669. * The material will try to infer what glossiness each pixel should be.
  44670. */
  44671. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44672. /**
  44673. * BJS is using an harcoded light falloff based on a manually sets up range.
  44674. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44675. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44676. */
  44677. _this._usePhysicalLightFalloff = true;
  44678. /**
  44679. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44680. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44681. */
  44682. _this._useRadianceOverAlpha = true;
  44683. /**
  44684. * Allows using an object space normal map (instead of tangent space).
  44685. */
  44686. _this._useObjectSpaceNormalMap = false;
  44687. /**
  44688. * Allows using the bump map in parallax mode.
  44689. */
  44690. _this._useParallax = false;
  44691. /**
  44692. * Allows using the bump map in parallax occlusion mode.
  44693. */
  44694. _this._useParallaxOcclusion = false;
  44695. /**
  44696. * Controls the scale bias of the parallax mode.
  44697. */
  44698. _this._parallaxScaleBias = 0.05;
  44699. /**
  44700. * If sets to true, disables all the lights affecting the material.
  44701. */
  44702. _this._disableLighting = false;
  44703. /**
  44704. * Number of Simultaneous lights allowed on the material.
  44705. */
  44706. _this._maxSimultaneousLights = 4;
  44707. /**
  44708. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44709. */
  44710. _this._invertNormalMapX = false;
  44711. /**
  44712. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44713. */
  44714. _this._invertNormalMapY = false;
  44715. /**
  44716. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44717. */
  44718. _this._twoSidedLighting = false;
  44719. /**
  44720. * Defines the alpha limits in alpha test mode.
  44721. */
  44722. _this._alphaCutOff = 0.4;
  44723. /**
  44724. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44725. */
  44726. _this._forceAlphaTest = false;
  44727. /**
  44728. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44729. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44730. */
  44731. _this._useAlphaFresnel = false;
  44732. /**
  44733. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44734. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44735. */
  44736. _this._useLinearAlphaFresnel = false;
  44737. /**
  44738. * The transparency mode of the material.
  44739. */
  44740. _this._transparencyMode = null;
  44741. /**
  44742. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44743. * from cos thetav and roughness:
  44744. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44745. */
  44746. _this._environmentBRDFTexture = null;
  44747. /**
  44748. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44749. */
  44750. _this._forceIrradianceInFragment = false;
  44751. /**
  44752. * Force normal to face away from face.
  44753. */
  44754. _this._forceNormalForward = false;
  44755. /**
  44756. * Enables specular anti aliasing in the PBR shader.
  44757. * It will both interacts on the Geometry for analytical and IBL lighting.
  44758. * It also prefilter the roughness map based on the bump values.
  44759. */
  44760. _this._enableSpecularAntiAliasing = false;
  44761. /**
  44762. * Stores the available render targets.
  44763. */
  44764. _this._renderTargets = new BABYLON.SmartArray(16);
  44765. /**
  44766. * Sets the global ambient color for the material used in lighting calculations.
  44767. */
  44768. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44769. /**
  44770. * If set to true, no lighting calculations will be applied.
  44771. */
  44772. _this._unlit = false;
  44773. // Setup the default processing configuration to the scene.
  44774. _this._attachImageProcessingConfiguration(null);
  44775. _this.getRenderTargetTextures = function () {
  44776. _this._renderTargets.reset();
  44777. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44778. _this._renderTargets.push(_this._reflectionTexture);
  44779. }
  44780. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44781. _this._renderTargets.push(_this._refractionTexture);
  44782. }
  44783. return _this._renderTargets;
  44784. };
  44785. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44786. return _this;
  44787. }
  44788. /**
  44789. * Attaches a new image processing configuration to the PBR Material.
  44790. * @param configuration
  44791. */
  44792. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44793. var _this = this;
  44794. if (configuration === this._imageProcessingConfiguration) {
  44795. return;
  44796. }
  44797. // Detaches observer.
  44798. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44799. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44800. }
  44801. // Pick the scene configuration if needed.
  44802. if (!configuration) {
  44803. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44804. }
  44805. else {
  44806. this._imageProcessingConfiguration = configuration;
  44807. }
  44808. // Attaches observer.
  44809. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44810. _this._markAllSubMeshesAsImageProcessingDirty();
  44811. });
  44812. };
  44813. /**
  44814. * Gets the name of the material class.
  44815. */
  44816. PBRBaseMaterial.prototype.getClassName = function () {
  44817. return "PBRBaseMaterial";
  44818. };
  44819. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44820. /**
  44821. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44822. */
  44823. get: function () {
  44824. return this._useLogarithmicDepth;
  44825. },
  44826. /**
  44827. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44828. */
  44829. set: function (value) {
  44830. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44831. },
  44832. enumerable: true,
  44833. configurable: true
  44834. });
  44835. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44836. /**
  44837. * Gets the current transparency mode.
  44838. */
  44839. get: function () {
  44840. return this._transparencyMode;
  44841. },
  44842. /**
  44843. * Sets the transparency mode of the material.
  44844. */
  44845. set: function (value) {
  44846. if (this._transparencyMode === value) {
  44847. return;
  44848. }
  44849. this._transparencyMode = value;
  44850. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44851. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44852. },
  44853. enumerable: true,
  44854. configurable: true
  44855. });
  44856. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44857. /**
  44858. * Returns true if alpha blending should be disabled.
  44859. */
  44860. get: function () {
  44861. return (this._linkRefractionWithTransparency ||
  44862. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44863. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44864. },
  44865. enumerable: true,
  44866. configurable: true
  44867. });
  44868. /**
  44869. * Specifies whether or not this material should be rendered in alpha blend mode.
  44870. */
  44871. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44872. if (this._disableAlphaBlending) {
  44873. return false;
  44874. }
  44875. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44876. };
  44877. /**
  44878. * Specifies if the mesh will require alpha blending.
  44879. * @param mesh - BJS mesh.
  44880. */
  44881. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44882. if (this._disableAlphaBlending) {
  44883. return false;
  44884. }
  44885. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44886. };
  44887. /**
  44888. * Specifies whether or not this material should be rendered in alpha test mode.
  44889. */
  44890. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44891. if (this._forceAlphaTest) {
  44892. return true;
  44893. }
  44894. if (this._linkRefractionWithTransparency) {
  44895. return false;
  44896. }
  44897. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44898. };
  44899. /**
  44900. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44901. */
  44902. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44903. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44904. };
  44905. /**
  44906. * Gets the texture used for the alpha test.
  44907. */
  44908. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44909. return this._albedoTexture;
  44910. };
  44911. /**
  44912. * Specifies that the submesh is ready to be used.
  44913. * @param mesh - BJS mesh.
  44914. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44915. * @param useInstances - Specifies that instances should be used.
  44916. * @returns - boolean indicating that the submesh is ready or not.
  44917. */
  44918. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44919. if (subMesh.effect && this.isFrozen) {
  44920. if (this._wasPreviouslyReady) {
  44921. return true;
  44922. }
  44923. }
  44924. if (!subMesh._materialDefines) {
  44925. subMesh._materialDefines = new PBRMaterialDefines();
  44926. }
  44927. var defines = subMesh._materialDefines;
  44928. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44929. if (defines._renderId === this.getScene().getRenderId()) {
  44930. return true;
  44931. }
  44932. }
  44933. var scene = this.getScene();
  44934. var engine = scene.getEngine();
  44935. if (defines._areTexturesDirty) {
  44936. if (scene.texturesEnabled) {
  44937. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44938. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44939. return false;
  44940. }
  44941. }
  44942. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44943. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44944. return false;
  44945. }
  44946. }
  44947. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44948. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44949. return false;
  44950. }
  44951. }
  44952. var reflectionTexture = this._getReflectionTexture();
  44953. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44954. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44955. return false;
  44956. }
  44957. }
  44958. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44959. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44960. return false;
  44961. }
  44962. }
  44963. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44964. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44965. return false;
  44966. }
  44967. }
  44968. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44969. if (this._metallicTexture) {
  44970. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44971. return false;
  44972. }
  44973. }
  44974. else if (this._reflectivityTexture) {
  44975. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44976. return false;
  44977. }
  44978. }
  44979. if (this._microSurfaceTexture) {
  44980. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44981. return false;
  44982. }
  44983. }
  44984. }
  44985. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44986. // Bump texture cannot be not blocking.
  44987. if (!this._bumpTexture.isReady()) {
  44988. return false;
  44989. }
  44990. }
  44991. var refractionTexture = this._getRefractionTexture();
  44992. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44993. if (!refractionTexture.isReadyOrNotBlocking()) {
  44994. return false;
  44995. }
  44996. }
  44997. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44998. // This is blocking.
  44999. if (!this._environmentBRDFTexture.isReady()) {
  45000. return false;
  45001. }
  45002. }
  45003. }
  45004. }
  45005. if (defines._areImageProcessingDirty) {
  45006. if (!this._imageProcessingConfiguration.isReady()) {
  45007. return false;
  45008. }
  45009. }
  45010. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45011. mesh.createNormals(true);
  45012. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45013. }
  45014. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45015. if (effect) {
  45016. scene.resetCachedMaterial();
  45017. subMesh.setEffect(effect, defines);
  45018. this.buildUniformLayout();
  45019. }
  45020. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45021. return false;
  45022. }
  45023. defines._renderId = scene.getRenderId();
  45024. this._wasPreviouslyReady = true;
  45025. return true;
  45026. };
  45027. /**
  45028. * Specifies if the material uses metallic roughness workflow.
  45029. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45030. */
  45031. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45032. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45033. return true;
  45034. }
  45035. return false;
  45036. };
  45037. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45038. if (onCompiled === void 0) { onCompiled = null; }
  45039. if (onError === void 0) { onError = null; }
  45040. if (useInstances === void 0) { useInstances = null; }
  45041. if (useClipPlane === void 0) { useClipPlane = null; }
  45042. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45043. if (!defines.isDirty) {
  45044. return null;
  45045. }
  45046. defines.markAsProcessed();
  45047. var scene = this.getScene();
  45048. var engine = scene.getEngine();
  45049. // Fallbacks
  45050. var fallbacks = new BABYLON.EffectFallbacks();
  45051. var fallbackRank = 0;
  45052. if (defines.USESPHERICALINVERTEX) {
  45053. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45054. }
  45055. if (defines.FOG) {
  45056. fallbacks.addFallback(fallbackRank, "FOG");
  45057. }
  45058. if (defines.SPECULARAA) {
  45059. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45060. }
  45061. if (defines.POINTSIZE) {
  45062. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45063. }
  45064. if (defines.LOGARITHMICDEPTH) {
  45065. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45066. }
  45067. if (defines.PARALLAX) {
  45068. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45069. }
  45070. if (defines.PARALLAXOCCLUSION) {
  45071. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45072. }
  45073. if (defines.ENVIRONMENTBRDF) {
  45074. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45075. }
  45076. if (defines.TANGENT) {
  45077. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45078. }
  45079. if (defines.BUMP) {
  45080. fallbacks.addFallback(fallbackRank++, "BUMP");
  45081. }
  45082. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45083. if (defines.SPECULARTERM) {
  45084. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45085. }
  45086. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45087. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45088. }
  45089. if (defines.LIGHTMAP) {
  45090. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45091. }
  45092. if (defines.NORMAL) {
  45093. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45094. }
  45095. if (defines.AMBIENT) {
  45096. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45097. }
  45098. if (defines.EMISSIVE) {
  45099. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45100. }
  45101. if (defines.VERTEXCOLOR) {
  45102. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45103. }
  45104. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45105. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45106. }
  45107. if (defines.MORPHTARGETS) {
  45108. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45109. }
  45110. //Attributes
  45111. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45112. if (defines.NORMAL) {
  45113. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45114. }
  45115. if (defines.TANGENT) {
  45116. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45117. }
  45118. if (defines.UV1) {
  45119. attribs.push(BABYLON.VertexBuffer.UVKind);
  45120. }
  45121. if (defines.UV2) {
  45122. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45123. }
  45124. if (defines.VERTEXCOLOR) {
  45125. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45126. }
  45127. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45128. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45129. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45130. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45131. "vFogInfos", "vFogColor", "pointSize",
  45132. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45133. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45134. "mBones",
  45135. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45136. "vLightingIntensity",
  45137. "logarithmicDepthConstant",
  45138. "vSphericalX", "vSphericalY", "vSphericalZ",
  45139. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45140. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45141. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45142. "vTangentSpaceParams"
  45143. ];
  45144. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45145. "bumpSampler", "lightmapSampler", "opacitySampler",
  45146. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45147. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45148. "microSurfaceSampler", "environmentBrdfSampler"];
  45149. var uniformBuffers = ["Material", "Scene"];
  45150. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45151. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45152. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45153. uniformsNames: uniforms,
  45154. uniformBuffersNames: uniformBuffers,
  45155. samplers: samplers,
  45156. defines: defines,
  45157. maxSimultaneousLights: this._maxSimultaneousLights
  45158. });
  45159. var join = defines.toString();
  45160. return engine.createEffect("pbr", {
  45161. attributes: attribs,
  45162. uniformsNames: uniforms,
  45163. uniformBuffersNames: uniformBuffers,
  45164. samplers: samplers,
  45165. defines: join,
  45166. fallbacks: fallbacks,
  45167. onCompiled: onCompiled,
  45168. onError: onError,
  45169. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45170. }, engine);
  45171. };
  45172. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45173. if (useInstances === void 0) { useInstances = null; }
  45174. if (useClipPlane === void 0) { useClipPlane = null; }
  45175. var scene = this.getScene();
  45176. var engine = scene.getEngine();
  45177. // Lights
  45178. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45179. defines._needNormals = true;
  45180. // Textures
  45181. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45182. if (defines._areTexturesDirty) {
  45183. defines._needUVs = false;
  45184. if (scene.texturesEnabled) {
  45185. if (scene.getEngine().getCaps().textureLOD) {
  45186. defines.LODBASEDMICROSFURACE = true;
  45187. }
  45188. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45189. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45190. }
  45191. else {
  45192. defines.ALBEDO = false;
  45193. }
  45194. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45195. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45196. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45197. }
  45198. else {
  45199. defines.AMBIENT = false;
  45200. }
  45201. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45202. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45203. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45204. }
  45205. else {
  45206. defines.OPACITY = false;
  45207. }
  45208. var reflectionTexture = this._getReflectionTexture();
  45209. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45210. defines.REFLECTION = true;
  45211. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45212. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45213. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45214. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45215. defines.INVERTCUBICMAP = true;
  45216. }
  45217. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45218. switch (reflectionTexture.coordinatesMode) {
  45219. case BABYLON.Texture.EXPLICIT_MODE:
  45220. defines.REFLECTIONMAP_EXPLICIT = true;
  45221. break;
  45222. case BABYLON.Texture.PLANAR_MODE:
  45223. defines.REFLECTIONMAP_PLANAR = true;
  45224. break;
  45225. case BABYLON.Texture.PROJECTION_MODE:
  45226. defines.REFLECTIONMAP_PROJECTION = true;
  45227. break;
  45228. case BABYLON.Texture.SKYBOX_MODE:
  45229. defines.REFLECTIONMAP_SKYBOX = true;
  45230. break;
  45231. case BABYLON.Texture.SPHERICAL_MODE:
  45232. defines.REFLECTIONMAP_SPHERICAL = true;
  45233. break;
  45234. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45235. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45236. break;
  45237. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45238. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45239. break;
  45240. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45241. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45242. break;
  45243. case BABYLON.Texture.CUBIC_MODE:
  45244. case BABYLON.Texture.INVCUBIC_MODE:
  45245. default:
  45246. defines.REFLECTIONMAP_CUBIC = true;
  45247. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45248. break;
  45249. }
  45250. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45251. if (reflectionTexture.sphericalPolynomial) {
  45252. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45253. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45254. defines.USESPHERICALINVERTEX = false;
  45255. }
  45256. else {
  45257. defines.USESPHERICALINVERTEX = true;
  45258. }
  45259. }
  45260. }
  45261. }
  45262. else {
  45263. defines.REFLECTION = false;
  45264. defines.REFLECTIONMAP_3D = false;
  45265. defines.REFLECTIONMAP_SPHERICAL = false;
  45266. defines.REFLECTIONMAP_PLANAR = false;
  45267. defines.REFLECTIONMAP_CUBIC = false;
  45268. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45269. defines.REFLECTIONMAP_PROJECTION = false;
  45270. defines.REFLECTIONMAP_SKYBOX = false;
  45271. defines.REFLECTIONMAP_EXPLICIT = false;
  45272. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45273. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45274. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45275. defines.INVERTCUBICMAP = false;
  45276. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45277. defines.USESPHERICALINVERTEX = false;
  45278. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45279. defines.LODINREFLECTIONALPHA = false;
  45280. defines.GAMMAREFLECTION = false;
  45281. }
  45282. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45283. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45284. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45285. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45286. }
  45287. else {
  45288. defines.LIGHTMAP = false;
  45289. }
  45290. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45291. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45292. }
  45293. else {
  45294. defines.EMISSIVE = false;
  45295. }
  45296. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45297. if (this._metallicTexture) {
  45298. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45299. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45300. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45301. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45302. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45303. }
  45304. else if (this._reflectivityTexture) {
  45305. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45306. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45307. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45308. }
  45309. else {
  45310. defines.REFLECTIVITY = false;
  45311. }
  45312. if (this._microSurfaceTexture) {
  45313. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45314. }
  45315. else {
  45316. defines.MICROSURFACEMAP = false;
  45317. }
  45318. }
  45319. else {
  45320. defines.REFLECTIVITY = false;
  45321. defines.MICROSURFACEMAP = false;
  45322. }
  45323. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45324. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45325. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45326. defines.PARALLAX = true;
  45327. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45328. }
  45329. else {
  45330. defines.PARALLAX = false;
  45331. }
  45332. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45333. }
  45334. else {
  45335. defines.BUMP = false;
  45336. }
  45337. var refractionTexture = this._getRefractionTexture();
  45338. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45339. defines.REFRACTION = true;
  45340. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45341. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45342. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45343. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45344. if (this._linkRefractionWithTransparency) {
  45345. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45346. }
  45347. }
  45348. else {
  45349. defines.REFRACTION = false;
  45350. }
  45351. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45352. defines.ENVIRONMENTBRDF = true;
  45353. }
  45354. else {
  45355. defines.ENVIRONMENTBRDF = false;
  45356. }
  45357. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45358. defines.ALPHAFROMALBEDO = true;
  45359. }
  45360. else {
  45361. defines.ALPHAFROMALBEDO = false;
  45362. }
  45363. }
  45364. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45365. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45366. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45367. if (!this.backFaceCulling && this._twoSidedLighting) {
  45368. defines.TWOSIDEDLIGHTING = true;
  45369. }
  45370. else {
  45371. defines.TWOSIDEDLIGHTING = false;
  45372. }
  45373. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45374. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45375. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45376. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45377. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45378. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45379. }
  45380. if (defines._areImageProcessingDirty) {
  45381. this._imageProcessingConfiguration.prepareDefines(defines);
  45382. }
  45383. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45384. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45385. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45386. // Misc.
  45387. if (defines._areMiscDirty) {
  45388. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45389. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45390. }
  45391. // Values that need to be evaluated on every frame
  45392. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45393. // Attribs
  45394. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45395. };
  45396. /**
  45397. * Force shader compilation
  45398. */
  45399. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45400. var _this = this;
  45401. var localOptions = __assign({ clipPlane: false }, options);
  45402. var defines = new PBRMaterialDefines();
  45403. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45404. if (effect.isReady()) {
  45405. if (onCompiled) {
  45406. onCompiled(this);
  45407. }
  45408. }
  45409. else {
  45410. effect.onCompileObservable.add(function () {
  45411. if (onCompiled) {
  45412. onCompiled(_this);
  45413. }
  45414. });
  45415. }
  45416. };
  45417. /**
  45418. * Initializes the uniform buffer layout for the shader.
  45419. */
  45420. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45421. // Order is important !
  45422. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45423. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45424. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45425. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45426. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45427. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45428. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45429. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45430. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45431. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45432. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45433. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45434. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45435. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45436. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45437. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45438. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45439. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45440. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45441. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45442. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45443. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45444. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45445. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45446. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45447. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45448. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45449. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45450. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45451. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45452. this._uniformBuffer.addUniform("pointSize", 1);
  45453. this._uniformBuffer.create();
  45454. };
  45455. /**
  45456. * Unbinds the textures.
  45457. */
  45458. PBRBaseMaterial.prototype.unbind = function () {
  45459. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45460. this._uniformBuffer.setTexture("reflectionSampler", null);
  45461. }
  45462. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45463. this._uniformBuffer.setTexture("refractionSampler", null);
  45464. }
  45465. _super.prototype.unbind.call(this);
  45466. };
  45467. /**
  45468. * Binds the submesh data.
  45469. * @param world - The world matrix.
  45470. * @param mesh - The BJS mesh.
  45471. * @param subMesh - A submesh of the BJS mesh.
  45472. */
  45473. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45474. var scene = this.getScene();
  45475. var defines = subMesh._materialDefines;
  45476. if (!defines) {
  45477. return;
  45478. }
  45479. var effect = subMesh.effect;
  45480. if (!effect) {
  45481. return;
  45482. }
  45483. this._activeEffect = effect;
  45484. // Matrices
  45485. this.bindOnlyWorldMatrix(world);
  45486. // Normal Matrix
  45487. if (defines.OBJECTSPACE_NORMALMAP) {
  45488. world.toNormalMatrix(this._normalMatrix);
  45489. this.bindOnlyNormalMatrix(this._normalMatrix);
  45490. }
  45491. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45492. // Bones
  45493. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45494. var reflectionTexture = null;
  45495. if (mustRebind) {
  45496. this._uniformBuffer.bindToEffect(effect, "Material");
  45497. this.bindViewProjection(effect);
  45498. reflectionTexture = this._getReflectionTexture();
  45499. var refractionTexture = this._getRefractionTexture();
  45500. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45501. // Texture uniforms
  45502. if (scene.texturesEnabled) {
  45503. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45504. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45505. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45506. }
  45507. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45508. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45509. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45510. }
  45511. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45512. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45513. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45514. }
  45515. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45516. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45517. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45518. if (reflectionTexture.boundingBoxSize) {
  45519. var cubeTexture = reflectionTexture;
  45520. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45521. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45522. }
  45523. var polynomials = reflectionTexture.sphericalPolynomial;
  45524. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45525. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45526. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45527. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45528. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45529. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45530. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45531. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45532. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45533. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45534. }
  45535. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45536. }
  45537. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45538. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45539. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45540. }
  45541. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45542. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45543. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45544. }
  45545. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45546. if (this._metallicTexture) {
  45547. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45548. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45549. }
  45550. else if (this._reflectivityTexture) {
  45551. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45552. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45553. }
  45554. if (this._microSurfaceTexture) {
  45555. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45556. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45557. }
  45558. }
  45559. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45560. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45561. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45562. if (scene._mirroredCameraPosition) {
  45563. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45564. }
  45565. else {
  45566. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45567. }
  45568. }
  45569. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45570. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45571. var depth = 1.0;
  45572. if (!refractionTexture.isCube) {
  45573. if (refractionTexture.depth) {
  45574. depth = refractionTexture.depth;
  45575. }
  45576. }
  45577. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45578. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45579. }
  45580. }
  45581. // Point size
  45582. if (this.pointsCloud) {
  45583. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45584. }
  45585. // Colors
  45586. if (defines.METALLICWORKFLOW) {
  45587. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45588. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45589. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45590. }
  45591. else {
  45592. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45593. }
  45594. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45595. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45596. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45597. // Misc
  45598. this._lightingInfos.x = this._directIntensity;
  45599. this._lightingInfos.y = this._emissiveIntensity;
  45600. this._lightingInfos.z = this._environmentIntensity;
  45601. this._lightingInfos.w = this._specularIntensity;
  45602. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45603. }
  45604. // Textures
  45605. if (scene.texturesEnabled) {
  45606. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45607. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45608. }
  45609. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45610. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45611. }
  45612. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45613. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45614. }
  45615. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45616. if (defines.LODBASEDMICROSFURACE) {
  45617. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45618. }
  45619. else {
  45620. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45621. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45622. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45623. }
  45624. }
  45625. if (defines.ENVIRONMENTBRDF) {
  45626. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45627. }
  45628. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45629. if (defines.LODBASEDMICROSFURACE) {
  45630. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45631. }
  45632. else {
  45633. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45634. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45635. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45636. }
  45637. }
  45638. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45639. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45640. }
  45641. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45642. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45643. }
  45644. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45645. if (this._metallicTexture) {
  45646. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45647. }
  45648. else if (this._reflectivityTexture) {
  45649. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45650. }
  45651. if (this._microSurfaceTexture) {
  45652. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45653. }
  45654. }
  45655. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45656. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45657. }
  45658. }
  45659. // Clip plane
  45660. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45661. // Colors
  45662. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45663. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45664. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45665. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45666. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45667. }
  45668. if (mustRebind || !this.isFrozen) {
  45669. // Lights
  45670. if (scene.lightsEnabled && !this._disableLighting) {
  45671. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45672. }
  45673. // View
  45674. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45675. this.bindView(effect);
  45676. }
  45677. // Fog
  45678. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45679. // Morph targets
  45680. if (defines.NUM_MORPH_INFLUENCERS) {
  45681. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45682. }
  45683. // image processing
  45684. this._imageProcessingConfiguration.bind(this._activeEffect);
  45685. // Log. depth
  45686. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45687. }
  45688. this._uniformBuffer.update();
  45689. this._afterBind(mesh, this._activeEffect);
  45690. };
  45691. /**
  45692. * Returns the animatable textures.
  45693. * @returns - Array of animatable textures.
  45694. */
  45695. PBRBaseMaterial.prototype.getAnimatables = function () {
  45696. var results = [];
  45697. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45698. results.push(this._albedoTexture);
  45699. }
  45700. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45701. results.push(this._ambientTexture);
  45702. }
  45703. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45704. results.push(this._opacityTexture);
  45705. }
  45706. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45707. results.push(this._reflectionTexture);
  45708. }
  45709. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45710. results.push(this._emissiveTexture);
  45711. }
  45712. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45713. results.push(this._metallicTexture);
  45714. }
  45715. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45716. results.push(this._reflectivityTexture);
  45717. }
  45718. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45719. results.push(this._bumpTexture);
  45720. }
  45721. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45722. results.push(this._lightmapTexture);
  45723. }
  45724. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45725. results.push(this._refractionTexture);
  45726. }
  45727. return results;
  45728. };
  45729. /**
  45730. * Returns the texture used for reflections.
  45731. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45732. */
  45733. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45734. if (this._reflectionTexture) {
  45735. return this._reflectionTexture;
  45736. }
  45737. return this.getScene().environmentTexture;
  45738. };
  45739. /**
  45740. * Returns the texture used for refraction or null if none is used.
  45741. * @returns - Refection texture if present. If no refraction texture and refraction
  45742. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45743. */
  45744. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45745. if (this._refractionTexture) {
  45746. return this._refractionTexture;
  45747. }
  45748. if (this._linkRefractionWithTransparency) {
  45749. return this.getScene().environmentTexture;
  45750. }
  45751. return null;
  45752. };
  45753. /**
  45754. * Disposes the resources of the material.
  45755. * @param forceDisposeEffect - Forces the disposal of effects.
  45756. * @param forceDisposeTextures - Forces the disposal of all textures.
  45757. */
  45758. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45759. if (forceDisposeTextures) {
  45760. if (this._albedoTexture) {
  45761. this._albedoTexture.dispose();
  45762. }
  45763. if (this._ambientTexture) {
  45764. this._ambientTexture.dispose();
  45765. }
  45766. if (this._opacityTexture) {
  45767. this._opacityTexture.dispose();
  45768. }
  45769. if (this._reflectionTexture) {
  45770. this._reflectionTexture.dispose();
  45771. }
  45772. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45773. this._environmentBRDFTexture.dispose();
  45774. }
  45775. if (this._emissiveTexture) {
  45776. this._emissiveTexture.dispose();
  45777. }
  45778. if (this._metallicTexture) {
  45779. this._metallicTexture.dispose();
  45780. }
  45781. if (this._reflectivityTexture) {
  45782. this._reflectivityTexture.dispose();
  45783. }
  45784. if (this._bumpTexture) {
  45785. this._bumpTexture.dispose();
  45786. }
  45787. if (this._lightmapTexture) {
  45788. this._lightmapTexture.dispose();
  45789. }
  45790. if (this._refractionTexture) {
  45791. this._refractionTexture.dispose();
  45792. }
  45793. }
  45794. this._renderTargets.dispose();
  45795. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45796. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45797. }
  45798. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45799. };
  45800. /**
  45801. * Stores the reflectivity values based on metallic roughness workflow.
  45802. */
  45803. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45804. __decorate([
  45805. BABYLON.serializeAsImageProcessingConfiguration()
  45806. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45807. __decorate([
  45808. BABYLON.serialize()
  45809. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45810. __decorate([
  45811. BABYLON.serialize()
  45812. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45813. return PBRBaseMaterial;
  45814. }(BABYLON.PushMaterial));
  45815. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45816. })(BABYLON || (BABYLON = {}));
  45817. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45818. var BABYLON;
  45819. (function (BABYLON) {
  45820. /**
  45821. * The Physically based simple base material of BJS.
  45822. *
  45823. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45824. * It is used as the base class for both the specGloss and metalRough conventions.
  45825. */
  45826. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45827. __extends(PBRBaseSimpleMaterial, _super);
  45828. /**
  45829. * Instantiates a new PBRMaterial instance.
  45830. *
  45831. * @param name The material name
  45832. * @param scene The scene the material will be use in.
  45833. */
  45834. function PBRBaseSimpleMaterial(name, scene) {
  45835. var _this = _super.call(this, name, scene) || this;
  45836. /**
  45837. * Number of Simultaneous lights allowed on the material.
  45838. */
  45839. _this.maxSimultaneousLights = 4;
  45840. /**
  45841. * If sets to true, disables all the lights affecting the material.
  45842. */
  45843. _this.disableLighting = false;
  45844. /**
  45845. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45846. */
  45847. _this.invertNormalMapX = false;
  45848. /**
  45849. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45850. */
  45851. _this.invertNormalMapY = false;
  45852. /**
  45853. * Emissivie color used to self-illuminate the model.
  45854. */
  45855. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45856. /**
  45857. * Occlusion Channel Strenght.
  45858. */
  45859. _this.occlusionStrength = 1.0;
  45860. _this.useLightmapAsShadowmap = false;
  45861. _this._useAlphaFromAlbedoTexture = true;
  45862. _this._useAmbientInGrayScale = true;
  45863. return _this;
  45864. }
  45865. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45866. /**
  45867. * Gets the current double sided mode.
  45868. */
  45869. get: function () {
  45870. return this._twoSidedLighting;
  45871. },
  45872. /**
  45873. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45874. */
  45875. set: function (value) {
  45876. if (this._twoSidedLighting === value) {
  45877. return;
  45878. }
  45879. this._twoSidedLighting = value;
  45880. this.backFaceCulling = !value;
  45881. this._markAllSubMeshesAsTexturesDirty();
  45882. },
  45883. enumerable: true,
  45884. configurable: true
  45885. });
  45886. /**
  45887. * Return the active textures of the material.
  45888. */
  45889. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45890. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45891. if (this.environmentTexture) {
  45892. activeTextures.push(this.environmentTexture);
  45893. }
  45894. if (this.normalTexture) {
  45895. activeTextures.push(this.normalTexture);
  45896. }
  45897. if (this.emissiveTexture) {
  45898. activeTextures.push(this.emissiveTexture);
  45899. }
  45900. if (this.occlusionTexture) {
  45901. activeTextures.push(this.occlusionTexture);
  45902. }
  45903. if (this.lightmapTexture) {
  45904. activeTextures.push(this.lightmapTexture);
  45905. }
  45906. return activeTextures;
  45907. };
  45908. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45909. if (_super.prototype.hasTexture.call(this, texture)) {
  45910. return true;
  45911. }
  45912. if (this.lightmapTexture === texture) {
  45913. return true;
  45914. }
  45915. return false;
  45916. };
  45917. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45918. return "PBRBaseSimpleMaterial";
  45919. };
  45920. __decorate([
  45921. BABYLON.serialize(),
  45922. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45923. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45924. __decorate([
  45925. BABYLON.serialize(),
  45926. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45927. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45928. __decorate([
  45929. BABYLON.serializeAsTexture(),
  45930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45931. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45932. __decorate([
  45933. BABYLON.serialize(),
  45934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45935. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45936. __decorate([
  45937. BABYLON.serialize(),
  45938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45939. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45940. __decorate([
  45941. BABYLON.serializeAsTexture(),
  45942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45943. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45944. __decorate([
  45945. BABYLON.serializeAsColor3("emissive"),
  45946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45947. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45948. __decorate([
  45949. BABYLON.serializeAsTexture(),
  45950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45951. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45952. __decorate([
  45953. BABYLON.serialize(),
  45954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45955. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45956. __decorate([
  45957. BABYLON.serializeAsTexture(),
  45958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45959. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45960. __decorate([
  45961. BABYLON.serialize(),
  45962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45963. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45964. __decorate([
  45965. BABYLON.serialize()
  45966. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45967. __decorate([
  45968. BABYLON.serializeAsTexture(),
  45969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45970. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45971. __decorate([
  45972. BABYLON.serialize(),
  45973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45974. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45975. return PBRBaseSimpleMaterial;
  45976. }(BABYLON.PBRBaseMaterial));
  45977. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45978. })(BABYLON || (BABYLON = {}));
  45979. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45980. var BABYLON;
  45981. (function (BABYLON) {
  45982. /**
  45983. * The Physically based material of BJS.
  45984. *
  45985. * This offers the main features of a standard PBR material.
  45986. * For more information, please refer to the documentation :
  45987. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45988. */
  45989. var PBRMaterial = /** @class */ (function (_super) {
  45990. __extends(PBRMaterial, _super);
  45991. /**
  45992. * Instantiates a new PBRMaterial instance.
  45993. *
  45994. * @param name The material name
  45995. * @param scene The scene the material will be use in.
  45996. */
  45997. function PBRMaterial(name, scene) {
  45998. var _this = _super.call(this, name, scene) || this;
  45999. /**
  46000. * Intensity of the direct lights e.g. the four lights available in your scene.
  46001. * This impacts both the direct diffuse and specular highlights.
  46002. */
  46003. _this.directIntensity = 1.0;
  46004. /**
  46005. * Intensity of the emissive part of the material.
  46006. * This helps controlling the emissive effect without modifying the emissive color.
  46007. */
  46008. _this.emissiveIntensity = 1.0;
  46009. /**
  46010. * Intensity of the environment e.g. how much the environment will light the object
  46011. * either through harmonics for rough material or through the refelction for shiny ones.
  46012. */
  46013. _this.environmentIntensity = 1.0;
  46014. /**
  46015. * This is a special control allowing the reduction of the specular highlights coming from the
  46016. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46017. */
  46018. _this.specularIntensity = 1.0;
  46019. /**
  46020. * Debug Control allowing disabling the bump map on this material.
  46021. */
  46022. _this.disableBumpMap = false;
  46023. /**
  46024. * AKA Occlusion Texture Intensity in other nomenclature.
  46025. */
  46026. _this.ambientTextureStrength = 1.0;
  46027. /**
  46028. * The color of a material in ambient lighting.
  46029. */
  46030. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46031. /**
  46032. * AKA Diffuse Color in other nomenclature.
  46033. */
  46034. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46035. /**
  46036. * AKA Specular Color in other nomenclature.
  46037. */
  46038. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46039. /**
  46040. * The color reflected from the material.
  46041. */
  46042. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46043. /**
  46044. * The color emitted from the material.
  46045. */
  46046. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46047. /**
  46048. * AKA Glossiness in other nomenclature.
  46049. */
  46050. _this.microSurface = 1.0;
  46051. /**
  46052. * source material index of refraction (IOR)' / 'destination material IOR.
  46053. */
  46054. _this.indexOfRefraction = 0.66;
  46055. /**
  46056. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46057. */
  46058. _this.invertRefractionY = false;
  46059. /**
  46060. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46061. * Materials half opaque for instance using refraction could benefit from this control.
  46062. */
  46063. _this.linkRefractionWithTransparency = false;
  46064. _this.useLightmapAsShadowmap = false;
  46065. /**
  46066. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46067. */
  46068. _this.useAlphaFromAlbedoTexture = false;
  46069. /**
  46070. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46071. */
  46072. _this.forceAlphaTest = false;
  46073. /**
  46074. * Defines the alpha limits in alpha test mode.
  46075. */
  46076. _this.alphaCutOff = 0.4;
  46077. /**
  46078. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  46079. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46080. */
  46081. _this.useSpecularOverAlpha = true;
  46082. /**
  46083. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46084. */
  46085. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46086. /**
  46087. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46088. */
  46089. _this.useRoughnessFromMetallicTextureAlpha = true;
  46090. /**
  46091. * Specifies if the metallic texture contains the roughness information in its green channel.
  46092. */
  46093. _this.useRoughnessFromMetallicTextureGreen = false;
  46094. /**
  46095. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46096. */
  46097. _this.useMetallnessFromMetallicTextureBlue = false;
  46098. /**
  46099. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46100. */
  46101. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46102. /**
  46103. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46104. */
  46105. _this.useAmbientInGrayScale = false;
  46106. /**
  46107. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46108. * The material will try to infer what glossiness each pixel should be.
  46109. */
  46110. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46111. /**
  46112. * BJS is using an harcoded light falloff based on a manually sets up range.
  46113. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46114. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46115. */
  46116. _this.usePhysicalLightFalloff = true;
  46117. /**
  46118. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46119. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46120. */
  46121. _this.useRadianceOverAlpha = true;
  46122. /**
  46123. * Allows using an object space normal map (instead of tangent space).
  46124. */
  46125. _this.useObjectSpaceNormalMap = false;
  46126. /**
  46127. * Allows using the bump map in parallax mode.
  46128. */
  46129. _this.useParallax = false;
  46130. /**
  46131. * Allows using the bump map in parallax occlusion mode.
  46132. */
  46133. _this.useParallaxOcclusion = false;
  46134. /**
  46135. * Controls the scale bias of the parallax mode.
  46136. */
  46137. _this.parallaxScaleBias = 0.05;
  46138. /**
  46139. * If sets to true, disables all the lights affecting the material.
  46140. */
  46141. _this.disableLighting = false;
  46142. /**
  46143. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46144. */
  46145. _this.forceIrradianceInFragment = false;
  46146. /**
  46147. * Number of Simultaneous lights allowed on the material.
  46148. */
  46149. _this.maxSimultaneousLights = 4;
  46150. /**
  46151. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46152. */
  46153. _this.invertNormalMapX = false;
  46154. /**
  46155. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46156. */
  46157. _this.invertNormalMapY = false;
  46158. /**
  46159. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46160. */
  46161. _this.twoSidedLighting = false;
  46162. /**
  46163. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46164. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46165. */
  46166. _this.useAlphaFresnel = false;
  46167. /**
  46168. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46169. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46170. */
  46171. _this.useLinearAlphaFresnel = false;
  46172. /**
  46173. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46174. * And/Or occlude the blended part.
  46175. */
  46176. _this.environmentBRDFTexture = null;
  46177. /**
  46178. * Force normal to face away from face.
  46179. */
  46180. _this.forceNormalForward = false;
  46181. /**
  46182. * Enables specular anti aliasing in the PBR shader.
  46183. * It will both interacts on the Geometry for analytical and IBL lighting.
  46184. * It also prefilter the roughness map based on the bump values.
  46185. */
  46186. _this.enableSpecularAntiAliasing = false;
  46187. /**
  46188. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46189. * makes the reflect vector face the model (under horizon).
  46190. */
  46191. _this.useHorizonOcclusion = true;
  46192. /**
  46193. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46194. * too much the area relying on ambient texture to define their ambient occlusion.
  46195. */
  46196. _this.useRadianceOcclusion = true;
  46197. /**
  46198. * If set to true, no lighting calculations will be applied.
  46199. */
  46200. _this.unlit = false;
  46201. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46202. return _this;
  46203. }
  46204. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  46205. /**
  46206. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46207. */
  46208. get: function () {
  46209. return this._PBRMATERIAL_OPAQUE;
  46210. },
  46211. enumerable: true,
  46212. configurable: true
  46213. });
  46214. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  46215. /**
  46216. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46217. */
  46218. get: function () {
  46219. return this._PBRMATERIAL_ALPHATEST;
  46220. },
  46221. enumerable: true,
  46222. configurable: true
  46223. });
  46224. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46225. /**
  46226. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46227. */
  46228. get: function () {
  46229. return this._PBRMATERIAL_ALPHABLEND;
  46230. },
  46231. enumerable: true,
  46232. configurable: true
  46233. });
  46234. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46235. /**
  46236. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46237. * They are also discarded below the alpha cutoff threshold to improve performances.
  46238. */
  46239. get: function () {
  46240. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46241. },
  46242. enumerable: true,
  46243. configurable: true
  46244. });
  46245. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46246. /**
  46247. * Gets the image processing configuration used either in this material.
  46248. */
  46249. get: function () {
  46250. return this._imageProcessingConfiguration;
  46251. },
  46252. /**
  46253. * Sets the Default image processing configuration used either in the this material.
  46254. *
  46255. * If sets to null, the scene one is in use.
  46256. */
  46257. set: function (value) {
  46258. this._attachImageProcessingConfiguration(value);
  46259. // Ensure the effect will be rebuilt.
  46260. this._markAllSubMeshesAsTexturesDirty();
  46261. },
  46262. enumerable: true,
  46263. configurable: true
  46264. });
  46265. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46266. /**
  46267. * Gets wether the color curves effect is enabled.
  46268. */
  46269. get: function () {
  46270. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46271. },
  46272. /**
  46273. * Sets wether the color curves effect is enabled.
  46274. */
  46275. set: function (value) {
  46276. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46277. },
  46278. enumerable: true,
  46279. configurable: true
  46280. });
  46281. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46282. /**
  46283. * Gets wether the color grading effect is enabled.
  46284. */
  46285. get: function () {
  46286. return this.imageProcessingConfiguration.colorGradingEnabled;
  46287. },
  46288. /**
  46289. * Gets wether the color grading effect is enabled.
  46290. */
  46291. set: function (value) {
  46292. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46293. },
  46294. enumerable: true,
  46295. configurable: true
  46296. });
  46297. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46298. /**
  46299. * Gets wether tonemapping is enabled or not.
  46300. */
  46301. get: function () {
  46302. return this._imageProcessingConfiguration.toneMappingEnabled;
  46303. },
  46304. /**
  46305. * Sets wether tonemapping is enabled or not
  46306. */
  46307. set: function (value) {
  46308. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46309. },
  46310. enumerable: true,
  46311. configurable: true
  46312. });
  46313. ;
  46314. ;
  46315. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46316. /**
  46317. * The camera exposure used on this material.
  46318. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46319. * This corresponds to a photographic exposure.
  46320. */
  46321. get: function () {
  46322. return this._imageProcessingConfiguration.exposure;
  46323. },
  46324. /**
  46325. * The camera exposure used on this material.
  46326. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46327. * This corresponds to a photographic exposure.
  46328. */
  46329. set: function (value) {
  46330. this._imageProcessingConfiguration.exposure = value;
  46331. },
  46332. enumerable: true,
  46333. configurable: true
  46334. });
  46335. ;
  46336. ;
  46337. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46338. /**
  46339. * Gets The camera contrast used on this material.
  46340. */
  46341. get: function () {
  46342. return this._imageProcessingConfiguration.contrast;
  46343. },
  46344. /**
  46345. * Sets The camera contrast used on this material.
  46346. */
  46347. set: function (value) {
  46348. this._imageProcessingConfiguration.contrast = value;
  46349. },
  46350. enumerable: true,
  46351. configurable: true
  46352. });
  46353. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46354. /**
  46355. * Gets the Color Grading 2D Lookup Texture.
  46356. */
  46357. get: function () {
  46358. return this._imageProcessingConfiguration.colorGradingTexture;
  46359. },
  46360. /**
  46361. * Sets the Color Grading 2D Lookup Texture.
  46362. */
  46363. set: function (value) {
  46364. this._imageProcessingConfiguration.colorGradingTexture = value;
  46365. },
  46366. enumerable: true,
  46367. configurable: true
  46368. });
  46369. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46370. /**
  46371. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46372. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46373. * 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;
  46374. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46375. */
  46376. get: function () {
  46377. return this._imageProcessingConfiguration.colorCurves;
  46378. },
  46379. /**
  46380. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46381. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46382. * 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;
  46383. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46384. */
  46385. set: function (value) {
  46386. this._imageProcessingConfiguration.colorCurves = value;
  46387. },
  46388. enumerable: true,
  46389. configurable: true
  46390. });
  46391. /**
  46392. * Returns the name of this material class.
  46393. */
  46394. PBRMaterial.prototype.getClassName = function () {
  46395. return "PBRMaterial";
  46396. };
  46397. /**
  46398. * Returns an array of the actively used textures.
  46399. * @returns - Array of BaseTextures
  46400. */
  46401. PBRMaterial.prototype.getActiveTextures = function () {
  46402. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46403. if (this._albedoTexture) {
  46404. activeTextures.push(this._albedoTexture);
  46405. }
  46406. if (this._ambientTexture) {
  46407. activeTextures.push(this._ambientTexture);
  46408. }
  46409. if (this._opacityTexture) {
  46410. activeTextures.push(this._opacityTexture);
  46411. }
  46412. if (this._reflectionTexture) {
  46413. activeTextures.push(this._reflectionTexture);
  46414. }
  46415. if (this._emissiveTexture) {
  46416. activeTextures.push(this._emissiveTexture);
  46417. }
  46418. if (this._reflectivityTexture) {
  46419. activeTextures.push(this._reflectivityTexture);
  46420. }
  46421. if (this._metallicTexture) {
  46422. activeTextures.push(this._metallicTexture);
  46423. }
  46424. if (this._microSurfaceTexture) {
  46425. activeTextures.push(this._microSurfaceTexture);
  46426. }
  46427. if (this._bumpTexture) {
  46428. activeTextures.push(this._bumpTexture);
  46429. }
  46430. if (this._lightmapTexture) {
  46431. activeTextures.push(this._lightmapTexture);
  46432. }
  46433. if (this._refractionTexture) {
  46434. activeTextures.push(this._refractionTexture);
  46435. }
  46436. return activeTextures;
  46437. };
  46438. /**
  46439. * Checks to see if a texture is used in the material.
  46440. * @param texture - Base texture to use.
  46441. * @returns - Boolean specifying if a texture is used in the material.
  46442. */
  46443. PBRMaterial.prototype.hasTexture = function (texture) {
  46444. if (_super.prototype.hasTexture.call(this, texture)) {
  46445. return true;
  46446. }
  46447. if (this._albedoTexture === texture) {
  46448. return true;
  46449. }
  46450. if (this._ambientTexture === texture) {
  46451. return true;
  46452. }
  46453. if (this._opacityTexture === texture) {
  46454. return true;
  46455. }
  46456. if (this._reflectionTexture === texture) {
  46457. return true;
  46458. }
  46459. if (this._reflectivityTexture === texture) {
  46460. return true;
  46461. }
  46462. if (this._metallicTexture === texture) {
  46463. return true;
  46464. }
  46465. if (this._microSurfaceTexture === texture) {
  46466. return true;
  46467. }
  46468. if (this._bumpTexture === texture) {
  46469. return true;
  46470. }
  46471. if (this._lightmapTexture === texture) {
  46472. return true;
  46473. }
  46474. if (this._refractionTexture === texture) {
  46475. return true;
  46476. }
  46477. return false;
  46478. };
  46479. /**
  46480. * Makes a duplicate of the current material.
  46481. * @param name - name to use for the new material.
  46482. */
  46483. PBRMaterial.prototype.clone = function (name) {
  46484. var _this = this;
  46485. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46486. clone.id = name;
  46487. clone.name = name;
  46488. return clone;
  46489. };
  46490. /**
  46491. * Serializes this PBR Material.
  46492. * @returns - An object with the serialized material.
  46493. */
  46494. PBRMaterial.prototype.serialize = function () {
  46495. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46496. serializationObject.customType = "BABYLON.PBRMaterial";
  46497. return serializationObject;
  46498. };
  46499. // Statics
  46500. /**
  46501. * Parses a PBR Material from a serialized object.
  46502. * @param source - Serialized object.
  46503. * @param scene - BJS scene instance.
  46504. * @param rootUrl - url for the scene object
  46505. * @returns - PBRMaterial
  46506. */
  46507. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46508. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46509. };
  46510. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46511. /**
  46512. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46513. */
  46514. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46515. /**
  46516. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46517. */
  46518. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46519. /**
  46520. * 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.
  46521. * They are also discarded below the alpha cutoff threshold to improve performances.
  46522. */
  46523. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46524. __decorate([
  46525. BABYLON.serialize(),
  46526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46527. ], PBRMaterial.prototype, "directIntensity", void 0);
  46528. __decorate([
  46529. BABYLON.serialize(),
  46530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46531. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46532. __decorate([
  46533. BABYLON.serialize(),
  46534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46535. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46536. __decorate([
  46537. BABYLON.serialize(),
  46538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46539. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46540. __decorate([
  46541. BABYLON.serialize(),
  46542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46543. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46544. __decorate([
  46545. BABYLON.serializeAsTexture(),
  46546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46547. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46548. __decorate([
  46549. BABYLON.serializeAsTexture(),
  46550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46551. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46552. __decorate([
  46553. BABYLON.serialize(),
  46554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46555. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46556. __decorate([
  46557. BABYLON.serializeAsTexture(),
  46558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46559. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46560. __decorate([
  46561. BABYLON.serializeAsTexture(),
  46562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46563. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46564. __decorate([
  46565. BABYLON.serializeAsTexture(),
  46566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46567. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46568. __decorate([
  46569. BABYLON.serializeAsTexture(),
  46570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46571. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46572. __decorate([
  46573. BABYLON.serializeAsTexture(),
  46574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46575. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46576. __decorate([
  46577. BABYLON.serialize(),
  46578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46579. ], PBRMaterial.prototype, "metallic", void 0);
  46580. __decorate([
  46581. BABYLON.serialize(),
  46582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46583. ], PBRMaterial.prototype, "roughness", void 0);
  46584. __decorate([
  46585. BABYLON.serializeAsTexture(),
  46586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46587. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46588. __decorate([
  46589. BABYLON.serializeAsTexture(),
  46590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46591. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46592. __decorate([
  46593. BABYLON.serializeAsTexture(),
  46594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46595. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46596. __decorate([
  46597. BABYLON.serializeAsTexture(),
  46598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46599. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46600. __decorate([
  46601. BABYLON.serializeAsColor3("ambient"),
  46602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46603. ], PBRMaterial.prototype, "ambientColor", void 0);
  46604. __decorate([
  46605. BABYLON.serializeAsColor3("albedo"),
  46606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46607. ], PBRMaterial.prototype, "albedoColor", void 0);
  46608. __decorate([
  46609. BABYLON.serializeAsColor3("reflectivity"),
  46610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46611. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46612. __decorate([
  46613. BABYLON.serializeAsColor3("reflection"),
  46614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46615. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46616. __decorate([
  46617. BABYLON.serializeAsColor3("emissive"),
  46618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46619. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46620. __decorate([
  46621. BABYLON.serialize(),
  46622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46623. ], PBRMaterial.prototype, "microSurface", void 0);
  46624. __decorate([
  46625. BABYLON.serialize(),
  46626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46627. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46628. __decorate([
  46629. BABYLON.serialize(),
  46630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46631. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46632. __decorate([
  46633. BABYLON.serialize(),
  46634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46635. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46636. __decorate([
  46637. BABYLON.serialize(),
  46638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46639. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46640. __decorate([
  46641. BABYLON.serialize(),
  46642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46643. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46644. __decorate([
  46645. BABYLON.serialize(),
  46646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46647. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46648. __decorate([
  46649. BABYLON.serialize(),
  46650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46651. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46652. __decorate([
  46653. BABYLON.serialize(),
  46654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46655. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46656. __decorate([
  46657. BABYLON.serialize(),
  46658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46659. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46660. __decorate([
  46661. BABYLON.serialize(),
  46662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46663. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46664. __decorate([
  46665. BABYLON.serialize(),
  46666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46667. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46668. __decorate([
  46669. BABYLON.serialize(),
  46670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46671. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46672. __decorate([
  46673. BABYLON.serialize(),
  46674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46675. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46676. __decorate([
  46677. BABYLON.serialize(),
  46678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46679. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46680. __decorate([
  46681. BABYLON.serialize(),
  46682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46683. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46684. __decorate([
  46685. BABYLON.serialize(),
  46686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46687. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46688. __decorate([
  46689. BABYLON.serialize(),
  46690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46691. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46692. __decorate([
  46693. BABYLON.serialize(),
  46694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46695. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46696. __decorate([
  46697. BABYLON.serialize(),
  46698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46699. ], PBRMaterial.prototype, "useParallax", void 0);
  46700. __decorate([
  46701. BABYLON.serialize(),
  46702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46703. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46704. __decorate([
  46705. BABYLON.serialize(),
  46706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46707. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46708. __decorate([
  46709. BABYLON.serialize(),
  46710. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46711. ], PBRMaterial.prototype, "disableLighting", void 0);
  46712. __decorate([
  46713. BABYLON.serialize(),
  46714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46715. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46716. __decorate([
  46717. BABYLON.serialize(),
  46718. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46719. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46720. __decorate([
  46721. BABYLON.serialize(),
  46722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46723. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46724. __decorate([
  46725. BABYLON.serialize(),
  46726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46727. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46728. __decorate([
  46729. BABYLON.serialize(),
  46730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46731. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46732. __decorate([
  46733. BABYLON.serialize(),
  46734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46735. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46736. __decorate([
  46737. BABYLON.serialize(),
  46738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46739. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46740. __decorate([
  46741. BABYLON.serializeAsTexture(),
  46742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46743. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46744. __decorate([
  46745. BABYLON.serialize(),
  46746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46747. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46748. __decorate([
  46749. BABYLON.serialize(),
  46750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46751. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46752. __decorate([
  46753. BABYLON.serialize(),
  46754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46755. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46756. __decorate([
  46757. BABYLON.serialize(),
  46758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46759. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46760. __decorate([
  46761. BABYLON.serialize(),
  46762. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46763. ], PBRMaterial.prototype, "unlit", void 0);
  46764. return PBRMaterial;
  46765. }(BABYLON.PBRBaseMaterial));
  46766. BABYLON.PBRMaterial = PBRMaterial;
  46767. })(BABYLON || (BABYLON = {}));
  46768. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46769. var BABYLON;
  46770. (function (BABYLON) {
  46771. /**
  46772. * The PBR material of BJS following the metal roughness convention.
  46773. *
  46774. * This fits to the PBR convention in the GLTF definition:
  46775. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46776. */
  46777. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46778. __extends(PBRMetallicRoughnessMaterial, _super);
  46779. /**
  46780. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46781. *
  46782. * @param name The material name
  46783. * @param scene The scene the material will be use in.
  46784. */
  46785. function PBRMetallicRoughnessMaterial(name, scene) {
  46786. var _this = _super.call(this, name, scene) || this;
  46787. _this._useRoughnessFromMetallicTextureAlpha = false;
  46788. _this._useRoughnessFromMetallicTextureGreen = true;
  46789. _this._useMetallnessFromMetallicTextureBlue = true;
  46790. _this.metallic = 1.0;
  46791. _this.roughness = 1.0;
  46792. return _this;
  46793. }
  46794. /**
  46795. * Return the currrent class name of the material.
  46796. */
  46797. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46798. return "PBRMetallicRoughnessMaterial";
  46799. };
  46800. /**
  46801. * Return the active textures of the material.
  46802. */
  46803. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46804. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46805. if (this.baseTexture) {
  46806. activeTextures.push(this.baseTexture);
  46807. }
  46808. if (this.metallicRoughnessTexture) {
  46809. activeTextures.push(this.metallicRoughnessTexture);
  46810. }
  46811. return activeTextures;
  46812. };
  46813. /**
  46814. * Checks to see if a texture is used in the material.
  46815. * @param texture - Base texture to use.
  46816. * @returns - Boolean specifying if a texture is used in the material.
  46817. */
  46818. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46819. if (_super.prototype.hasTexture.call(this, texture)) {
  46820. return true;
  46821. }
  46822. if (this.baseTexture === texture) {
  46823. return true;
  46824. }
  46825. if (this.metallicRoughnessTexture === texture) {
  46826. return true;
  46827. }
  46828. return false;
  46829. };
  46830. /**
  46831. * Makes a duplicate of the current material.
  46832. * @param name - name to use for the new material.
  46833. */
  46834. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46835. var _this = this;
  46836. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46837. clone.id = name;
  46838. clone.name = name;
  46839. return clone;
  46840. };
  46841. /**
  46842. * Serialize the material to a parsable JSON object.
  46843. */
  46844. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46845. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46846. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46847. return serializationObject;
  46848. };
  46849. /**
  46850. * Parses a JSON object correponding to the serialize function.
  46851. */
  46852. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46853. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46854. };
  46855. __decorate([
  46856. BABYLON.serializeAsColor3(),
  46857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46858. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46859. __decorate([
  46860. BABYLON.serializeAsTexture(),
  46861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46862. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46863. __decorate([
  46864. BABYLON.serialize(),
  46865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46866. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46867. __decorate([
  46868. BABYLON.serialize(),
  46869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46870. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46871. __decorate([
  46872. BABYLON.serializeAsTexture(),
  46873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46874. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46875. return PBRMetallicRoughnessMaterial;
  46876. }(BABYLON.PBRBaseSimpleMaterial));
  46877. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46878. })(BABYLON || (BABYLON = {}));
  46879. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46880. var BABYLON;
  46881. (function (BABYLON) {
  46882. /**
  46883. * The PBR material of BJS following the specular glossiness convention.
  46884. *
  46885. * This fits to the PBR convention in the GLTF definition:
  46886. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46887. */
  46888. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46889. __extends(PBRSpecularGlossinessMaterial, _super);
  46890. /**
  46891. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46892. *
  46893. * @param name The material name
  46894. * @param scene The scene the material will be use in.
  46895. */
  46896. function PBRSpecularGlossinessMaterial(name, scene) {
  46897. var _this = _super.call(this, name, scene) || this;
  46898. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46899. return _this;
  46900. }
  46901. /**
  46902. * Return the currrent class name of the material.
  46903. */
  46904. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46905. return "PBRSpecularGlossinessMaterial";
  46906. };
  46907. /**
  46908. * Return the active textures of the material.
  46909. */
  46910. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46911. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46912. if (this.diffuseTexture) {
  46913. activeTextures.push(this.diffuseTexture);
  46914. }
  46915. if (this.specularGlossinessTexture) {
  46916. activeTextures.push(this.specularGlossinessTexture);
  46917. }
  46918. return activeTextures;
  46919. };
  46920. /**
  46921. * Checks to see if a texture is used in the material.
  46922. * @param texture - Base texture to use.
  46923. * @returns - Boolean specifying if a texture is used in the material.
  46924. */
  46925. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46926. if (_super.prototype.hasTexture.call(this, texture)) {
  46927. return true;
  46928. }
  46929. if (this.diffuseTexture === texture) {
  46930. return true;
  46931. }
  46932. if (this.specularGlossinessTexture === texture) {
  46933. return true;
  46934. }
  46935. return false;
  46936. };
  46937. /**
  46938. * Makes a duplicate of the current material.
  46939. * @param name - name to use for the new material.
  46940. */
  46941. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46942. var _this = this;
  46943. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46944. clone.id = name;
  46945. clone.name = name;
  46946. return clone;
  46947. };
  46948. /**
  46949. * Serialize the material to a parsable JSON object.
  46950. */
  46951. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46952. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46953. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46954. return serializationObject;
  46955. };
  46956. /**
  46957. * Parses a JSON object correponding to the serialize function.
  46958. */
  46959. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46960. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46961. };
  46962. __decorate([
  46963. BABYLON.serializeAsColor3("diffuse"),
  46964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46965. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46966. __decorate([
  46967. BABYLON.serializeAsTexture(),
  46968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46969. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46970. __decorate([
  46971. BABYLON.serializeAsColor3("specular"),
  46972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46973. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46974. __decorate([
  46975. BABYLON.serialize(),
  46976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46977. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46978. __decorate([
  46979. BABYLON.serializeAsTexture(),
  46980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46981. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46982. return PBRSpecularGlossinessMaterial;
  46983. }(BABYLON.PBRBaseSimpleMaterial));
  46984. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46985. })(BABYLON || (BABYLON = {}));
  46986. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46987. var BABYLON;
  46988. (function (BABYLON) {
  46989. BABYLON.CameraInputTypes = {};
  46990. var CameraInputsManager = /** @class */ (function () {
  46991. function CameraInputsManager(camera) {
  46992. this.attached = {};
  46993. this.camera = camera;
  46994. this.checkInputs = function () { };
  46995. }
  46996. /**
  46997. * Add an input method to a camera.
  46998. * builtin inputs example: camera.inputs.addGamepad();
  46999. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  47000. * @param input camera input method
  47001. */
  47002. CameraInputsManager.prototype.add = function (input) {
  47003. var type = input.getSimpleName();
  47004. if (this.attached[type]) {
  47005. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47006. return;
  47007. }
  47008. this.attached[type] = input;
  47009. input.camera = this.camera;
  47010. //for checkInputs, we are dynamically creating a function
  47011. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47012. if (input.checkInputs) {
  47013. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47014. }
  47015. if (this.attachedElement) {
  47016. input.attachControl(this.attachedElement);
  47017. }
  47018. };
  47019. /**
  47020. * Remove a specific input method from a camera
  47021. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47022. * @param inputToRemove camera input method
  47023. */
  47024. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47025. for (var cam in this.attached) {
  47026. var input = this.attached[cam];
  47027. if (input === inputToRemove) {
  47028. input.detachControl(this.attachedElement);
  47029. input.camera = null;
  47030. delete this.attached[cam];
  47031. this.rebuildInputCheck();
  47032. }
  47033. }
  47034. };
  47035. CameraInputsManager.prototype.removeByType = function (inputType) {
  47036. for (var cam in this.attached) {
  47037. var input = this.attached[cam];
  47038. if (input.getClassName() === inputType) {
  47039. input.detachControl(this.attachedElement);
  47040. input.camera = null;
  47041. delete this.attached[cam];
  47042. this.rebuildInputCheck();
  47043. }
  47044. }
  47045. };
  47046. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47047. var current = this.checkInputs;
  47048. return function () {
  47049. current();
  47050. fn();
  47051. };
  47052. };
  47053. CameraInputsManager.prototype.attachInput = function (input) {
  47054. if (this.attachedElement) {
  47055. input.attachControl(this.attachedElement, this.noPreventDefault);
  47056. }
  47057. };
  47058. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47059. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47060. if (this.attachedElement) {
  47061. return;
  47062. }
  47063. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47064. this.attachedElement = element;
  47065. this.noPreventDefault = noPreventDefault;
  47066. for (var cam in this.attached) {
  47067. this.attached[cam].attachControl(element, noPreventDefault);
  47068. }
  47069. };
  47070. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47071. if (disconnect === void 0) { disconnect = false; }
  47072. if (this.attachedElement !== element) {
  47073. return;
  47074. }
  47075. for (var cam in this.attached) {
  47076. this.attached[cam].detachControl(element);
  47077. if (disconnect) {
  47078. this.attached[cam].camera = null;
  47079. }
  47080. }
  47081. this.attachedElement = null;
  47082. };
  47083. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47084. this.checkInputs = function () { };
  47085. for (var cam in this.attached) {
  47086. var input = this.attached[cam];
  47087. if (input.checkInputs) {
  47088. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47089. }
  47090. }
  47091. };
  47092. /**
  47093. * Remove all attached input methods from a camera
  47094. */
  47095. CameraInputsManager.prototype.clear = function () {
  47096. if (this.attachedElement) {
  47097. this.detachElement(this.attachedElement, true);
  47098. }
  47099. this.attached = {};
  47100. this.attachedElement = null;
  47101. this.checkInputs = function () { };
  47102. };
  47103. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47104. var inputs = {};
  47105. for (var cam in this.attached) {
  47106. var input = this.attached[cam];
  47107. var res = BABYLON.SerializationHelper.Serialize(input);
  47108. inputs[input.getClassName()] = res;
  47109. }
  47110. serializedCamera.inputsmgr = inputs;
  47111. };
  47112. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47113. var parsedInputs = parsedCamera.inputsmgr;
  47114. if (parsedInputs) {
  47115. this.clear();
  47116. for (var n in parsedInputs) {
  47117. var construct = BABYLON.CameraInputTypes[n];
  47118. if (construct) {
  47119. var parsedinput = parsedInputs[n];
  47120. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47121. this.add(input);
  47122. }
  47123. }
  47124. }
  47125. else {
  47126. //2016-03-08 this part is for managing backward compatibility
  47127. for (var n in this.attached) {
  47128. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47129. if (construct) {
  47130. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47131. this.remove(this.attached[n]);
  47132. this.add(input);
  47133. }
  47134. }
  47135. }
  47136. };
  47137. return CameraInputsManager;
  47138. }());
  47139. BABYLON.CameraInputsManager = CameraInputsManager;
  47140. })(BABYLON || (BABYLON = {}));
  47141. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47142. var BABYLON;
  47143. (function (BABYLON) {
  47144. var TargetCamera = /** @class */ (function (_super) {
  47145. __extends(TargetCamera, _super);
  47146. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47147. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47148. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47149. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47150. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47151. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47152. _this.speed = 2.0;
  47153. _this.noRotationConstraint = false;
  47154. _this.lockedTarget = null;
  47155. _this._currentTarget = BABYLON.Vector3.Zero();
  47156. _this._viewMatrix = BABYLON.Matrix.Zero();
  47157. _this._camMatrix = BABYLON.Matrix.Zero();
  47158. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47159. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47160. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47161. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  47162. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47163. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47164. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47165. return _this;
  47166. }
  47167. TargetCamera.prototype.getFrontPosition = function (distance) {
  47168. this.getWorldMatrix();
  47169. var direction = this.getTarget().subtract(this.position);
  47170. direction.normalize();
  47171. direction.scaleInPlace(distance);
  47172. return this.globalPosition.add(direction);
  47173. };
  47174. TargetCamera.prototype._getLockedTargetPosition = function () {
  47175. if (!this.lockedTarget) {
  47176. return null;
  47177. }
  47178. if (this.lockedTarget.absolutePosition) {
  47179. this.lockedTarget.computeWorldMatrix();
  47180. }
  47181. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47182. };
  47183. TargetCamera.prototype.storeState = function () {
  47184. this._storedPosition = this.position.clone();
  47185. this._storedRotation = this.rotation.clone();
  47186. if (this.rotationQuaternion) {
  47187. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47188. }
  47189. return _super.prototype.storeState.call(this);
  47190. };
  47191. /**
  47192. * Restored camera state. You must call storeState() first
  47193. */
  47194. TargetCamera.prototype._restoreStateValues = function () {
  47195. if (!_super.prototype._restoreStateValues.call(this)) {
  47196. return false;
  47197. }
  47198. this.position = this._storedPosition.clone();
  47199. this.rotation = this._storedRotation.clone();
  47200. if (this.rotationQuaternion) {
  47201. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47202. }
  47203. this.cameraDirection.copyFromFloats(0, 0, 0);
  47204. this.cameraRotation.copyFromFloats(0, 0);
  47205. return true;
  47206. };
  47207. // Cache
  47208. TargetCamera.prototype._initCache = function () {
  47209. _super.prototype._initCache.call(this);
  47210. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47211. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47212. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47213. };
  47214. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47215. if (!ignoreParentClass) {
  47216. _super.prototype._updateCache.call(this);
  47217. }
  47218. var lockedTargetPosition = this._getLockedTargetPosition();
  47219. if (!lockedTargetPosition) {
  47220. this._cache.lockedTarget = null;
  47221. }
  47222. else {
  47223. if (!this._cache.lockedTarget) {
  47224. this._cache.lockedTarget = lockedTargetPosition.clone();
  47225. }
  47226. else {
  47227. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47228. }
  47229. }
  47230. this._cache.rotation.copyFrom(this.rotation);
  47231. if (this.rotationQuaternion)
  47232. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47233. };
  47234. // Synchronized
  47235. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47236. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47237. return false;
  47238. }
  47239. var lockedTargetPosition = this._getLockedTargetPosition();
  47240. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47241. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47242. };
  47243. // Methods
  47244. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47245. var engine = this.getEngine();
  47246. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47247. };
  47248. // Target
  47249. TargetCamera.prototype.setTarget = function (target) {
  47250. this.upVector.normalize();
  47251. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47252. this._camMatrix.invert();
  47253. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47254. var vDir = target.subtract(this.position);
  47255. if (vDir.x >= 0.0) {
  47256. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47257. }
  47258. else {
  47259. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47260. }
  47261. this.rotation.z = 0;
  47262. if (isNaN(this.rotation.x)) {
  47263. this.rotation.x = 0;
  47264. }
  47265. if (isNaN(this.rotation.y)) {
  47266. this.rotation.y = 0;
  47267. }
  47268. if (isNaN(this.rotation.z)) {
  47269. this.rotation.z = 0;
  47270. }
  47271. if (this.rotationQuaternion) {
  47272. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47273. }
  47274. };
  47275. /**
  47276. * Return the current target position of the camera. This value is expressed in local space.
  47277. */
  47278. TargetCamera.prototype.getTarget = function () {
  47279. return this._currentTarget;
  47280. };
  47281. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47282. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47283. };
  47284. TargetCamera.prototype._updatePosition = function () {
  47285. if (this.parent) {
  47286. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47287. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47288. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47289. return;
  47290. }
  47291. this.position.addInPlace(this.cameraDirection);
  47292. };
  47293. TargetCamera.prototype._checkInputs = function () {
  47294. var needToMove = this._decideIfNeedsToMove();
  47295. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47296. // Move
  47297. if (needToMove) {
  47298. this._updatePosition();
  47299. }
  47300. // Rotate
  47301. if (needToRotate) {
  47302. this.rotation.x += this.cameraRotation.x;
  47303. this.rotation.y += this.cameraRotation.y;
  47304. //rotate, if quaternion is set and rotation was used
  47305. if (this.rotationQuaternion) {
  47306. var len = this.rotation.lengthSquared();
  47307. if (len) {
  47308. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47309. }
  47310. }
  47311. if (!this.noRotationConstraint) {
  47312. var limit = (Math.PI / 2) * 0.95;
  47313. if (this.rotation.x > limit)
  47314. this.rotation.x = limit;
  47315. if (this.rotation.x < -limit)
  47316. this.rotation.x = -limit;
  47317. }
  47318. }
  47319. // Inertia
  47320. if (needToMove) {
  47321. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47322. this.cameraDirection.x = 0;
  47323. }
  47324. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47325. this.cameraDirection.y = 0;
  47326. }
  47327. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47328. this.cameraDirection.z = 0;
  47329. }
  47330. this.cameraDirection.scaleInPlace(this.inertia);
  47331. }
  47332. if (needToRotate) {
  47333. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47334. this.cameraRotation.x = 0;
  47335. }
  47336. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47337. this.cameraRotation.y = 0;
  47338. }
  47339. this.cameraRotation.scaleInPlace(this.inertia);
  47340. }
  47341. _super.prototype._checkInputs.call(this);
  47342. };
  47343. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47344. if (this.rotationQuaternion) {
  47345. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47346. }
  47347. else {
  47348. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47349. }
  47350. //update the up vector!
  47351. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47352. };
  47353. TargetCamera.prototype._getViewMatrix = function () {
  47354. if (this.lockedTarget) {
  47355. this.setTarget(this._getLockedTargetPosition());
  47356. }
  47357. // Compute
  47358. this._updateCameraRotationMatrix();
  47359. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47360. // Computing target and final matrix
  47361. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47362. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47363. return this._viewMatrix;
  47364. };
  47365. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47366. if (this.parent) {
  47367. var parentWorldMatrix = this.parent.getWorldMatrix();
  47368. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47369. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47370. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47371. this._markSyncedWithParent();
  47372. }
  47373. else {
  47374. this._globalPosition.copyFrom(this.position);
  47375. this._globalCurrentTarget.copyFrom(target);
  47376. this._globalCurrentUpVector.copyFrom(up);
  47377. }
  47378. if (this.getScene().useRightHandedSystem) {
  47379. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47380. }
  47381. else {
  47382. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47383. }
  47384. };
  47385. /**
  47386. * @override
  47387. * Override Camera.createRigCamera
  47388. */
  47389. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47390. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47391. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47392. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47393. if (!this.rotationQuaternion) {
  47394. this.rotationQuaternion = new BABYLON.Quaternion();
  47395. }
  47396. rigCamera._cameraRigParams = {};
  47397. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47398. }
  47399. return rigCamera;
  47400. }
  47401. return null;
  47402. };
  47403. /**
  47404. * @override
  47405. * Override Camera._updateRigCameras
  47406. */
  47407. TargetCamera.prototype._updateRigCameras = function () {
  47408. var camLeft = this._rigCameras[0];
  47409. var camRight = this._rigCameras[1];
  47410. switch (this.cameraRigMode) {
  47411. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47412. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47413. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47414. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47415. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47416. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47417. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47418. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47419. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47420. camLeft.setTarget(this.getTarget());
  47421. camRight.setTarget(this.getTarget());
  47422. break;
  47423. case BABYLON.Camera.RIG_MODE_VR:
  47424. if (camLeft.rotationQuaternion) {
  47425. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47426. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47427. }
  47428. else {
  47429. camLeft.rotation.copyFrom(this.rotation);
  47430. camRight.rotation.copyFrom(this.rotation);
  47431. }
  47432. camLeft.position.copyFrom(this.position);
  47433. camRight.position.copyFrom(this.position);
  47434. break;
  47435. }
  47436. _super.prototype._updateRigCameras.call(this);
  47437. };
  47438. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47439. if (!this._rigCamTransformMatrix) {
  47440. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47441. }
  47442. var target = this.getTarget();
  47443. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47444. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47445. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47446. };
  47447. TargetCamera.prototype.getClassName = function () {
  47448. return "TargetCamera";
  47449. };
  47450. __decorate([
  47451. BABYLON.serializeAsVector3()
  47452. ], TargetCamera.prototype, "rotation", void 0);
  47453. __decorate([
  47454. BABYLON.serialize()
  47455. ], TargetCamera.prototype, "speed", void 0);
  47456. __decorate([
  47457. BABYLON.serializeAsMeshReference("lockedTargetId")
  47458. ], TargetCamera.prototype, "lockedTarget", void 0);
  47459. return TargetCamera;
  47460. }(BABYLON.Camera));
  47461. BABYLON.TargetCamera = TargetCamera;
  47462. })(BABYLON || (BABYLON = {}));
  47463. //# sourceMappingURL=babylon.targetCamera.js.map
  47464. var BABYLON;
  47465. (function (BABYLON) {
  47466. var FreeCameraMouseInput = /** @class */ (function () {
  47467. function FreeCameraMouseInput(touchEnabled) {
  47468. if (touchEnabled === void 0) { touchEnabled = true; }
  47469. this.touchEnabled = touchEnabled;
  47470. this.buttons = [0, 1, 2];
  47471. this.angularSensibility = 2000.0;
  47472. this.previousPosition = null;
  47473. }
  47474. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47475. var _this = this;
  47476. var engine = this.camera.getEngine();
  47477. if (!this._pointerInput) {
  47478. this._pointerInput = function (p, s) {
  47479. var evt = p.event;
  47480. if (engine.isInVRExclusivePointerMode) {
  47481. return;
  47482. }
  47483. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47484. return;
  47485. }
  47486. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47487. return;
  47488. }
  47489. var srcElement = (evt.srcElement || evt.target);
  47490. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47491. try {
  47492. srcElement.setPointerCapture(evt.pointerId);
  47493. }
  47494. catch (e) {
  47495. //Nothing to do with the error. Execution will continue.
  47496. }
  47497. _this.previousPosition = {
  47498. x: evt.clientX,
  47499. y: evt.clientY
  47500. };
  47501. if (!noPreventDefault) {
  47502. evt.preventDefault();
  47503. element.focus();
  47504. }
  47505. }
  47506. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47507. try {
  47508. srcElement.releasePointerCapture(evt.pointerId);
  47509. }
  47510. catch (e) {
  47511. //Nothing to do with the error.
  47512. }
  47513. _this.previousPosition = null;
  47514. if (!noPreventDefault) {
  47515. evt.preventDefault();
  47516. }
  47517. }
  47518. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47519. if (!_this.previousPosition || engine.isPointerLock) {
  47520. return;
  47521. }
  47522. var offsetX = evt.clientX - _this.previousPosition.x;
  47523. if (_this.camera.getScene().useRightHandedSystem)
  47524. offsetX *= -1;
  47525. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47526. offsetX *= -1;
  47527. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47528. var offsetY = evt.clientY - _this.previousPosition.y;
  47529. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47530. _this.previousPosition = {
  47531. x: evt.clientX,
  47532. y: evt.clientY
  47533. };
  47534. if (!noPreventDefault) {
  47535. evt.preventDefault();
  47536. }
  47537. }
  47538. };
  47539. }
  47540. this._onMouseMove = function (evt) {
  47541. if (!engine.isPointerLock) {
  47542. return;
  47543. }
  47544. if (engine.isInVRExclusivePointerMode) {
  47545. return;
  47546. }
  47547. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47548. if (_this.camera.getScene().useRightHandedSystem)
  47549. offsetX *= -1;
  47550. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47551. offsetX *= -1;
  47552. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47553. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47554. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47555. _this.previousPosition = null;
  47556. if (!noPreventDefault) {
  47557. evt.preventDefault();
  47558. }
  47559. };
  47560. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47561. element.addEventListener("mousemove", this._onMouseMove, false);
  47562. };
  47563. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47564. if (this._observer && element) {
  47565. this.camera.getScene().onPointerObservable.remove(this._observer);
  47566. if (this._onMouseMove) {
  47567. element.removeEventListener("mousemove", this._onMouseMove);
  47568. }
  47569. this._observer = null;
  47570. this._onMouseMove = null;
  47571. this.previousPosition = null;
  47572. }
  47573. };
  47574. FreeCameraMouseInput.prototype.getClassName = function () {
  47575. return "FreeCameraMouseInput";
  47576. };
  47577. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47578. return "mouse";
  47579. };
  47580. __decorate([
  47581. BABYLON.serialize()
  47582. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47583. __decorate([
  47584. BABYLON.serialize()
  47585. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47586. return FreeCameraMouseInput;
  47587. }());
  47588. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47589. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47590. })(BABYLON || (BABYLON = {}));
  47591. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47592. var BABYLON;
  47593. (function (BABYLON) {
  47594. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47595. function FreeCameraKeyboardMoveInput() {
  47596. this._keys = new Array();
  47597. this.keysUp = [38];
  47598. this.keysDown = [40];
  47599. this.keysLeft = [37];
  47600. this.keysRight = [39];
  47601. }
  47602. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47603. var _this = this;
  47604. if (this._onCanvasBlurObserver) {
  47605. return;
  47606. }
  47607. this._scene = this.camera.getScene();
  47608. this._engine = this._scene.getEngine();
  47609. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47610. _this._keys = [];
  47611. });
  47612. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47613. var evt = info.event;
  47614. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47615. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47616. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47617. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47618. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47619. var index = _this._keys.indexOf(evt.keyCode);
  47620. if (index === -1) {
  47621. _this._keys.push(evt.keyCode);
  47622. }
  47623. if (!noPreventDefault) {
  47624. evt.preventDefault();
  47625. }
  47626. }
  47627. }
  47628. else {
  47629. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47630. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47631. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47632. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47633. var index = _this._keys.indexOf(evt.keyCode);
  47634. if (index >= 0) {
  47635. _this._keys.splice(index, 1);
  47636. }
  47637. if (!noPreventDefault) {
  47638. evt.preventDefault();
  47639. }
  47640. }
  47641. }
  47642. });
  47643. };
  47644. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47645. if (this._scene) {
  47646. if (this._onKeyboardObserver) {
  47647. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47648. }
  47649. if (this._onCanvasBlurObserver) {
  47650. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47651. }
  47652. this._onKeyboardObserver = null;
  47653. this._onCanvasBlurObserver = null;
  47654. }
  47655. this._keys = [];
  47656. };
  47657. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47658. if (this._onKeyboardObserver) {
  47659. var camera = this.camera;
  47660. // Keyboard
  47661. for (var index = 0; index < this._keys.length; index++) {
  47662. var keyCode = this._keys[index];
  47663. var speed = camera._computeLocalCameraSpeed();
  47664. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47665. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47666. }
  47667. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47668. camera._localDirection.copyFromFloats(0, 0, speed);
  47669. }
  47670. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47671. camera._localDirection.copyFromFloats(speed, 0, 0);
  47672. }
  47673. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47674. camera._localDirection.copyFromFloats(0, 0, -speed);
  47675. }
  47676. if (camera.getScene().useRightHandedSystem) {
  47677. camera._localDirection.z *= -1;
  47678. }
  47679. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47680. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47681. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47682. }
  47683. }
  47684. };
  47685. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47686. return "FreeCameraKeyboardMoveInput";
  47687. };
  47688. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47689. this._keys = [];
  47690. };
  47691. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47692. return "keyboard";
  47693. };
  47694. __decorate([
  47695. BABYLON.serialize()
  47696. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47697. __decorate([
  47698. BABYLON.serialize()
  47699. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47700. __decorate([
  47701. BABYLON.serialize()
  47702. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47703. __decorate([
  47704. BABYLON.serialize()
  47705. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47706. return FreeCameraKeyboardMoveInput;
  47707. }());
  47708. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47709. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47710. })(BABYLON || (BABYLON = {}));
  47711. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47712. var BABYLON;
  47713. (function (BABYLON) {
  47714. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47715. __extends(FreeCameraInputsManager, _super);
  47716. function FreeCameraInputsManager(camera) {
  47717. return _super.call(this, camera) || this;
  47718. }
  47719. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47720. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47721. return this;
  47722. };
  47723. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47724. if (touchEnabled === void 0) { touchEnabled = true; }
  47725. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47726. return this;
  47727. };
  47728. FreeCameraInputsManager.prototype.addGamepad = function () {
  47729. this.add(new BABYLON.FreeCameraGamepadInput());
  47730. return this;
  47731. };
  47732. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47733. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47734. return this;
  47735. };
  47736. FreeCameraInputsManager.prototype.addTouch = function () {
  47737. this.add(new BABYLON.FreeCameraTouchInput());
  47738. return this;
  47739. };
  47740. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47741. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47742. return this;
  47743. };
  47744. return FreeCameraInputsManager;
  47745. }(BABYLON.CameraInputsManager));
  47746. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47747. })(BABYLON || (BABYLON = {}));
  47748. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47749. var BABYLON;
  47750. (function (BABYLON) {
  47751. var FreeCamera = /** @class */ (function (_super) {
  47752. __extends(FreeCamera, _super);
  47753. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47754. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47755. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47756. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47757. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47758. _this.checkCollisions = false;
  47759. _this.applyGravity = false;
  47760. _this._needMoveForGravity = false;
  47761. _this._oldPosition = BABYLON.Vector3.Zero();
  47762. _this._diffPosition = BABYLON.Vector3.Zero();
  47763. _this._newPosition = BABYLON.Vector3.Zero();
  47764. // Collisions
  47765. _this._collisionMask = -1;
  47766. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47767. if (collidedMesh === void 0) { collidedMesh = null; }
  47768. //TODO move this to the collision coordinator!
  47769. if (_this.getScene().workerCollisions)
  47770. newPosition.multiplyInPlace(_this._collider._radius);
  47771. var updatePosition = function (newPos) {
  47772. _this._newPosition.copyFrom(newPos);
  47773. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47774. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47775. _this.position.addInPlace(_this._diffPosition);
  47776. if (_this.onCollide && collidedMesh) {
  47777. _this.onCollide(collidedMesh);
  47778. }
  47779. }
  47780. };
  47781. updatePosition(newPosition);
  47782. };
  47783. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47784. _this.inputs.addKeyboard().addMouse();
  47785. return _this;
  47786. }
  47787. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47788. //-- begin properties for backward compatibility for inputs
  47789. /**
  47790. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47791. * Higher values reduce sensitivity.
  47792. */
  47793. get: function () {
  47794. var mouse = this.inputs.attached["mouse"];
  47795. if (mouse)
  47796. return mouse.angularSensibility;
  47797. return 0;
  47798. },
  47799. /**
  47800. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47801. * Higher values reduce sensitivity.
  47802. */
  47803. set: function (value) {
  47804. var mouse = this.inputs.attached["mouse"];
  47805. if (mouse)
  47806. mouse.angularSensibility = value;
  47807. },
  47808. enumerable: true,
  47809. configurable: true
  47810. });
  47811. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47812. get: function () {
  47813. var keyboard = this.inputs.attached["keyboard"];
  47814. if (keyboard)
  47815. return keyboard.keysUp;
  47816. return [];
  47817. },
  47818. set: function (value) {
  47819. var keyboard = this.inputs.attached["keyboard"];
  47820. if (keyboard)
  47821. keyboard.keysUp = value;
  47822. },
  47823. enumerable: true,
  47824. configurable: true
  47825. });
  47826. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47827. get: function () {
  47828. var keyboard = this.inputs.attached["keyboard"];
  47829. if (keyboard)
  47830. return keyboard.keysDown;
  47831. return [];
  47832. },
  47833. set: function (value) {
  47834. var keyboard = this.inputs.attached["keyboard"];
  47835. if (keyboard)
  47836. keyboard.keysDown = value;
  47837. },
  47838. enumerable: true,
  47839. configurable: true
  47840. });
  47841. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47842. get: function () {
  47843. var keyboard = this.inputs.attached["keyboard"];
  47844. if (keyboard)
  47845. return keyboard.keysLeft;
  47846. return [];
  47847. },
  47848. set: function (value) {
  47849. var keyboard = this.inputs.attached["keyboard"];
  47850. if (keyboard)
  47851. keyboard.keysLeft = value;
  47852. },
  47853. enumerable: true,
  47854. configurable: true
  47855. });
  47856. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47857. get: function () {
  47858. var keyboard = this.inputs.attached["keyboard"];
  47859. if (keyboard)
  47860. return keyboard.keysRight;
  47861. return [];
  47862. },
  47863. set: function (value) {
  47864. var keyboard = this.inputs.attached["keyboard"];
  47865. if (keyboard)
  47866. keyboard.keysRight = value;
  47867. },
  47868. enumerable: true,
  47869. configurable: true
  47870. });
  47871. // Controls
  47872. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47873. this.inputs.attachElement(element, noPreventDefault);
  47874. };
  47875. FreeCamera.prototype.detachControl = function (element) {
  47876. this.inputs.detachElement(element);
  47877. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47878. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47879. };
  47880. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47881. get: function () {
  47882. return this._collisionMask;
  47883. },
  47884. set: function (mask) {
  47885. this._collisionMask = !isNaN(mask) ? mask : -1;
  47886. },
  47887. enumerable: true,
  47888. configurable: true
  47889. });
  47890. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47891. var globalPosition;
  47892. if (this.parent) {
  47893. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47894. }
  47895. else {
  47896. globalPosition = this.position;
  47897. }
  47898. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47899. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47900. if (!this._collider) {
  47901. this._collider = new BABYLON.Collider();
  47902. }
  47903. this._collider._radius = this.ellipsoid;
  47904. this._collider.collisionMask = this._collisionMask;
  47905. //no need for clone, as long as gravity is not on.
  47906. var actualDisplacement = displacement;
  47907. //add gravity to the direction to prevent the dual-collision checking
  47908. if (this.applyGravity) {
  47909. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47910. actualDisplacement = displacement.add(this.getScene().gravity);
  47911. }
  47912. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47913. };
  47914. FreeCamera.prototype._checkInputs = function () {
  47915. if (!this._localDirection) {
  47916. this._localDirection = BABYLON.Vector3.Zero();
  47917. this._transformedDirection = BABYLON.Vector3.Zero();
  47918. }
  47919. this.inputs.checkInputs();
  47920. _super.prototype._checkInputs.call(this);
  47921. };
  47922. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47923. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47924. };
  47925. FreeCamera.prototype._updatePosition = function () {
  47926. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47927. this._collideWithWorld(this.cameraDirection);
  47928. }
  47929. else {
  47930. _super.prototype._updatePosition.call(this);
  47931. }
  47932. };
  47933. FreeCamera.prototype.dispose = function () {
  47934. this.inputs.clear();
  47935. _super.prototype.dispose.call(this);
  47936. };
  47937. FreeCamera.prototype.getClassName = function () {
  47938. return "FreeCamera";
  47939. };
  47940. __decorate([
  47941. BABYLON.serializeAsVector3()
  47942. ], FreeCamera.prototype, "ellipsoid", void 0);
  47943. __decorate([
  47944. BABYLON.serializeAsVector3()
  47945. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47946. __decorate([
  47947. BABYLON.serialize()
  47948. ], FreeCamera.prototype, "checkCollisions", void 0);
  47949. __decorate([
  47950. BABYLON.serialize()
  47951. ], FreeCamera.prototype, "applyGravity", void 0);
  47952. return FreeCamera;
  47953. }(BABYLON.TargetCamera));
  47954. BABYLON.FreeCamera = FreeCamera;
  47955. })(BABYLON || (BABYLON = {}));
  47956. //# sourceMappingURL=babylon.freeCamera.js.map
  47957. var BABYLON;
  47958. (function (BABYLON) {
  47959. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47960. function ArcRotateCameraKeyboardMoveInput() {
  47961. this._keys = new Array();
  47962. this.keysUp = [38];
  47963. this.keysDown = [40];
  47964. this.keysLeft = [37];
  47965. this.keysRight = [39];
  47966. this.keysReset = [220];
  47967. this.panningSensibility = 50.0;
  47968. this.zoomingSensibility = 25.0;
  47969. this.useAltToZoom = true;
  47970. }
  47971. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47972. var _this = this;
  47973. if (this._onCanvasBlurObserver) {
  47974. return;
  47975. }
  47976. this._scene = this.camera.getScene();
  47977. this._engine = this._scene.getEngine();
  47978. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47979. _this._keys = [];
  47980. });
  47981. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47982. var evt = info.event;
  47983. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47984. _this._ctrlPressed = evt.ctrlKey;
  47985. _this._altPressed = evt.altKey;
  47986. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47987. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47988. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47989. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47990. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47991. var index = _this._keys.indexOf(evt.keyCode);
  47992. if (index === -1) {
  47993. _this._keys.push(evt.keyCode);
  47994. }
  47995. if (evt.preventDefault) {
  47996. if (!noPreventDefault) {
  47997. evt.preventDefault();
  47998. }
  47999. }
  48000. }
  48001. }
  48002. else {
  48003. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48004. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48005. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48006. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48007. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48008. var index = _this._keys.indexOf(evt.keyCode);
  48009. if (index >= 0) {
  48010. _this._keys.splice(index, 1);
  48011. }
  48012. if (evt.preventDefault) {
  48013. if (!noPreventDefault) {
  48014. evt.preventDefault();
  48015. }
  48016. }
  48017. }
  48018. }
  48019. });
  48020. };
  48021. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48022. if (this._scene) {
  48023. if (this._onKeyboardObserver) {
  48024. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48025. }
  48026. if (this._onCanvasBlurObserver) {
  48027. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48028. }
  48029. this._onKeyboardObserver = null;
  48030. this._onCanvasBlurObserver = null;
  48031. }
  48032. this._keys = [];
  48033. };
  48034. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48035. if (this._onKeyboardObserver) {
  48036. var camera = this.camera;
  48037. for (var index = 0; index < this._keys.length; index++) {
  48038. var keyCode = this._keys[index];
  48039. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48040. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48041. camera.inertialPanningX -= 1 / this.panningSensibility;
  48042. }
  48043. else {
  48044. camera.inertialAlphaOffset -= 0.01;
  48045. }
  48046. }
  48047. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48048. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48049. camera.inertialPanningY += 1 / this.panningSensibility;
  48050. }
  48051. else if (this._altPressed && this.useAltToZoom) {
  48052. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  48053. }
  48054. else {
  48055. camera.inertialBetaOffset -= 0.01;
  48056. }
  48057. }
  48058. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48059. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48060. camera.inertialPanningX += 1 / this.panningSensibility;
  48061. }
  48062. else {
  48063. camera.inertialAlphaOffset += 0.01;
  48064. }
  48065. }
  48066. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48067. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48068. camera.inertialPanningY -= 1 / this.panningSensibility;
  48069. }
  48070. else if (this._altPressed && this.useAltToZoom) {
  48071. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48072. }
  48073. else {
  48074. camera.inertialBetaOffset += 0.01;
  48075. }
  48076. }
  48077. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48078. camera.restoreState();
  48079. }
  48080. }
  48081. }
  48082. };
  48083. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48084. return "ArcRotateCameraKeyboardMoveInput";
  48085. };
  48086. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48087. return "keyboard";
  48088. };
  48089. __decorate([
  48090. BABYLON.serialize()
  48091. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48092. __decorate([
  48093. BABYLON.serialize()
  48094. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48095. __decorate([
  48096. BABYLON.serialize()
  48097. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48098. __decorate([
  48099. BABYLON.serialize()
  48100. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48101. __decorate([
  48102. BABYLON.serialize()
  48103. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48104. __decorate([
  48105. BABYLON.serialize()
  48106. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48107. __decorate([
  48108. BABYLON.serialize()
  48109. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48110. __decorate([
  48111. BABYLON.serialize()
  48112. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48113. return ArcRotateCameraKeyboardMoveInput;
  48114. }());
  48115. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48116. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48117. })(BABYLON || (BABYLON = {}));
  48118. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48119. var BABYLON;
  48120. (function (BABYLON) {
  48121. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48122. function ArcRotateCameraMouseWheelInput() {
  48123. this.wheelPrecision = 3.0;
  48124. /**
  48125. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48126. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48127. */
  48128. this.wheelDeltaPercentage = 0;
  48129. }
  48130. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48131. var _this = this;
  48132. this._wheel = function (p, s) {
  48133. //sanity check - this should be a PointerWheel event.
  48134. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48135. return;
  48136. var event = p.event;
  48137. var delta = 0;
  48138. if (event.wheelDelta) {
  48139. if (_this.wheelDeltaPercentage) {
  48140. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48141. if (event.wheelDelta > 0) {
  48142. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48143. }
  48144. else {
  48145. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48146. }
  48147. }
  48148. else {
  48149. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48150. }
  48151. }
  48152. else if (event.detail) {
  48153. delta = -event.detail / _this.wheelPrecision;
  48154. }
  48155. if (delta)
  48156. _this.camera.inertialRadiusOffset += delta;
  48157. if (event.preventDefault) {
  48158. if (!noPreventDefault) {
  48159. event.preventDefault();
  48160. }
  48161. }
  48162. };
  48163. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48164. };
  48165. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48166. if (this._observer && element) {
  48167. this.camera.getScene().onPointerObservable.remove(this._observer);
  48168. this._observer = null;
  48169. this._wheel = null;
  48170. }
  48171. };
  48172. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48173. return "ArcRotateCameraMouseWheelInput";
  48174. };
  48175. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48176. return "mousewheel";
  48177. };
  48178. __decorate([
  48179. BABYLON.serialize()
  48180. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48181. __decorate([
  48182. BABYLON.serialize()
  48183. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48184. return ArcRotateCameraMouseWheelInput;
  48185. }());
  48186. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48187. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48188. })(BABYLON || (BABYLON = {}));
  48189. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48190. var BABYLON;
  48191. (function (BABYLON) {
  48192. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48193. function ArcRotateCameraPointersInput() {
  48194. this.buttons = [0, 1, 2];
  48195. this.angularSensibilityX = 1000.0;
  48196. this.angularSensibilityY = 1000.0;
  48197. this.pinchPrecision = 12.0;
  48198. /**
  48199. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48200. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48201. */
  48202. this.pinchDeltaPercentage = 0;
  48203. this.panningSensibility = 1000.0;
  48204. this.multiTouchPanning = true;
  48205. this.multiTouchPanAndZoom = true;
  48206. this._isPanClick = false;
  48207. this.pinchInwards = true;
  48208. }
  48209. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48210. var _this = this;
  48211. var engine = this.camera.getEngine();
  48212. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48213. var pointA = null;
  48214. var pointB = null;
  48215. var previousPinchSquaredDistance = 0;
  48216. var initialDistance = 0;
  48217. var twoFingerActivityCount = 0;
  48218. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48219. this._pointerInput = function (p, s) {
  48220. var evt = p.event;
  48221. var isTouch = p.event.pointerType === "touch";
  48222. if (engine.isInVRExclusivePointerMode) {
  48223. return;
  48224. }
  48225. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48226. return;
  48227. }
  48228. var srcElement = (evt.srcElement || evt.target);
  48229. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48230. try {
  48231. srcElement.setPointerCapture(evt.pointerId);
  48232. }
  48233. catch (e) {
  48234. //Nothing to do with the error. Execution will continue.
  48235. }
  48236. // Manage panning with pan button click
  48237. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48238. // manage pointers
  48239. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48240. if (pointA === null) {
  48241. pointA = cacheSoloPointer;
  48242. }
  48243. else if (pointB === null) {
  48244. pointB = cacheSoloPointer;
  48245. }
  48246. if (!noPreventDefault) {
  48247. evt.preventDefault();
  48248. element.focus();
  48249. }
  48250. }
  48251. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48252. _this.camera.restoreState();
  48253. }
  48254. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48255. try {
  48256. srcElement.releasePointerCapture(evt.pointerId);
  48257. }
  48258. catch (e) {
  48259. //Nothing to do with the error.
  48260. }
  48261. cacheSoloPointer = null;
  48262. previousPinchSquaredDistance = 0;
  48263. previousMultiTouchPanPosition.isPaning = false;
  48264. previousMultiTouchPanPosition.isPinching = false;
  48265. twoFingerActivityCount = 0;
  48266. initialDistance = 0;
  48267. if (!isTouch) {
  48268. pointB = null; // Mouse and pen are mono pointer
  48269. }
  48270. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48271. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48272. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48273. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48274. if (engine._badOS) {
  48275. pointA = pointB = null;
  48276. }
  48277. else {
  48278. //only remove the impacted pointer in case of multitouch allowing on most
  48279. //platforms switching from rotate to zoom and pan seamlessly.
  48280. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48281. pointA = pointB;
  48282. pointB = null;
  48283. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48284. }
  48285. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48286. pointB = null;
  48287. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48288. }
  48289. else {
  48290. pointA = pointB = null;
  48291. }
  48292. }
  48293. if (!noPreventDefault) {
  48294. evt.preventDefault();
  48295. }
  48296. }
  48297. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48298. if (!noPreventDefault) {
  48299. evt.preventDefault();
  48300. }
  48301. // One button down
  48302. if (pointA && pointB === null && cacheSoloPointer) {
  48303. if (_this.panningSensibility !== 0 &&
  48304. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48305. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48306. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48307. }
  48308. else {
  48309. var offsetX = evt.clientX - cacheSoloPointer.x;
  48310. var offsetY = evt.clientY - cacheSoloPointer.y;
  48311. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48312. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48313. }
  48314. cacheSoloPointer.x = evt.clientX;
  48315. cacheSoloPointer.y = evt.clientY;
  48316. }
  48317. // Two buttons down: pinch/pan
  48318. else if (pointA && pointB) {
  48319. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48320. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48321. ed.x = evt.clientX;
  48322. ed.y = evt.clientY;
  48323. var direction = _this.pinchInwards ? 1 : -1;
  48324. var distX = pointA.x - pointB.x;
  48325. var distY = pointA.y - pointB.y;
  48326. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48327. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48328. if (previousPinchSquaredDistance === 0) {
  48329. initialDistance = pinchDistance;
  48330. previousPinchSquaredDistance = pinchSquaredDistance;
  48331. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48332. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48333. return;
  48334. }
  48335. if (_this.multiTouchPanAndZoom) {
  48336. if (_this.pinchDeltaPercentage) {
  48337. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48338. }
  48339. else {
  48340. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48341. (_this.pinchPrecision *
  48342. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48343. direction);
  48344. }
  48345. if (_this.panningSensibility !== 0) {
  48346. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48347. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48348. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48349. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48350. previousMultiTouchPanPosition.x = pointersCenterX;
  48351. previousMultiTouchPanPosition.y = pointersCenterY;
  48352. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48353. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48354. }
  48355. }
  48356. else {
  48357. twoFingerActivityCount++;
  48358. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48359. if (_this.pinchDeltaPercentage) {
  48360. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48361. }
  48362. else {
  48363. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48364. (_this.pinchPrecision *
  48365. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48366. direction);
  48367. }
  48368. previousMultiTouchPanPosition.isPaning = false;
  48369. previousMultiTouchPanPosition.isPinching = true;
  48370. }
  48371. else {
  48372. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48373. if (!previousMultiTouchPanPosition.isPaning) {
  48374. previousMultiTouchPanPosition.isPaning = true;
  48375. previousMultiTouchPanPosition.isPinching = false;
  48376. previousMultiTouchPanPosition.x = ed.x;
  48377. previousMultiTouchPanPosition.y = ed.y;
  48378. return;
  48379. }
  48380. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48381. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48382. }
  48383. }
  48384. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48385. previousMultiTouchPanPosition.x = ed.x;
  48386. previousMultiTouchPanPosition.y = ed.y;
  48387. }
  48388. }
  48389. previousPinchSquaredDistance = pinchSquaredDistance;
  48390. }
  48391. }
  48392. };
  48393. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48394. this._onContextMenu = function (evt) {
  48395. evt.preventDefault();
  48396. };
  48397. if (!this.camera._useCtrlForPanning) {
  48398. element.addEventListener("contextmenu", this._onContextMenu, false);
  48399. }
  48400. this._onLostFocus = function () {
  48401. //this._keys = [];
  48402. pointA = pointB = null;
  48403. previousPinchSquaredDistance = 0;
  48404. previousMultiTouchPanPosition.isPaning = false;
  48405. previousMultiTouchPanPosition.isPinching = false;
  48406. twoFingerActivityCount = 0;
  48407. cacheSoloPointer = null;
  48408. initialDistance = 0;
  48409. };
  48410. this._onMouseMove = function (evt) {
  48411. if (!engine.isPointerLock) {
  48412. return;
  48413. }
  48414. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48415. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48416. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48417. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48418. if (!noPreventDefault) {
  48419. evt.preventDefault();
  48420. }
  48421. };
  48422. this._onGestureStart = function (e) {
  48423. if (window.MSGesture === undefined) {
  48424. return;
  48425. }
  48426. if (!_this._MSGestureHandler) {
  48427. _this._MSGestureHandler = new MSGesture();
  48428. _this._MSGestureHandler.target = element;
  48429. }
  48430. _this._MSGestureHandler.addPointer(e.pointerId);
  48431. };
  48432. this._onGesture = function (e) {
  48433. _this.camera.radius *= e.scale;
  48434. if (e.preventDefault) {
  48435. if (!noPreventDefault) {
  48436. e.stopPropagation();
  48437. e.preventDefault();
  48438. }
  48439. }
  48440. };
  48441. element.addEventListener("mousemove", this._onMouseMove, false);
  48442. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48443. element.addEventListener("MSGestureChange", this._onGesture, false);
  48444. BABYLON.Tools.RegisterTopRootEvents([
  48445. { name: "blur", handler: this._onLostFocus }
  48446. ]);
  48447. };
  48448. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48449. if (this._onLostFocus) {
  48450. BABYLON.Tools.UnregisterTopRootEvents([
  48451. { name: "blur", handler: this._onLostFocus }
  48452. ]);
  48453. }
  48454. if (element && this._observer) {
  48455. this.camera.getScene().onPointerObservable.remove(this._observer);
  48456. this._observer = null;
  48457. if (this._onContextMenu) {
  48458. element.removeEventListener("contextmenu", this._onContextMenu);
  48459. }
  48460. if (this._onMouseMove) {
  48461. element.removeEventListener("mousemove", this._onMouseMove);
  48462. }
  48463. if (this._onGestureStart) {
  48464. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48465. }
  48466. if (this._onGesture) {
  48467. element.removeEventListener("MSGestureChange", this._onGesture);
  48468. }
  48469. this._isPanClick = false;
  48470. this.pinchInwards = true;
  48471. this._onMouseMove = null;
  48472. this._onGestureStart = null;
  48473. this._onGesture = null;
  48474. this._MSGestureHandler = null;
  48475. this._onLostFocus = null;
  48476. this._onContextMenu = null;
  48477. }
  48478. };
  48479. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48480. return "ArcRotateCameraPointersInput";
  48481. };
  48482. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48483. return "pointers";
  48484. };
  48485. __decorate([
  48486. BABYLON.serialize()
  48487. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48488. __decorate([
  48489. BABYLON.serialize()
  48490. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48491. __decorate([
  48492. BABYLON.serialize()
  48493. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48494. __decorate([
  48495. BABYLON.serialize()
  48496. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48497. __decorate([
  48498. BABYLON.serialize()
  48499. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48500. __decorate([
  48501. BABYLON.serialize()
  48502. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48503. __decorate([
  48504. BABYLON.serialize()
  48505. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48506. __decorate([
  48507. BABYLON.serialize()
  48508. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48509. return ArcRotateCameraPointersInput;
  48510. }());
  48511. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48512. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48513. })(BABYLON || (BABYLON = {}));
  48514. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48515. var BABYLON;
  48516. (function (BABYLON) {
  48517. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48518. __extends(ArcRotateCameraInputsManager, _super);
  48519. function ArcRotateCameraInputsManager(camera) {
  48520. return _super.call(this, camera) || this;
  48521. }
  48522. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48523. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48524. return this;
  48525. };
  48526. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48527. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48528. return this;
  48529. };
  48530. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48531. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48532. return this;
  48533. };
  48534. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48535. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48536. return this;
  48537. };
  48538. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48539. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48540. return this;
  48541. };
  48542. return ArcRotateCameraInputsManager;
  48543. }(BABYLON.CameraInputsManager));
  48544. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48545. })(BABYLON || (BABYLON = {}));
  48546. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48547. var BABYLON;
  48548. (function (BABYLON) {
  48549. var ArcRotateCamera = /** @class */ (function (_super) {
  48550. __extends(ArcRotateCamera, _super);
  48551. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48552. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48553. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48554. _this.inertialAlphaOffset = 0;
  48555. _this.inertialBetaOffset = 0;
  48556. _this.inertialRadiusOffset = 0;
  48557. _this.lowerAlphaLimit = null;
  48558. _this.upperAlphaLimit = null;
  48559. _this.lowerBetaLimit = 0.01;
  48560. _this.upperBetaLimit = Math.PI;
  48561. _this.lowerRadiusLimit = null;
  48562. _this.upperRadiusLimit = null;
  48563. _this.inertialPanningX = 0;
  48564. _this.inertialPanningY = 0;
  48565. _this.pinchToPanMaxDistance = 20;
  48566. _this.panningDistanceLimit = null;
  48567. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48568. _this.panningInertia = 0.9;
  48569. //-- end properties for backward compatibility for inputs
  48570. _this.zoomOnFactor = 1;
  48571. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48572. _this.allowUpsideDown = true;
  48573. _this._viewMatrix = new BABYLON.Matrix();
  48574. // Panning
  48575. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48576. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48577. _this.checkCollisions = false;
  48578. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48579. _this._previousPosition = BABYLON.Vector3.Zero();
  48580. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48581. _this._newPosition = BABYLON.Vector3.Zero();
  48582. _this._computationVector = BABYLON.Vector3.Zero();
  48583. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48584. if (collidedMesh === void 0) { collidedMesh = null; }
  48585. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48586. newPosition.multiplyInPlace(_this._collider._radius);
  48587. }
  48588. if (!collidedMesh) {
  48589. _this._previousPosition.copyFrom(_this.position);
  48590. }
  48591. else {
  48592. _this.setPosition(newPosition);
  48593. if (_this.onCollide) {
  48594. _this.onCollide(collidedMesh);
  48595. }
  48596. }
  48597. // Recompute because of constraints
  48598. var cosa = Math.cos(_this.alpha);
  48599. var sina = Math.sin(_this.alpha);
  48600. var cosb = Math.cos(_this.beta);
  48601. var sinb = Math.sin(_this.beta);
  48602. if (sinb === 0) {
  48603. sinb = 0.0001;
  48604. }
  48605. var target = _this._getTargetPosition();
  48606. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48607. target.addToRef(_this._computationVector, _this._newPosition);
  48608. _this.position.copyFrom(_this._newPosition);
  48609. var up = _this.upVector;
  48610. if (_this.allowUpsideDown && _this.beta < 0) {
  48611. up = up.clone();
  48612. up = up.negate();
  48613. }
  48614. _this._computeViewMatrix(_this.position, target, up);
  48615. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48616. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48617. _this._collisionTriggered = false;
  48618. };
  48619. _this._target = BABYLON.Vector3.Zero();
  48620. if (target) {
  48621. _this.setTarget(target);
  48622. }
  48623. _this.alpha = alpha;
  48624. _this.beta = beta;
  48625. _this.radius = radius;
  48626. _this.getViewMatrix();
  48627. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48628. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48629. return _this;
  48630. }
  48631. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48632. get: function () {
  48633. return this._target;
  48634. },
  48635. set: function (value) {
  48636. this.setTarget(value);
  48637. },
  48638. enumerable: true,
  48639. configurable: true
  48640. });
  48641. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48642. //-- begin properties for backward compatibility for inputs
  48643. get: function () {
  48644. var pointers = this.inputs.attached["pointers"];
  48645. if (pointers)
  48646. return pointers.angularSensibilityX;
  48647. return 0;
  48648. },
  48649. set: function (value) {
  48650. var pointers = this.inputs.attached["pointers"];
  48651. if (pointers) {
  48652. pointers.angularSensibilityX = value;
  48653. }
  48654. },
  48655. enumerable: true,
  48656. configurable: true
  48657. });
  48658. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48659. get: function () {
  48660. var pointers = this.inputs.attached["pointers"];
  48661. if (pointers)
  48662. return pointers.angularSensibilityY;
  48663. return 0;
  48664. },
  48665. set: function (value) {
  48666. var pointers = this.inputs.attached["pointers"];
  48667. if (pointers) {
  48668. pointers.angularSensibilityY = value;
  48669. }
  48670. },
  48671. enumerable: true,
  48672. configurable: true
  48673. });
  48674. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48675. get: function () {
  48676. var pointers = this.inputs.attached["pointers"];
  48677. if (pointers)
  48678. return pointers.pinchPrecision;
  48679. return 0;
  48680. },
  48681. set: function (value) {
  48682. var pointers = this.inputs.attached["pointers"];
  48683. if (pointers) {
  48684. pointers.pinchPrecision = value;
  48685. }
  48686. },
  48687. enumerable: true,
  48688. configurable: true
  48689. });
  48690. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48691. get: function () {
  48692. var pointers = this.inputs.attached["pointers"];
  48693. if (pointers)
  48694. return pointers.pinchDeltaPercentage;
  48695. return 0;
  48696. },
  48697. set: function (value) {
  48698. var pointers = this.inputs.attached["pointers"];
  48699. if (pointers) {
  48700. pointers.pinchDeltaPercentage = value;
  48701. }
  48702. },
  48703. enumerable: true,
  48704. configurable: true
  48705. });
  48706. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48707. get: function () {
  48708. var pointers = this.inputs.attached["pointers"];
  48709. if (pointers)
  48710. return pointers.panningSensibility;
  48711. return 0;
  48712. },
  48713. set: function (value) {
  48714. var pointers = this.inputs.attached["pointers"];
  48715. if (pointers) {
  48716. pointers.panningSensibility = value;
  48717. }
  48718. },
  48719. enumerable: true,
  48720. configurable: true
  48721. });
  48722. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48723. get: function () {
  48724. var keyboard = this.inputs.attached["keyboard"];
  48725. if (keyboard)
  48726. return keyboard.keysUp;
  48727. return [];
  48728. },
  48729. set: function (value) {
  48730. var keyboard = this.inputs.attached["keyboard"];
  48731. if (keyboard)
  48732. keyboard.keysUp = value;
  48733. },
  48734. enumerable: true,
  48735. configurable: true
  48736. });
  48737. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48738. get: function () {
  48739. var keyboard = this.inputs.attached["keyboard"];
  48740. if (keyboard)
  48741. return keyboard.keysDown;
  48742. return [];
  48743. },
  48744. set: function (value) {
  48745. var keyboard = this.inputs.attached["keyboard"];
  48746. if (keyboard)
  48747. keyboard.keysDown = value;
  48748. },
  48749. enumerable: true,
  48750. configurable: true
  48751. });
  48752. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48753. get: function () {
  48754. var keyboard = this.inputs.attached["keyboard"];
  48755. if (keyboard)
  48756. return keyboard.keysLeft;
  48757. return [];
  48758. },
  48759. set: function (value) {
  48760. var keyboard = this.inputs.attached["keyboard"];
  48761. if (keyboard)
  48762. keyboard.keysLeft = value;
  48763. },
  48764. enumerable: true,
  48765. configurable: true
  48766. });
  48767. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48768. get: function () {
  48769. var keyboard = this.inputs.attached["keyboard"];
  48770. if (keyboard)
  48771. return keyboard.keysRight;
  48772. return [];
  48773. },
  48774. set: function (value) {
  48775. var keyboard = this.inputs.attached["keyboard"];
  48776. if (keyboard)
  48777. keyboard.keysRight = value;
  48778. },
  48779. enumerable: true,
  48780. configurable: true
  48781. });
  48782. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48783. get: function () {
  48784. var mousewheel = this.inputs.attached["mousewheel"];
  48785. if (mousewheel)
  48786. return mousewheel.wheelPrecision;
  48787. return 0;
  48788. },
  48789. set: function (value) {
  48790. var mousewheel = this.inputs.attached["mousewheel"];
  48791. if (mousewheel)
  48792. mousewheel.wheelPrecision = value;
  48793. },
  48794. enumerable: true,
  48795. configurable: true
  48796. });
  48797. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48798. get: function () {
  48799. var mousewheel = this.inputs.attached["mousewheel"];
  48800. if (mousewheel)
  48801. return mousewheel.wheelDeltaPercentage;
  48802. return 0;
  48803. },
  48804. set: function (value) {
  48805. var mousewheel = this.inputs.attached["mousewheel"];
  48806. if (mousewheel)
  48807. mousewheel.wheelDeltaPercentage = value;
  48808. },
  48809. enumerable: true,
  48810. configurable: true
  48811. });
  48812. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48813. get: function () {
  48814. return this._bouncingBehavior;
  48815. },
  48816. enumerable: true,
  48817. configurable: true
  48818. });
  48819. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48820. get: function () {
  48821. return this._bouncingBehavior != null;
  48822. },
  48823. set: function (value) {
  48824. if (value === this.useBouncingBehavior) {
  48825. return;
  48826. }
  48827. if (value) {
  48828. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48829. this.addBehavior(this._bouncingBehavior);
  48830. }
  48831. else if (this._bouncingBehavior) {
  48832. this.removeBehavior(this._bouncingBehavior);
  48833. this._bouncingBehavior = null;
  48834. }
  48835. },
  48836. enumerable: true,
  48837. configurable: true
  48838. });
  48839. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48840. get: function () {
  48841. return this._framingBehavior;
  48842. },
  48843. enumerable: true,
  48844. configurable: true
  48845. });
  48846. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48847. get: function () {
  48848. return this._framingBehavior != null;
  48849. },
  48850. set: function (value) {
  48851. if (value === this.useFramingBehavior) {
  48852. return;
  48853. }
  48854. if (value) {
  48855. this._framingBehavior = new BABYLON.FramingBehavior();
  48856. this.addBehavior(this._framingBehavior);
  48857. }
  48858. else if (this._framingBehavior) {
  48859. this.removeBehavior(this._framingBehavior);
  48860. this._framingBehavior = null;
  48861. }
  48862. },
  48863. enumerable: true,
  48864. configurable: true
  48865. });
  48866. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48867. get: function () {
  48868. return this._autoRotationBehavior;
  48869. },
  48870. enumerable: true,
  48871. configurable: true
  48872. });
  48873. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48874. get: function () {
  48875. return this._autoRotationBehavior != null;
  48876. },
  48877. set: function (value) {
  48878. if (value === this.useAutoRotationBehavior) {
  48879. return;
  48880. }
  48881. if (value) {
  48882. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48883. this.addBehavior(this._autoRotationBehavior);
  48884. }
  48885. else if (this._autoRotationBehavior) {
  48886. this.removeBehavior(this._autoRotationBehavior);
  48887. this._autoRotationBehavior = null;
  48888. }
  48889. },
  48890. enumerable: true,
  48891. configurable: true
  48892. });
  48893. // Cache
  48894. ArcRotateCamera.prototype._initCache = function () {
  48895. _super.prototype._initCache.call(this);
  48896. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48897. this._cache.alpha = undefined;
  48898. this._cache.beta = undefined;
  48899. this._cache.radius = undefined;
  48900. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48901. };
  48902. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48903. if (!ignoreParentClass) {
  48904. _super.prototype._updateCache.call(this);
  48905. }
  48906. this._cache._target.copyFrom(this._getTargetPosition());
  48907. this._cache.alpha = this.alpha;
  48908. this._cache.beta = this.beta;
  48909. this._cache.radius = this.radius;
  48910. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48911. };
  48912. ArcRotateCamera.prototype._getTargetPosition = function () {
  48913. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48914. var pos = this._targetHost.getAbsolutePosition();
  48915. if (this._targetBoundingCenter) {
  48916. pos.addToRef(this._targetBoundingCenter, this._target);
  48917. }
  48918. else {
  48919. this._target.copyFrom(pos);
  48920. }
  48921. }
  48922. var lockedTargetPosition = this._getLockedTargetPosition();
  48923. if (lockedTargetPosition) {
  48924. return lockedTargetPosition;
  48925. }
  48926. return this._target;
  48927. };
  48928. ArcRotateCamera.prototype.storeState = function () {
  48929. this._storedAlpha = this.alpha;
  48930. this._storedBeta = this.beta;
  48931. this._storedRadius = this.radius;
  48932. this._storedTarget = this._getTargetPosition().clone();
  48933. return _super.prototype.storeState.call(this);
  48934. };
  48935. /**
  48936. * Restored camera state. You must call storeState() first
  48937. */
  48938. ArcRotateCamera.prototype._restoreStateValues = function () {
  48939. if (!_super.prototype._restoreStateValues.call(this)) {
  48940. return false;
  48941. }
  48942. this.alpha = this._storedAlpha;
  48943. this.beta = this._storedBeta;
  48944. this.radius = this._storedRadius;
  48945. this.setTarget(this._storedTarget.clone());
  48946. this.inertialAlphaOffset = 0;
  48947. this.inertialBetaOffset = 0;
  48948. this.inertialRadiusOffset = 0;
  48949. this.inertialPanningX = 0;
  48950. this.inertialPanningY = 0;
  48951. return true;
  48952. };
  48953. // Synchronized
  48954. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48955. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48956. return false;
  48957. return this._cache._target.equals(this._getTargetPosition())
  48958. && this._cache.alpha === this.alpha
  48959. && this._cache.beta === this.beta
  48960. && this._cache.radius === this.radius
  48961. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48962. };
  48963. // Methods
  48964. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48965. var _this = this;
  48966. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48967. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48968. this._useCtrlForPanning = useCtrlForPanning;
  48969. this._panningMouseButton = panningMouseButton;
  48970. this.inputs.attachElement(element, noPreventDefault);
  48971. this._reset = function () {
  48972. _this.inertialAlphaOffset = 0;
  48973. _this.inertialBetaOffset = 0;
  48974. _this.inertialRadiusOffset = 0;
  48975. _this.inertialPanningX = 0;
  48976. _this.inertialPanningY = 0;
  48977. };
  48978. };
  48979. ArcRotateCamera.prototype.detachControl = function (element) {
  48980. this.inputs.detachElement(element);
  48981. if (this._reset) {
  48982. this._reset();
  48983. }
  48984. };
  48985. ArcRotateCamera.prototype._checkInputs = function () {
  48986. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48987. if (this._collisionTriggered) {
  48988. return;
  48989. }
  48990. this.inputs.checkInputs();
  48991. // Inertia
  48992. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48993. var inertialAlphaOffset = this.inertialAlphaOffset;
  48994. if (this.beta <= 0)
  48995. inertialAlphaOffset *= -1;
  48996. if (this.getScene().useRightHandedSystem)
  48997. inertialAlphaOffset *= -1;
  48998. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48999. inertialAlphaOffset *= -1;
  49000. this.alpha += inertialAlphaOffset;
  49001. this.beta += this.inertialBetaOffset;
  49002. this.radius -= this.inertialRadiusOffset;
  49003. this.inertialAlphaOffset *= this.inertia;
  49004. this.inertialBetaOffset *= this.inertia;
  49005. this.inertialRadiusOffset *= this.inertia;
  49006. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  49007. this.inertialAlphaOffset = 0;
  49008. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  49009. this.inertialBetaOffset = 0;
  49010. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49011. this.inertialRadiusOffset = 0;
  49012. }
  49013. // Panning inertia
  49014. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49015. if (!this._localDirection) {
  49016. this._localDirection = BABYLON.Vector3.Zero();
  49017. this._transformedDirection = BABYLON.Vector3.Zero();
  49018. }
  49019. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49020. this._localDirection.multiplyInPlace(this.panningAxis);
  49021. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49022. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49023. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49024. if (!this.panningAxis.y) {
  49025. this._transformedDirection.y = 0;
  49026. }
  49027. if (!this._targetHost) {
  49028. if (this.panningDistanceLimit) {
  49029. this._transformedDirection.addInPlace(this._target);
  49030. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49031. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49032. this._target.copyFrom(this._transformedDirection);
  49033. }
  49034. }
  49035. else {
  49036. this._target.addInPlace(this._transformedDirection);
  49037. }
  49038. }
  49039. this.inertialPanningX *= this.panningInertia;
  49040. this.inertialPanningY *= this.panningInertia;
  49041. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49042. this.inertialPanningX = 0;
  49043. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49044. this.inertialPanningY = 0;
  49045. }
  49046. // Limits
  49047. this._checkLimits();
  49048. _super.prototype._checkInputs.call(this);
  49049. };
  49050. ArcRotateCamera.prototype._checkLimits = function () {
  49051. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49052. if (this.allowUpsideDown && this.beta > Math.PI) {
  49053. this.beta = this.beta - (2 * Math.PI);
  49054. }
  49055. }
  49056. else {
  49057. if (this.beta < this.lowerBetaLimit) {
  49058. this.beta = this.lowerBetaLimit;
  49059. }
  49060. }
  49061. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49062. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49063. this.beta = this.beta + (2 * Math.PI);
  49064. }
  49065. }
  49066. else {
  49067. if (this.beta > this.upperBetaLimit) {
  49068. this.beta = this.upperBetaLimit;
  49069. }
  49070. }
  49071. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  49072. this.alpha = this.lowerAlphaLimit;
  49073. }
  49074. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  49075. this.alpha = this.upperAlphaLimit;
  49076. }
  49077. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  49078. this.radius = this.lowerRadiusLimit;
  49079. }
  49080. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  49081. this.radius = this.upperRadiusLimit;
  49082. }
  49083. };
  49084. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49085. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49086. this.radius = this._computationVector.length();
  49087. if (this.radius === 0) {
  49088. this.radius = 0.0001; // Just to avoid division by zero
  49089. }
  49090. // Alpha
  49091. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49092. if (this._computationVector.z < 0) {
  49093. this.alpha = 2 * Math.PI - this.alpha;
  49094. }
  49095. // Beta
  49096. this.beta = Math.acos(this._computationVector.y / this.radius);
  49097. this._checkLimits();
  49098. };
  49099. ArcRotateCamera.prototype.setPosition = function (position) {
  49100. if (this.position.equals(position)) {
  49101. return;
  49102. }
  49103. this.position.copyFrom(position);
  49104. this.rebuildAnglesAndRadius();
  49105. };
  49106. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49107. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49108. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49109. if (target.getBoundingInfo) {
  49110. if (toBoundingCenter) {
  49111. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49112. }
  49113. else {
  49114. this._targetBoundingCenter = null;
  49115. }
  49116. this._targetHost = target;
  49117. this._target = this._getTargetPosition();
  49118. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49119. }
  49120. else {
  49121. var newTarget = target;
  49122. var currentTarget = this._getTargetPosition();
  49123. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49124. return;
  49125. }
  49126. this._targetHost = null;
  49127. this._target = newTarget;
  49128. this._targetBoundingCenter = null;
  49129. this.onMeshTargetChangedObservable.notifyObservers(null);
  49130. }
  49131. this.rebuildAnglesAndRadius();
  49132. };
  49133. ArcRotateCamera.prototype._getViewMatrix = function () {
  49134. // Compute
  49135. var cosa = Math.cos(this.alpha);
  49136. var sina = Math.sin(this.alpha);
  49137. var cosb = Math.cos(this.beta);
  49138. var sinb = Math.sin(this.beta);
  49139. if (sinb === 0) {
  49140. sinb = 0.0001;
  49141. }
  49142. var target = this._getTargetPosition();
  49143. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49144. target.addToRef(this._computationVector, this._newPosition);
  49145. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49146. if (!this._collider) {
  49147. this._collider = new BABYLON.Collider();
  49148. }
  49149. this._collider._radius = this.collisionRadius;
  49150. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49151. this._collisionTriggered = true;
  49152. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49153. }
  49154. else {
  49155. this.position.copyFrom(this._newPosition);
  49156. var up = this.upVector;
  49157. if (this.allowUpsideDown && sinb < 0) {
  49158. up = up.clone();
  49159. up = up.negate();
  49160. }
  49161. this._computeViewMatrix(this.position, target, up);
  49162. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49163. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49164. }
  49165. this._currentTarget = target;
  49166. return this._viewMatrix;
  49167. };
  49168. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49169. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49170. meshes = meshes || this.getScene().meshes;
  49171. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49172. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49173. this.radius = distance * this.zoomOnFactor;
  49174. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49175. };
  49176. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49177. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49178. var meshesOrMinMaxVector;
  49179. var distance;
  49180. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49181. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49182. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49183. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49184. }
  49185. else { //minMaxVector and distance
  49186. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49187. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49188. distance = minMaxVectorAndDistance.distance;
  49189. }
  49190. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49191. if (!doNotUpdateMaxZ) {
  49192. this.maxZ = distance * 2;
  49193. }
  49194. };
  49195. /**
  49196. * @override
  49197. * Override Camera.createRigCamera
  49198. */
  49199. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49200. var alphaShift = 0;
  49201. switch (this.cameraRigMode) {
  49202. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49203. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49204. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49205. case BABYLON.Camera.RIG_MODE_VR:
  49206. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49207. break;
  49208. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49209. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49210. break;
  49211. }
  49212. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49213. rigCam._cameraRigParams = {};
  49214. return rigCam;
  49215. };
  49216. /**
  49217. * @override
  49218. * Override Camera._updateRigCameras
  49219. */
  49220. ArcRotateCamera.prototype._updateRigCameras = function () {
  49221. var camLeft = this._rigCameras[0];
  49222. var camRight = this._rigCameras[1];
  49223. camLeft.beta = camRight.beta = this.beta;
  49224. camLeft.radius = camRight.radius = this.radius;
  49225. switch (this.cameraRigMode) {
  49226. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49227. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49228. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49229. case BABYLON.Camera.RIG_MODE_VR:
  49230. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49231. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49232. break;
  49233. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49234. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49235. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49236. break;
  49237. }
  49238. _super.prototype._updateRigCameras.call(this);
  49239. };
  49240. ArcRotateCamera.prototype.dispose = function () {
  49241. this.inputs.clear();
  49242. _super.prototype.dispose.call(this);
  49243. };
  49244. ArcRotateCamera.prototype.getClassName = function () {
  49245. return "ArcRotateCamera";
  49246. };
  49247. __decorate([
  49248. BABYLON.serialize()
  49249. ], ArcRotateCamera.prototype, "alpha", void 0);
  49250. __decorate([
  49251. BABYLON.serialize()
  49252. ], ArcRotateCamera.prototype, "beta", void 0);
  49253. __decorate([
  49254. BABYLON.serialize()
  49255. ], ArcRotateCamera.prototype, "radius", void 0);
  49256. __decorate([
  49257. BABYLON.serializeAsVector3("target")
  49258. ], ArcRotateCamera.prototype, "_target", void 0);
  49259. __decorate([
  49260. BABYLON.serialize()
  49261. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49262. __decorate([
  49263. BABYLON.serialize()
  49264. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49265. __decorate([
  49266. BABYLON.serialize()
  49267. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49268. __decorate([
  49269. BABYLON.serialize()
  49270. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49271. __decorate([
  49272. BABYLON.serialize()
  49273. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49274. __decorate([
  49275. BABYLON.serialize()
  49276. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49277. __decorate([
  49278. BABYLON.serialize()
  49279. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49280. __decorate([
  49281. BABYLON.serialize()
  49282. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49283. __decorate([
  49284. BABYLON.serialize()
  49285. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49286. __decorate([
  49287. BABYLON.serialize()
  49288. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49289. __decorate([
  49290. BABYLON.serialize()
  49291. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49292. __decorate([
  49293. BABYLON.serialize()
  49294. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49295. __decorate([
  49296. BABYLON.serialize()
  49297. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49298. __decorate([
  49299. BABYLON.serializeAsVector3()
  49300. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49301. __decorate([
  49302. BABYLON.serialize()
  49303. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49304. __decorate([
  49305. BABYLON.serialize()
  49306. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49307. __decorate([
  49308. BABYLON.serialize()
  49309. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49310. return ArcRotateCamera;
  49311. }(BABYLON.TargetCamera));
  49312. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49313. })(BABYLON || (BABYLON = {}));
  49314. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49315. var BABYLON;
  49316. (function (BABYLON) {
  49317. /**
  49318. * The HemisphericLight simulates the ambient environment light,
  49319. * so the passed direction is the light reflection direction, not the incoming direction.
  49320. */
  49321. var HemisphericLight = /** @class */ (function (_super) {
  49322. __extends(HemisphericLight, _super);
  49323. /**
  49324. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49325. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49326. * The HemisphericLight can't cast shadows.
  49327. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49328. * @param name The friendly name of the light
  49329. * @param direction The direction of the light reflection
  49330. * @param scene The scene the light belongs to
  49331. */
  49332. function HemisphericLight(name, direction, scene) {
  49333. var _this = _super.call(this, name, scene) || this;
  49334. /**
  49335. * The groundColor is the light in the opposite direction to the one specified during creation.
  49336. * 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.
  49337. */
  49338. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49339. _this.direction = direction || BABYLON.Vector3.Up();
  49340. return _this;
  49341. }
  49342. HemisphericLight.prototype._buildUniformLayout = function () {
  49343. this._uniformBuffer.addUniform("vLightData", 4);
  49344. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49345. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49346. this._uniformBuffer.addUniform("vLightGround", 3);
  49347. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49348. this._uniformBuffer.addUniform("depthValues", 2);
  49349. this._uniformBuffer.create();
  49350. };
  49351. /**
  49352. * Returns the string "HemisphericLight".
  49353. * @return The class name
  49354. */
  49355. HemisphericLight.prototype.getClassName = function () {
  49356. return "HemisphericLight";
  49357. };
  49358. /**
  49359. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49360. * Returns the updated direction.
  49361. * @param target The target the direction should point to
  49362. * @return The computed direction
  49363. */
  49364. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49365. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49366. return this.direction;
  49367. };
  49368. /**
  49369. * Returns the shadow generator associated to the light.
  49370. * @returns Always null for hemispheric lights because it does not support shadows.
  49371. */
  49372. HemisphericLight.prototype.getShadowGenerator = function () {
  49373. return null;
  49374. };
  49375. /**
  49376. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49377. * @param effect The effect to update
  49378. * @param lightIndex The index of the light in the effect to update
  49379. * @returns The hemispheric light
  49380. */
  49381. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49382. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49383. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49384. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49385. return this;
  49386. };
  49387. /**
  49388. * @hidden internal use only.
  49389. */
  49390. HemisphericLight.prototype._getWorldMatrix = function () {
  49391. if (!this._worldMatrix) {
  49392. this._worldMatrix = BABYLON.Matrix.Identity();
  49393. }
  49394. return this._worldMatrix;
  49395. };
  49396. /**
  49397. * Returns the integer 3.
  49398. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49399. */
  49400. HemisphericLight.prototype.getTypeID = function () {
  49401. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49402. };
  49403. __decorate([
  49404. BABYLON.serializeAsColor3()
  49405. ], HemisphericLight.prototype, "groundColor", void 0);
  49406. __decorate([
  49407. BABYLON.serializeAsVector3()
  49408. ], HemisphericLight.prototype, "direction", void 0);
  49409. return HemisphericLight;
  49410. }(BABYLON.Light));
  49411. BABYLON.HemisphericLight = HemisphericLight;
  49412. })(BABYLON || (BABYLON = {}));
  49413. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49414. var BABYLON;
  49415. (function (BABYLON) {
  49416. /**
  49417. * Base implementation IShadowLight
  49418. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49419. */
  49420. var ShadowLight = /** @class */ (function (_super) {
  49421. __extends(ShadowLight, _super);
  49422. function ShadowLight() {
  49423. var _this = _super !== null && _super.apply(this, arguments) || this;
  49424. _this._needProjectionMatrixCompute = true;
  49425. return _this;
  49426. }
  49427. ShadowLight.prototype._setPosition = function (value) {
  49428. this._position = value;
  49429. };
  49430. Object.defineProperty(ShadowLight.prototype, "position", {
  49431. /**
  49432. * Sets the position the shadow will be casted from. Also use as the light position for both
  49433. * point and spot lights.
  49434. */
  49435. get: function () {
  49436. return this._position;
  49437. },
  49438. /**
  49439. * Sets the position the shadow will be casted from. Also use as the light position for both
  49440. * point and spot lights.
  49441. */
  49442. set: function (value) {
  49443. this._setPosition(value);
  49444. },
  49445. enumerable: true,
  49446. configurable: true
  49447. });
  49448. ShadowLight.prototype._setDirection = function (value) {
  49449. this._direction = value;
  49450. };
  49451. Object.defineProperty(ShadowLight.prototype, "direction", {
  49452. /**
  49453. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49454. * Also use as the light direction on spot and directional lights.
  49455. */
  49456. get: function () {
  49457. return this._direction;
  49458. },
  49459. /**
  49460. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49461. * Also use as the light direction on spot and directional lights.
  49462. */
  49463. set: function (value) {
  49464. this._setDirection(value);
  49465. },
  49466. enumerable: true,
  49467. configurable: true
  49468. });
  49469. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49470. /**
  49471. * Gets the shadow projection clipping minimum z value.
  49472. */
  49473. get: function () {
  49474. return this._shadowMinZ;
  49475. },
  49476. /**
  49477. * Sets the shadow projection clipping minimum z value.
  49478. */
  49479. set: function (value) {
  49480. this._shadowMinZ = value;
  49481. this.forceProjectionMatrixCompute();
  49482. },
  49483. enumerable: true,
  49484. configurable: true
  49485. });
  49486. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49487. /**
  49488. * Sets the shadow projection clipping maximum z value.
  49489. */
  49490. get: function () {
  49491. return this._shadowMaxZ;
  49492. },
  49493. /**
  49494. * Gets the shadow projection clipping maximum z value.
  49495. */
  49496. set: function (value) {
  49497. this._shadowMaxZ = value;
  49498. this.forceProjectionMatrixCompute();
  49499. },
  49500. enumerable: true,
  49501. configurable: true
  49502. });
  49503. /**
  49504. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49505. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49506. */
  49507. ShadowLight.prototype.computeTransformedInformation = function () {
  49508. if (this.parent && this.parent.getWorldMatrix) {
  49509. if (!this.transformedPosition) {
  49510. this.transformedPosition = BABYLON.Vector3.Zero();
  49511. }
  49512. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49513. // In case the direction is present.
  49514. if (this.direction) {
  49515. if (!this.transformedDirection) {
  49516. this.transformedDirection = BABYLON.Vector3.Zero();
  49517. }
  49518. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49519. }
  49520. return true;
  49521. }
  49522. return false;
  49523. };
  49524. /**
  49525. * Return the depth scale used for the shadow map.
  49526. * @returns the depth scale.
  49527. */
  49528. ShadowLight.prototype.getDepthScale = function () {
  49529. return 50.0;
  49530. };
  49531. /**
  49532. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49533. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49534. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49535. */
  49536. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49537. return this.transformedDirection ? this.transformedDirection : this.direction;
  49538. };
  49539. /**
  49540. * Returns the ShadowLight absolute position in the World.
  49541. * @returns the position vector in world space
  49542. */
  49543. ShadowLight.prototype.getAbsolutePosition = function () {
  49544. return this.transformedPosition ? this.transformedPosition : this.position;
  49545. };
  49546. /**
  49547. * Sets the ShadowLight direction toward the passed target.
  49548. * @param target The point tot target in local space
  49549. * @returns the updated ShadowLight direction
  49550. */
  49551. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49552. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49553. return this.direction;
  49554. };
  49555. /**
  49556. * Returns the light rotation in euler definition.
  49557. * @returns the x y z rotation in local space.
  49558. */
  49559. ShadowLight.prototype.getRotation = function () {
  49560. this.direction.normalize();
  49561. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49562. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49563. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49564. };
  49565. /**
  49566. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49567. * @returns true if a cube texture needs to be use
  49568. */
  49569. ShadowLight.prototype.needCube = function () {
  49570. return false;
  49571. };
  49572. /**
  49573. * Detects if the projection matrix requires to be recomputed this frame.
  49574. * @returns true if it requires to be recomputed otherwise, false.
  49575. */
  49576. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49577. return this._needProjectionMatrixCompute;
  49578. };
  49579. /**
  49580. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49581. */
  49582. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49583. this._needProjectionMatrixCompute = true;
  49584. };
  49585. /**
  49586. * Get the world matrix of the sahdow lights.
  49587. * @hidden Internal Use Only
  49588. */
  49589. ShadowLight.prototype._getWorldMatrix = function () {
  49590. if (!this._worldMatrix) {
  49591. this._worldMatrix = BABYLON.Matrix.Identity();
  49592. }
  49593. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49594. return this._worldMatrix;
  49595. };
  49596. /**
  49597. * Gets the minZ used for shadow according to both the scene and the light.
  49598. * @param activeCamera The camera we are returning the min for
  49599. * @returns the depth min z
  49600. */
  49601. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49602. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49603. };
  49604. /**
  49605. * Gets the maxZ used for shadow according to both the scene and the light.
  49606. * @param activeCamera The camera we are returning the max for
  49607. * @returns the depth max z
  49608. */
  49609. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49610. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49611. };
  49612. /**
  49613. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49614. * @param matrix The materix to updated with the projection information
  49615. * @param viewMatrix The transform matrix of the light
  49616. * @param renderList The list of mesh to render in the map
  49617. * @returns The current light
  49618. */
  49619. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49620. if (this.customProjectionMatrixBuilder) {
  49621. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49622. }
  49623. else {
  49624. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49625. }
  49626. return this;
  49627. };
  49628. __decorate([
  49629. BABYLON.serializeAsVector3()
  49630. ], ShadowLight.prototype, "position", null);
  49631. __decorate([
  49632. BABYLON.serializeAsVector3()
  49633. ], ShadowLight.prototype, "direction", null);
  49634. __decorate([
  49635. BABYLON.serialize()
  49636. ], ShadowLight.prototype, "shadowMinZ", null);
  49637. __decorate([
  49638. BABYLON.serialize()
  49639. ], ShadowLight.prototype, "shadowMaxZ", null);
  49640. return ShadowLight;
  49641. }(BABYLON.Light));
  49642. BABYLON.ShadowLight = ShadowLight;
  49643. })(BABYLON || (BABYLON = {}));
  49644. //# sourceMappingURL=babylon.shadowLight.js.map
  49645. var BABYLON;
  49646. (function (BABYLON) {
  49647. /**
  49648. * A point light is a light defined by an unique point in world space.
  49649. * The light is emitted in every direction from this point.
  49650. * A good example of a point light is a standard light bulb.
  49651. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49652. */
  49653. var PointLight = /** @class */ (function (_super) {
  49654. __extends(PointLight, _super);
  49655. /**
  49656. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49657. * A PointLight emits the light in every direction.
  49658. * It can cast shadows.
  49659. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49660. * ```javascript
  49661. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49662. * ```
  49663. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49664. * @param name The light friendly name
  49665. * @param position The position of the point light in the scene
  49666. * @param scene The scene the lights belongs to
  49667. */
  49668. function PointLight(name, position, scene) {
  49669. var _this = _super.call(this, name, scene) || this;
  49670. _this._shadowAngle = Math.PI / 2;
  49671. _this.position = position;
  49672. return _this;
  49673. }
  49674. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49675. /**
  49676. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49677. * This specifies what angle the shadow will use to be created.
  49678. *
  49679. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49680. */
  49681. get: function () {
  49682. return this._shadowAngle;
  49683. },
  49684. /**
  49685. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49686. * This specifies what angle the shadow will use to be created.
  49687. *
  49688. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49689. */
  49690. set: function (value) {
  49691. this._shadowAngle = value;
  49692. this.forceProjectionMatrixCompute();
  49693. },
  49694. enumerable: true,
  49695. configurable: true
  49696. });
  49697. Object.defineProperty(PointLight.prototype, "direction", {
  49698. /**
  49699. * Gets the direction if it has been set.
  49700. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49701. */
  49702. get: function () {
  49703. return this._direction;
  49704. },
  49705. /**
  49706. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49707. */
  49708. set: function (value) {
  49709. var previousNeedCube = this.needCube();
  49710. this._direction = value;
  49711. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49712. this._shadowGenerator.recreateShadowMap();
  49713. }
  49714. },
  49715. enumerable: true,
  49716. configurable: true
  49717. });
  49718. /**
  49719. * Returns the string "PointLight"
  49720. * @returns the class name
  49721. */
  49722. PointLight.prototype.getClassName = function () {
  49723. return "PointLight";
  49724. };
  49725. /**
  49726. * Returns the integer 0.
  49727. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49728. */
  49729. PointLight.prototype.getTypeID = function () {
  49730. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49731. };
  49732. /**
  49733. * Specifies wether or not the shadowmap should be a cube texture.
  49734. * @returns true if the shadowmap needs to be a cube texture.
  49735. */
  49736. PointLight.prototype.needCube = function () {
  49737. return !this.direction;
  49738. };
  49739. /**
  49740. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49741. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49742. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49743. */
  49744. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49745. if (this.direction) {
  49746. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49747. }
  49748. else {
  49749. switch (faceIndex) {
  49750. case 0:
  49751. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49752. case 1:
  49753. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49754. case 2:
  49755. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49756. case 3:
  49757. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49758. case 4:
  49759. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49760. case 5:
  49761. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49762. }
  49763. }
  49764. return BABYLON.Vector3.Zero();
  49765. };
  49766. /**
  49767. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49768. * - fov = PI / 2
  49769. * - aspect ratio : 1.0
  49770. * - z-near and far equal to the active camera minZ and maxZ.
  49771. * Returns the PointLight.
  49772. */
  49773. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49774. var activeCamera = this.getScene().activeCamera;
  49775. if (!activeCamera) {
  49776. return;
  49777. }
  49778. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49779. };
  49780. PointLight.prototype._buildUniformLayout = function () {
  49781. this._uniformBuffer.addUniform("vLightData", 4);
  49782. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49783. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49784. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49785. this._uniformBuffer.addUniform("depthValues", 2);
  49786. this._uniformBuffer.create();
  49787. };
  49788. /**
  49789. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49790. * @param effect The effect to update
  49791. * @param lightIndex The index of the light in the effect to update
  49792. * @returns The point light
  49793. */
  49794. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49795. if (this.computeTransformedInformation()) {
  49796. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49797. return this;
  49798. }
  49799. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49800. return this;
  49801. };
  49802. __decorate([
  49803. BABYLON.serialize()
  49804. ], PointLight.prototype, "shadowAngle", null);
  49805. return PointLight;
  49806. }(BABYLON.ShadowLight));
  49807. BABYLON.PointLight = PointLight;
  49808. })(BABYLON || (BABYLON = {}));
  49809. //# sourceMappingURL=babylon.pointLight.js.map
  49810. var BABYLON;
  49811. (function (BABYLON) {
  49812. /**
  49813. * A directional light is defined by a direction (what a surprise!).
  49814. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49815. * 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.
  49816. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49817. */
  49818. var DirectionalLight = /** @class */ (function (_super) {
  49819. __extends(DirectionalLight, _super);
  49820. /**
  49821. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49822. * The directional light is emitted from everywhere in the given direction.
  49823. * It can cast shawdows.
  49824. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49825. * @param name The friendly name of the light
  49826. * @param direction The direction of the light
  49827. * @param scene The scene the light belongs to
  49828. */
  49829. function DirectionalLight(name, direction, scene) {
  49830. var _this = _super.call(this, name, scene) || this;
  49831. _this._shadowFrustumSize = 0;
  49832. _this._shadowOrthoScale = 0.1;
  49833. /**
  49834. * Automatically compute the projection matrix to best fit (including all the casters)
  49835. * on each frame.
  49836. */
  49837. _this.autoUpdateExtends = true;
  49838. // Cache
  49839. _this._orthoLeft = Number.MAX_VALUE;
  49840. _this._orthoRight = Number.MIN_VALUE;
  49841. _this._orthoTop = Number.MIN_VALUE;
  49842. _this._orthoBottom = Number.MAX_VALUE;
  49843. _this.position = direction.scale(-1.0);
  49844. _this.direction = direction;
  49845. return _this;
  49846. }
  49847. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49848. /**
  49849. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49850. */
  49851. get: function () {
  49852. return this._shadowFrustumSize;
  49853. },
  49854. /**
  49855. * Specifies a fix frustum size for the shadow generation.
  49856. */
  49857. set: function (value) {
  49858. this._shadowFrustumSize = value;
  49859. this.forceProjectionMatrixCompute();
  49860. },
  49861. enumerable: true,
  49862. configurable: true
  49863. });
  49864. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49865. /**
  49866. * Gets the shadow projection scale against the optimal computed one.
  49867. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49868. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49869. */
  49870. get: function () {
  49871. return this._shadowOrthoScale;
  49872. },
  49873. /**
  49874. * Sets the shadow projection scale against the optimal computed one.
  49875. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49876. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49877. */
  49878. set: function (value) {
  49879. this._shadowOrthoScale = value;
  49880. this.forceProjectionMatrixCompute();
  49881. },
  49882. enumerable: true,
  49883. configurable: true
  49884. });
  49885. /**
  49886. * Returns the string "DirectionalLight".
  49887. * @return The class name
  49888. */
  49889. DirectionalLight.prototype.getClassName = function () {
  49890. return "DirectionalLight";
  49891. };
  49892. /**
  49893. * Returns the integer 1.
  49894. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49895. */
  49896. DirectionalLight.prototype.getTypeID = function () {
  49897. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49898. };
  49899. /**
  49900. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49901. * Returns the DirectionalLight Shadow projection matrix.
  49902. */
  49903. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49904. if (this.shadowFrustumSize > 0) {
  49905. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49906. }
  49907. else {
  49908. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49909. }
  49910. };
  49911. /**
  49912. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49913. * Returns the DirectionalLight Shadow projection matrix.
  49914. */
  49915. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49916. var activeCamera = this.getScene().activeCamera;
  49917. if (!activeCamera) {
  49918. return;
  49919. }
  49920. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49921. };
  49922. /**
  49923. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49924. * Returns the DirectionalLight Shadow projection matrix.
  49925. */
  49926. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49927. var activeCamera = this.getScene().activeCamera;
  49928. if (!activeCamera) {
  49929. return;
  49930. }
  49931. // Check extends
  49932. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49933. var tempVector3 = BABYLON.Vector3.Zero();
  49934. this._orthoLeft = Number.MAX_VALUE;
  49935. this._orthoRight = Number.MIN_VALUE;
  49936. this._orthoTop = Number.MIN_VALUE;
  49937. this._orthoBottom = Number.MAX_VALUE;
  49938. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49939. var mesh = renderList[meshIndex];
  49940. if (!mesh) {
  49941. continue;
  49942. }
  49943. var boundingInfo = mesh.getBoundingInfo();
  49944. var boundingBox = boundingInfo.boundingBox;
  49945. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49946. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49947. if (tempVector3.x < this._orthoLeft)
  49948. this._orthoLeft = tempVector3.x;
  49949. if (tempVector3.y < this._orthoBottom)
  49950. this._orthoBottom = tempVector3.y;
  49951. if (tempVector3.x > this._orthoRight)
  49952. this._orthoRight = tempVector3.x;
  49953. if (tempVector3.y > this._orthoTop)
  49954. this._orthoTop = tempVector3.y;
  49955. }
  49956. }
  49957. }
  49958. var xOffset = this._orthoRight - this._orthoLeft;
  49959. var yOffset = this._orthoTop - this._orthoBottom;
  49960. 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);
  49961. };
  49962. DirectionalLight.prototype._buildUniformLayout = function () {
  49963. this._uniformBuffer.addUniform("vLightData", 4);
  49964. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49965. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49966. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49967. this._uniformBuffer.addUniform("depthValues", 2);
  49968. this._uniformBuffer.create();
  49969. };
  49970. /**
  49971. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49972. * @param effect The effect to update
  49973. * @param lightIndex The index of the light in the effect to update
  49974. * @returns The directional light
  49975. */
  49976. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49977. if (this.computeTransformedInformation()) {
  49978. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49979. return this;
  49980. }
  49981. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49982. return this;
  49983. };
  49984. /**
  49985. * Gets the minZ used for shadow according to both the scene and the light.
  49986. *
  49987. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49988. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49989. * @param activeCamera The camera we are returning the min for
  49990. * @returns the depth min z
  49991. */
  49992. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49993. return 1;
  49994. };
  49995. /**
  49996. * Gets the maxZ used for shadow according to both the scene and the light.
  49997. *
  49998. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49999. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50000. * @param activeCamera The camera we are returning the max for
  50001. * @returns the depth max z
  50002. */
  50003. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  50004. return 1;
  50005. };
  50006. __decorate([
  50007. BABYLON.serialize()
  50008. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  50009. __decorate([
  50010. BABYLON.serialize()
  50011. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  50012. __decorate([
  50013. BABYLON.serialize()
  50014. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  50015. return DirectionalLight;
  50016. }(BABYLON.ShadowLight));
  50017. BABYLON.DirectionalLight = DirectionalLight;
  50018. })(BABYLON || (BABYLON = {}));
  50019. //# sourceMappingURL=babylon.directionalLight.js.map
  50020. var BABYLON;
  50021. (function (BABYLON) {
  50022. /**
  50023. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50024. * These values define a cone of light starting from the position, emitting toward the direction.
  50025. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50026. * and the exponent defines the speed of the decay of the light with distance (reach).
  50027. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50028. */
  50029. var SpotLight = /** @class */ (function (_super) {
  50030. __extends(SpotLight, _super);
  50031. /**
  50032. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50033. * It can cast shadows.
  50034. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50035. * @param name The light friendly name
  50036. * @param position The position of the spot light in the scene
  50037. * @param direction The direction of the light in the scene
  50038. * @param angle The cone angle of the light in Radians
  50039. * @param exponent The light decay speed with the distance from the emission spot
  50040. * @param scene The scene the lights belongs to
  50041. */
  50042. function SpotLight(name, position, direction, angle, exponent, scene) {
  50043. var _this = _super.call(this, name, scene) || this;
  50044. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50045. _this._projectionTextureLightNear = 1e-6;
  50046. _this._projectionTextureLightFar = 1000.0;
  50047. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50048. _this._projectionTextureViewLightDirty = true;
  50049. _this._projectionTextureProjectionLightDirty = true;
  50050. _this._projectionTextureDirty = true;
  50051. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50052. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50053. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50054. _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);
  50055. _this.position = position;
  50056. _this.direction = direction;
  50057. _this.angle = angle;
  50058. _this.exponent = exponent;
  50059. return _this;
  50060. }
  50061. Object.defineProperty(SpotLight.prototype, "angle", {
  50062. /**
  50063. * Gets the cone angle of the spot light in Radians.
  50064. */
  50065. get: function () {
  50066. return this._angle;
  50067. },
  50068. /**
  50069. * Sets the cone angle of the spot light in Radians.
  50070. */
  50071. set: function (value) {
  50072. this._angle = value;
  50073. this._projectionTextureProjectionLightDirty = true;
  50074. this.forceProjectionMatrixCompute();
  50075. },
  50076. enumerable: true,
  50077. configurable: true
  50078. });
  50079. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50080. /**
  50081. * Allows scaling the angle of the light for shadow generation only.
  50082. */
  50083. get: function () {
  50084. return this._shadowAngleScale;
  50085. },
  50086. /**
  50087. * Allows scaling the angle of the light for shadow generation only.
  50088. */
  50089. set: function (value) {
  50090. this._shadowAngleScale = value;
  50091. this.forceProjectionMatrixCompute();
  50092. },
  50093. enumerable: true,
  50094. configurable: true
  50095. });
  50096. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50097. /**
  50098. * Allows reading the projecton texture
  50099. */
  50100. get: function () {
  50101. return this._projectionTextureMatrix;
  50102. },
  50103. enumerable: true,
  50104. configurable: true
  50105. });
  50106. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50107. /**
  50108. * Gets the near clip of the Spotlight for texture projection.
  50109. */
  50110. get: function () {
  50111. return this._projectionTextureLightNear;
  50112. },
  50113. /**
  50114. * Sets the near clip of the Spotlight for texture projection.
  50115. */
  50116. set: function (value) {
  50117. this._projectionTextureLightNear = value;
  50118. this._projectionTextureProjectionLightDirty = true;
  50119. },
  50120. enumerable: true,
  50121. configurable: true
  50122. });
  50123. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50124. /**
  50125. * Gets the far clip of the Spotlight for texture projection.
  50126. */
  50127. get: function () {
  50128. return this._projectionTextureLightFar;
  50129. },
  50130. /**
  50131. * Sets the far clip of the Spotlight for texture projection.
  50132. */
  50133. set: function (value) {
  50134. this._projectionTextureLightFar = value;
  50135. this._projectionTextureProjectionLightDirty = true;
  50136. },
  50137. enumerable: true,
  50138. configurable: true
  50139. });
  50140. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50141. /**
  50142. * Gets the Up vector of the Spotlight for texture projection.
  50143. */
  50144. get: function () {
  50145. return this._projectionTextureUpDirection;
  50146. },
  50147. /**
  50148. * Sets the Up vector of the Spotlight for texture projection.
  50149. */
  50150. set: function (value) {
  50151. this._projectionTextureUpDirection = value;
  50152. this._projectionTextureProjectionLightDirty = true;
  50153. },
  50154. enumerable: true,
  50155. configurable: true
  50156. });
  50157. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50158. /**
  50159. * Gets the projection texture of the light.
  50160. */
  50161. get: function () {
  50162. return this._projectionTexture;
  50163. },
  50164. /**
  50165. * Sets the projection texture of the light.
  50166. */
  50167. set: function (value) {
  50168. this._projectionTexture = value;
  50169. this._projectionTextureDirty = true;
  50170. },
  50171. enumerable: true,
  50172. configurable: true
  50173. });
  50174. /**
  50175. * Returns the string "SpotLight".
  50176. * @returns the class name
  50177. */
  50178. SpotLight.prototype.getClassName = function () {
  50179. return "SpotLight";
  50180. };
  50181. /**
  50182. * Returns the integer 2.
  50183. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50184. */
  50185. SpotLight.prototype.getTypeID = function () {
  50186. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50187. };
  50188. /**
  50189. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50190. */
  50191. SpotLight.prototype._setDirection = function (value) {
  50192. _super.prototype._setDirection.call(this, value);
  50193. this._projectionTextureViewLightDirty = true;
  50194. };
  50195. /**
  50196. * Overrides the position setter to recompute the projection texture view light Matrix.
  50197. */
  50198. SpotLight.prototype._setPosition = function (value) {
  50199. _super.prototype._setPosition.call(this, value);
  50200. this._projectionTextureViewLightDirty = true;
  50201. };
  50202. /**
  50203. * 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.
  50204. * Returns the SpotLight.
  50205. */
  50206. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50207. var activeCamera = this.getScene().activeCamera;
  50208. if (!activeCamera) {
  50209. return;
  50210. }
  50211. this._shadowAngleScale = this._shadowAngleScale || 1;
  50212. var angle = this._shadowAngleScale * this._angle;
  50213. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50214. };
  50215. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50216. this._projectionTextureViewLightDirty = false;
  50217. this._projectionTextureDirty = true;
  50218. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50219. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50220. };
  50221. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50222. this._projectionTextureProjectionLightDirty = false;
  50223. this._projectionTextureDirty = true;
  50224. var light_far = this.projectionTextureLightFar;
  50225. var light_near = this.projectionTextureLightNear;
  50226. var P = light_far / (light_far - light_near);
  50227. var Q = -P * light_near;
  50228. var S = 1.0 / Math.tan(this._angle / 2.0);
  50229. var A = 1.0;
  50230. 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);
  50231. };
  50232. /**
  50233. * Main function for light texture projection matrix computing.
  50234. */
  50235. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50236. this._projectionTextureDirty = false;
  50237. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50238. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50239. };
  50240. SpotLight.prototype._buildUniformLayout = function () {
  50241. this._uniformBuffer.addUniform("vLightData", 4);
  50242. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50243. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50244. this._uniformBuffer.addUniform("vLightDirection", 3);
  50245. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50246. this._uniformBuffer.addUniform("depthValues", 2);
  50247. this._uniformBuffer.create();
  50248. };
  50249. /**
  50250. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50251. * @param effect The effect to update
  50252. * @param lightIndex The index of the light in the effect to update
  50253. * @returns The spot light
  50254. */
  50255. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50256. var normalizeDirection;
  50257. if (this.computeTransformedInformation()) {
  50258. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50259. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50260. }
  50261. else {
  50262. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50263. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50264. }
  50265. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50266. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50267. if (this._projectionTextureViewLightDirty) {
  50268. this._computeProjectionTextureViewLightMatrix();
  50269. }
  50270. if (this._projectionTextureProjectionLightDirty) {
  50271. this._computeProjectionTextureProjectionLightMatrix();
  50272. }
  50273. if (this._projectionTextureDirty) {
  50274. this._computeProjectionTextureMatrix();
  50275. }
  50276. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50277. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50278. }
  50279. return this;
  50280. };
  50281. /**
  50282. * Disposes the light and the associated resources.
  50283. */
  50284. SpotLight.prototype.dispose = function () {
  50285. _super.prototype.dispose.call(this);
  50286. if (this._projectionTexture) {
  50287. this._projectionTexture.dispose();
  50288. }
  50289. };
  50290. __decorate([
  50291. BABYLON.serialize()
  50292. ], SpotLight.prototype, "angle", null);
  50293. __decorate([
  50294. BABYLON.serialize()
  50295. ], SpotLight.prototype, "shadowAngleScale", null);
  50296. __decorate([
  50297. BABYLON.serialize()
  50298. ], SpotLight.prototype, "exponent", void 0);
  50299. __decorate([
  50300. BABYLON.serialize()
  50301. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50302. __decorate([
  50303. BABYLON.serialize()
  50304. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50305. __decorate([
  50306. BABYLON.serialize()
  50307. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50308. __decorate([
  50309. BABYLON.serializeAsTexture("projectedLightTexture")
  50310. ], SpotLight.prototype, "_projectionTexture", void 0);
  50311. return SpotLight;
  50312. }(BABYLON.ShadowLight));
  50313. BABYLON.SpotLight = SpotLight;
  50314. })(BABYLON || (BABYLON = {}));
  50315. //# sourceMappingURL=babylon.spotLight.js.map
  50316. var BABYLON;
  50317. (function (BABYLON) {
  50318. /**
  50319. * Class used to override all child animations of a given target
  50320. */
  50321. var AnimationPropertiesOverride = /** @class */ (function () {
  50322. function AnimationPropertiesOverride() {
  50323. /**
  50324. * Gets or sets a value indicating if animation blending must be used
  50325. */
  50326. this.enableBlending = false;
  50327. /**
  50328. * Gets or sets the blending speed to use when enableBlending is true
  50329. */
  50330. this.blendingSpeed = 0.01;
  50331. /**
  50332. * Gets or sets the default loop mode to use
  50333. */
  50334. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50335. }
  50336. return AnimationPropertiesOverride;
  50337. }());
  50338. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50339. })(BABYLON || (BABYLON = {}));
  50340. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50341. var BABYLON;
  50342. (function (BABYLON) {
  50343. /**
  50344. * Represents the range of an animation
  50345. */
  50346. var AnimationRange = /** @class */ (function () {
  50347. /**
  50348. * Initializes the range of an animation
  50349. * @param name The name of the animation range
  50350. * @param from The starting frame of the animation
  50351. * @param to The ending frame of the animation
  50352. */
  50353. function AnimationRange(
  50354. /**The name of the animation range**/
  50355. name,
  50356. /**The starting frame of the animation */
  50357. from,
  50358. /**The ending frame of the animation*/
  50359. to) {
  50360. this.name = name;
  50361. this.from = from;
  50362. this.to = to;
  50363. }
  50364. /**
  50365. * Makes a copy of the animation range
  50366. * @returns A copy of the animation range
  50367. */
  50368. AnimationRange.prototype.clone = function () {
  50369. return new AnimationRange(this.name, this.from, this.to);
  50370. };
  50371. return AnimationRange;
  50372. }());
  50373. BABYLON.AnimationRange = AnimationRange;
  50374. /**
  50375. * Composed of a frame, and an action function
  50376. */
  50377. var AnimationEvent = /** @class */ (function () {
  50378. /**
  50379. * Initializes the animation event
  50380. * @param frame The frame for which the event is triggered
  50381. * @param action The event to perform when triggered
  50382. * @param onlyOnce Specifies if the event should be triggered only once
  50383. */
  50384. function AnimationEvent(
  50385. /** The frame for which the event is triggered **/
  50386. frame,
  50387. /** The event to perform when triggered **/
  50388. action,
  50389. /** Specifies if the event should be triggered only once**/
  50390. onlyOnce) {
  50391. this.frame = frame;
  50392. this.action = action;
  50393. this.onlyOnce = onlyOnce;
  50394. /**
  50395. * Specifies if the animation event is done
  50396. */
  50397. this.isDone = false;
  50398. }
  50399. /** @hidden */
  50400. AnimationEvent.prototype._clone = function () {
  50401. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50402. };
  50403. return AnimationEvent;
  50404. }());
  50405. BABYLON.AnimationEvent = AnimationEvent;
  50406. /**
  50407. * A cursor which tracks a point on a path
  50408. */
  50409. var PathCursor = /** @class */ (function () {
  50410. /**
  50411. * Initializes the path cursor
  50412. * @param path The path to track
  50413. */
  50414. function PathCursor(path) {
  50415. this.path = path;
  50416. /**
  50417. * Stores path cursor callbacks for when an onchange event is triggered
  50418. */
  50419. this._onchange = new Array();
  50420. /**
  50421. * The value of the path cursor
  50422. */
  50423. this.value = 0;
  50424. /**
  50425. * The animation array of the path cursor
  50426. */
  50427. this.animations = new Array();
  50428. }
  50429. /**
  50430. * Gets the cursor point on the path
  50431. * @returns A point on the path cursor at the cursor location
  50432. */
  50433. PathCursor.prototype.getPoint = function () {
  50434. var point = this.path.getPointAtLengthPosition(this.value);
  50435. return new BABYLON.Vector3(point.x, 0, point.y);
  50436. };
  50437. /**
  50438. * Moves the cursor ahead by the step amount
  50439. * @param step The amount to move the cursor forward
  50440. * @returns This path cursor
  50441. */
  50442. PathCursor.prototype.moveAhead = function (step) {
  50443. if (step === void 0) { step = 0.002; }
  50444. this.move(step);
  50445. return this;
  50446. };
  50447. /**
  50448. * Moves the cursor behind by the step amount
  50449. * @param step The amount to move the cursor back
  50450. * @returns This path cursor
  50451. */
  50452. PathCursor.prototype.moveBack = function (step) {
  50453. if (step === void 0) { step = 0.002; }
  50454. this.move(-step);
  50455. return this;
  50456. };
  50457. /**
  50458. * Moves the cursor by the step amount
  50459. * If the step amount is greater than one, an exception is thrown
  50460. * @param step The amount to move the cursor
  50461. * @returns This path cursor
  50462. */
  50463. PathCursor.prototype.move = function (step) {
  50464. if (Math.abs(step) > 1) {
  50465. throw "step size should be less than 1.";
  50466. }
  50467. this.value += step;
  50468. this.ensureLimits();
  50469. this.raiseOnChange();
  50470. return this;
  50471. };
  50472. /**
  50473. * Ensures that the value is limited between zero and one
  50474. * @returns This path cursor
  50475. */
  50476. PathCursor.prototype.ensureLimits = function () {
  50477. while (this.value > 1) {
  50478. this.value -= 1;
  50479. }
  50480. while (this.value < 0) {
  50481. this.value += 1;
  50482. }
  50483. return this;
  50484. };
  50485. /**
  50486. * Runs onchange callbacks on change (used by the animation engine)
  50487. * @returns This path cursor
  50488. */
  50489. PathCursor.prototype.raiseOnChange = function () {
  50490. var _this = this;
  50491. this._onchange.forEach(function (f) { return f(_this); });
  50492. return this;
  50493. };
  50494. /**
  50495. * Executes a function on change
  50496. * @param f A path cursor onchange callback
  50497. * @returns This path cursor
  50498. */
  50499. PathCursor.prototype.onchange = function (f) {
  50500. this._onchange.push(f);
  50501. return this;
  50502. };
  50503. return PathCursor;
  50504. }());
  50505. BABYLON.PathCursor = PathCursor;
  50506. /**
  50507. * Enum for the animation key frame interpolation type
  50508. */
  50509. var AnimationKeyInterpolation;
  50510. (function (AnimationKeyInterpolation) {
  50511. /**
  50512. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50513. */
  50514. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50515. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50516. /**
  50517. * Class used to store any kind of animation
  50518. */
  50519. var Animation = /** @class */ (function () {
  50520. /**
  50521. * Initializes the animation
  50522. * @param name Name of the animation
  50523. * @param targetProperty Property to animate
  50524. * @param framePerSecond The frames per second of the animation
  50525. * @param dataType The data type of the animation
  50526. * @param loopMode The loop mode of the animation
  50527. * @param enableBlendings Specifies if blending should be enabled
  50528. */
  50529. function Animation(
  50530. /**Name of the animation */
  50531. name,
  50532. /**Property to animate */
  50533. targetProperty,
  50534. /**The frames per second of the animation */
  50535. framePerSecond,
  50536. /**The data type of the animation */
  50537. dataType,
  50538. /**The loop mode of the animation */
  50539. loopMode,
  50540. /**Specifies if blending should be enabled */
  50541. enableBlending) {
  50542. this.name = name;
  50543. this.targetProperty = targetProperty;
  50544. this.framePerSecond = framePerSecond;
  50545. this.dataType = dataType;
  50546. this.loopMode = loopMode;
  50547. this.enableBlending = enableBlending;
  50548. /**
  50549. * @hidden Internal use only
  50550. */
  50551. this._runtimeAnimations = new Array();
  50552. /**
  50553. * The set of event that will be linked to this animation
  50554. */
  50555. this._events = new Array();
  50556. /**
  50557. * Stores the blending speed of the animation
  50558. */
  50559. this.blendingSpeed = 0.01;
  50560. /**
  50561. * Stores the animation ranges for the animation
  50562. */
  50563. this._ranges = {};
  50564. this.targetPropertyPath = targetProperty.split(".");
  50565. this.dataType = dataType;
  50566. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50567. }
  50568. /**
  50569. * @hidden Internal use
  50570. */
  50571. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50572. var dataType = undefined;
  50573. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50574. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50575. }
  50576. else if (from instanceof BABYLON.Quaternion) {
  50577. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50578. }
  50579. else if (from instanceof BABYLON.Vector3) {
  50580. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50581. }
  50582. else if (from instanceof BABYLON.Vector2) {
  50583. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50584. }
  50585. else if (from instanceof BABYLON.Color3) {
  50586. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50587. }
  50588. else if (from instanceof BABYLON.Size) {
  50589. dataType = Animation.ANIMATIONTYPE_SIZE;
  50590. }
  50591. if (dataType == undefined) {
  50592. return null;
  50593. }
  50594. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50595. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50596. animation.setKeys(keys);
  50597. if (easingFunction !== undefined) {
  50598. animation.setEasingFunction(easingFunction);
  50599. }
  50600. return animation;
  50601. };
  50602. /**
  50603. * Sets up an animation
  50604. * @param property The property to animate
  50605. * @param animationType The animation type to apply
  50606. * @param framePerSecond The frames per second of the animation
  50607. * @param easingFunction The easing function used in the animation
  50608. * @returns The created animation
  50609. */
  50610. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50611. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50612. animation.setEasingFunction(easingFunction);
  50613. return animation;
  50614. };
  50615. /**
  50616. * Create and start an animation on a node
  50617. * @param name defines the name of the global animation that will be run on all nodes
  50618. * @param node defines the root node where the animation will take place
  50619. * @param targetProperty defines property to animate
  50620. * @param framePerSecond defines the number of frame per second yo use
  50621. * @param totalFrame defines the number of frames in total
  50622. * @param from defines the initial value
  50623. * @param to defines the final value
  50624. * @param loopMode defines which loop mode you want to use (off by default)
  50625. * @param easingFunction defines the easing function to use (linear by default)
  50626. * @param onAnimationEnd defines the callback to call when animation end
  50627. * @returns the animatable created for this animation
  50628. */
  50629. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50630. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50631. if (!animation) {
  50632. return null;
  50633. }
  50634. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50635. };
  50636. /**
  50637. * Create and start an animation on a node and its descendants
  50638. * @param name defines the name of the global animation that will be run on all nodes
  50639. * @param node defines the root node where the animation will take place
  50640. * @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
  50641. * @param targetProperty defines property to animate
  50642. * @param framePerSecond defines the number of frame per second to use
  50643. * @param totalFrame defines the number of frames in total
  50644. * @param from defines the initial value
  50645. * @param to defines the final value
  50646. * @param loopMode defines which loop mode you want to use (off by default)
  50647. * @param easingFunction defines the easing function to use (linear by default)
  50648. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50649. * @returns the list of animatables created for all nodes
  50650. * @example https://www.babylonjs-playground.com/#MH0VLI
  50651. */
  50652. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50653. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50654. if (!animation) {
  50655. return null;
  50656. }
  50657. var scene = node.getScene();
  50658. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50659. };
  50660. /**
  50661. * Creates a new animation, merges it with the existing animations and starts it
  50662. * @param name Name of the animation
  50663. * @param node Node which contains the scene that begins the animations
  50664. * @param targetProperty Specifies which property to animate
  50665. * @param framePerSecond The frames per second of the animation
  50666. * @param totalFrame The total number of frames
  50667. * @param from The frame at the beginning of the animation
  50668. * @param to The frame at the end of the animation
  50669. * @param loopMode Specifies the loop mode of the animation
  50670. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50671. * @param onAnimationEnd Callback to run once the animation is complete
  50672. * @returns Nullable animation
  50673. */
  50674. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50675. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50676. if (!animation) {
  50677. return null;
  50678. }
  50679. node.animations.push(animation);
  50680. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50681. };
  50682. /**
  50683. * Transition property of an host to the target Value
  50684. * @param property The property to transition
  50685. * @param targetValue The target Value of the property
  50686. * @param host The object where the property to animate belongs
  50687. * @param scene Scene used to run the animation
  50688. * @param frameRate Framerate (in frame/s) to use
  50689. * @param transition The transition type we want to use
  50690. * @param duration The duration of the animation, in milliseconds
  50691. * @param onAnimationEnd Callback trigger at the end of the animation
  50692. * @returns Nullable animation
  50693. */
  50694. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50695. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50696. if (duration <= 0) {
  50697. host[property] = targetValue;
  50698. if (onAnimationEnd) {
  50699. onAnimationEnd();
  50700. }
  50701. return null;
  50702. }
  50703. var endFrame = frameRate * (duration / 1000);
  50704. transition.setKeys([{
  50705. frame: 0,
  50706. value: host[property].clone ? host[property].clone() : host[property]
  50707. },
  50708. {
  50709. frame: endFrame,
  50710. value: targetValue
  50711. }]);
  50712. if (!host.animations) {
  50713. host.animations = [];
  50714. }
  50715. host.animations.push(transition);
  50716. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50717. animation.onAnimationEnd = onAnimationEnd;
  50718. return animation;
  50719. };
  50720. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50721. /**
  50722. * Return the array of runtime animations currently using this animation
  50723. */
  50724. get: function () {
  50725. return this._runtimeAnimations;
  50726. },
  50727. enumerable: true,
  50728. configurable: true
  50729. });
  50730. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50731. /**
  50732. * Specifies if any of the runtime animations are currently running
  50733. */
  50734. get: function () {
  50735. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50736. var runtimeAnimation = _a[_i];
  50737. if (!runtimeAnimation.isStopped) {
  50738. return true;
  50739. }
  50740. }
  50741. return false;
  50742. },
  50743. enumerable: true,
  50744. configurable: true
  50745. });
  50746. // Methods
  50747. /**
  50748. * Converts the animation to a string
  50749. * @param fullDetails support for multiple levels of logging within scene loading
  50750. * @returns String form of the animation
  50751. */
  50752. Animation.prototype.toString = function (fullDetails) {
  50753. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50754. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50755. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50756. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50757. if (fullDetails) {
  50758. ret += ", Ranges: {";
  50759. var first = true;
  50760. for (var name in this._ranges) {
  50761. if (first) {
  50762. ret += ", ";
  50763. first = false;
  50764. }
  50765. ret += name;
  50766. }
  50767. ret += "}";
  50768. }
  50769. return ret;
  50770. };
  50771. /**
  50772. * Add an event to this animation
  50773. * @param event Event to add
  50774. */
  50775. Animation.prototype.addEvent = function (event) {
  50776. this._events.push(event);
  50777. };
  50778. /**
  50779. * Remove all events found at the given frame
  50780. * @param frame The frame to remove events from
  50781. */
  50782. Animation.prototype.removeEvents = function (frame) {
  50783. for (var index = 0; index < this._events.length; index++) {
  50784. if (this._events[index].frame === frame) {
  50785. this._events.splice(index, 1);
  50786. index--;
  50787. }
  50788. }
  50789. };
  50790. /**
  50791. * Retrieves all the events from the animation
  50792. * @returns Events from the animation
  50793. */
  50794. Animation.prototype.getEvents = function () {
  50795. return this._events;
  50796. };
  50797. /**
  50798. * Creates an animation range
  50799. * @param name Name of the animation range
  50800. * @param from Starting frame of the animation range
  50801. * @param to Ending frame of the animation
  50802. */
  50803. Animation.prototype.createRange = function (name, from, to) {
  50804. // check name not already in use; could happen for bones after serialized
  50805. if (!this._ranges[name]) {
  50806. this._ranges[name] = new AnimationRange(name, from, to);
  50807. }
  50808. };
  50809. /**
  50810. * Deletes an animation range by name
  50811. * @param name Name of the animation range to delete
  50812. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50813. */
  50814. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50815. if (deleteFrames === void 0) { deleteFrames = true; }
  50816. var range = this._ranges[name];
  50817. if (!range) {
  50818. return;
  50819. }
  50820. if (deleteFrames) {
  50821. var from = range.from;
  50822. var to = range.to;
  50823. // this loop MUST go high to low for multiple splices to work
  50824. for (var key = this._keys.length - 1; key >= 0; key--) {
  50825. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50826. this._keys.splice(key, 1);
  50827. }
  50828. }
  50829. }
  50830. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50831. };
  50832. /**
  50833. * Gets the animation range by name, or null if not defined
  50834. * @param name Name of the animation range
  50835. * @returns Nullable animation range
  50836. */
  50837. Animation.prototype.getRange = function (name) {
  50838. return this._ranges[name];
  50839. };
  50840. /**
  50841. * Gets the key frames from the animation
  50842. * @returns The key frames of the animation
  50843. */
  50844. Animation.prototype.getKeys = function () {
  50845. return this._keys;
  50846. };
  50847. /**
  50848. * Gets the highest frame rate of the animation
  50849. * @returns Highest frame rate of the animation
  50850. */
  50851. Animation.prototype.getHighestFrame = function () {
  50852. var ret = 0;
  50853. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50854. if (ret < this._keys[key].frame) {
  50855. ret = this._keys[key].frame;
  50856. }
  50857. }
  50858. return ret;
  50859. };
  50860. /**
  50861. * Gets the easing function of the animation
  50862. * @returns Easing function of the animation
  50863. */
  50864. Animation.prototype.getEasingFunction = function () {
  50865. return this._easingFunction;
  50866. };
  50867. /**
  50868. * Sets the easing function of the animation
  50869. * @param easingFunction A custom mathematical formula for animation
  50870. */
  50871. Animation.prototype.setEasingFunction = function (easingFunction) {
  50872. this._easingFunction = easingFunction;
  50873. };
  50874. /**
  50875. * Interpolates a scalar linearly
  50876. * @param startValue Start value of the animation curve
  50877. * @param endValue End value of the animation curve
  50878. * @param gradient Scalar amount to interpolate
  50879. * @returns Interpolated scalar value
  50880. */
  50881. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50882. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50883. };
  50884. /**
  50885. * Interpolates a scalar cubically
  50886. * @param startValue Start value of the animation curve
  50887. * @param outTangent End tangent of the animation
  50888. * @param endValue End value of the animation curve
  50889. * @param inTangent Start tangent of the animation curve
  50890. * @param gradient Scalar amount to interpolate
  50891. * @returns Interpolated scalar value
  50892. */
  50893. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50894. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50895. };
  50896. /**
  50897. * Interpolates a quaternion using a spherical linear interpolation
  50898. * @param startValue Start value of the animation curve
  50899. * @param endValue End value of the animation curve
  50900. * @param gradient Scalar amount to interpolate
  50901. * @returns Interpolated quaternion value
  50902. */
  50903. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50904. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50905. };
  50906. /**
  50907. * Interpolates a quaternion cubically
  50908. * @param startValue Start value of the animation curve
  50909. * @param outTangent End tangent of the animation curve
  50910. * @param endValue End value of the animation curve
  50911. * @param inTangent Start tangent of the animation curve
  50912. * @param gradient Scalar amount to interpolate
  50913. * @returns Interpolated quaternion value
  50914. */
  50915. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50916. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50917. };
  50918. /**
  50919. * Interpolates a Vector3 linearl
  50920. * @param startValue Start value of the animation curve
  50921. * @param endValue End value of the animation curve
  50922. * @param gradient Scalar amount to interpolate
  50923. * @returns Interpolated scalar value
  50924. */
  50925. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50926. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50927. };
  50928. /**
  50929. * Interpolates a Vector3 cubically
  50930. * @param startValue Start value of the animation curve
  50931. * @param outTangent End tangent of the animation
  50932. * @param endValue End value of the animation curve
  50933. * @param inTangent Start tangent of the animation curve
  50934. * @param gradient Scalar amount to interpolate
  50935. * @returns InterpolatedVector3 value
  50936. */
  50937. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50938. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50939. };
  50940. /**
  50941. * Interpolates a Vector2 linearly
  50942. * @param startValue Start value of the animation curve
  50943. * @param endValue End value of the animation curve
  50944. * @param gradient Scalar amount to interpolate
  50945. * @returns Interpolated Vector2 value
  50946. */
  50947. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50948. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50949. };
  50950. /**
  50951. * Interpolates a Vector2 cubically
  50952. * @param startValue Start value of the animation curve
  50953. * @param outTangent End tangent of the animation
  50954. * @param endValue End value of the animation curve
  50955. * @param inTangent Start tangent of the animation curve
  50956. * @param gradient Scalar amount to interpolate
  50957. * @returns Interpolated Vector2 value
  50958. */
  50959. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50960. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50961. };
  50962. /**
  50963. * Interpolates a size linearly
  50964. * @param startValue Start value of the animation curve
  50965. * @param endValue End value of the animation curve
  50966. * @param gradient Scalar amount to interpolate
  50967. * @returns Interpolated Size value
  50968. */
  50969. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50970. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50971. };
  50972. /**
  50973. * Interpolates a Color3 linearly
  50974. * @param startValue Start value of the animation curve
  50975. * @param endValue End value of the animation curve
  50976. * @param gradient Scalar amount to interpolate
  50977. * @returns Interpolated Color3 value
  50978. */
  50979. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50980. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50981. };
  50982. /**
  50983. * @hidden Internal use only
  50984. */
  50985. Animation.prototype._getKeyValue = function (value) {
  50986. if (typeof value === "function") {
  50987. return value();
  50988. }
  50989. return value;
  50990. };
  50991. /**
  50992. * @hidden Internal use only
  50993. */
  50994. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50995. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50996. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50997. }
  50998. var keys = this.getKeys();
  50999. // Try to get a hash to find the right key
  51000. 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));
  51001. if (keys[startKeyIndex].frame >= currentFrame) {
  51002. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  51003. startKeyIndex--;
  51004. }
  51005. }
  51006. for (var key = startKeyIndex; key < keys.length; key++) {
  51007. var endKey = keys[key + 1];
  51008. if (endKey.frame >= currentFrame) {
  51009. var startKey = keys[key];
  51010. var startValue = this._getKeyValue(startKey.value);
  51011. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51012. return startValue;
  51013. }
  51014. var endValue = this._getKeyValue(endKey.value);
  51015. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51016. var frameDelta = endKey.frame - startKey.frame;
  51017. // gradient : percent of currentFrame between the frame inf and the frame sup
  51018. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51019. // check for easingFunction and correction of gradient
  51020. var easingFunction = this.getEasingFunction();
  51021. if (easingFunction != null) {
  51022. gradient = easingFunction.ease(gradient);
  51023. }
  51024. switch (this.dataType) {
  51025. // Float
  51026. case Animation.ANIMATIONTYPE_FLOAT:
  51027. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51028. switch (loopMode) {
  51029. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51030. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51031. return floatValue;
  51032. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51033. return offsetValue * repeatCount + floatValue;
  51034. }
  51035. break;
  51036. // Quaternion
  51037. case Animation.ANIMATIONTYPE_QUATERNION:
  51038. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51039. switch (loopMode) {
  51040. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51041. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51042. return quatValue;
  51043. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51044. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51045. }
  51046. return quatValue;
  51047. // Vector3
  51048. case Animation.ANIMATIONTYPE_VECTOR3:
  51049. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51050. switch (loopMode) {
  51051. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51052. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51053. return vec3Value;
  51054. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51055. return vec3Value.add(offsetValue.scale(repeatCount));
  51056. }
  51057. // Vector2
  51058. case Animation.ANIMATIONTYPE_VECTOR2:
  51059. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51060. switch (loopMode) {
  51061. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51062. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51063. return vec2Value;
  51064. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51065. return vec2Value.add(offsetValue.scale(repeatCount));
  51066. }
  51067. // Size
  51068. case Animation.ANIMATIONTYPE_SIZE:
  51069. switch (loopMode) {
  51070. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51071. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51072. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51073. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51074. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51075. }
  51076. // Color3
  51077. case Animation.ANIMATIONTYPE_COLOR3:
  51078. switch (loopMode) {
  51079. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51080. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51081. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51082. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51083. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51084. }
  51085. // Matrix
  51086. case Animation.ANIMATIONTYPE_MATRIX:
  51087. switch (loopMode) {
  51088. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51089. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51090. if (Animation.AllowMatricesInterpolation) {
  51091. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51092. }
  51093. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51094. return startValue;
  51095. }
  51096. default:
  51097. break;
  51098. }
  51099. break;
  51100. }
  51101. }
  51102. return this._getKeyValue(keys[keys.length - 1].value);
  51103. };
  51104. /**
  51105. * Defines the function to use to interpolate matrices
  51106. * @param startValue defines the start matrix
  51107. * @param endValue defines the end matrix
  51108. * @param gradient defines the gradient between both matrices
  51109. * @param result defines an optional target matrix where to store the interpolation
  51110. * @returns the interpolated matrix
  51111. */
  51112. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51113. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51114. if (result) {
  51115. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51116. return result;
  51117. }
  51118. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51119. }
  51120. if (result) {
  51121. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51122. return result;
  51123. }
  51124. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51125. };
  51126. /**
  51127. * Makes a copy of the animation
  51128. * @returns Cloned animation
  51129. */
  51130. Animation.prototype.clone = function () {
  51131. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51132. clone.enableBlending = this.enableBlending;
  51133. clone.blendingSpeed = this.blendingSpeed;
  51134. if (this._keys) {
  51135. clone.setKeys(this._keys);
  51136. }
  51137. if (this._ranges) {
  51138. clone._ranges = {};
  51139. for (var name in this._ranges) {
  51140. var range = this._ranges[name];
  51141. if (!range) {
  51142. continue;
  51143. }
  51144. clone._ranges[name] = range.clone();
  51145. }
  51146. }
  51147. return clone;
  51148. };
  51149. /**
  51150. * Sets the key frames of the animation
  51151. * @param values The animation key frames to set
  51152. */
  51153. Animation.prototype.setKeys = function (values) {
  51154. this._keys = values.slice(0);
  51155. };
  51156. /**
  51157. * Serializes the animation to an object
  51158. * @returns Serialized object
  51159. */
  51160. Animation.prototype.serialize = function () {
  51161. var serializationObject = {};
  51162. serializationObject.name = this.name;
  51163. serializationObject.property = this.targetProperty;
  51164. serializationObject.framePerSecond = this.framePerSecond;
  51165. serializationObject.dataType = this.dataType;
  51166. serializationObject.loopBehavior = this.loopMode;
  51167. serializationObject.enableBlending = this.enableBlending;
  51168. serializationObject.blendingSpeed = this.blendingSpeed;
  51169. var dataType = this.dataType;
  51170. serializationObject.keys = [];
  51171. var keys = this.getKeys();
  51172. for (var index = 0; index < keys.length; index++) {
  51173. var animationKey = keys[index];
  51174. var key = {};
  51175. key.frame = animationKey.frame;
  51176. switch (dataType) {
  51177. case Animation.ANIMATIONTYPE_FLOAT:
  51178. key.values = [animationKey.value];
  51179. break;
  51180. case Animation.ANIMATIONTYPE_QUATERNION:
  51181. case Animation.ANIMATIONTYPE_MATRIX:
  51182. case Animation.ANIMATIONTYPE_VECTOR3:
  51183. case Animation.ANIMATIONTYPE_COLOR3:
  51184. key.values = animationKey.value.asArray();
  51185. break;
  51186. }
  51187. serializationObject.keys.push(key);
  51188. }
  51189. serializationObject.ranges = [];
  51190. for (var name in this._ranges) {
  51191. var source = this._ranges[name];
  51192. if (!source) {
  51193. continue;
  51194. }
  51195. var range = {};
  51196. range.name = name;
  51197. range.from = source.from;
  51198. range.to = source.to;
  51199. serializationObject.ranges.push(range);
  51200. }
  51201. return serializationObject;
  51202. };
  51203. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51204. /**
  51205. * Get the float animation type
  51206. */
  51207. get: function () {
  51208. return Animation._ANIMATIONTYPE_FLOAT;
  51209. },
  51210. enumerable: true,
  51211. configurable: true
  51212. });
  51213. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51214. /**
  51215. * Get the Vector3 animation type
  51216. */
  51217. get: function () {
  51218. return Animation._ANIMATIONTYPE_VECTOR3;
  51219. },
  51220. enumerable: true,
  51221. configurable: true
  51222. });
  51223. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51224. /**
  51225. * Get the Vectpr2 animation type
  51226. */
  51227. get: function () {
  51228. return Animation._ANIMATIONTYPE_VECTOR2;
  51229. },
  51230. enumerable: true,
  51231. configurable: true
  51232. });
  51233. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51234. /**
  51235. * Get the Size animation type
  51236. */
  51237. get: function () {
  51238. return Animation._ANIMATIONTYPE_SIZE;
  51239. },
  51240. enumerable: true,
  51241. configurable: true
  51242. });
  51243. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51244. /**
  51245. * Get the Quaternion animation type
  51246. */
  51247. get: function () {
  51248. return Animation._ANIMATIONTYPE_QUATERNION;
  51249. },
  51250. enumerable: true,
  51251. configurable: true
  51252. });
  51253. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51254. /**
  51255. * Get the Matrix animation type
  51256. */
  51257. get: function () {
  51258. return Animation._ANIMATIONTYPE_MATRIX;
  51259. },
  51260. enumerable: true,
  51261. configurable: true
  51262. });
  51263. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51264. /**
  51265. * Get the Color3 animation type
  51266. */
  51267. get: function () {
  51268. return Animation._ANIMATIONTYPE_COLOR3;
  51269. },
  51270. enumerable: true,
  51271. configurable: true
  51272. });
  51273. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51274. /**
  51275. * Get the Relative Loop Mode
  51276. */
  51277. get: function () {
  51278. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51279. },
  51280. enumerable: true,
  51281. configurable: true
  51282. });
  51283. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51284. /**
  51285. * Get the Cycle Loop Mode
  51286. */
  51287. get: function () {
  51288. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51289. },
  51290. enumerable: true,
  51291. configurable: true
  51292. });
  51293. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51294. /**
  51295. * Get the Constant Loop Mode
  51296. */
  51297. get: function () {
  51298. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51299. },
  51300. enumerable: true,
  51301. configurable: true
  51302. });
  51303. /** @hidden */
  51304. Animation._UniversalLerp = function (left, right, amount) {
  51305. var constructor = left.constructor;
  51306. if (constructor.Lerp) { // Lerp supported
  51307. return constructor.Lerp(left, right, amount);
  51308. }
  51309. else if (constructor.Slerp) { // Slerp supported
  51310. return constructor.Slerp(left, right, amount);
  51311. }
  51312. else if (left.toFixed) { // Number
  51313. return left * (1.0 - amount) + amount * right;
  51314. }
  51315. else { // Blending not supported
  51316. return right;
  51317. }
  51318. };
  51319. /**
  51320. * Parses an animation object and creates an animation
  51321. * @param parsedAnimation Parsed animation object
  51322. * @returns Animation object
  51323. */
  51324. Animation.Parse = function (parsedAnimation) {
  51325. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51326. var dataType = parsedAnimation.dataType;
  51327. var keys = [];
  51328. var data;
  51329. var index;
  51330. if (parsedAnimation.enableBlending) {
  51331. animation.enableBlending = parsedAnimation.enableBlending;
  51332. }
  51333. if (parsedAnimation.blendingSpeed) {
  51334. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51335. }
  51336. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51337. var key = parsedAnimation.keys[index];
  51338. var inTangent;
  51339. var outTangent;
  51340. switch (dataType) {
  51341. case Animation.ANIMATIONTYPE_FLOAT:
  51342. data = key.values[0];
  51343. if (key.values.length >= 1) {
  51344. inTangent = key.values[1];
  51345. }
  51346. if (key.values.length >= 2) {
  51347. outTangent = key.values[2];
  51348. }
  51349. break;
  51350. case Animation.ANIMATIONTYPE_QUATERNION:
  51351. data = BABYLON.Quaternion.FromArray(key.values);
  51352. if (key.values.length >= 8) {
  51353. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51354. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51355. inTangent = _inTangent;
  51356. }
  51357. }
  51358. if (key.values.length >= 12) {
  51359. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51360. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51361. outTangent = _outTangent;
  51362. }
  51363. }
  51364. break;
  51365. case Animation.ANIMATIONTYPE_MATRIX:
  51366. data = BABYLON.Matrix.FromArray(key.values);
  51367. break;
  51368. case Animation.ANIMATIONTYPE_COLOR3:
  51369. data = BABYLON.Color3.FromArray(key.values);
  51370. break;
  51371. case Animation.ANIMATIONTYPE_VECTOR3:
  51372. default:
  51373. data = BABYLON.Vector3.FromArray(key.values);
  51374. break;
  51375. }
  51376. var keyData = {};
  51377. keyData.frame = key.frame;
  51378. keyData.value = data;
  51379. if (inTangent != undefined) {
  51380. keyData.inTangent = inTangent;
  51381. }
  51382. if (outTangent != undefined) {
  51383. keyData.outTangent = outTangent;
  51384. }
  51385. keys.push(keyData);
  51386. }
  51387. animation.setKeys(keys);
  51388. if (parsedAnimation.ranges) {
  51389. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51390. data = parsedAnimation.ranges[index];
  51391. animation.createRange(data.name, data.from, data.to);
  51392. }
  51393. }
  51394. return animation;
  51395. };
  51396. /**
  51397. * Appends the serialized animations from the source animations
  51398. * @param source Source containing the animations
  51399. * @param destination Target to store the animations
  51400. */
  51401. Animation.AppendSerializedAnimations = function (source, destination) {
  51402. if (source.animations) {
  51403. destination.animations = [];
  51404. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51405. var animation = source.animations[animationIndex];
  51406. destination.animations.push(animation.serialize());
  51407. }
  51408. }
  51409. };
  51410. /**
  51411. * Use matrix interpolation instead of using direct key value when animating matrices
  51412. */
  51413. Animation.AllowMatricesInterpolation = false;
  51414. /**
  51415. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51416. */
  51417. Animation.AllowMatrixDecomposeForInterpolation = true;
  51418. // Statics
  51419. /**
  51420. * Float animation type
  51421. */
  51422. Animation._ANIMATIONTYPE_FLOAT = 0;
  51423. /**
  51424. * Vector3 animation type
  51425. */
  51426. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51427. /**
  51428. * Quaternion animation type
  51429. */
  51430. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51431. /**
  51432. * Matrix animation type
  51433. */
  51434. Animation._ANIMATIONTYPE_MATRIX = 3;
  51435. /**
  51436. * Color3 animation type
  51437. */
  51438. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51439. /**
  51440. * Vector2 animation type
  51441. */
  51442. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51443. /**
  51444. * Size animation type
  51445. */
  51446. Animation._ANIMATIONTYPE_SIZE = 6;
  51447. /**
  51448. * Relative Loop Mode
  51449. */
  51450. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51451. /**
  51452. * Cycle Loop Mode
  51453. */
  51454. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51455. /**
  51456. * Constant Loop Mode
  51457. */
  51458. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51459. return Animation;
  51460. }());
  51461. BABYLON.Animation = Animation;
  51462. })(BABYLON || (BABYLON = {}));
  51463. //# sourceMappingURL=babylon.animation.js.map
  51464. var BABYLON;
  51465. (function (BABYLON) {
  51466. /**
  51467. * This class defines the direct association between an animation and a target
  51468. */
  51469. var TargetedAnimation = /** @class */ (function () {
  51470. function TargetedAnimation() {
  51471. }
  51472. return TargetedAnimation;
  51473. }());
  51474. BABYLON.TargetedAnimation = TargetedAnimation;
  51475. /**
  51476. * Use this class to create coordinated animations on multiple targets
  51477. */
  51478. var AnimationGroup = /** @class */ (function () {
  51479. function AnimationGroup(name, scene) {
  51480. if (scene === void 0) { scene = null; }
  51481. this.name = name;
  51482. this._targetedAnimations = new Array();
  51483. this._animatables = new Array();
  51484. this._from = Number.MAX_VALUE;
  51485. this._to = -Number.MAX_VALUE;
  51486. this._speedRatio = 1;
  51487. this.onAnimationEndObservable = new BABYLON.Observable();
  51488. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51489. this._scene.animationGroups.push(this);
  51490. }
  51491. Object.defineProperty(AnimationGroup.prototype, "from", {
  51492. /**
  51493. * Gets the first frame
  51494. */
  51495. get: function () {
  51496. return this._from;
  51497. },
  51498. enumerable: true,
  51499. configurable: true
  51500. });
  51501. Object.defineProperty(AnimationGroup.prototype, "to", {
  51502. /**
  51503. * Gets the last frame
  51504. */
  51505. get: function () {
  51506. return this._to;
  51507. },
  51508. enumerable: true,
  51509. configurable: true
  51510. });
  51511. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51512. /**
  51513. * Define if the animations are started
  51514. */
  51515. get: function () {
  51516. return this._isStarted;
  51517. },
  51518. enumerable: true,
  51519. configurable: true
  51520. });
  51521. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51522. /**
  51523. * Gets or sets the speed ratio to use for all animations
  51524. */
  51525. get: function () {
  51526. return this._speedRatio;
  51527. },
  51528. /**
  51529. * Gets or sets the speed ratio to use for all animations
  51530. */
  51531. set: function (value) {
  51532. if (this._speedRatio === value) {
  51533. return;
  51534. }
  51535. this._speedRatio = value;
  51536. for (var index = 0; index < this._animatables.length; index++) {
  51537. var animatable = this._animatables[index];
  51538. animatable.speedRatio = this._speedRatio;
  51539. }
  51540. },
  51541. enumerable: true,
  51542. configurable: true
  51543. });
  51544. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51545. /**
  51546. * Gets the targeted animations for this animation group
  51547. */
  51548. get: function () {
  51549. return this._targetedAnimations;
  51550. },
  51551. enumerable: true,
  51552. configurable: true
  51553. });
  51554. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51555. /**
  51556. * returning the list of animatables controlled by this animation group.
  51557. */
  51558. get: function () {
  51559. return this._animatables;
  51560. },
  51561. enumerable: true,
  51562. configurable: true
  51563. });
  51564. /**
  51565. * Add an animation (with its target) in the group
  51566. * @param animation defines the animation we want to add
  51567. * @param target defines the target of the animation
  51568. * @returns the {BABYLON.TargetedAnimation} object
  51569. */
  51570. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51571. var targetedAnimation = {
  51572. animation: animation,
  51573. target: target
  51574. };
  51575. var keys = animation.getKeys();
  51576. if (this._from > keys[0].frame) {
  51577. this._from = keys[0].frame;
  51578. }
  51579. if (this._to < keys[keys.length - 1].frame) {
  51580. this._to = keys[keys.length - 1].frame;
  51581. }
  51582. this._targetedAnimations.push(targetedAnimation);
  51583. return targetedAnimation;
  51584. };
  51585. /**
  51586. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51587. * It can add constant keys at begin or end
  51588. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51589. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51590. */
  51591. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51592. if (beginFrame === void 0) { beginFrame = null; }
  51593. if (endFrame === void 0) { endFrame = null; }
  51594. if (beginFrame == null)
  51595. beginFrame = this._from;
  51596. if (endFrame == null)
  51597. endFrame = this._to;
  51598. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51599. var targetedAnimation = this._targetedAnimations[index];
  51600. var keys = targetedAnimation.animation.getKeys();
  51601. var startKey = keys[0];
  51602. var endKey = keys[keys.length - 1];
  51603. if (startKey.frame > beginFrame) {
  51604. var newKey = {
  51605. frame: beginFrame,
  51606. value: startKey.value,
  51607. inTangent: startKey.inTangent,
  51608. outTangent: startKey.outTangent,
  51609. interpolation: startKey.interpolation
  51610. };
  51611. keys.splice(0, 0, newKey);
  51612. }
  51613. if (endKey.frame < endFrame) {
  51614. var newKey = {
  51615. frame: endFrame,
  51616. value: endKey.value,
  51617. inTangent: endKey.outTangent,
  51618. outTangent: endKey.outTangent,
  51619. interpolation: endKey.interpolation
  51620. };
  51621. keys.push(newKey);
  51622. }
  51623. }
  51624. this._from = beginFrame;
  51625. this._to = endFrame;
  51626. return this;
  51627. };
  51628. /**
  51629. * Start all animations on given targets
  51630. * @param loop defines if animations must loop
  51631. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51632. * @param from defines the from key (optional)
  51633. * @param to defines the to key (optional)
  51634. * @returns the current animation group
  51635. */
  51636. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51637. var _this = this;
  51638. if (loop === void 0) { loop = false; }
  51639. if (speedRatio === void 0) { speedRatio = 1; }
  51640. if (this._isStarted || this._targetedAnimations.length === 0) {
  51641. return this;
  51642. }
  51643. var _loop_1 = function (targetedAnimation) {
  51644. 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 () {
  51645. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51646. }));
  51647. };
  51648. var this_1 = this;
  51649. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51650. var targetedAnimation = _a[_i];
  51651. _loop_1(targetedAnimation);
  51652. }
  51653. this._speedRatio = speedRatio;
  51654. this._isStarted = true;
  51655. return this;
  51656. };
  51657. /**
  51658. * Pause all animations
  51659. */
  51660. AnimationGroup.prototype.pause = function () {
  51661. if (!this._isStarted) {
  51662. return this;
  51663. }
  51664. for (var index = 0; index < this._animatables.length; index++) {
  51665. var animatable = this._animatables[index];
  51666. animatable.pause();
  51667. }
  51668. return this;
  51669. };
  51670. /**
  51671. * Play all animations to initial state
  51672. * This function will start() the animations if they were not started or will restart() them if they were paused
  51673. * @param loop defines if animations must loop
  51674. */
  51675. AnimationGroup.prototype.play = function (loop) {
  51676. if (this.isStarted) {
  51677. if (loop !== undefined) {
  51678. for (var index = 0; index < this._animatables.length; index++) {
  51679. var animatable = this._animatables[index];
  51680. animatable.loopAnimation = loop;
  51681. }
  51682. }
  51683. this.restart();
  51684. }
  51685. else {
  51686. this.start(loop, this._speedRatio);
  51687. }
  51688. return this;
  51689. };
  51690. /**
  51691. * Reset all animations to initial state
  51692. */
  51693. AnimationGroup.prototype.reset = function () {
  51694. if (!this._isStarted) {
  51695. return this;
  51696. }
  51697. for (var index = 0; index < this._animatables.length; index++) {
  51698. var animatable = this._animatables[index];
  51699. animatable.reset();
  51700. }
  51701. return this;
  51702. };
  51703. /**
  51704. * Restart animations from key 0
  51705. */
  51706. AnimationGroup.prototype.restart = function () {
  51707. if (!this._isStarted) {
  51708. return this;
  51709. }
  51710. for (var index = 0; index < this._animatables.length; index++) {
  51711. var animatable = this._animatables[index];
  51712. animatable.restart();
  51713. }
  51714. return this;
  51715. };
  51716. /**
  51717. * Stop all animations
  51718. */
  51719. AnimationGroup.prototype.stop = function () {
  51720. if (!this._isStarted) {
  51721. return this;
  51722. }
  51723. for (var index = 0; index < this._animatables.length; index++) {
  51724. var animatable = this._animatables[index];
  51725. animatable.stop();
  51726. }
  51727. this._isStarted = false;
  51728. return this;
  51729. };
  51730. /**
  51731. * Set animation weight for all animatables
  51732. * @param weight defines the weight to use
  51733. * @return the animationGroup
  51734. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51735. */
  51736. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51737. for (var index = 0; index < this._animatables.length; index++) {
  51738. var animatable = this._animatables[index];
  51739. animatable.weight = weight;
  51740. }
  51741. return this;
  51742. };
  51743. /**
  51744. * Synchronize and normalize all animatables with a source animatable
  51745. * @param root defines the root animatable to synchronize with
  51746. * @return the animationGroup
  51747. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51748. */
  51749. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51750. for (var index = 0; index < this._animatables.length; index++) {
  51751. var animatable = this._animatables[index];
  51752. animatable.syncWith(root);
  51753. }
  51754. return this;
  51755. };
  51756. /**
  51757. * Goes to a specific frame in this animation group
  51758. * @param frame the frame number to go to
  51759. * @return the animationGroup
  51760. */
  51761. AnimationGroup.prototype.goToFrame = function (frame) {
  51762. if (!this._isStarted) {
  51763. return this;
  51764. }
  51765. for (var index = 0; index < this._animatables.length; index++) {
  51766. var animatable = this._animatables[index];
  51767. animatable.goToFrame(frame);
  51768. }
  51769. return this;
  51770. };
  51771. /**
  51772. * Dispose all associated resources
  51773. */
  51774. AnimationGroup.prototype.dispose = function () {
  51775. this._targetedAnimations = [];
  51776. this._animatables = [];
  51777. var index = this._scene.animationGroups.indexOf(this);
  51778. if (index > -1) {
  51779. this._scene.animationGroups.splice(index, 1);
  51780. }
  51781. };
  51782. return AnimationGroup;
  51783. }());
  51784. BABYLON.AnimationGroup = AnimationGroup;
  51785. })(BABYLON || (BABYLON = {}));
  51786. //# sourceMappingURL=babylon.animationGroup.js.map
  51787. var BABYLON;
  51788. (function (BABYLON) {
  51789. /**
  51790. * Defines a runtime animation
  51791. */
  51792. var RuntimeAnimation = /** @class */ (function () {
  51793. /**
  51794. * Create a new RuntimeAnimation object
  51795. * @param target defines the target of the animation
  51796. * @param animation defines the source animation object
  51797. * @param scene defines the hosting scene
  51798. * @param host defines the initiating Animatable
  51799. */
  51800. function RuntimeAnimation(target, animation, scene, host) {
  51801. var _this = this;
  51802. this._events = new Array();
  51803. /**
  51804. * The current frame of the runtime animation
  51805. */
  51806. this._currentFrame = 0;
  51807. /**
  51808. * The original value of the runtime animation
  51809. */
  51810. this._originalValue = new Array();
  51811. /**
  51812. * The offsets cache of the runtime animation
  51813. */
  51814. this._offsetsCache = {};
  51815. /**
  51816. * The high limits cache of the runtime animation
  51817. */
  51818. this._highLimitsCache = {};
  51819. /**
  51820. * Specifies if the runtime animation has been stopped
  51821. */
  51822. this._stopped = false;
  51823. /**
  51824. * The blending factor of the runtime animation
  51825. */
  51826. this._blendingFactor = 0;
  51827. /**
  51828. * The target path of the runtime animation
  51829. */
  51830. this._targetPath = "";
  51831. /**
  51832. * The weight of the runtime animation
  51833. */
  51834. this._weight = 1.0;
  51835. /**
  51836. * The ratio offset of the runtime animation
  51837. */
  51838. this._ratioOffset = 0;
  51839. /**
  51840. * The previous delay of the runtime animation
  51841. */
  51842. this._previousDelay = 0;
  51843. /**
  51844. * The previous ratio of the runtime animation
  51845. */
  51846. this._previousRatio = 0;
  51847. this._animation = animation;
  51848. this._target = target;
  51849. this._scene = scene;
  51850. this._host = host;
  51851. animation._runtimeAnimations.push(this);
  51852. // Cloning events locally
  51853. var events = animation.getEvents();
  51854. if (events && events.length > 0) {
  51855. events.forEach(function (e) {
  51856. _this._events.push(e._clone());
  51857. });
  51858. }
  51859. }
  51860. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51861. /**
  51862. * Gets the current frame of the runtime animation
  51863. */
  51864. get: function () {
  51865. return this._currentFrame;
  51866. },
  51867. enumerable: true,
  51868. configurable: true
  51869. });
  51870. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51871. /**
  51872. * Gets the weight of the runtime animation
  51873. */
  51874. get: function () {
  51875. return this._weight;
  51876. },
  51877. enumerable: true,
  51878. configurable: true
  51879. });
  51880. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51881. /**
  51882. * Gets the current value of the runtime animation
  51883. */
  51884. get: function () {
  51885. return this._currentValue;
  51886. },
  51887. enumerable: true,
  51888. configurable: true
  51889. });
  51890. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51891. /**
  51892. * Gets the target path of the runtime animation
  51893. */
  51894. get: function () {
  51895. return this._targetPath;
  51896. },
  51897. enumerable: true,
  51898. configurable: true
  51899. });
  51900. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51901. /**
  51902. * Gets the actual target of the runtime animation
  51903. */
  51904. get: function () {
  51905. return this._activeTarget;
  51906. },
  51907. enumerable: true,
  51908. configurable: true
  51909. });
  51910. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51911. /**
  51912. * Gets the animation from the runtime animation
  51913. */
  51914. get: function () {
  51915. return this._animation;
  51916. },
  51917. enumerable: true,
  51918. configurable: true
  51919. });
  51920. /**
  51921. * Resets the runtime animation to the beginning
  51922. * @param restoreOriginal defines whether to restore the target property to the original value
  51923. */
  51924. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51925. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51926. if (restoreOriginal) {
  51927. if (this._target instanceof Array) {
  51928. var index = 0;
  51929. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51930. var target = _a[_i];
  51931. if (this._originalValue[index] !== undefined) {
  51932. this._setValue(target, this._originalValue[index], -1);
  51933. }
  51934. index++;
  51935. }
  51936. }
  51937. else {
  51938. if (this._originalValue[0] !== undefined) {
  51939. this._setValue(this._target, this._originalValue[0], -1);
  51940. }
  51941. }
  51942. }
  51943. this._offsetsCache = {};
  51944. this._highLimitsCache = {};
  51945. this._currentFrame = 0;
  51946. this._blendingFactor = 0;
  51947. this._originalValue = new Array();
  51948. // Events
  51949. for (var index = 0; index < this._events.length; index++) {
  51950. this._events[index].isDone = false;
  51951. }
  51952. };
  51953. /**
  51954. * Specifies if the runtime animation is stopped
  51955. * @returns Boolean specifying if the runtime animation is stopped
  51956. */
  51957. RuntimeAnimation.prototype.isStopped = function () {
  51958. return this._stopped;
  51959. };
  51960. /**
  51961. * Disposes of the runtime animation
  51962. */
  51963. RuntimeAnimation.prototype.dispose = function () {
  51964. var index = this._animation.runtimeAnimations.indexOf(this);
  51965. if (index > -1) {
  51966. this._animation.runtimeAnimations.splice(index, 1);
  51967. }
  51968. };
  51969. /**
  51970. * Interpolates the animation from the current frame
  51971. * @param currentFrame The frame to interpolate the animation to
  51972. * @param repeatCount The number of times that the animation should loop
  51973. * @param loopMode The type of looping mode to use
  51974. * @param offsetValue Animation offset value
  51975. * @param highLimitValue The high limit value
  51976. * @returns The interpolated value
  51977. */
  51978. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51979. this._currentFrame = currentFrame;
  51980. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51981. this._workValue = BABYLON.Matrix.Zero();
  51982. }
  51983. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51984. };
  51985. /**
  51986. * Apply the interpolated value to the target
  51987. * @param currentValue defines the value computed by the animation
  51988. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51989. */
  51990. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51991. if (weight === void 0) { weight = 1.0; }
  51992. if (this._target instanceof Array) {
  51993. var index = 0;
  51994. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51995. var target = _a[_i];
  51996. this._setValue(target, currentValue, weight, index);
  51997. index++;
  51998. }
  51999. }
  52000. else {
  52001. this._setValue(this._target, currentValue, weight);
  52002. }
  52003. };
  52004. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  52005. if (targetIndex === void 0) { targetIndex = 0; }
  52006. // Set value
  52007. var path;
  52008. var destination;
  52009. var targetPropertyPath = this._animation.targetPropertyPath;
  52010. if (targetPropertyPath.length > 1) {
  52011. var property = target[targetPropertyPath[0]];
  52012. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  52013. property = property[targetPropertyPath[index]];
  52014. }
  52015. path = targetPropertyPath[targetPropertyPath.length - 1];
  52016. destination = property;
  52017. }
  52018. else {
  52019. path = targetPropertyPath[0];
  52020. destination = target;
  52021. }
  52022. this._targetPath = path;
  52023. this._activeTarget = destination;
  52024. this._weight = weight;
  52025. if (this._originalValue[targetIndex] === undefined) {
  52026. var originalValue = void 0;
  52027. if (destination.getRestPose && path === "_matrix") { // For bones
  52028. originalValue = destination.getRestPose();
  52029. }
  52030. else {
  52031. originalValue = destination[path];
  52032. }
  52033. if (originalValue && originalValue.clone) {
  52034. this._originalValue[targetIndex] = originalValue.clone();
  52035. }
  52036. else {
  52037. this._originalValue[targetIndex] = originalValue;
  52038. }
  52039. }
  52040. // Blending
  52041. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52042. if (enableBlending && this._blendingFactor <= 1.0) {
  52043. if (!this._originalBlendValue) {
  52044. var originalValue = destination[path];
  52045. if (originalValue.clone) {
  52046. this._originalBlendValue = originalValue.clone();
  52047. }
  52048. else {
  52049. this._originalBlendValue = originalValue;
  52050. }
  52051. }
  52052. if (this._originalBlendValue.m) { // Matrix
  52053. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52054. if (this._currentValue) {
  52055. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52056. }
  52057. else {
  52058. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52059. }
  52060. }
  52061. else {
  52062. if (this._currentValue) {
  52063. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52064. }
  52065. else {
  52066. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52067. }
  52068. }
  52069. }
  52070. else {
  52071. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52072. }
  52073. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52074. this._blendingFactor += blendingSpeed;
  52075. }
  52076. else {
  52077. this._currentValue = currentValue;
  52078. }
  52079. if (weight !== -1.0) {
  52080. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52081. }
  52082. else {
  52083. destination[path] = this._currentValue;
  52084. }
  52085. if (target.markAsDirty) {
  52086. target.markAsDirty(this._animation.targetProperty);
  52087. }
  52088. };
  52089. /**
  52090. * Gets the loop pmode of the runtime animation
  52091. * @returns Loop Mode
  52092. */
  52093. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52094. if (this._target && this._target.animationPropertiesOverride) {
  52095. return this._target.animationPropertiesOverride.loopMode;
  52096. }
  52097. return this._animation.loopMode;
  52098. };
  52099. /**
  52100. * Move the current animation to a given frame
  52101. * @param frame defines the frame to move to
  52102. */
  52103. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52104. var keys = this._animation.getKeys();
  52105. if (frame < keys[0].frame) {
  52106. frame = keys[0].frame;
  52107. }
  52108. else if (frame > keys[keys.length - 1].frame) {
  52109. frame = keys[keys.length - 1].frame;
  52110. }
  52111. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52112. this.setValue(currentValue, -1);
  52113. };
  52114. /**
  52115. * @hidden Internal use only
  52116. */
  52117. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52118. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52119. this._ratioOffset = this._previousRatio - newRatio;
  52120. };
  52121. /**
  52122. * Execute the current animation
  52123. * @param delay defines the delay to add to the current frame
  52124. * @param from defines the lower bound of the animation range
  52125. * @param to defines the upper bound of the animation range
  52126. * @param loop defines if the current animation must loop
  52127. * @param speedRatio defines the current speed ratio
  52128. * @param weight defines the weight of the animation (default is -1 so no weight)
  52129. * @returns a boolean indicating if the animation has ended
  52130. */
  52131. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52132. if (weight === void 0) { weight = -1.0; }
  52133. var targetPropertyPath = this._animation.targetPropertyPath;
  52134. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52135. this._stopped = true;
  52136. return false;
  52137. }
  52138. var returnValue = true;
  52139. var keys = this._animation.getKeys();
  52140. // Adding a start key at frame 0 if missing
  52141. if (keys[0].frame !== 0) {
  52142. var newKey = { frame: 0, value: keys[0].value };
  52143. keys.splice(0, 0, newKey);
  52144. }
  52145. // Check limits
  52146. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52147. from = keys[0].frame;
  52148. }
  52149. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52150. to = keys[keys.length - 1].frame;
  52151. }
  52152. //to and from cannot be the same key
  52153. if (from === to) {
  52154. if (from > keys[0].frame) {
  52155. from--;
  52156. }
  52157. else if (to < keys[keys.length - 1].frame) {
  52158. to++;
  52159. }
  52160. }
  52161. // Compute ratio
  52162. var range = to - from;
  52163. var offsetValue;
  52164. // ratio represents the frame delta between from and to
  52165. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52166. var highLimitValue = 0;
  52167. this._previousDelay = delay;
  52168. this._previousRatio = ratio;
  52169. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  52170. returnValue = false;
  52171. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52172. }
  52173. else {
  52174. // Get max value if required
  52175. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52176. var keyOffset = to.toString() + from.toString();
  52177. if (!this._offsetsCache[keyOffset]) {
  52178. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52179. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52180. switch (this._animation.dataType) {
  52181. // Float
  52182. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52183. this._offsetsCache[keyOffset] = toValue - fromValue;
  52184. break;
  52185. // Quaternion
  52186. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52187. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52188. break;
  52189. // Vector3
  52190. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52191. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52192. // Vector2
  52193. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52194. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52195. // Size
  52196. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52197. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52198. // Color3
  52199. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52200. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52201. default:
  52202. break;
  52203. }
  52204. this._highLimitsCache[keyOffset] = toValue;
  52205. }
  52206. highLimitValue = this._highLimitsCache[keyOffset];
  52207. offsetValue = this._offsetsCache[keyOffset];
  52208. }
  52209. }
  52210. if (offsetValue === undefined) {
  52211. switch (this._animation.dataType) {
  52212. // Float
  52213. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52214. offsetValue = 0;
  52215. break;
  52216. // Quaternion
  52217. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52218. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  52219. break;
  52220. // Vector3
  52221. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52222. offsetValue = BABYLON.Vector3.Zero();
  52223. break;
  52224. // Vector2
  52225. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52226. offsetValue = BABYLON.Vector2.Zero();
  52227. break;
  52228. // Size
  52229. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52230. offsetValue = BABYLON.Size.Zero();
  52231. break;
  52232. // Color3
  52233. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52234. offsetValue = BABYLON.Color3.Black();
  52235. }
  52236. }
  52237. // Compute value
  52238. var repeatCount = (ratio / range) >> 0;
  52239. var currentFrame = returnValue ? from + ratio % range : to;
  52240. // Need to normalize?
  52241. if (this._host && this._host.syncRoot) {
  52242. var syncRoot = this._host.syncRoot;
  52243. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52244. currentFrame = from + (to - from) * hostNormalizedFrame;
  52245. }
  52246. // Reset events if looping
  52247. var events = this._events;
  52248. if (range > 0 && this.currentFrame > currentFrame ||
  52249. range < 0 && this.currentFrame < currentFrame) {
  52250. // Need to reset animation events
  52251. for (var index = 0; index < events.length; index++) {
  52252. if (!events[index].onlyOnce) {
  52253. // reset event, the animation is looping
  52254. events[index].isDone = false;
  52255. }
  52256. }
  52257. }
  52258. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52259. // Set value
  52260. this.setValue(currentValue, weight);
  52261. // Check events
  52262. for (var index = 0; index < events.length; index++) {
  52263. // Make sure current frame has passed event frame and that event frame is within the current range
  52264. // Also, handle both forward and reverse animations
  52265. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52266. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52267. var event = events[index];
  52268. if (!event.isDone) {
  52269. // If event should be done only once, remove it.
  52270. if (event.onlyOnce) {
  52271. events.splice(index, 1);
  52272. index--;
  52273. }
  52274. event.isDone = true;
  52275. event.action();
  52276. } // Don't do anything if the event has already be done.
  52277. }
  52278. }
  52279. if (!returnValue) {
  52280. this._stopped = true;
  52281. }
  52282. return returnValue;
  52283. };
  52284. return RuntimeAnimation;
  52285. }());
  52286. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52287. })(BABYLON || (BABYLON = {}));
  52288. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52289. var BABYLON;
  52290. (function (BABYLON) {
  52291. var Animatable = /** @class */ (function () {
  52292. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52293. if (fromFrame === void 0) { fromFrame = 0; }
  52294. if (toFrame === void 0) { toFrame = 100; }
  52295. if (loopAnimation === void 0) { loopAnimation = false; }
  52296. if (speedRatio === void 0) { speedRatio = 1.0; }
  52297. this.target = target;
  52298. this.fromFrame = fromFrame;
  52299. this.toFrame = toFrame;
  52300. this.loopAnimation = loopAnimation;
  52301. this.onAnimationEnd = onAnimationEnd;
  52302. this._localDelayOffset = null;
  52303. this._pausedDelay = null;
  52304. this._runtimeAnimations = new Array();
  52305. this._paused = false;
  52306. this._speedRatio = 1;
  52307. this._weight = -1.0;
  52308. this.animationStarted = false;
  52309. /**
  52310. * Observer raised when the animation ends
  52311. */
  52312. this.onAnimationEndObservable = new BABYLON.Observable();
  52313. this._scene = scene;
  52314. if (animations) {
  52315. this.appendAnimations(target, animations);
  52316. }
  52317. this._speedRatio = speedRatio;
  52318. scene._activeAnimatables.push(this);
  52319. }
  52320. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52321. /**
  52322. * Gets the root Animatable used to synchronize and normalize animations
  52323. */
  52324. get: function () {
  52325. return this._syncRoot;
  52326. },
  52327. enumerable: true,
  52328. configurable: true
  52329. });
  52330. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52331. /**
  52332. * Gets the current frame of the first RuntimeAnimation
  52333. * Used to synchronize Animatables
  52334. */
  52335. get: function () {
  52336. if (this._runtimeAnimations.length === 0) {
  52337. return 0;
  52338. }
  52339. return this._runtimeAnimations[0].currentFrame;
  52340. },
  52341. enumerable: true,
  52342. configurable: true
  52343. });
  52344. Object.defineProperty(Animatable.prototype, "weight", {
  52345. /**
  52346. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52347. */
  52348. get: function () {
  52349. return this._weight;
  52350. },
  52351. set: function (value) {
  52352. if (value === -1) { // -1 is ok and means no weight
  52353. this._weight = -1;
  52354. return;
  52355. }
  52356. // Else weight must be in [0, 1] range
  52357. this._weight = Math.min(Math.max(value, 0), 1.0);
  52358. },
  52359. enumerable: true,
  52360. configurable: true
  52361. });
  52362. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52363. /**
  52364. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52365. */
  52366. get: function () {
  52367. return this._speedRatio;
  52368. },
  52369. set: function (value) {
  52370. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52371. var animation = this._runtimeAnimations[index];
  52372. animation._prepareForSpeedRatioChange(value);
  52373. }
  52374. this._speedRatio = value;
  52375. },
  52376. enumerable: true,
  52377. configurable: true
  52378. });
  52379. // Methods
  52380. /**
  52381. * Synchronize and normalize current Animatable with a source Animatable
  52382. * This is useful when using animation weights and when animations are not of the same length
  52383. * @param root defines the root Animatable to synchronize with
  52384. * @returns the current Animatable
  52385. */
  52386. Animatable.prototype.syncWith = function (root) {
  52387. this._syncRoot = root;
  52388. if (root) {
  52389. // Make sure this animatable will animate after the root
  52390. var index = this._scene._activeAnimatables.indexOf(this);
  52391. if (index > -1) {
  52392. this._scene._activeAnimatables.splice(index, 1);
  52393. this._scene._activeAnimatables.push(this);
  52394. }
  52395. }
  52396. return this;
  52397. };
  52398. Animatable.prototype.getAnimations = function () {
  52399. return this._runtimeAnimations;
  52400. };
  52401. Animatable.prototype.appendAnimations = function (target, animations) {
  52402. for (var index = 0; index < animations.length; index++) {
  52403. var animation = animations[index];
  52404. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52405. }
  52406. };
  52407. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52408. var runtimeAnimations = this._runtimeAnimations;
  52409. for (var index = 0; index < runtimeAnimations.length; index++) {
  52410. if (runtimeAnimations[index].animation.targetProperty === property) {
  52411. return runtimeAnimations[index].animation;
  52412. }
  52413. }
  52414. return null;
  52415. };
  52416. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52417. var runtimeAnimations = this._runtimeAnimations;
  52418. for (var index = 0; index < runtimeAnimations.length; index++) {
  52419. if (runtimeAnimations[index].animation.targetProperty === property) {
  52420. return runtimeAnimations[index];
  52421. }
  52422. }
  52423. return null;
  52424. };
  52425. Animatable.prototype.reset = function () {
  52426. var runtimeAnimations = this._runtimeAnimations;
  52427. for (var index = 0; index < runtimeAnimations.length; index++) {
  52428. runtimeAnimations[index].reset(true);
  52429. }
  52430. this._localDelayOffset = null;
  52431. this._pausedDelay = null;
  52432. };
  52433. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52434. var runtimeAnimations = this._runtimeAnimations;
  52435. for (var index = 0; index < runtimeAnimations.length; index++) {
  52436. runtimeAnimations[index].animation.enableBlending = true;
  52437. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52438. }
  52439. };
  52440. Animatable.prototype.disableBlending = function () {
  52441. var runtimeAnimations = this._runtimeAnimations;
  52442. for (var index = 0; index < runtimeAnimations.length; index++) {
  52443. runtimeAnimations[index].animation.enableBlending = false;
  52444. }
  52445. };
  52446. Animatable.prototype.goToFrame = function (frame) {
  52447. var runtimeAnimations = this._runtimeAnimations;
  52448. if (runtimeAnimations[0]) {
  52449. var fps = runtimeAnimations[0].animation.framePerSecond;
  52450. var currentFrame = runtimeAnimations[0].currentFrame;
  52451. var adjustTime = frame - currentFrame;
  52452. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52453. if (this._localDelayOffset === null) {
  52454. this._localDelayOffset = 0;
  52455. }
  52456. this._localDelayOffset -= delay;
  52457. }
  52458. for (var index = 0; index < runtimeAnimations.length; index++) {
  52459. runtimeAnimations[index].goToFrame(frame);
  52460. }
  52461. };
  52462. Animatable.prototype.pause = function () {
  52463. if (this._paused) {
  52464. return;
  52465. }
  52466. this._paused = true;
  52467. };
  52468. Animatable.prototype.restart = function () {
  52469. this._paused = false;
  52470. };
  52471. Animatable.prototype._raiseOnAnimationEnd = function () {
  52472. if (this.onAnimationEnd) {
  52473. this.onAnimationEnd();
  52474. }
  52475. this.onAnimationEndObservable.notifyObservers(this);
  52476. };
  52477. Animatable.prototype.stop = function (animationName) {
  52478. if (animationName) {
  52479. var idx = this._scene._activeAnimatables.indexOf(this);
  52480. if (idx > -1) {
  52481. var runtimeAnimations = this._runtimeAnimations;
  52482. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52483. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52484. continue;
  52485. }
  52486. runtimeAnimations[index].dispose();
  52487. runtimeAnimations.splice(index, 1);
  52488. }
  52489. if (runtimeAnimations.length == 0) {
  52490. this._scene._activeAnimatables.splice(idx, 1);
  52491. this._raiseOnAnimationEnd();
  52492. }
  52493. }
  52494. }
  52495. else {
  52496. var index = this._scene._activeAnimatables.indexOf(this);
  52497. if (index > -1) {
  52498. this._scene._activeAnimatables.splice(index, 1);
  52499. var runtimeAnimations = this._runtimeAnimations;
  52500. for (var index = 0; index < runtimeAnimations.length; index++) {
  52501. runtimeAnimations[index].dispose();
  52502. }
  52503. this._raiseOnAnimationEnd();
  52504. }
  52505. }
  52506. };
  52507. /**
  52508. * Wait asynchronously for the animation to end
  52509. * @returns a promise which will be fullfilled when the animation ends
  52510. */
  52511. Animatable.prototype.waitAsync = function () {
  52512. var _this = this;
  52513. return new Promise(function (resolve, reject) {
  52514. _this.onAnimationEndObservable.add(function () {
  52515. resolve(_this);
  52516. }, undefined, undefined, _this, true);
  52517. });
  52518. };
  52519. /** @hidden */
  52520. Animatable.prototype._animate = function (delay) {
  52521. if (this._paused) {
  52522. this.animationStarted = false;
  52523. if (this._pausedDelay === null) {
  52524. this._pausedDelay = delay;
  52525. }
  52526. return true;
  52527. }
  52528. if (this._localDelayOffset === null) {
  52529. this._localDelayOffset = delay;
  52530. this._pausedDelay = null;
  52531. }
  52532. else if (this._pausedDelay !== null) {
  52533. this._localDelayOffset += delay - this._pausedDelay;
  52534. this._pausedDelay = null;
  52535. }
  52536. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52537. return true;
  52538. }
  52539. // Animating
  52540. var running = false;
  52541. var runtimeAnimations = this._runtimeAnimations;
  52542. var index;
  52543. for (index = 0; index < runtimeAnimations.length; index++) {
  52544. var animation = runtimeAnimations[index];
  52545. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52546. running = running || isRunning;
  52547. }
  52548. this.animationStarted = running;
  52549. if (!running) {
  52550. // Remove from active animatables
  52551. index = this._scene._activeAnimatables.indexOf(this);
  52552. this._scene._activeAnimatables.splice(index, 1);
  52553. // Dispose all runtime animations
  52554. for (index = 0; index < runtimeAnimations.length; index++) {
  52555. runtimeAnimations[index].dispose();
  52556. }
  52557. }
  52558. if (!running) {
  52559. this._raiseOnAnimationEnd();
  52560. this.onAnimationEnd = null;
  52561. this.onAnimationEndObservable.clear();
  52562. }
  52563. return running;
  52564. };
  52565. return Animatable;
  52566. }());
  52567. BABYLON.Animatable = Animatable;
  52568. })(BABYLON || (BABYLON = {}));
  52569. //# sourceMappingURL=babylon.animatable.js.map
  52570. var BABYLON;
  52571. (function (BABYLON) {
  52572. var EasingFunction = /** @class */ (function () {
  52573. function EasingFunction() {
  52574. // Properties
  52575. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52576. }
  52577. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52578. get: function () {
  52579. return EasingFunction._EASINGMODE_EASEIN;
  52580. },
  52581. enumerable: true,
  52582. configurable: true
  52583. });
  52584. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52585. get: function () {
  52586. return EasingFunction._EASINGMODE_EASEOUT;
  52587. },
  52588. enumerable: true,
  52589. configurable: true
  52590. });
  52591. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52592. get: function () {
  52593. return EasingFunction._EASINGMODE_EASEINOUT;
  52594. },
  52595. enumerable: true,
  52596. configurable: true
  52597. });
  52598. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52599. var n = Math.min(Math.max(easingMode, 0), 2);
  52600. this._easingMode = n;
  52601. };
  52602. EasingFunction.prototype.getEasingMode = function () {
  52603. return this._easingMode;
  52604. };
  52605. EasingFunction.prototype.easeInCore = function (gradient) {
  52606. throw new Error('You must implement this method');
  52607. };
  52608. EasingFunction.prototype.ease = function (gradient) {
  52609. switch (this._easingMode) {
  52610. case EasingFunction.EASINGMODE_EASEIN:
  52611. return this.easeInCore(gradient);
  52612. case EasingFunction.EASINGMODE_EASEOUT:
  52613. return (1 - this.easeInCore(1 - gradient));
  52614. }
  52615. if (gradient >= 0.5) {
  52616. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52617. }
  52618. return (this.easeInCore(gradient * 2) * 0.5);
  52619. };
  52620. //Statics
  52621. EasingFunction._EASINGMODE_EASEIN = 0;
  52622. EasingFunction._EASINGMODE_EASEOUT = 1;
  52623. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52624. return EasingFunction;
  52625. }());
  52626. BABYLON.EasingFunction = EasingFunction;
  52627. var CircleEase = /** @class */ (function (_super) {
  52628. __extends(CircleEase, _super);
  52629. function CircleEase() {
  52630. return _super !== null && _super.apply(this, arguments) || this;
  52631. }
  52632. CircleEase.prototype.easeInCore = function (gradient) {
  52633. gradient = Math.max(0, Math.min(1, gradient));
  52634. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52635. };
  52636. return CircleEase;
  52637. }(EasingFunction));
  52638. BABYLON.CircleEase = CircleEase;
  52639. var BackEase = /** @class */ (function (_super) {
  52640. __extends(BackEase, _super);
  52641. function BackEase(amplitude) {
  52642. if (amplitude === void 0) { amplitude = 1; }
  52643. var _this = _super.call(this) || this;
  52644. _this.amplitude = amplitude;
  52645. return _this;
  52646. }
  52647. BackEase.prototype.easeInCore = function (gradient) {
  52648. var num = Math.max(0, this.amplitude);
  52649. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52650. };
  52651. return BackEase;
  52652. }(EasingFunction));
  52653. BABYLON.BackEase = BackEase;
  52654. var BounceEase = /** @class */ (function (_super) {
  52655. __extends(BounceEase, _super);
  52656. function BounceEase(bounces, bounciness) {
  52657. if (bounces === void 0) { bounces = 3; }
  52658. if (bounciness === void 0) { bounciness = 2; }
  52659. var _this = _super.call(this) || this;
  52660. _this.bounces = bounces;
  52661. _this.bounciness = bounciness;
  52662. return _this;
  52663. }
  52664. BounceEase.prototype.easeInCore = function (gradient) {
  52665. var y = Math.max(0.0, this.bounces);
  52666. var bounciness = this.bounciness;
  52667. if (bounciness <= 1.0) {
  52668. bounciness = 1.001;
  52669. }
  52670. var num9 = Math.pow(bounciness, y);
  52671. var num5 = 1.0 - bounciness;
  52672. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52673. var num15 = gradient * num4;
  52674. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52675. var num3 = Math.floor(num65);
  52676. var num13 = num3 + 1.0;
  52677. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52678. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52679. var num7 = (num8 + num12) * 0.5;
  52680. var num6 = gradient - num7;
  52681. var num2 = num7 - num8;
  52682. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52683. };
  52684. return BounceEase;
  52685. }(EasingFunction));
  52686. BABYLON.BounceEase = BounceEase;
  52687. var CubicEase = /** @class */ (function (_super) {
  52688. __extends(CubicEase, _super);
  52689. function CubicEase() {
  52690. return _super !== null && _super.apply(this, arguments) || this;
  52691. }
  52692. CubicEase.prototype.easeInCore = function (gradient) {
  52693. return (gradient * gradient * gradient);
  52694. };
  52695. return CubicEase;
  52696. }(EasingFunction));
  52697. BABYLON.CubicEase = CubicEase;
  52698. var ElasticEase = /** @class */ (function (_super) {
  52699. __extends(ElasticEase, _super);
  52700. function ElasticEase(oscillations, springiness) {
  52701. if (oscillations === void 0) { oscillations = 3; }
  52702. if (springiness === void 0) { springiness = 3; }
  52703. var _this = _super.call(this) || this;
  52704. _this.oscillations = oscillations;
  52705. _this.springiness = springiness;
  52706. return _this;
  52707. }
  52708. ElasticEase.prototype.easeInCore = function (gradient) {
  52709. var num2;
  52710. var num3 = Math.max(0.0, this.oscillations);
  52711. var num = Math.max(0.0, this.springiness);
  52712. if (num == 0) {
  52713. num2 = gradient;
  52714. }
  52715. else {
  52716. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52717. }
  52718. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52719. };
  52720. return ElasticEase;
  52721. }(EasingFunction));
  52722. BABYLON.ElasticEase = ElasticEase;
  52723. var ExponentialEase = /** @class */ (function (_super) {
  52724. __extends(ExponentialEase, _super);
  52725. function ExponentialEase(exponent) {
  52726. if (exponent === void 0) { exponent = 2; }
  52727. var _this = _super.call(this) || this;
  52728. _this.exponent = exponent;
  52729. return _this;
  52730. }
  52731. ExponentialEase.prototype.easeInCore = function (gradient) {
  52732. if (this.exponent <= 0) {
  52733. return gradient;
  52734. }
  52735. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52736. };
  52737. return ExponentialEase;
  52738. }(EasingFunction));
  52739. BABYLON.ExponentialEase = ExponentialEase;
  52740. var PowerEase = /** @class */ (function (_super) {
  52741. __extends(PowerEase, _super);
  52742. function PowerEase(power) {
  52743. if (power === void 0) { power = 2; }
  52744. var _this = _super.call(this) || this;
  52745. _this.power = power;
  52746. return _this;
  52747. }
  52748. PowerEase.prototype.easeInCore = function (gradient) {
  52749. var y = Math.max(0.0, this.power);
  52750. return Math.pow(gradient, y);
  52751. };
  52752. return PowerEase;
  52753. }(EasingFunction));
  52754. BABYLON.PowerEase = PowerEase;
  52755. var QuadraticEase = /** @class */ (function (_super) {
  52756. __extends(QuadraticEase, _super);
  52757. function QuadraticEase() {
  52758. return _super !== null && _super.apply(this, arguments) || this;
  52759. }
  52760. QuadraticEase.prototype.easeInCore = function (gradient) {
  52761. return (gradient * gradient);
  52762. };
  52763. return QuadraticEase;
  52764. }(EasingFunction));
  52765. BABYLON.QuadraticEase = QuadraticEase;
  52766. var QuarticEase = /** @class */ (function (_super) {
  52767. __extends(QuarticEase, _super);
  52768. function QuarticEase() {
  52769. return _super !== null && _super.apply(this, arguments) || this;
  52770. }
  52771. QuarticEase.prototype.easeInCore = function (gradient) {
  52772. return (gradient * gradient * gradient * gradient);
  52773. };
  52774. return QuarticEase;
  52775. }(EasingFunction));
  52776. BABYLON.QuarticEase = QuarticEase;
  52777. var QuinticEase = /** @class */ (function (_super) {
  52778. __extends(QuinticEase, _super);
  52779. function QuinticEase() {
  52780. return _super !== null && _super.apply(this, arguments) || this;
  52781. }
  52782. QuinticEase.prototype.easeInCore = function (gradient) {
  52783. return (gradient * gradient * gradient * gradient * gradient);
  52784. };
  52785. return QuinticEase;
  52786. }(EasingFunction));
  52787. BABYLON.QuinticEase = QuinticEase;
  52788. var SineEase = /** @class */ (function (_super) {
  52789. __extends(SineEase, _super);
  52790. function SineEase() {
  52791. return _super !== null && _super.apply(this, arguments) || this;
  52792. }
  52793. SineEase.prototype.easeInCore = function (gradient) {
  52794. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52795. };
  52796. return SineEase;
  52797. }(EasingFunction));
  52798. BABYLON.SineEase = SineEase;
  52799. var BezierCurveEase = /** @class */ (function (_super) {
  52800. __extends(BezierCurveEase, _super);
  52801. function BezierCurveEase(x1, y1, x2, y2) {
  52802. if (x1 === void 0) { x1 = 0; }
  52803. if (y1 === void 0) { y1 = 0; }
  52804. if (x2 === void 0) { x2 = 1; }
  52805. if (y2 === void 0) { y2 = 1; }
  52806. var _this = _super.call(this) || this;
  52807. _this.x1 = x1;
  52808. _this.y1 = y1;
  52809. _this.x2 = x2;
  52810. _this.y2 = y2;
  52811. return _this;
  52812. }
  52813. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52814. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52815. };
  52816. return BezierCurveEase;
  52817. }(EasingFunction));
  52818. BABYLON.BezierCurveEase = BezierCurveEase;
  52819. })(BABYLON || (BABYLON = {}));
  52820. //# sourceMappingURL=babylon.easing.js.map
  52821. var BABYLON;
  52822. (function (BABYLON) {
  52823. /**
  52824. * A Condition applied to an Action
  52825. */
  52826. var Condition = /** @class */ (function () {
  52827. /**
  52828. * Creates a new Condition
  52829. * @param actionManager the manager of the action the condition is applied to
  52830. */
  52831. function Condition(actionManager) {
  52832. this._actionManager = actionManager;
  52833. }
  52834. /**
  52835. * Check if the current condition is valid
  52836. * @returns a boolean
  52837. */
  52838. Condition.prototype.isValid = function () {
  52839. return true;
  52840. };
  52841. /**
  52842. * Internal only
  52843. * @hidden
  52844. */
  52845. Condition.prototype._getProperty = function (propertyPath) {
  52846. return this._actionManager._getProperty(propertyPath);
  52847. };
  52848. /**
  52849. * Internal only
  52850. * @hidden
  52851. */
  52852. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52853. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52854. };
  52855. /**
  52856. * Serialize placeholder for child classes
  52857. * @returns the serialized object
  52858. */
  52859. Condition.prototype.serialize = function () {
  52860. };
  52861. /**
  52862. * Internal only
  52863. * @hidden
  52864. */
  52865. Condition.prototype._serialize = function (serializedCondition) {
  52866. return {
  52867. type: 2,
  52868. children: [],
  52869. name: serializedCondition.name,
  52870. properties: serializedCondition.properties
  52871. };
  52872. };
  52873. return Condition;
  52874. }());
  52875. BABYLON.Condition = Condition;
  52876. /**
  52877. * Defines specific conditional operators as extensions of Condition
  52878. */
  52879. var ValueCondition = /** @class */ (function (_super) {
  52880. __extends(ValueCondition, _super);
  52881. /**
  52882. * Creates a new ValueCondition
  52883. * @param actionManager manager for the action the condition applies to
  52884. * @param target for the action
  52885. * @param propertyPath path to specify the property of the target the conditional operator uses
  52886. * @param value the value compared by the conditional operator against the current value of the property
  52887. * @param operator the conditional operator, default ValueCondition.IsEqual
  52888. */
  52889. function ValueCondition(actionManager, target,
  52890. /** path to specify the property of the target the conditional operator uses */
  52891. propertyPath,
  52892. /** the value compared by the conditional operator against the current value of the property */
  52893. value,
  52894. /** the conditional operator, default ValueCondition.IsEqual */
  52895. operator) {
  52896. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52897. var _this = _super.call(this, actionManager) || this;
  52898. _this.propertyPath = propertyPath;
  52899. _this.value = value;
  52900. _this.operator = operator;
  52901. _this._target = target;
  52902. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52903. _this._property = _this._getProperty(_this.propertyPath);
  52904. return _this;
  52905. }
  52906. Object.defineProperty(ValueCondition, "IsEqual", {
  52907. /**
  52908. * returns the number for IsEqual
  52909. */
  52910. get: function () {
  52911. return ValueCondition._IsEqual;
  52912. },
  52913. enumerable: true,
  52914. configurable: true
  52915. });
  52916. Object.defineProperty(ValueCondition, "IsDifferent", {
  52917. /**
  52918. * Returns the number for IsDifferent
  52919. */
  52920. get: function () {
  52921. return ValueCondition._IsDifferent;
  52922. },
  52923. enumerable: true,
  52924. configurable: true
  52925. });
  52926. Object.defineProperty(ValueCondition, "IsGreater", {
  52927. /**
  52928. * Returns the number for IsGreater
  52929. */
  52930. get: function () {
  52931. return ValueCondition._IsGreater;
  52932. },
  52933. enumerable: true,
  52934. configurable: true
  52935. });
  52936. Object.defineProperty(ValueCondition, "IsLesser", {
  52937. /**
  52938. * Returns the number for IsLesser
  52939. */
  52940. get: function () {
  52941. return ValueCondition._IsLesser;
  52942. },
  52943. enumerable: true,
  52944. configurable: true
  52945. });
  52946. /**
  52947. * Compares the given value with the property value for the specified conditional operator
  52948. * @returns the result of the comparison
  52949. */
  52950. ValueCondition.prototype.isValid = function () {
  52951. switch (this.operator) {
  52952. case ValueCondition.IsGreater:
  52953. return this._effectiveTarget[this._property] > this.value;
  52954. case ValueCondition.IsLesser:
  52955. return this._effectiveTarget[this._property] < this.value;
  52956. case ValueCondition.IsEqual:
  52957. case ValueCondition.IsDifferent:
  52958. var check;
  52959. if (this.value.equals) {
  52960. check = this.value.equals(this._effectiveTarget[this._property]);
  52961. }
  52962. else {
  52963. check = this.value === this._effectiveTarget[this._property];
  52964. }
  52965. return this.operator === ValueCondition.IsEqual ? check : !check;
  52966. }
  52967. return false;
  52968. };
  52969. /**
  52970. * Serialize the ValueCondition into a JSON compatible object
  52971. * @returns serialization object
  52972. */
  52973. ValueCondition.prototype.serialize = function () {
  52974. return this._serialize({
  52975. name: "ValueCondition",
  52976. properties: [
  52977. BABYLON.Action._GetTargetProperty(this._target),
  52978. { name: "propertyPath", value: this.propertyPath },
  52979. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52980. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52981. ]
  52982. });
  52983. };
  52984. /**
  52985. * Gets the name of the conditional operator for the ValueCondition
  52986. * @param operator the conditional operator
  52987. * @returns the name
  52988. */
  52989. ValueCondition.GetOperatorName = function (operator) {
  52990. switch (operator) {
  52991. case ValueCondition._IsEqual: return "IsEqual";
  52992. case ValueCondition._IsDifferent: return "IsDifferent";
  52993. case ValueCondition._IsGreater: return "IsGreater";
  52994. case ValueCondition._IsLesser: return "IsLesser";
  52995. default: return "";
  52996. }
  52997. };
  52998. /**
  52999. * Internal only
  53000. * @hidden
  53001. */
  53002. ValueCondition._IsEqual = 0;
  53003. /**
  53004. * Internal only
  53005. * @hidden
  53006. */
  53007. ValueCondition._IsDifferent = 1;
  53008. /**
  53009. * Internal only
  53010. * @hidden
  53011. */
  53012. ValueCondition._IsGreater = 2;
  53013. /**
  53014. * Internal only
  53015. * @hidden
  53016. */
  53017. ValueCondition._IsLesser = 3;
  53018. return ValueCondition;
  53019. }(Condition));
  53020. BABYLON.ValueCondition = ValueCondition;
  53021. /**
  53022. * Defines a predicate condition as an extension of Condition
  53023. */
  53024. var PredicateCondition = /** @class */ (function (_super) {
  53025. __extends(PredicateCondition, _super);
  53026. /**
  53027. * Creates a new PredicateCondition
  53028. * @param actionManager manager for the action the condition applies to
  53029. * @param predicate defines the predicate function used to validate the condition
  53030. */
  53031. function PredicateCondition(actionManager,
  53032. /** defines the predicate function used to validate the condition */
  53033. predicate) {
  53034. var _this = _super.call(this, actionManager) || this;
  53035. _this.predicate = predicate;
  53036. return _this;
  53037. }
  53038. /**
  53039. * @returns the validity of the predicate condition
  53040. */
  53041. PredicateCondition.prototype.isValid = function () {
  53042. return this.predicate();
  53043. };
  53044. return PredicateCondition;
  53045. }(Condition));
  53046. BABYLON.PredicateCondition = PredicateCondition;
  53047. /**
  53048. * Defines a state condition as an extension of Condition
  53049. */
  53050. var StateCondition = /** @class */ (function (_super) {
  53051. __extends(StateCondition, _super);
  53052. /**
  53053. * Creates a new StateCondition
  53054. * @param actionManager manager for the action the condition applies to
  53055. * @param target of the condition
  53056. * @param value to compare with target state
  53057. */
  53058. function StateCondition(actionManager, target, value) {
  53059. var _this = _super.call(this, actionManager) || this;
  53060. _this.value = value;
  53061. _this._target = target;
  53062. return _this;
  53063. }
  53064. /**
  53065. * @returns the validity of the state
  53066. */
  53067. StateCondition.prototype.isValid = function () {
  53068. return this._target.state === this.value;
  53069. };
  53070. /**
  53071. * Serialize the StateCondition into a JSON compatible object
  53072. * @returns serialization object
  53073. */
  53074. StateCondition.prototype.serialize = function () {
  53075. return this._serialize({
  53076. name: "StateCondition",
  53077. properties: [
  53078. BABYLON.Action._GetTargetProperty(this._target),
  53079. { name: "value", value: this.value }
  53080. ]
  53081. });
  53082. };
  53083. return StateCondition;
  53084. }(Condition));
  53085. BABYLON.StateCondition = StateCondition;
  53086. })(BABYLON || (BABYLON = {}));
  53087. //# sourceMappingURL=babylon.condition.js.map
  53088. var BABYLON;
  53089. (function (BABYLON) {
  53090. /**
  53091. * The action to be carried out following a trigger
  53092. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53093. */
  53094. var Action = /** @class */ (function () {
  53095. /**
  53096. * Creates a new Action
  53097. * @param triggerOptions the trigger, with or without parameters, for the action
  53098. * @param condition an optional determinant of action
  53099. */
  53100. function Action(
  53101. /** the trigger, with or without parameters, for the action */
  53102. triggerOptions, condition) {
  53103. this.triggerOptions = triggerOptions;
  53104. /**
  53105. * An event triggered prior to action being executed.
  53106. */
  53107. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53108. if (triggerOptions.parameter) {
  53109. this.trigger = triggerOptions.trigger;
  53110. this._triggerParameter = triggerOptions.parameter;
  53111. }
  53112. else {
  53113. this.trigger = triggerOptions;
  53114. }
  53115. this._nextActiveAction = this;
  53116. this._condition = condition;
  53117. }
  53118. /**
  53119. * Internal only
  53120. * @hidden
  53121. */
  53122. Action.prototype._prepare = function () {
  53123. };
  53124. /**
  53125. * Gets the trigger parameters
  53126. * @returns the trigger parameters
  53127. */
  53128. Action.prototype.getTriggerParameter = function () {
  53129. return this._triggerParameter;
  53130. };
  53131. /**
  53132. * Internal only - executes current action event
  53133. * @hidden
  53134. */
  53135. Action.prototype._executeCurrent = function (evt) {
  53136. if (this._nextActiveAction._condition) {
  53137. var condition = this._nextActiveAction._condition;
  53138. var currentRenderId = this._actionManager.getScene().getRenderId();
  53139. // We cache the current evaluation for the current frame
  53140. if (condition._evaluationId === currentRenderId) {
  53141. if (!condition._currentResult) {
  53142. return;
  53143. }
  53144. }
  53145. else {
  53146. condition._evaluationId = currentRenderId;
  53147. if (!condition.isValid()) {
  53148. condition._currentResult = false;
  53149. return;
  53150. }
  53151. condition._currentResult = true;
  53152. }
  53153. }
  53154. this.onBeforeExecuteObservable.notifyObservers(this);
  53155. this._nextActiveAction.execute(evt);
  53156. this.skipToNextActiveAction();
  53157. };
  53158. /**
  53159. * Execute placeholder for child classes
  53160. * @param evt optional action event
  53161. */
  53162. Action.prototype.execute = function (evt) {
  53163. };
  53164. /**
  53165. * Skips to next active action
  53166. */
  53167. Action.prototype.skipToNextActiveAction = function () {
  53168. if (this._nextActiveAction._child) {
  53169. if (!this._nextActiveAction._child._actionManager) {
  53170. this._nextActiveAction._child._actionManager = this._actionManager;
  53171. }
  53172. this._nextActiveAction = this._nextActiveAction._child;
  53173. }
  53174. else {
  53175. this._nextActiveAction = this;
  53176. }
  53177. };
  53178. /**
  53179. * Adds action to chain of actions, may be a DoNothingAction
  53180. * @param action defines the next action to execute
  53181. * @returns The action passed in
  53182. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53183. */
  53184. Action.prototype.then = function (action) {
  53185. this._child = action;
  53186. action._actionManager = this._actionManager;
  53187. action._prepare();
  53188. return action;
  53189. };
  53190. /**
  53191. * Internal only
  53192. * @hidden
  53193. */
  53194. Action.prototype._getProperty = function (propertyPath) {
  53195. return this._actionManager._getProperty(propertyPath);
  53196. };
  53197. /**
  53198. * Internal only
  53199. * @hidden
  53200. */
  53201. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53202. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53203. };
  53204. /**
  53205. * Serialize placeholder for child classes
  53206. * @param parent of child
  53207. * @returns the serialized object
  53208. */
  53209. Action.prototype.serialize = function (parent) {
  53210. };
  53211. /**
  53212. * Internal only called by serialize
  53213. * @hidden
  53214. */
  53215. Action.prototype._serialize = function (serializedAction, parent) {
  53216. var serializationObject = {
  53217. type: 1,
  53218. children: [],
  53219. name: serializedAction.name,
  53220. properties: serializedAction.properties || []
  53221. };
  53222. // Serialize child
  53223. if (this._child) {
  53224. this._child.serialize(serializationObject);
  53225. }
  53226. // Check if "this" has a condition
  53227. if (this._condition) {
  53228. var serializedCondition = this._condition.serialize();
  53229. serializedCondition.children.push(serializationObject);
  53230. if (parent) {
  53231. parent.children.push(serializedCondition);
  53232. }
  53233. return serializedCondition;
  53234. }
  53235. if (parent) {
  53236. parent.children.push(serializationObject);
  53237. }
  53238. return serializationObject;
  53239. };
  53240. /**
  53241. * Internal only
  53242. * @hidden
  53243. */
  53244. Action._SerializeValueAsString = function (value) {
  53245. if (typeof value === "number") {
  53246. return value.toString();
  53247. }
  53248. if (typeof value === "boolean") {
  53249. return value ? "true" : "false";
  53250. }
  53251. if (value instanceof BABYLON.Vector2) {
  53252. return value.x + ", " + value.y;
  53253. }
  53254. if (value instanceof BABYLON.Vector3) {
  53255. return value.x + ", " + value.y + ", " + value.z;
  53256. }
  53257. if (value instanceof BABYLON.Color3) {
  53258. return value.r + ", " + value.g + ", " + value.b;
  53259. }
  53260. if (value instanceof BABYLON.Color4) {
  53261. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53262. }
  53263. return value; // string
  53264. };
  53265. /**
  53266. * Internal only
  53267. * @hidden
  53268. */
  53269. Action._GetTargetProperty = function (target) {
  53270. return {
  53271. name: "target",
  53272. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53273. : target instanceof BABYLON.Light ? "LightProperties"
  53274. : target instanceof BABYLON.Camera ? "CameraProperties"
  53275. : "SceneProperties",
  53276. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53277. };
  53278. };
  53279. return Action;
  53280. }());
  53281. BABYLON.Action = Action;
  53282. })(BABYLON || (BABYLON = {}));
  53283. //# sourceMappingURL=babylon.action.js.map
  53284. var BABYLON;
  53285. (function (BABYLON) {
  53286. /**
  53287. * ActionEvent is the event being sent when an action is triggered.
  53288. */
  53289. var ActionEvent = /** @class */ (function () {
  53290. /**
  53291. * Creates a new ActionEvent
  53292. * @param source The mesh or sprite that triggered the action
  53293. * @param pointerX The X mouse cursor position at the time of the event
  53294. * @param pointerY The Y mouse cursor position at the time of the event
  53295. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53296. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53297. * @param additionalData additional data for the event
  53298. */
  53299. function ActionEvent(
  53300. /** The mesh or sprite that triggered the action */
  53301. source,
  53302. /** The X mouse cursor position at the time of the event */
  53303. pointerX,
  53304. /** The Y mouse cursor position at the time of the event */
  53305. pointerY,
  53306. /** The mesh that is currently pointed at (can be null) */
  53307. meshUnderPointer,
  53308. /** the original (browser) event that triggered the ActionEvent */
  53309. sourceEvent,
  53310. /** additional data for the event */
  53311. additionalData) {
  53312. this.source = source;
  53313. this.pointerX = pointerX;
  53314. this.pointerY = pointerY;
  53315. this.meshUnderPointer = meshUnderPointer;
  53316. this.sourceEvent = sourceEvent;
  53317. this.additionalData = additionalData;
  53318. }
  53319. /**
  53320. * Helper function to auto-create an ActionEvent from a source mesh.
  53321. * @param source The source mesh that triggered the event
  53322. * @param evt The original (browser) event
  53323. * @param additionalData additional data for the event
  53324. * @returns the new ActionEvent
  53325. */
  53326. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53327. var scene = source.getScene();
  53328. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53329. };
  53330. /**
  53331. * Helper function to auto-create an ActionEvent from a source sprite
  53332. * @param source The source sprite that triggered the event
  53333. * @param scene Scene associated with the sprite
  53334. * @param evt The original (browser) event
  53335. * @param additionalData additional data for the event
  53336. * @returns the new ActionEvent
  53337. */
  53338. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53339. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53340. };
  53341. /**
  53342. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53343. * @param scene the scene where the event occurred
  53344. * @param evt The original (browser) event
  53345. * @returns the new ActionEvent
  53346. */
  53347. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53348. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53349. };
  53350. /**
  53351. * Helper function to auto-create an ActionEvent from a primitive
  53352. * @param prim defines the target primitive
  53353. * @param pointerPos defines the pointer position
  53354. * @param evt The original (browser) event
  53355. * @param additionalData additional data for the event
  53356. * @returns the new ActionEvent
  53357. */
  53358. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53359. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53360. };
  53361. return ActionEvent;
  53362. }());
  53363. BABYLON.ActionEvent = ActionEvent;
  53364. /**
  53365. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53366. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53367. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53368. */
  53369. var ActionManager = /** @class */ (function () {
  53370. /**
  53371. * Creates a new action manager
  53372. * @param scene defines the hosting scene
  53373. */
  53374. function ActionManager(scene) {
  53375. // Members
  53376. /** Gets the list of actions */
  53377. this.actions = new Array();
  53378. /** Gets the cursor to use when hovering items */
  53379. this.hoverCursor = '';
  53380. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53381. scene._actionManagers.push(this);
  53382. }
  53383. Object.defineProperty(ActionManager, "NothingTrigger", {
  53384. /**
  53385. * Nothing
  53386. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53387. */
  53388. get: function () {
  53389. return ActionManager._NothingTrigger;
  53390. },
  53391. enumerable: true,
  53392. configurable: true
  53393. });
  53394. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53395. /**
  53396. * On pick
  53397. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53398. */
  53399. get: function () {
  53400. return ActionManager._OnPickTrigger;
  53401. },
  53402. enumerable: true,
  53403. configurable: true
  53404. });
  53405. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53406. /**
  53407. * On left pick
  53408. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53409. */
  53410. get: function () {
  53411. return ActionManager._OnLeftPickTrigger;
  53412. },
  53413. enumerable: true,
  53414. configurable: true
  53415. });
  53416. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53417. /**
  53418. * On right pick
  53419. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53420. */
  53421. get: function () {
  53422. return ActionManager._OnRightPickTrigger;
  53423. },
  53424. enumerable: true,
  53425. configurable: true
  53426. });
  53427. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53428. /**
  53429. * On center pick
  53430. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53431. */
  53432. get: function () {
  53433. return ActionManager._OnCenterPickTrigger;
  53434. },
  53435. enumerable: true,
  53436. configurable: true
  53437. });
  53438. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53439. /**
  53440. * On pick down
  53441. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53442. */
  53443. get: function () {
  53444. return ActionManager._OnPickDownTrigger;
  53445. },
  53446. enumerable: true,
  53447. configurable: true
  53448. });
  53449. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53450. /**
  53451. * On double pick
  53452. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53453. */
  53454. get: function () {
  53455. return ActionManager._OnDoublePickTrigger;
  53456. },
  53457. enumerable: true,
  53458. configurable: true
  53459. });
  53460. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53461. /**
  53462. * On pick up
  53463. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53464. */
  53465. get: function () {
  53466. return ActionManager._OnPickUpTrigger;
  53467. },
  53468. enumerable: true,
  53469. configurable: true
  53470. });
  53471. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53472. /**
  53473. * On pick out.
  53474. * This trigger will only be raised if you also declared a OnPickDown
  53475. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53476. */
  53477. get: function () {
  53478. return ActionManager._OnPickOutTrigger;
  53479. },
  53480. enumerable: true,
  53481. configurable: true
  53482. });
  53483. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53484. /**
  53485. * On long press
  53486. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53487. */
  53488. get: function () {
  53489. return ActionManager._OnLongPressTrigger;
  53490. },
  53491. enumerable: true,
  53492. configurable: true
  53493. });
  53494. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53495. /**
  53496. * On pointer over
  53497. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53498. */
  53499. get: function () {
  53500. return ActionManager._OnPointerOverTrigger;
  53501. },
  53502. enumerable: true,
  53503. configurable: true
  53504. });
  53505. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53506. /**
  53507. * On pointer out
  53508. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53509. */
  53510. get: function () {
  53511. return ActionManager._OnPointerOutTrigger;
  53512. },
  53513. enumerable: true,
  53514. configurable: true
  53515. });
  53516. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53517. /**
  53518. * On every frame
  53519. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53520. */
  53521. get: function () {
  53522. return ActionManager._OnEveryFrameTrigger;
  53523. },
  53524. enumerable: true,
  53525. configurable: true
  53526. });
  53527. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53528. /**
  53529. * On intersection enter
  53530. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53531. */
  53532. get: function () {
  53533. return ActionManager._OnIntersectionEnterTrigger;
  53534. },
  53535. enumerable: true,
  53536. configurable: true
  53537. });
  53538. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53539. /**
  53540. * On intersection exit
  53541. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53542. */
  53543. get: function () {
  53544. return ActionManager._OnIntersectionExitTrigger;
  53545. },
  53546. enumerable: true,
  53547. configurable: true
  53548. });
  53549. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53550. /**
  53551. * On key down
  53552. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53553. */
  53554. get: function () {
  53555. return ActionManager._OnKeyDownTrigger;
  53556. },
  53557. enumerable: true,
  53558. configurable: true
  53559. });
  53560. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53561. /**
  53562. * On key up
  53563. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53564. */
  53565. get: function () {
  53566. return ActionManager._OnKeyUpTrigger;
  53567. },
  53568. enumerable: true,
  53569. configurable: true
  53570. });
  53571. // Methods
  53572. /**
  53573. * Releases all associated resources
  53574. */
  53575. ActionManager.prototype.dispose = function () {
  53576. var index = this._scene._actionManagers.indexOf(this);
  53577. for (var i = 0; i < this.actions.length; i++) {
  53578. var action = this.actions[i];
  53579. ActionManager.Triggers[action.trigger]--;
  53580. if (ActionManager.Triggers[action.trigger] === 0) {
  53581. delete ActionManager.Triggers[action.trigger];
  53582. }
  53583. }
  53584. if (index > -1) {
  53585. this._scene._actionManagers.splice(index, 1);
  53586. }
  53587. };
  53588. /**
  53589. * Gets hosting scene
  53590. * @returns the hosting scene
  53591. */
  53592. ActionManager.prototype.getScene = function () {
  53593. return this._scene;
  53594. };
  53595. /**
  53596. * Does this action manager handles actions of any of the given triggers
  53597. * @param triggers defines the triggers to be tested
  53598. * @return a boolean indicating whether one (or more) of the triggers is handled
  53599. */
  53600. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53601. for (var index = 0; index < this.actions.length; index++) {
  53602. var action = this.actions[index];
  53603. if (triggers.indexOf(action.trigger) > -1) {
  53604. return true;
  53605. }
  53606. }
  53607. return false;
  53608. };
  53609. /**
  53610. * Does this action manager handles actions of a given trigger
  53611. * @param trigger defines the trigger to be tested
  53612. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53613. * @return whether the trigger is handled
  53614. */
  53615. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53616. for (var index = 0; index < this.actions.length; index++) {
  53617. var action = this.actions[index];
  53618. if (action.trigger === trigger) {
  53619. if (parameterPredicate) {
  53620. if (parameterPredicate(action.getTriggerParameter())) {
  53621. return true;
  53622. }
  53623. }
  53624. else {
  53625. return true;
  53626. }
  53627. }
  53628. }
  53629. return false;
  53630. };
  53631. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53632. /**
  53633. * Does this action manager has pointer triggers
  53634. */
  53635. get: function () {
  53636. for (var index = 0; index < this.actions.length; index++) {
  53637. var action = this.actions[index];
  53638. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53639. return true;
  53640. }
  53641. }
  53642. return false;
  53643. },
  53644. enumerable: true,
  53645. configurable: true
  53646. });
  53647. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53648. /**
  53649. * Does this action manager has pick triggers
  53650. */
  53651. get: function () {
  53652. for (var index = 0; index < this.actions.length; index++) {
  53653. var action = this.actions[index];
  53654. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53655. return true;
  53656. }
  53657. }
  53658. return false;
  53659. },
  53660. enumerable: true,
  53661. configurable: true
  53662. });
  53663. Object.defineProperty(ActionManager, "HasTriggers", {
  53664. /**
  53665. * Does exist one action manager with at least one trigger
  53666. **/
  53667. get: function () {
  53668. for (var t in ActionManager.Triggers) {
  53669. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53670. return true;
  53671. }
  53672. }
  53673. return false;
  53674. },
  53675. enumerable: true,
  53676. configurable: true
  53677. });
  53678. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53679. /**
  53680. * Does exist one action manager with at least one pick trigger
  53681. **/
  53682. get: function () {
  53683. for (var t in ActionManager.Triggers) {
  53684. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53685. var t_int = parseInt(t);
  53686. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53687. return true;
  53688. }
  53689. }
  53690. }
  53691. return false;
  53692. },
  53693. enumerable: true,
  53694. configurable: true
  53695. });
  53696. /**
  53697. * Does exist one action manager that handles actions of a given trigger
  53698. * @param trigger defines the trigger to be tested
  53699. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53700. **/
  53701. ActionManager.HasSpecificTrigger = function (trigger) {
  53702. for (var t in ActionManager.Triggers) {
  53703. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53704. var t_int = parseInt(t);
  53705. if (t_int === trigger) {
  53706. return true;
  53707. }
  53708. }
  53709. }
  53710. return false;
  53711. };
  53712. /**
  53713. * Registers an action to this action manager
  53714. * @param action defines the action to be registered
  53715. * @return the action amended (prepared) after registration
  53716. */
  53717. ActionManager.prototype.registerAction = function (action) {
  53718. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53719. if (this.getScene().actionManager !== this) {
  53720. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53721. return null;
  53722. }
  53723. }
  53724. this.actions.push(action);
  53725. if (ActionManager.Triggers[action.trigger]) {
  53726. ActionManager.Triggers[action.trigger]++;
  53727. }
  53728. else {
  53729. ActionManager.Triggers[action.trigger] = 1;
  53730. }
  53731. action._actionManager = this;
  53732. action._prepare();
  53733. return action;
  53734. };
  53735. /**
  53736. * Unregisters an action to this action manager
  53737. * @param action defines the action to be unregistered
  53738. * @return a boolean indicating whether the action has been unregistered
  53739. */
  53740. ActionManager.prototype.unregisterAction = function (action) {
  53741. var index = this.actions.indexOf(action);
  53742. if (index !== -1) {
  53743. this.actions.splice(index, 1);
  53744. ActionManager.Triggers[action.trigger] -= 1;
  53745. if (ActionManager.Triggers[action.trigger] === 0) {
  53746. delete ActionManager.Triggers[action.trigger];
  53747. }
  53748. delete action._actionManager;
  53749. return true;
  53750. }
  53751. return false;
  53752. };
  53753. /**
  53754. * Process a specific trigger
  53755. * @param trigger defines the trigger to process
  53756. * @param evt defines the event details to be processed
  53757. */
  53758. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53759. for (var index = 0; index < this.actions.length; index++) {
  53760. var action = this.actions[index];
  53761. if (action.trigger === trigger) {
  53762. if (evt) {
  53763. if (trigger === ActionManager.OnKeyUpTrigger
  53764. || trigger === ActionManager.OnKeyDownTrigger) {
  53765. var parameter = action.getTriggerParameter();
  53766. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53767. if (!parameter.toLowerCase) {
  53768. continue;
  53769. }
  53770. var lowerCase = parameter.toLowerCase();
  53771. if (lowerCase !== evt.sourceEvent.key) {
  53772. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53773. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53774. if (actualkey !== lowerCase) {
  53775. continue;
  53776. }
  53777. }
  53778. }
  53779. }
  53780. }
  53781. action._executeCurrent(evt);
  53782. }
  53783. }
  53784. };
  53785. /** @hidden */
  53786. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53787. var properties = propertyPath.split(".");
  53788. for (var index = 0; index < properties.length - 1; index++) {
  53789. target = target[properties[index]];
  53790. }
  53791. return target;
  53792. };
  53793. /** @hidden */
  53794. ActionManager.prototype._getProperty = function (propertyPath) {
  53795. var properties = propertyPath.split(".");
  53796. return properties[properties.length - 1];
  53797. };
  53798. /**
  53799. * Serialize this manager to a JSON object
  53800. * @param name defines the property name to store this manager
  53801. * @returns a JSON representation of this manager
  53802. */
  53803. ActionManager.prototype.serialize = function (name) {
  53804. var root = {
  53805. children: new Array(),
  53806. name: name,
  53807. type: 3,
  53808. properties: new Array() // Empty for root but required
  53809. };
  53810. for (var i = 0; i < this.actions.length; i++) {
  53811. var triggerObject = {
  53812. type: 0,
  53813. children: new Array(),
  53814. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53815. properties: new Array()
  53816. };
  53817. var triggerOptions = this.actions[i].triggerOptions;
  53818. if (triggerOptions && typeof triggerOptions !== "number") {
  53819. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53820. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53821. }
  53822. else {
  53823. var parameter = {};
  53824. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53825. if (triggerOptions.parameter.mesh) {
  53826. parameter._meshId = triggerOptions.parameter.mesh.id;
  53827. }
  53828. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53829. }
  53830. }
  53831. // Serialize child action, recursively
  53832. this.actions[i].serialize(triggerObject);
  53833. // Add serialized trigger
  53834. root.children.push(triggerObject);
  53835. }
  53836. return root;
  53837. };
  53838. /**
  53839. * Creates a new ActionManager from a JSON data
  53840. * @param parsedActions defines the JSON data to read from
  53841. * @param object defines the hosting mesh
  53842. * @param scene defines the hosting scene
  53843. */
  53844. ActionManager.Parse = function (parsedActions, object, scene) {
  53845. var actionManager = new ActionManager(scene);
  53846. if (object === null)
  53847. scene.actionManager = actionManager;
  53848. else
  53849. object.actionManager = actionManager;
  53850. // instanciate a new object
  53851. var instanciate = function (name, params) {
  53852. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53853. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53854. newInstance.constructor.apply(newInstance, params);
  53855. return newInstance;
  53856. };
  53857. var parseParameter = function (name, value, target, propertyPath) {
  53858. if (propertyPath === null) {
  53859. // String, boolean or float
  53860. var floatValue = parseFloat(value);
  53861. if (value === "true" || value === "false")
  53862. return value === "true";
  53863. else
  53864. return isNaN(floatValue) ? value : floatValue;
  53865. }
  53866. var effectiveTarget = propertyPath.split(".");
  53867. var values = value.split(",");
  53868. // Get effective Target
  53869. for (var i = 0; i < effectiveTarget.length; i++) {
  53870. target = target[effectiveTarget[i]];
  53871. }
  53872. // Return appropriate value with its type
  53873. if (typeof (target) === "boolean")
  53874. return values[0] === "true";
  53875. if (typeof (target) === "string")
  53876. return values[0];
  53877. // Parameters with multiple values such as Vector3 etc.
  53878. var split = new Array();
  53879. for (var i = 0; i < values.length; i++)
  53880. split.push(parseFloat(values[i]));
  53881. if (target instanceof BABYLON.Vector3)
  53882. return BABYLON.Vector3.FromArray(split);
  53883. if (target instanceof BABYLON.Vector4)
  53884. return BABYLON.Vector4.FromArray(split);
  53885. if (target instanceof BABYLON.Color3)
  53886. return BABYLON.Color3.FromArray(split);
  53887. if (target instanceof BABYLON.Color4)
  53888. return BABYLON.Color4.FromArray(split);
  53889. return parseFloat(values[0]);
  53890. };
  53891. // traverse graph per trigger
  53892. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53893. if (combineArray === void 0) { combineArray = null; }
  53894. if (parsedAction.detached)
  53895. return;
  53896. var parameters = new Array();
  53897. var target = null;
  53898. var propertyPath = null;
  53899. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53900. // Parameters
  53901. if (parsedAction.type === 2)
  53902. parameters.push(actionManager);
  53903. else
  53904. parameters.push(trigger);
  53905. if (combine) {
  53906. var actions = new Array();
  53907. for (var j = 0; j < parsedAction.combine.length; j++) {
  53908. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53909. }
  53910. parameters.push(actions);
  53911. }
  53912. else {
  53913. for (var i = 0; i < parsedAction.properties.length; i++) {
  53914. var value = parsedAction.properties[i].value;
  53915. var name = parsedAction.properties[i].name;
  53916. var targetType = parsedAction.properties[i].targetType;
  53917. if (name === "target")
  53918. if (targetType !== null && targetType === "SceneProperties")
  53919. value = target = scene;
  53920. else
  53921. value = target = scene.getNodeByName(value);
  53922. else if (name === "parent")
  53923. value = scene.getNodeByName(value);
  53924. else if (name === "sound")
  53925. value = scene.getSoundByName(value);
  53926. else if (name !== "propertyPath") {
  53927. if (parsedAction.type === 2 && name === "operator")
  53928. value = BABYLON.ValueCondition[value];
  53929. else
  53930. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53931. }
  53932. else {
  53933. propertyPath = value;
  53934. }
  53935. parameters.push(value);
  53936. }
  53937. }
  53938. if (combineArray === null) {
  53939. parameters.push(condition);
  53940. }
  53941. else {
  53942. parameters.push(null);
  53943. }
  53944. // If interpolate value action
  53945. if (parsedAction.name === "InterpolateValueAction") {
  53946. var param = parameters[parameters.length - 2];
  53947. parameters[parameters.length - 1] = param;
  53948. parameters[parameters.length - 2] = condition;
  53949. }
  53950. // Action or condition(s) and not CombineAction
  53951. var newAction = instanciate(parsedAction.name, parameters);
  53952. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53953. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53954. if (action)
  53955. action.then(nothing);
  53956. else
  53957. actionManager.registerAction(nothing);
  53958. action = nothing;
  53959. }
  53960. if (combineArray === null) {
  53961. if (newAction instanceof BABYLON.Condition) {
  53962. condition = newAction;
  53963. newAction = action;
  53964. }
  53965. else {
  53966. condition = null;
  53967. if (action)
  53968. action.then(newAction);
  53969. else
  53970. actionManager.registerAction(newAction);
  53971. }
  53972. }
  53973. else {
  53974. combineArray.push(newAction);
  53975. }
  53976. for (var i = 0; i < parsedAction.children.length; i++)
  53977. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53978. };
  53979. // triggers
  53980. for (var i = 0; i < parsedActions.children.length; i++) {
  53981. var triggerParams;
  53982. var trigger = parsedActions.children[i];
  53983. if (trigger.properties.length > 0) {
  53984. var param = trigger.properties[0].value;
  53985. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53986. if (value._meshId) {
  53987. value.mesh = scene.getMeshByID(value._meshId);
  53988. }
  53989. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53990. }
  53991. else
  53992. triggerParams = ActionManager[trigger.name];
  53993. for (var j = 0; j < trigger.children.length; j++) {
  53994. if (!trigger.detached)
  53995. traverse(trigger.children[j], triggerParams, null, null);
  53996. }
  53997. }
  53998. };
  53999. /**
  54000. * Get a trigger name by index
  54001. * @param trigger defines the trigger index
  54002. * @returns a trigger name
  54003. */
  54004. ActionManager.GetTriggerName = function (trigger) {
  54005. switch (trigger) {
  54006. case 0: return "NothingTrigger";
  54007. case 1: return "OnPickTrigger";
  54008. case 2: return "OnLeftPickTrigger";
  54009. case 3: return "OnRightPickTrigger";
  54010. case 4: return "OnCenterPickTrigger";
  54011. case 5: return "OnPickDownTrigger";
  54012. case 6: return "OnPickUpTrigger";
  54013. case 7: return "OnLongPressTrigger";
  54014. case 8: return "OnPointerOverTrigger";
  54015. case 9: return "OnPointerOutTrigger";
  54016. case 10: return "OnEveryFrameTrigger";
  54017. case 11: return "OnIntersectionEnterTrigger";
  54018. case 12: return "OnIntersectionExitTrigger";
  54019. case 13: return "OnKeyDownTrigger";
  54020. case 14: return "OnKeyUpTrigger";
  54021. case 15: return "OnPickOutTrigger";
  54022. default: return "";
  54023. }
  54024. };
  54025. // Statics
  54026. ActionManager._NothingTrigger = 0;
  54027. ActionManager._OnPickTrigger = 1;
  54028. ActionManager._OnLeftPickTrigger = 2;
  54029. ActionManager._OnRightPickTrigger = 3;
  54030. ActionManager._OnCenterPickTrigger = 4;
  54031. ActionManager._OnPickDownTrigger = 5;
  54032. ActionManager._OnDoublePickTrigger = 6;
  54033. ActionManager._OnPickUpTrigger = 7;
  54034. ActionManager._OnLongPressTrigger = 8;
  54035. ActionManager._OnPointerOverTrigger = 9;
  54036. ActionManager._OnPointerOutTrigger = 10;
  54037. ActionManager._OnEveryFrameTrigger = 11;
  54038. ActionManager._OnIntersectionEnterTrigger = 12;
  54039. ActionManager._OnIntersectionExitTrigger = 13;
  54040. ActionManager._OnKeyDownTrigger = 14;
  54041. ActionManager._OnKeyUpTrigger = 15;
  54042. ActionManager._OnPickOutTrigger = 16;
  54043. /** Gets the list of active triggers */
  54044. ActionManager.Triggers = {};
  54045. return ActionManager;
  54046. }());
  54047. BABYLON.ActionManager = ActionManager;
  54048. })(BABYLON || (BABYLON = {}));
  54049. //# sourceMappingURL=babylon.actionManager.js.map
  54050. var BABYLON;
  54051. (function (BABYLON) {
  54052. var InterpolateValueAction = /** @class */ (function (_super) {
  54053. __extends(InterpolateValueAction, _super);
  54054. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54055. if (duration === void 0) { duration = 1000; }
  54056. var _this = _super.call(this, triggerOptions, condition) || this;
  54057. _this.propertyPath = propertyPath;
  54058. _this.value = value;
  54059. _this.duration = duration;
  54060. _this.stopOtherAnimations = stopOtherAnimations;
  54061. _this.onInterpolationDone = onInterpolationDone;
  54062. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54063. _this._target = _this._effectiveTarget = target;
  54064. return _this;
  54065. }
  54066. InterpolateValueAction.prototype._prepare = function () {
  54067. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54068. this._property = this._getProperty(this.propertyPath);
  54069. };
  54070. InterpolateValueAction.prototype.execute = function () {
  54071. var _this = this;
  54072. var scene = this._actionManager.getScene();
  54073. var keys = [
  54074. {
  54075. frame: 0,
  54076. value: this._effectiveTarget[this._property]
  54077. }, {
  54078. frame: 100,
  54079. value: this.value
  54080. }
  54081. ];
  54082. var dataType;
  54083. if (typeof this.value === "number") {
  54084. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54085. }
  54086. else if (this.value instanceof BABYLON.Color3) {
  54087. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54088. }
  54089. else if (this.value instanceof BABYLON.Vector3) {
  54090. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54091. }
  54092. else if (this.value instanceof BABYLON.Matrix) {
  54093. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54094. }
  54095. else if (this.value instanceof BABYLON.Quaternion) {
  54096. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54097. }
  54098. else {
  54099. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54100. return;
  54101. }
  54102. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54103. animation.setKeys(keys);
  54104. if (this.stopOtherAnimations) {
  54105. scene.stopAnimation(this._effectiveTarget);
  54106. }
  54107. var wrapper = function () {
  54108. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54109. if (_this.onInterpolationDone) {
  54110. _this.onInterpolationDone();
  54111. }
  54112. };
  54113. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54114. };
  54115. InterpolateValueAction.prototype.serialize = function (parent) {
  54116. return _super.prototype._serialize.call(this, {
  54117. name: "InterpolateValueAction",
  54118. properties: [
  54119. BABYLON.Action._GetTargetProperty(this._target),
  54120. { name: "propertyPath", value: this.propertyPath },
  54121. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54122. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54123. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54124. ]
  54125. }, parent);
  54126. };
  54127. return InterpolateValueAction;
  54128. }(BABYLON.Action));
  54129. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54130. })(BABYLON || (BABYLON = {}));
  54131. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54132. var BABYLON;
  54133. (function (BABYLON) {
  54134. var SwitchBooleanAction = /** @class */ (function (_super) {
  54135. __extends(SwitchBooleanAction, _super);
  54136. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54137. var _this = _super.call(this, triggerOptions, condition) || this;
  54138. _this.propertyPath = propertyPath;
  54139. _this._target = _this._effectiveTarget = target;
  54140. return _this;
  54141. }
  54142. SwitchBooleanAction.prototype._prepare = function () {
  54143. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54144. this._property = this._getProperty(this.propertyPath);
  54145. };
  54146. SwitchBooleanAction.prototype.execute = function () {
  54147. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54148. };
  54149. SwitchBooleanAction.prototype.serialize = function (parent) {
  54150. return _super.prototype._serialize.call(this, {
  54151. name: "SwitchBooleanAction",
  54152. properties: [
  54153. BABYLON.Action._GetTargetProperty(this._target),
  54154. { name: "propertyPath", value: this.propertyPath }
  54155. ]
  54156. }, parent);
  54157. };
  54158. return SwitchBooleanAction;
  54159. }(BABYLON.Action));
  54160. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54161. var SetStateAction = /** @class */ (function (_super) {
  54162. __extends(SetStateAction, _super);
  54163. function SetStateAction(triggerOptions, target, value, condition) {
  54164. var _this = _super.call(this, triggerOptions, condition) || this;
  54165. _this.value = value;
  54166. _this._target = target;
  54167. return _this;
  54168. }
  54169. SetStateAction.prototype.execute = function () {
  54170. this._target.state = this.value;
  54171. };
  54172. SetStateAction.prototype.serialize = function (parent) {
  54173. return _super.prototype._serialize.call(this, {
  54174. name: "SetStateAction",
  54175. properties: [
  54176. BABYLON.Action._GetTargetProperty(this._target),
  54177. { name: "value", value: this.value }
  54178. ]
  54179. }, parent);
  54180. };
  54181. return SetStateAction;
  54182. }(BABYLON.Action));
  54183. BABYLON.SetStateAction = SetStateAction;
  54184. var SetValueAction = /** @class */ (function (_super) {
  54185. __extends(SetValueAction, _super);
  54186. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54187. var _this = _super.call(this, triggerOptions, condition) || this;
  54188. _this.propertyPath = propertyPath;
  54189. _this.value = value;
  54190. _this._target = _this._effectiveTarget = target;
  54191. return _this;
  54192. }
  54193. SetValueAction.prototype._prepare = function () {
  54194. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54195. this._property = this._getProperty(this.propertyPath);
  54196. };
  54197. SetValueAction.prototype.execute = function () {
  54198. this._effectiveTarget[this._property] = this.value;
  54199. if (this._target.markAsDirty) {
  54200. this._target.markAsDirty(this._property);
  54201. }
  54202. };
  54203. SetValueAction.prototype.serialize = function (parent) {
  54204. return _super.prototype._serialize.call(this, {
  54205. name: "SetValueAction",
  54206. properties: [
  54207. BABYLON.Action._GetTargetProperty(this._target),
  54208. { name: "propertyPath", value: this.propertyPath },
  54209. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54210. ]
  54211. }, parent);
  54212. };
  54213. return SetValueAction;
  54214. }(BABYLON.Action));
  54215. BABYLON.SetValueAction = SetValueAction;
  54216. var IncrementValueAction = /** @class */ (function (_super) {
  54217. __extends(IncrementValueAction, _super);
  54218. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54219. var _this = _super.call(this, triggerOptions, condition) || this;
  54220. _this.propertyPath = propertyPath;
  54221. _this.value = value;
  54222. _this._target = _this._effectiveTarget = target;
  54223. return _this;
  54224. }
  54225. IncrementValueAction.prototype._prepare = function () {
  54226. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54227. this._property = this._getProperty(this.propertyPath);
  54228. if (typeof this._effectiveTarget[this._property] !== "number") {
  54229. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54230. }
  54231. };
  54232. IncrementValueAction.prototype.execute = function () {
  54233. this._effectiveTarget[this._property] += this.value;
  54234. if (this._target.markAsDirty) {
  54235. this._target.markAsDirty(this._property);
  54236. }
  54237. };
  54238. IncrementValueAction.prototype.serialize = function (parent) {
  54239. return _super.prototype._serialize.call(this, {
  54240. name: "IncrementValueAction",
  54241. properties: [
  54242. BABYLON.Action._GetTargetProperty(this._target),
  54243. { name: "propertyPath", value: this.propertyPath },
  54244. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54245. ]
  54246. }, parent);
  54247. };
  54248. return IncrementValueAction;
  54249. }(BABYLON.Action));
  54250. BABYLON.IncrementValueAction = IncrementValueAction;
  54251. var PlayAnimationAction = /** @class */ (function (_super) {
  54252. __extends(PlayAnimationAction, _super);
  54253. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54254. var _this = _super.call(this, triggerOptions, condition) || this;
  54255. _this.from = from;
  54256. _this.to = to;
  54257. _this.loop = loop;
  54258. _this._target = target;
  54259. return _this;
  54260. }
  54261. PlayAnimationAction.prototype._prepare = function () {
  54262. };
  54263. PlayAnimationAction.prototype.execute = function () {
  54264. var scene = this._actionManager.getScene();
  54265. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54266. };
  54267. PlayAnimationAction.prototype.serialize = function (parent) {
  54268. return _super.prototype._serialize.call(this, {
  54269. name: "PlayAnimationAction",
  54270. properties: [
  54271. BABYLON.Action._GetTargetProperty(this._target),
  54272. { name: "from", value: String(this.from) },
  54273. { name: "to", value: String(this.to) },
  54274. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54275. ]
  54276. }, parent);
  54277. };
  54278. return PlayAnimationAction;
  54279. }(BABYLON.Action));
  54280. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54281. var StopAnimationAction = /** @class */ (function (_super) {
  54282. __extends(StopAnimationAction, _super);
  54283. function StopAnimationAction(triggerOptions, target, condition) {
  54284. var _this = _super.call(this, triggerOptions, condition) || this;
  54285. _this._target = target;
  54286. return _this;
  54287. }
  54288. StopAnimationAction.prototype._prepare = function () {
  54289. };
  54290. StopAnimationAction.prototype.execute = function () {
  54291. var scene = this._actionManager.getScene();
  54292. scene.stopAnimation(this._target);
  54293. };
  54294. StopAnimationAction.prototype.serialize = function (parent) {
  54295. return _super.prototype._serialize.call(this, {
  54296. name: "StopAnimationAction",
  54297. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54298. }, parent);
  54299. };
  54300. return StopAnimationAction;
  54301. }(BABYLON.Action));
  54302. BABYLON.StopAnimationAction = StopAnimationAction;
  54303. var DoNothingAction = /** @class */ (function (_super) {
  54304. __extends(DoNothingAction, _super);
  54305. function DoNothingAction(triggerOptions, condition) {
  54306. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54307. return _super.call(this, triggerOptions, condition) || this;
  54308. }
  54309. DoNothingAction.prototype.execute = function () {
  54310. };
  54311. DoNothingAction.prototype.serialize = function (parent) {
  54312. return _super.prototype._serialize.call(this, {
  54313. name: "DoNothingAction",
  54314. properties: []
  54315. }, parent);
  54316. };
  54317. return DoNothingAction;
  54318. }(BABYLON.Action));
  54319. BABYLON.DoNothingAction = DoNothingAction;
  54320. var CombineAction = /** @class */ (function (_super) {
  54321. __extends(CombineAction, _super);
  54322. function CombineAction(triggerOptions, children, condition) {
  54323. var _this = _super.call(this, triggerOptions, condition) || this;
  54324. _this.children = children;
  54325. return _this;
  54326. }
  54327. CombineAction.prototype._prepare = function () {
  54328. for (var index = 0; index < this.children.length; index++) {
  54329. this.children[index]._actionManager = this._actionManager;
  54330. this.children[index]._prepare();
  54331. }
  54332. };
  54333. CombineAction.prototype.execute = function (evt) {
  54334. for (var index = 0; index < this.children.length; index++) {
  54335. this.children[index].execute(evt);
  54336. }
  54337. };
  54338. CombineAction.prototype.serialize = function (parent) {
  54339. var serializationObject = _super.prototype._serialize.call(this, {
  54340. name: "CombineAction",
  54341. properties: [],
  54342. combine: []
  54343. }, parent);
  54344. for (var i = 0; i < this.children.length; i++) {
  54345. serializationObject.combine.push(this.children[i].serialize(null));
  54346. }
  54347. return serializationObject;
  54348. };
  54349. return CombineAction;
  54350. }(BABYLON.Action));
  54351. BABYLON.CombineAction = CombineAction;
  54352. var ExecuteCodeAction = /** @class */ (function (_super) {
  54353. __extends(ExecuteCodeAction, _super);
  54354. function ExecuteCodeAction(triggerOptions, func, condition) {
  54355. var _this = _super.call(this, triggerOptions, condition) || this;
  54356. _this.func = func;
  54357. return _this;
  54358. }
  54359. ExecuteCodeAction.prototype.execute = function (evt) {
  54360. this.func(evt);
  54361. };
  54362. return ExecuteCodeAction;
  54363. }(BABYLON.Action));
  54364. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54365. var SetParentAction = /** @class */ (function (_super) {
  54366. __extends(SetParentAction, _super);
  54367. function SetParentAction(triggerOptions, target, parent, condition) {
  54368. var _this = _super.call(this, triggerOptions, condition) || this;
  54369. _this._target = target;
  54370. _this._parent = parent;
  54371. return _this;
  54372. }
  54373. SetParentAction.prototype._prepare = function () {
  54374. };
  54375. SetParentAction.prototype.execute = function () {
  54376. if (this._target.parent === this._parent) {
  54377. return;
  54378. }
  54379. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54380. invertParentWorldMatrix.invert();
  54381. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54382. this._target.parent = this._parent;
  54383. };
  54384. SetParentAction.prototype.serialize = function (parent) {
  54385. return _super.prototype._serialize.call(this, {
  54386. name: "SetParentAction",
  54387. properties: [
  54388. BABYLON.Action._GetTargetProperty(this._target),
  54389. BABYLON.Action._GetTargetProperty(this._parent),
  54390. ]
  54391. }, parent);
  54392. };
  54393. return SetParentAction;
  54394. }(BABYLON.Action));
  54395. BABYLON.SetParentAction = SetParentAction;
  54396. var PlaySoundAction = /** @class */ (function (_super) {
  54397. __extends(PlaySoundAction, _super);
  54398. function PlaySoundAction(triggerOptions, sound, condition) {
  54399. var _this = _super.call(this, triggerOptions, condition) || this;
  54400. _this._sound = sound;
  54401. return _this;
  54402. }
  54403. PlaySoundAction.prototype._prepare = function () {
  54404. };
  54405. PlaySoundAction.prototype.execute = function () {
  54406. if (this._sound !== undefined)
  54407. this._sound.play();
  54408. };
  54409. PlaySoundAction.prototype.serialize = function (parent) {
  54410. return _super.prototype._serialize.call(this, {
  54411. name: "PlaySoundAction",
  54412. properties: [{ name: "sound", value: this._sound.name }]
  54413. }, parent);
  54414. };
  54415. return PlaySoundAction;
  54416. }(BABYLON.Action));
  54417. BABYLON.PlaySoundAction = PlaySoundAction;
  54418. var StopSoundAction = /** @class */ (function (_super) {
  54419. __extends(StopSoundAction, _super);
  54420. function StopSoundAction(triggerOptions, sound, condition) {
  54421. var _this = _super.call(this, triggerOptions, condition) || this;
  54422. _this._sound = sound;
  54423. return _this;
  54424. }
  54425. StopSoundAction.prototype._prepare = function () {
  54426. };
  54427. StopSoundAction.prototype.execute = function () {
  54428. if (this._sound !== undefined)
  54429. this._sound.stop();
  54430. };
  54431. StopSoundAction.prototype.serialize = function (parent) {
  54432. return _super.prototype._serialize.call(this, {
  54433. name: "StopSoundAction",
  54434. properties: [{ name: "sound", value: this._sound.name }]
  54435. }, parent);
  54436. };
  54437. return StopSoundAction;
  54438. }(BABYLON.Action));
  54439. BABYLON.StopSoundAction = StopSoundAction;
  54440. })(BABYLON || (BABYLON = {}));
  54441. //# sourceMappingURL=babylon.directActions.js.map
  54442. var BABYLON;
  54443. (function (BABYLON) {
  54444. var SpriteManager = /** @class */ (function () {
  54445. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54446. if (epsilon === void 0) { epsilon = 0.01; }
  54447. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54448. this.name = name;
  54449. this.sprites = new Array();
  54450. this.renderingGroupId = 0;
  54451. this.layerMask = 0x0FFFFFFF;
  54452. this.fogEnabled = true;
  54453. this.isPickable = false;
  54454. /**
  54455. * An event triggered when the manager is disposed.
  54456. */
  54457. this.onDisposeObservable = new BABYLON.Observable();
  54458. this._vertexBuffers = {};
  54459. this._capacity = capacity;
  54460. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54461. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54462. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54463. if (cellSize.width && cellSize.height) {
  54464. this.cellWidth = cellSize.width;
  54465. this.cellHeight = cellSize.height;
  54466. }
  54467. else if (cellSize !== undefined) {
  54468. this.cellWidth = cellSize;
  54469. this.cellHeight = cellSize;
  54470. }
  54471. else {
  54472. return;
  54473. }
  54474. this._epsilon = epsilon;
  54475. this._scene = scene;
  54476. this._scene.spriteManagers.push(this);
  54477. var indices = [];
  54478. var index = 0;
  54479. for (var count = 0; count < capacity; count++) {
  54480. indices.push(index);
  54481. indices.push(index + 1);
  54482. indices.push(index + 2);
  54483. indices.push(index);
  54484. indices.push(index + 2);
  54485. indices.push(index + 3);
  54486. index += 4;
  54487. }
  54488. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54489. // VBO
  54490. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54491. this._vertexData = new Float32Array(capacity * 16 * 4);
  54492. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54493. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54494. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54495. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54496. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54497. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54498. this._vertexBuffers["options"] = options;
  54499. this._vertexBuffers["cellInfo"] = cellInfo;
  54500. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54501. // Effects
  54502. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54503. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54504. }
  54505. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54506. set: function (callback) {
  54507. if (this._onDisposeObserver) {
  54508. this.onDisposeObservable.remove(this._onDisposeObserver);
  54509. }
  54510. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54511. },
  54512. enumerable: true,
  54513. configurable: true
  54514. });
  54515. Object.defineProperty(SpriteManager.prototype, "texture", {
  54516. get: function () {
  54517. return this._spriteTexture;
  54518. },
  54519. set: function (value) {
  54520. this._spriteTexture = value;
  54521. },
  54522. enumerable: true,
  54523. configurable: true
  54524. });
  54525. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54526. var arrayOffset = index * 16;
  54527. if (offsetX === 0)
  54528. offsetX = this._epsilon;
  54529. else if (offsetX === 1)
  54530. offsetX = 1 - this._epsilon;
  54531. if (offsetY === 0)
  54532. offsetY = this._epsilon;
  54533. else if (offsetY === 1)
  54534. offsetY = 1 - this._epsilon;
  54535. this._vertexData[arrayOffset] = sprite.position.x;
  54536. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54537. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54538. this._vertexData[arrayOffset + 3] = sprite.angle;
  54539. this._vertexData[arrayOffset + 4] = sprite.width;
  54540. this._vertexData[arrayOffset + 5] = sprite.height;
  54541. this._vertexData[arrayOffset + 6] = offsetX;
  54542. this._vertexData[arrayOffset + 7] = offsetY;
  54543. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54544. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54545. var offset = (sprite.cellIndex / rowSize) >> 0;
  54546. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54547. this._vertexData[arrayOffset + 11] = offset;
  54548. // Color
  54549. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54550. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54551. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54552. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54553. };
  54554. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54555. var count = Math.min(this._capacity, this.sprites.length);
  54556. var min = BABYLON.Vector3.Zero();
  54557. var max = BABYLON.Vector3.Zero();
  54558. var distance = Number.MAX_VALUE;
  54559. var currentSprite = null;
  54560. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54561. var cameraView = camera.getViewMatrix();
  54562. for (var index = 0; index < count; index++) {
  54563. var sprite = this.sprites[index];
  54564. if (!sprite) {
  54565. continue;
  54566. }
  54567. if (predicate) {
  54568. if (!predicate(sprite)) {
  54569. continue;
  54570. }
  54571. }
  54572. else if (!sprite.isPickable) {
  54573. continue;
  54574. }
  54575. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54576. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54577. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54578. if (ray.intersectsBoxMinMax(min, max)) {
  54579. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54580. if (distance > currentDistance) {
  54581. distance = currentDistance;
  54582. currentSprite = sprite;
  54583. if (fastCheck) {
  54584. break;
  54585. }
  54586. }
  54587. }
  54588. }
  54589. if (currentSprite) {
  54590. var result = new BABYLON.PickingInfo();
  54591. result.hit = true;
  54592. result.pickedSprite = currentSprite;
  54593. result.distance = distance;
  54594. return result;
  54595. }
  54596. return null;
  54597. };
  54598. SpriteManager.prototype.render = function () {
  54599. // Check
  54600. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54601. return;
  54602. var engine = this._scene.getEngine();
  54603. var baseSize = this._spriteTexture.getBaseSize();
  54604. // Sprites
  54605. var deltaTime = engine.getDeltaTime();
  54606. var max = Math.min(this._capacity, this.sprites.length);
  54607. var rowSize = baseSize.width / this.cellWidth;
  54608. var offset = 0;
  54609. for (var index = 0; index < max; index++) {
  54610. var sprite = this.sprites[index];
  54611. if (!sprite) {
  54612. continue;
  54613. }
  54614. sprite._animate(deltaTime);
  54615. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54616. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54617. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54618. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54619. }
  54620. this._buffer.update(this._vertexData);
  54621. // Render
  54622. var effect = this._effectBase;
  54623. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54624. effect = this._effectFog;
  54625. }
  54626. engine.enableEffect(effect);
  54627. var viewMatrix = this._scene.getViewMatrix();
  54628. effect.setTexture("diffuseSampler", this._spriteTexture);
  54629. effect.setMatrix("view", viewMatrix);
  54630. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54631. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54632. // Fog
  54633. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54634. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54635. effect.setColor3("vFogColor", this._scene.fogColor);
  54636. }
  54637. // VBOs
  54638. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54639. // Draw order
  54640. engine.setDepthFunctionToLessOrEqual();
  54641. effect.setBool("alphaTest", true);
  54642. engine.setColorWrite(false);
  54643. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54644. engine.setColorWrite(true);
  54645. effect.setBool("alphaTest", false);
  54646. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54647. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54648. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54649. };
  54650. SpriteManager.prototype.dispose = function () {
  54651. if (this._buffer) {
  54652. this._buffer.dispose();
  54653. this._buffer = null;
  54654. }
  54655. if (this._indexBuffer) {
  54656. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54657. this._indexBuffer = null;
  54658. }
  54659. if (this._spriteTexture) {
  54660. this._spriteTexture.dispose();
  54661. this._spriteTexture = null;
  54662. }
  54663. // Remove from scene
  54664. var index = this._scene.spriteManagers.indexOf(this);
  54665. this._scene.spriteManagers.splice(index, 1);
  54666. // Callback
  54667. this.onDisposeObservable.notifyObservers(this);
  54668. this.onDisposeObservable.clear();
  54669. };
  54670. return SpriteManager;
  54671. }());
  54672. BABYLON.SpriteManager = SpriteManager;
  54673. })(BABYLON || (BABYLON = {}));
  54674. //# sourceMappingURL=babylon.spriteManager.js.map
  54675. var BABYLON;
  54676. (function (BABYLON) {
  54677. var Sprite = /** @class */ (function () {
  54678. function Sprite(name, manager) {
  54679. this.name = name;
  54680. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54681. this.width = 1.0;
  54682. this.height = 1.0;
  54683. this.angle = 0;
  54684. this.cellIndex = 0;
  54685. this.invertU = 0;
  54686. this.invertV = 0;
  54687. this.animations = new Array();
  54688. this.isPickable = false;
  54689. this._animationStarted = false;
  54690. this._loopAnimation = false;
  54691. this._fromIndex = 0;
  54692. this._toIndex = 0;
  54693. this._delay = 0;
  54694. this._direction = 1;
  54695. this._time = 0;
  54696. this._manager = manager;
  54697. this._manager.sprites.push(this);
  54698. this.position = BABYLON.Vector3.Zero();
  54699. }
  54700. Object.defineProperty(Sprite.prototype, "size", {
  54701. get: function () {
  54702. return this.width;
  54703. },
  54704. set: function (value) {
  54705. this.width = value;
  54706. this.height = value;
  54707. },
  54708. enumerable: true,
  54709. configurable: true
  54710. });
  54711. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54712. this._fromIndex = from;
  54713. this._toIndex = to;
  54714. this._loopAnimation = loop;
  54715. this._delay = delay;
  54716. this._animationStarted = true;
  54717. this._direction = from < to ? 1 : -1;
  54718. this.cellIndex = from;
  54719. this._time = 0;
  54720. this._onAnimationEnd = onAnimationEnd;
  54721. };
  54722. Sprite.prototype.stopAnimation = function () {
  54723. this._animationStarted = false;
  54724. };
  54725. Sprite.prototype._animate = function (deltaTime) {
  54726. if (!this._animationStarted)
  54727. return;
  54728. this._time += deltaTime;
  54729. if (this._time > this._delay) {
  54730. this._time = this._time % this._delay;
  54731. this.cellIndex += this._direction;
  54732. if (this.cellIndex > this._toIndex) {
  54733. if (this._loopAnimation) {
  54734. this.cellIndex = this._fromIndex;
  54735. }
  54736. else {
  54737. this.cellIndex = this._toIndex;
  54738. this._animationStarted = false;
  54739. if (this._onAnimationEnd) {
  54740. this._onAnimationEnd();
  54741. }
  54742. if (this.disposeWhenFinishedAnimating) {
  54743. this.dispose();
  54744. }
  54745. }
  54746. }
  54747. }
  54748. };
  54749. Sprite.prototype.dispose = function () {
  54750. for (var i = 0; i < this._manager.sprites.length; i++) {
  54751. if (this._manager.sprites[i] == this) {
  54752. this._manager.sprites.splice(i, 1);
  54753. }
  54754. }
  54755. };
  54756. return Sprite;
  54757. }());
  54758. BABYLON.Sprite = Sprite;
  54759. })(BABYLON || (BABYLON = {}));
  54760. //# sourceMappingURL=babylon.sprite.js.map
  54761. var BABYLON;
  54762. (function (BABYLON) {
  54763. var IntersectionInfo = /** @class */ (function () {
  54764. function IntersectionInfo(bu, bv, distance) {
  54765. this.bu = bu;
  54766. this.bv = bv;
  54767. this.distance = distance;
  54768. this.faceId = 0;
  54769. this.subMeshId = 0;
  54770. }
  54771. return IntersectionInfo;
  54772. }());
  54773. BABYLON.IntersectionInfo = IntersectionInfo;
  54774. var PickingInfo = /** @class */ (function () {
  54775. function PickingInfo() {
  54776. this.hit = false;
  54777. this.distance = 0;
  54778. this.pickedPoint = null;
  54779. this.pickedMesh = null;
  54780. this.bu = 0;
  54781. this.bv = 0;
  54782. this.faceId = -1;
  54783. this.subMeshId = 0;
  54784. this.pickedSprite = null;
  54785. }
  54786. // Methods
  54787. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54788. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54789. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54790. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54791. return null;
  54792. }
  54793. var indices = this.pickedMesh.getIndices();
  54794. if (!indices) {
  54795. return null;
  54796. }
  54797. var result;
  54798. if (useVerticesNormals) {
  54799. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54800. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54801. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54802. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54803. normal0 = normal0.scale(this.bu);
  54804. normal1 = normal1.scale(this.bv);
  54805. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54806. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54807. }
  54808. else {
  54809. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54810. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54811. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54812. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54813. var p1p2 = vertex1.subtract(vertex2);
  54814. var p3p2 = vertex3.subtract(vertex2);
  54815. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54816. }
  54817. if (useWorldCoordinates) {
  54818. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54819. }
  54820. return BABYLON.Vector3.Normalize(result);
  54821. };
  54822. PickingInfo.prototype.getTextureCoordinates = function () {
  54823. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54824. return null;
  54825. }
  54826. var indices = this.pickedMesh.getIndices();
  54827. if (!indices) {
  54828. return null;
  54829. }
  54830. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54831. if (!uvs) {
  54832. return null;
  54833. }
  54834. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54835. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54836. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54837. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54838. uv1 = uv1.scale(this.bu);
  54839. uv2 = uv2.scale(this.bv);
  54840. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54841. };
  54842. return PickingInfo;
  54843. }());
  54844. BABYLON.PickingInfo = PickingInfo;
  54845. })(BABYLON || (BABYLON = {}));
  54846. //# sourceMappingURL=babylon.pickingInfo.js.map
  54847. var BABYLON;
  54848. (function (BABYLON) {
  54849. var Ray = /** @class */ (function () {
  54850. function Ray(origin, direction, length) {
  54851. if (length === void 0) { length = Number.MAX_VALUE; }
  54852. this.origin = origin;
  54853. this.direction = direction;
  54854. this.length = length;
  54855. }
  54856. // Methods
  54857. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54858. var d = 0.0;
  54859. var maxValue = Number.MAX_VALUE;
  54860. var inv;
  54861. var min;
  54862. var max;
  54863. var temp;
  54864. if (Math.abs(this.direction.x) < 0.0000001) {
  54865. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54866. return false;
  54867. }
  54868. }
  54869. else {
  54870. inv = 1.0 / this.direction.x;
  54871. min = (minimum.x - this.origin.x) * inv;
  54872. max = (maximum.x - this.origin.x) * inv;
  54873. if (max === -Infinity) {
  54874. max = Infinity;
  54875. }
  54876. if (min > max) {
  54877. temp = min;
  54878. min = max;
  54879. max = temp;
  54880. }
  54881. d = Math.max(min, d);
  54882. maxValue = Math.min(max, maxValue);
  54883. if (d > maxValue) {
  54884. return false;
  54885. }
  54886. }
  54887. if (Math.abs(this.direction.y) < 0.0000001) {
  54888. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54889. return false;
  54890. }
  54891. }
  54892. else {
  54893. inv = 1.0 / this.direction.y;
  54894. min = (minimum.y - this.origin.y) * inv;
  54895. max = (maximum.y - this.origin.y) * inv;
  54896. if (max === -Infinity) {
  54897. max = Infinity;
  54898. }
  54899. if (min > max) {
  54900. temp = min;
  54901. min = max;
  54902. max = temp;
  54903. }
  54904. d = Math.max(min, d);
  54905. maxValue = Math.min(max, maxValue);
  54906. if (d > maxValue) {
  54907. return false;
  54908. }
  54909. }
  54910. if (Math.abs(this.direction.z) < 0.0000001) {
  54911. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54912. return false;
  54913. }
  54914. }
  54915. else {
  54916. inv = 1.0 / this.direction.z;
  54917. min = (minimum.z - this.origin.z) * inv;
  54918. max = (maximum.z - this.origin.z) * inv;
  54919. if (max === -Infinity) {
  54920. max = Infinity;
  54921. }
  54922. if (min > max) {
  54923. temp = min;
  54924. min = max;
  54925. max = temp;
  54926. }
  54927. d = Math.max(min, d);
  54928. maxValue = Math.min(max, maxValue);
  54929. if (d > maxValue) {
  54930. return false;
  54931. }
  54932. }
  54933. return true;
  54934. };
  54935. Ray.prototype.intersectsBox = function (box) {
  54936. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54937. };
  54938. Ray.prototype.intersectsSphere = function (sphere) {
  54939. var x = sphere.center.x - this.origin.x;
  54940. var y = sphere.center.y - this.origin.y;
  54941. var z = sphere.center.z - this.origin.z;
  54942. var pyth = (x * x) + (y * y) + (z * z);
  54943. var rr = sphere.radius * sphere.radius;
  54944. if (pyth <= rr) {
  54945. return true;
  54946. }
  54947. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54948. if (dot < 0.0) {
  54949. return false;
  54950. }
  54951. var temp = pyth - (dot * dot);
  54952. return temp <= rr;
  54953. };
  54954. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54955. if (!this._edge1) {
  54956. this._edge1 = BABYLON.Vector3.Zero();
  54957. this._edge2 = BABYLON.Vector3.Zero();
  54958. this._pvec = BABYLON.Vector3.Zero();
  54959. this._tvec = BABYLON.Vector3.Zero();
  54960. this._qvec = BABYLON.Vector3.Zero();
  54961. }
  54962. vertex1.subtractToRef(vertex0, this._edge1);
  54963. vertex2.subtractToRef(vertex0, this._edge2);
  54964. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54965. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54966. if (det === 0) {
  54967. return null;
  54968. }
  54969. var invdet = 1 / det;
  54970. this.origin.subtractToRef(vertex0, this._tvec);
  54971. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54972. if (bu < 0 || bu > 1.0) {
  54973. return null;
  54974. }
  54975. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54976. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54977. if (bv < 0 || bu + bv > 1.0) {
  54978. return null;
  54979. }
  54980. //check if the distance is longer than the predefined length.
  54981. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54982. if (distance > this.length) {
  54983. return null;
  54984. }
  54985. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54986. };
  54987. Ray.prototype.intersectsPlane = function (plane) {
  54988. var distance;
  54989. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54990. if (Math.abs(result1) < 9.99999997475243E-07) {
  54991. return null;
  54992. }
  54993. else {
  54994. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54995. distance = (-plane.d - result2) / result1;
  54996. if (distance < 0.0) {
  54997. if (distance < -9.99999997475243E-07) {
  54998. return null;
  54999. }
  55000. else {
  55001. return 0;
  55002. }
  55003. }
  55004. return distance;
  55005. }
  55006. };
  55007. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55008. var tm = BABYLON.Tmp.Matrix[0];
  55009. mesh.getWorldMatrix().invertToRef(tm);
  55010. if (this._tmpRay) {
  55011. Ray.TransformToRef(this, tm, this._tmpRay);
  55012. }
  55013. else {
  55014. this._tmpRay = Ray.Transform(this, tm);
  55015. }
  55016. return mesh.intersects(this._tmpRay, fastCheck);
  55017. };
  55018. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55019. if (results) {
  55020. results.length = 0;
  55021. }
  55022. else {
  55023. results = [];
  55024. }
  55025. for (var i = 0; i < meshes.length; i++) {
  55026. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55027. if (pickInfo.hit) {
  55028. results.push(pickInfo);
  55029. }
  55030. }
  55031. results.sort(this._comparePickingInfo);
  55032. return results;
  55033. };
  55034. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55035. if (pickingInfoA.distance < pickingInfoB.distance) {
  55036. return -1;
  55037. }
  55038. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55039. return 1;
  55040. }
  55041. else {
  55042. return 0;
  55043. }
  55044. };
  55045. /**
  55046. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55047. * @param sega the first point of the segment to test the intersection against
  55048. * @param segb the second point of the segment to test the intersection against
  55049. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55050. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55051. */
  55052. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55053. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55054. var u = segb.subtract(sega);
  55055. var v = rsegb.subtract(this.origin);
  55056. var w = sega.subtract(this.origin);
  55057. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55058. var b = BABYLON.Vector3.Dot(u, v);
  55059. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55060. var d = BABYLON.Vector3.Dot(u, w);
  55061. var e = BABYLON.Vector3.Dot(v, w);
  55062. var D = a * c - b * b; // always >= 0
  55063. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55064. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55065. // compute the line parameters of the two closest points
  55066. if (D < Ray.smallnum) { // the lines are almost parallel
  55067. sN = 0.0; // force using point P0 on segment S1
  55068. sD = 1.0; // to prevent possible division by 0.0 later
  55069. tN = e;
  55070. tD = c;
  55071. }
  55072. else { // get the closest points on the infinite lines
  55073. sN = (b * e - c * d);
  55074. tN = (a * e - b * d);
  55075. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55076. sN = 0.0;
  55077. tN = e;
  55078. tD = c;
  55079. }
  55080. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55081. sN = sD;
  55082. tN = e + b;
  55083. tD = c;
  55084. }
  55085. }
  55086. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55087. tN = 0.0;
  55088. // recompute sc for this edge
  55089. if (-d < 0.0) {
  55090. sN = 0.0;
  55091. }
  55092. else if (-d > a)
  55093. sN = sD;
  55094. else {
  55095. sN = -d;
  55096. sD = a;
  55097. }
  55098. }
  55099. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55100. tN = tD;
  55101. // recompute sc for this edge
  55102. if ((-d + b) < 0.0) {
  55103. sN = 0;
  55104. }
  55105. else if ((-d + b) > a) {
  55106. sN = sD;
  55107. }
  55108. else {
  55109. sN = (-d + b);
  55110. sD = a;
  55111. }
  55112. }
  55113. // finally do the division to get sc and tc
  55114. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55115. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55116. // get the difference of the two closest points
  55117. var qtc = v.multiplyByFloats(tc, tc, tc);
  55118. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55119. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55120. if (isIntersected) {
  55121. return qtc.length();
  55122. }
  55123. return -1;
  55124. };
  55125. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55126. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55127. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55128. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55129. this.direction.normalize();
  55130. return this;
  55131. };
  55132. // Statics
  55133. Ray.Zero = function () {
  55134. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55135. };
  55136. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55137. var result = Ray.Zero();
  55138. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55139. };
  55140. /**
  55141. * 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
  55142. * transformed to the given world matrix.
  55143. * @param origin The origin point
  55144. * @param end The end point
  55145. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55146. */
  55147. Ray.CreateNewFromTo = function (origin, end, world) {
  55148. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55149. var direction = end.subtract(origin);
  55150. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55151. direction.normalize();
  55152. return Ray.Transform(new Ray(origin, direction, length), world);
  55153. };
  55154. Ray.Transform = function (ray, matrix) {
  55155. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55156. Ray.TransformToRef(ray, matrix, result);
  55157. return result;
  55158. };
  55159. Ray.TransformToRef = function (ray, matrix, result) {
  55160. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55161. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55162. result.length = ray.length;
  55163. var dir = result.direction;
  55164. var len = dir.length();
  55165. if (!(len === 0 || len === 1)) {
  55166. var num = 1.0 / len;
  55167. dir.x *= num;
  55168. dir.y *= num;
  55169. dir.z *= num;
  55170. result.length *= len;
  55171. }
  55172. };
  55173. Ray.smallnum = 0.00000001;
  55174. Ray.rayl = 10e8;
  55175. return Ray;
  55176. }());
  55177. BABYLON.Ray = Ray;
  55178. })(BABYLON || (BABYLON = {}));
  55179. //# sourceMappingURL=babylon.ray.js.map
  55180. var BABYLON;
  55181. (function (BABYLON) {
  55182. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55183. if (boxMin.x > sphereCenter.x + sphereRadius)
  55184. return false;
  55185. if (sphereCenter.x - sphereRadius > boxMax.x)
  55186. return false;
  55187. if (boxMin.y > sphereCenter.y + sphereRadius)
  55188. return false;
  55189. if (sphereCenter.y - sphereRadius > boxMax.y)
  55190. return false;
  55191. if (boxMin.z > sphereCenter.z + sphereRadius)
  55192. return false;
  55193. if (sphereCenter.z - sphereRadius > boxMax.z)
  55194. return false;
  55195. return true;
  55196. };
  55197. var getLowestRoot = (function () {
  55198. var result = { root: 0, found: false };
  55199. return function (a, b, c, maxR) {
  55200. result.root = 0;
  55201. result.found = false;
  55202. var determinant = b * b - 4.0 * a * c;
  55203. if (determinant < 0)
  55204. return result;
  55205. var sqrtD = Math.sqrt(determinant);
  55206. var r1 = (-b - sqrtD) / (2.0 * a);
  55207. var r2 = (-b + sqrtD) / (2.0 * a);
  55208. if (r1 > r2) {
  55209. var temp = r2;
  55210. r2 = r1;
  55211. r1 = temp;
  55212. }
  55213. if (r1 > 0 && r1 < maxR) {
  55214. result.root = r1;
  55215. result.found = true;
  55216. return result;
  55217. }
  55218. if (r2 > 0 && r2 < maxR) {
  55219. result.root = r2;
  55220. result.found = true;
  55221. return result;
  55222. }
  55223. return result;
  55224. };
  55225. })();
  55226. var Collider = /** @class */ (function () {
  55227. function Collider() {
  55228. this._collisionPoint = BABYLON.Vector3.Zero();
  55229. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55230. this._tempVector = BABYLON.Vector3.Zero();
  55231. this._tempVector2 = BABYLON.Vector3.Zero();
  55232. this._tempVector3 = BABYLON.Vector3.Zero();
  55233. this._tempVector4 = BABYLON.Vector3.Zero();
  55234. this._edge = BABYLON.Vector3.Zero();
  55235. this._baseToVertex = BABYLON.Vector3.Zero();
  55236. this._destinationPoint = BABYLON.Vector3.Zero();
  55237. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55238. this._displacementVector = BABYLON.Vector3.Zero();
  55239. this._radius = BABYLON.Vector3.One();
  55240. this._retry = 0;
  55241. this._basePointWorld = BABYLON.Vector3.Zero();
  55242. this._velocityWorld = BABYLON.Vector3.Zero();
  55243. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55244. this._collisionMask = -1;
  55245. }
  55246. Object.defineProperty(Collider.prototype, "collisionMask", {
  55247. get: function () {
  55248. return this._collisionMask;
  55249. },
  55250. set: function (mask) {
  55251. this._collisionMask = !isNaN(mask) ? mask : -1;
  55252. },
  55253. enumerable: true,
  55254. configurable: true
  55255. });
  55256. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55257. /**
  55258. * Gets the plane normal used to compute the sliding response (in local space)
  55259. */
  55260. get: function () {
  55261. return this._slidePlaneNormal;
  55262. },
  55263. enumerable: true,
  55264. configurable: true
  55265. });
  55266. // Methods
  55267. Collider.prototype._initialize = function (source, dir, e) {
  55268. this._velocity = dir;
  55269. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55270. this._basePoint = source;
  55271. source.multiplyToRef(this._radius, this._basePointWorld);
  55272. dir.multiplyToRef(this._radius, this._velocityWorld);
  55273. this._velocityWorldLength = this._velocityWorld.length();
  55274. this._epsilon = e;
  55275. this.collisionFound = false;
  55276. };
  55277. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55278. pa.subtractToRef(point, this._tempVector);
  55279. pb.subtractToRef(point, this._tempVector2);
  55280. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55281. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55282. if (d < 0)
  55283. return false;
  55284. pc.subtractToRef(point, this._tempVector3);
  55285. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55286. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55287. if (d < 0)
  55288. return false;
  55289. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55290. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55291. return d >= 0;
  55292. };
  55293. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55294. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55295. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55296. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55297. return false;
  55298. }
  55299. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55300. return false;
  55301. return true;
  55302. };
  55303. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55304. var t0;
  55305. var embeddedInPlane = false;
  55306. //defensive programming, actually not needed.
  55307. if (!trianglePlaneArray) {
  55308. trianglePlaneArray = [];
  55309. }
  55310. if (!trianglePlaneArray[faceIndex]) {
  55311. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55312. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55313. }
  55314. var trianglePlane = trianglePlaneArray[faceIndex];
  55315. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55316. return;
  55317. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55318. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55319. if (normalDotVelocity == 0) {
  55320. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55321. return;
  55322. embeddedInPlane = true;
  55323. t0 = 0;
  55324. }
  55325. else {
  55326. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55327. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55328. if (t0 > t1) {
  55329. var temp = t1;
  55330. t1 = t0;
  55331. t0 = temp;
  55332. }
  55333. if (t0 > 1.0 || t1 < 0.0)
  55334. return;
  55335. if (t0 < 0)
  55336. t0 = 0;
  55337. if (t0 > 1.0)
  55338. t0 = 1.0;
  55339. }
  55340. this._collisionPoint.copyFromFloats(0, 0, 0);
  55341. var found = false;
  55342. var t = 1.0;
  55343. if (!embeddedInPlane) {
  55344. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55345. this._velocity.scaleToRef(t0, this._tempVector);
  55346. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55347. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55348. found = true;
  55349. t = t0;
  55350. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55351. }
  55352. }
  55353. if (!found) {
  55354. var velocitySquaredLength = this._velocity.lengthSquared();
  55355. var a = velocitySquaredLength;
  55356. this._basePoint.subtractToRef(p1, this._tempVector);
  55357. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55358. var c = this._tempVector.lengthSquared() - 1.0;
  55359. var lowestRoot = getLowestRoot(a, b, c, t);
  55360. if (lowestRoot.found) {
  55361. t = lowestRoot.root;
  55362. found = true;
  55363. this._collisionPoint.copyFrom(p1);
  55364. }
  55365. this._basePoint.subtractToRef(p2, this._tempVector);
  55366. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55367. c = this._tempVector.lengthSquared() - 1.0;
  55368. lowestRoot = getLowestRoot(a, b, c, t);
  55369. if (lowestRoot.found) {
  55370. t = lowestRoot.root;
  55371. found = true;
  55372. this._collisionPoint.copyFrom(p2);
  55373. }
  55374. this._basePoint.subtractToRef(p3, this._tempVector);
  55375. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55376. c = this._tempVector.lengthSquared() - 1.0;
  55377. lowestRoot = getLowestRoot(a, b, c, t);
  55378. if (lowestRoot.found) {
  55379. t = lowestRoot.root;
  55380. found = true;
  55381. this._collisionPoint.copyFrom(p3);
  55382. }
  55383. p2.subtractToRef(p1, this._edge);
  55384. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55385. var edgeSquaredLength = this._edge.lengthSquared();
  55386. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55387. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55388. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55389. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55390. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55391. lowestRoot = getLowestRoot(a, b, c, t);
  55392. if (lowestRoot.found) {
  55393. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55394. if (f >= 0.0 && f <= 1.0) {
  55395. t = lowestRoot.root;
  55396. found = true;
  55397. this._edge.scaleInPlace(f);
  55398. p1.addToRef(this._edge, this._collisionPoint);
  55399. }
  55400. }
  55401. p3.subtractToRef(p2, this._edge);
  55402. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55403. edgeSquaredLength = this._edge.lengthSquared();
  55404. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55405. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55406. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55407. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55408. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55409. lowestRoot = getLowestRoot(a, b, c, t);
  55410. if (lowestRoot.found) {
  55411. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55412. if (f >= 0.0 && f <= 1.0) {
  55413. t = lowestRoot.root;
  55414. found = true;
  55415. this._edge.scaleInPlace(f);
  55416. p2.addToRef(this._edge, this._collisionPoint);
  55417. }
  55418. }
  55419. p1.subtractToRef(p3, this._edge);
  55420. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55421. edgeSquaredLength = this._edge.lengthSquared();
  55422. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55423. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55424. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55425. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55426. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55427. lowestRoot = getLowestRoot(a, b, c, t);
  55428. if (lowestRoot.found) {
  55429. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55430. if (f >= 0.0 && f <= 1.0) {
  55431. t = lowestRoot.root;
  55432. found = true;
  55433. this._edge.scaleInPlace(f);
  55434. p3.addToRef(this._edge, this._collisionPoint);
  55435. }
  55436. }
  55437. }
  55438. if (found) {
  55439. var distToCollision = t * this._velocity.length();
  55440. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55441. if (!this.intersectionPoint) {
  55442. this.intersectionPoint = this._collisionPoint.clone();
  55443. }
  55444. else {
  55445. this.intersectionPoint.copyFrom(this._collisionPoint);
  55446. }
  55447. this._nearestDistance = distToCollision;
  55448. this.collisionFound = true;
  55449. }
  55450. }
  55451. };
  55452. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55453. for (var i = indexStart; i < indexEnd; i += 3) {
  55454. var p1 = pts[indices[i] - decal];
  55455. var p2 = pts[indices[i + 1] - decal];
  55456. var p3 = pts[indices[i + 2] - decal];
  55457. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55458. }
  55459. };
  55460. Collider.prototype._getResponse = function (pos, vel) {
  55461. pos.addToRef(vel, this._destinationPoint);
  55462. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55463. this._basePoint.addToRef(vel, pos);
  55464. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55465. this._slidePlaneNormal.normalize();
  55466. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55467. pos.addInPlace(this._displacementVector);
  55468. this.intersectionPoint.addInPlace(this._displacementVector);
  55469. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55470. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55471. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55472. };
  55473. return Collider;
  55474. }());
  55475. BABYLON.Collider = Collider;
  55476. })(BABYLON || (BABYLON = {}));
  55477. //# sourceMappingURL=babylon.collider.js.map
  55478. var BABYLON;
  55479. (function (BABYLON) {
  55480. //WebWorker code will be inserted to this variable.
  55481. BABYLON.CollisionWorker = "";
  55482. /** Defines supported task for worker process */
  55483. var WorkerTaskType;
  55484. (function (WorkerTaskType) {
  55485. /** Initialization */
  55486. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55487. /** Update of geometry */
  55488. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55489. /** Evaluate collision */
  55490. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55491. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55492. /** Defines kind of replies returned by worker */
  55493. var WorkerReplyType;
  55494. (function (WorkerReplyType) {
  55495. /** Success */
  55496. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55497. /** Unkown error */
  55498. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55499. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55500. var CollisionCoordinatorWorker = /** @class */ (function () {
  55501. function CollisionCoordinatorWorker() {
  55502. var _this = this;
  55503. this._scaledPosition = BABYLON.Vector3.Zero();
  55504. this._scaledVelocity = BABYLON.Vector3.Zero();
  55505. this.onMeshUpdated = function (transformNode) {
  55506. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55507. };
  55508. this.onGeometryUpdated = function (geometry) {
  55509. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55510. };
  55511. this._afterRender = function () {
  55512. if (!_this._init)
  55513. return;
  55514. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55515. return;
  55516. }
  55517. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55518. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55519. if (_this._runningUpdated > 4) {
  55520. return;
  55521. }
  55522. ++_this._runningUpdated;
  55523. var payload = {
  55524. updatedMeshes: _this._addUpdateMeshesList,
  55525. updatedGeometries: _this._addUpdateGeometriesList,
  55526. removedGeometries: _this._toRemoveGeometryArray,
  55527. removedMeshes: _this._toRemoveMeshesArray
  55528. };
  55529. var message = {
  55530. payload: payload,
  55531. taskType: WorkerTaskType.UPDATE
  55532. };
  55533. var serializable = [];
  55534. for (var id in payload.updatedGeometries) {
  55535. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55536. //prepare transferables
  55537. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55538. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55539. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55540. }
  55541. }
  55542. _this._worker.postMessage(message, serializable);
  55543. _this._addUpdateMeshesList = {};
  55544. _this._addUpdateGeometriesList = {};
  55545. _this._toRemoveGeometryArray = [];
  55546. _this._toRemoveMeshesArray = [];
  55547. };
  55548. this._onMessageFromWorker = function (e) {
  55549. var returnData = e.data;
  55550. if (returnData.error != WorkerReplyType.SUCCESS) {
  55551. //TODO what errors can be returned from the worker?
  55552. BABYLON.Tools.Warn("error returned from worker!");
  55553. return;
  55554. }
  55555. switch (returnData.taskType) {
  55556. case WorkerTaskType.INIT:
  55557. _this._init = true;
  55558. //Update the worked with ALL of the scene's current state
  55559. _this._scene.meshes.forEach(function (mesh) {
  55560. _this.onMeshAdded(mesh);
  55561. });
  55562. _this._scene.getGeometries().forEach(function (geometry) {
  55563. _this.onGeometryAdded(geometry);
  55564. });
  55565. break;
  55566. case WorkerTaskType.UPDATE:
  55567. _this._runningUpdated--;
  55568. break;
  55569. case WorkerTaskType.COLLIDE:
  55570. var returnPayload = returnData.payload;
  55571. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55572. return;
  55573. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55574. if (callback) {
  55575. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55576. if (mesh) {
  55577. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55578. }
  55579. }
  55580. //cleanup
  55581. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55582. break;
  55583. }
  55584. };
  55585. this._collisionsCallbackArray = [];
  55586. this._init = false;
  55587. this._runningUpdated = 0;
  55588. this._addUpdateMeshesList = {};
  55589. this._addUpdateGeometriesList = {};
  55590. this._toRemoveGeometryArray = [];
  55591. this._toRemoveMeshesArray = [];
  55592. }
  55593. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55594. if (!this._init)
  55595. return;
  55596. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55597. return;
  55598. position.divideToRef(collider._radius, this._scaledPosition);
  55599. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55600. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55601. var payload = {
  55602. collider: {
  55603. position: this._scaledPosition.asArray(),
  55604. velocity: this._scaledVelocity.asArray(),
  55605. radius: collider._radius.asArray()
  55606. },
  55607. collisionId: collisionIndex,
  55608. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55609. maximumRetry: maximumRetry
  55610. };
  55611. var message = {
  55612. payload: payload,
  55613. taskType: WorkerTaskType.COLLIDE
  55614. };
  55615. this._worker.postMessage(message);
  55616. };
  55617. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55618. this._scene = scene;
  55619. this._scene.registerAfterRender(this._afterRender);
  55620. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55621. this._worker = new Worker(workerUrl);
  55622. this._worker.onmessage = this._onMessageFromWorker;
  55623. var message = {
  55624. payload: {},
  55625. taskType: WorkerTaskType.INIT
  55626. };
  55627. this._worker.postMessage(message);
  55628. };
  55629. CollisionCoordinatorWorker.prototype.destroy = function () {
  55630. this._scene.unregisterAfterRender(this._afterRender);
  55631. this._worker.terminate();
  55632. };
  55633. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55634. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55635. this.onMeshUpdated(mesh);
  55636. };
  55637. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55638. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55639. };
  55640. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55641. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55642. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55643. this.onGeometryUpdated(geometry);
  55644. };
  55645. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55646. this._toRemoveGeometryArray.push(geometry.id);
  55647. };
  55648. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55649. var submeshes = [];
  55650. if (mesh.subMeshes) {
  55651. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55652. var boundingInfo = sm.getBoundingInfo();
  55653. return {
  55654. position: idx,
  55655. verticesStart: sm.verticesStart,
  55656. verticesCount: sm.verticesCount,
  55657. indexStart: sm.indexStart,
  55658. indexCount: sm.indexCount,
  55659. hasMaterial: !!sm.getMaterial(),
  55660. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55661. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55662. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55663. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55664. };
  55665. });
  55666. }
  55667. var geometryId = null;
  55668. if (mesh instanceof BABYLON.Mesh) {
  55669. var geometry = mesh.geometry;
  55670. geometryId = geometry ? geometry.id : null;
  55671. }
  55672. else if (mesh instanceof BABYLON.InstancedMesh) {
  55673. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55674. geometryId = geometry ? geometry.id : null;
  55675. }
  55676. var boundingInfo = mesh.getBoundingInfo();
  55677. return {
  55678. uniqueId: mesh.uniqueId,
  55679. id: mesh.id,
  55680. name: mesh.name,
  55681. geometryId: geometryId,
  55682. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55683. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55684. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55685. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55686. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55687. subMeshes: submeshes,
  55688. checkCollisions: mesh.checkCollisions
  55689. };
  55690. };
  55691. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55692. return {
  55693. id: geometry.id,
  55694. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55695. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55696. indices: new Uint32Array(geometry.getIndices() || []),
  55697. };
  55698. };
  55699. return CollisionCoordinatorWorker;
  55700. }());
  55701. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55702. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55703. function CollisionCoordinatorLegacy() {
  55704. this._scaledPosition = BABYLON.Vector3.Zero();
  55705. this._scaledVelocity = BABYLON.Vector3.Zero();
  55706. this._finalPosition = BABYLON.Vector3.Zero();
  55707. }
  55708. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55709. position.divideToRef(collider._radius, this._scaledPosition);
  55710. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55711. collider.collidedMesh = null;
  55712. collider._retry = 0;
  55713. collider._initialVelocity = this._scaledVelocity;
  55714. collider._initialPosition = this._scaledPosition;
  55715. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55716. this._finalPosition.multiplyInPlace(collider._radius);
  55717. //run the callback
  55718. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55719. };
  55720. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55721. this._scene = scene;
  55722. };
  55723. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55724. //Legacy need no destruction method.
  55725. };
  55726. //No update in legacy mode
  55727. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55728. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55729. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55730. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55731. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55732. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55733. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55734. if (excludedMesh === void 0) { excludedMesh = null; }
  55735. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55736. if (collider._retry >= maximumRetry) {
  55737. finalPosition.copyFrom(position);
  55738. return;
  55739. }
  55740. // Check if this is a mesh else camera or -1
  55741. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55742. collider._initialize(position, velocity, closeDistance);
  55743. // Check all meshes
  55744. for (var index = 0; index < this._scene.meshes.length; index++) {
  55745. var mesh = this._scene.meshes[index];
  55746. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55747. mesh._checkCollision(collider);
  55748. }
  55749. }
  55750. if (!collider.collisionFound) {
  55751. position.addToRef(velocity, finalPosition);
  55752. return;
  55753. }
  55754. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55755. collider._getResponse(position, velocity);
  55756. }
  55757. if (velocity.length() <= closeDistance) {
  55758. finalPosition.copyFrom(position);
  55759. return;
  55760. }
  55761. collider._retry++;
  55762. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55763. };
  55764. return CollisionCoordinatorLegacy;
  55765. }());
  55766. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55767. })(BABYLON || (BABYLON = {}));
  55768. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55769. var BABYLON;
  55770. (function (BABYLON) {
  55771. /**
  55772. * A particle represents one of the element emitted by a particle system.
  55773. * This is mainly define by its coordinates, direction, velocity and age.
  55774. */
  55775. var Particle = /** @class */ (function () {
  55776. /**
  55777. * Creates a new instance Particle
  55778. * @param particleSystem the particle system the particle belongs to
  55779. */
  55780. function Particle(
  55781. /**
  55782. * particleSystem the particle system the particle belongs to.
  55783. */
  55784. particleSystem) {
  55785. this.particleSystem = particleSystem;
  55786. /**
  55787. * The world position of the particle in the scene.
  55788. */
  55789. this.position = BABYLON.Vector3.Zero();
  55790. /**
  55791. * The world direction of the particle in the scene.
  55792. */
  55793. this.direction = BABYLON.Vector3.Zero();
  55794. /**
  55795. * The color of the particle.
  55796. */
  55797. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55798. /**
  55799. * The color change of the particle per step.
  55800. */
  55801. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55802. /**
  55803. * Defines how long will the life of the particle be.
  55804. */
  55805. this.lifeTime = 1.0;
  55806. /**
  55807. * The current age of the particle.
  55808. */
  55809. this.age = 0;
  55810. /**
  55811. * The current size of the particle.
  55812. */
  55813. this.size = 0;
  55814. /**
  55815. * The current angle of the particle.
  55816. */
  55817. this.angle = 0;
  55818. /**
  55819. * Defines how fast is the angle changing.
  55820. */
  55821. this.angularSpeed = 0;
  55822. /**
  55823. * Defines the cell index used by the particle to be rendered from a sprite.
  55824. */
  55825. this.cellIndex = 0;
  55826. this._currentFrameCounter = 0;
  55827. if (!this.particleSystem.isAnimationSheetEnabled) {
  55828. return;
  55829. }
  55830. this.updateCellInfoFromSystem();
  55831. }
  55832. Particle.prototype.updateCellInfoFromSystem = function () {
  55833. this.cellIndex = this.particleSystem.startSpriteCellID;
  55834. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55835. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55836. }
  55837. else {
  55838. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55839. }
  55840. };
  55841. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55842. // (ageOffset / scaledUpdateSpeed) / available cells
  55843. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55844. this._currentFrameCounter += scaledUpdateSpeed;
  55845. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55846. this._currentFrameCounter = 0;
  55847. this.cellIndex++;
  55848. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55849. this.cellIndex = this.particleSystem.endSpriteCellID;
  55850. }
  55851. }
  55852. };
  55853. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55854. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55855. this.cellIndex++;
  55856. this._currentFrameCounter = 0;
  55857. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55858. if (this.particleSystem.spriteCellLoop) {
  55859. this.cellIndex = this.particleSystem.startSpriteCellID;
  55860. }
  55861. else {
  55862. this.cellIndex = this.particleSystem.endSpriteCellID;
  55863. }
  55864. }
  55865. }
  55866. else {
  55867. this._currentFrameCounter++;
  55868. }
  55869. };
  55870. /**
  55871. * Copy the properties of particle to another one.
  55872. * @param other the particle to copy the information to.
  55873. */
  55874. Particle.prototype.copyTo = function (other) {
  55875. other.position.copyFrom(this.position);
  55876. other.direction.copyFrom(this.direction);
  55877. other.color.copyFrom(this.color);
  55878. other.colorStep.copyFrom(this.colorStep);
  55879. other.lifeTime = this.lifeTime;
  55880. other.age = this.age;
  55881. other.size = this.size;
  55882. other.angle = this.angle;
  55883. other.angularSpeed = this.angularSpeed;
  55884. other.particleSystem = this.particleSystem;
  55885. other.cellIndex = this.cellIndex;
  55886. };
  55887. return Particle;
  55888. }());
  55889. BABYLON.Particle = Particle;
  55890. })(BABYLON || (BABYLON = {}));
  55891. //# sourceMappingURL=babylon.particle.js.map
  55892. var BABYLON;
  55893. (function (BABYLON) {
  55894. /**
  55895. * This represents a particle system in Babylon.
  55896. * 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.
  55897. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55898. * @example https://doc.babylonjs.com/babylon101/particles
  55899. */
  55900. var ParticleSystem = /** @class */ (function () {
  55901. /**
  55902. * Instantiates a particle system.
  55903. * 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.
  55904. * @param name The name of the particle system
  55905. * @param capacity The max number of particles alive at the same time
  55906. * @param scene The scene the particle system belongs to
  55907. * @param customEffect a custom effect used to change the way particles are rendered by default
  55908. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55909. * @param epsilon Offset used to render the particles
  55910. */
  55911. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55912. if (customEffect === void 0) { customEffect = null; }
  55913. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55914. if (epsilon === void 0) { epsilon = 0.01; }
  55915. var _this = this;
  55916. /**
  55917. * List of animations used by the particle system.
  55918. */
  55919. this.animations = [];
  55920. /**
  55921. * The rendering group used by the Particle system to chose when to render.
  55922. */
  55923. this.renderingGroupId = 0;
  55924. /**
  55925. * The emitter represents the Mesh or position we are attaching the particle system to.
  55926. */
  55927. this.emitter = null;
  55928. /**
  55929. * The maximum number of particles to emit per frame
  55930. */
  55931. this.emitRate = 10;
  55932. /**
  55933. * If you want to launch only a few particles at once, that can be done, as well.
  55934. */
  55935. this.manualEmitCount = -1;
  55936. /**
  55937. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55938. */
  55939. this.updateSpeed = 0.01;
  55940. /**
  55941. * The amount of time the particle system is running (depends of the overall update speed).
  55942. */
  55943. this.targetStopDuration = 0;
  55944. /**
  55945. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55946. */
  55947. this.disposeOnStop = false;
  55948. /**
  55949. * Minimum power of emitting particles.
  55950. */
  55951. this.minEmitPower = 1;
  55952. /**
  55953. * Maximum power of emitting particles.
  55954. */
  55955. this.maxEmitPower = 1;
  55956. /**
  55957. * Minimum life time of emitting particles.
  55958. */
  55959. this.minLifeTime = 1;
  55960. /**
  55961. * Maximum life time of emitting particles.
  55962. */
  55963. this.maxLifeTime = 1;
  55964. /**
  55965. * Minimum Size of emitting particles.
  55966. */
  55967. this.minSize = 1;
  55968. /**
  55969. * Maximum Size of emitting particles.
  55970. */
  55971. this.maxSize = 1;
  55972. /**
  55973. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55974. */
  55975. this.minAngularSpeed = 0;
  55976. /**
  55977. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55978. */
  55979. this.maxAngularSpeed = 0;
  55980. /**
  55981. * The layer mask we are rendering the particles through.
  55982. */
  55983. this.layerMask = 0x0FFFFFFF;
  55984. /**
  55985. * This can help using your own shader to render the particle system.
  55986. * The according effect will be created
  55987. */
  55988. this.customShader = null;
  55989. /**
  55990. * By default particle system starts as soon as they are created. This prevents the
  55991. * automatic start to happen and let you decide when to start emitting particles.
  55992. */
  55993. this.preventAutoStart = false;
  55994. /**
  55995. * Callback triggered when the particle animation is ending.
  55996. */
  55997. this.onAnimationEnd = null;
  55998. /**
  55999. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56000. */
  56001. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  56002. /**
  56003. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56004. * to override the particles.
  56005. */
  56006. this.forceDepthWrite = false;
  56007. /**
  56008. * You can use gravity if you want to give an orientation to your particles.
  56009. */
  56010. this.gravity = BABYLON.Vector3.Zero();
  56011. /**
  56012. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56013. */
  56014. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56015. /**
  56016. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56017. */
  56018. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56019. /**
  56020. * Color the particle will have at the end of its lifetime.
  56021. */
  56022. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  56023. /**
  56024. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  56025. */
  56026. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56027. /**
  56028. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  56029. */
  56030. this.spriteCellLoop = true;
  56031. /**
  56032. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  56033. */
  56034. this.spriteCellChangeSpeed = 0;
  56035. /**
  56036. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  56037. */
  56038. this.startSpriteCellID = 0;
  56039. /**
  56040. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  56041. */
  56042. this.endSpriteCellID = 0;
  56043. /**
  56044. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  56045. */
  56046. this.spriteCellWidth = 0;
  56047. /**
  56048. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  56049. */
  56050. this.spriteCellHeight = 0;
  56051. /**
  56052. * An event triggered when the system is disposed.
  56053. */
  56054. this.onDisposeObservable = new BABYLON.Observable();
  56055. this._particles = new Array();
  56056. this._stockParticles = new Array();
  56057. this._newPartsExcess = 0;
  56058. this._vertexBuffers = {};
  56059. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56060. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56061. this._scaledDirection = BABYLON.Vector3.Zero();
  56062. this._scaledGravity = BABYLON.Vector3.Zero();
  56063. this._currentRenderId = -1;
  56064. this._started = false;
  56065. this._stopped = false;
  56066. this._actualFrame = 0;
  56067. this._vertexBufferSize = 11;
  56068. // start of sub system methods
  56069. /**
  56070. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56071. * Its lifetime will start back at 0.
  56072. */
  56073. this.recycleParticle = function (particle) {
  56074. var lastParticle = _this._particles.pop();
  56075. if (lastParticle !== particle) {
  56076. lastParticle.copyTo(particle);
  56077. }
  56078. _this._stockParticles.push(lastParticle);
  56079. };
  56080. this._createParticle = function () {
  56081. var particle;
  56082. if (_this._stockParticles.length !== 0) {
  56083. particle = _this._stockParticles.pop();
  56084. particle.age = 0;
  56085. particle.cellIndex = _this.startSpriteCellID;
  56086. }
  56087. else {
  56088. particle = new BABYLON.Particle(_this);
  56089. }
  56090. return particle;
  56091. };
  56092. this._emitFromParticle = function (particle) {
  56093. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56094. return;
  56095. }
  56096. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56097. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56098. subSystem._rootParticleSystem = _this;
  56099. _this.activeSubSystems.push(subSystem);
  56100. subSystem.start();
  56101. };
  56102. this._appendParticleVertexes = null;
  56103. this.id = name;
  56104. this.name = name;
  56105. this._capacity = capacity;
  56106. this._epsilon = epsilon;
  56107. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56108. if (isAnimationSheetEnabled) {
  56109. this._vertexBufferSize = 12;
  56110. }
  56111. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56112. this._customEffect = customEffect;
  56113. scene.particleSystems.push(this);
  56114. this._createIndexBuffer();
  56115. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  56116. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  56117. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  56118. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  56119. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  56120. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  56121. if (this._isAnimationSheetEnabled) {
  56122. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  56123. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56124. }
  56125. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56126. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56127. this._vertexBuffers["options"] = options;
  56128. // Default emitter type
  56129. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56130. this.updateFunction = function (particles) {
  56131. for (var index = 0; index < particles.length; index++) {
  56132. var particle = particles[index];
  56133. particle.age += _this._scaledUpdateSpeed;
  56134. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56135. _this._emitFromParticle(particle);
  56136. _this.recycleParticle(particle);
  56137. index--;
  56138. continue;
  56139. }
  56140. else {
  56141. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56142. particle.color.addInPlace(_this._scaledColorStep);
  56143. if (particle.color.a < 0)
  56144. particle.color.a = 0;
  56145. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56146. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  56147. particle.position.addInPlace(_this._scaledDirection);
  56148. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56149. particle.direction.addInPlace(_this._scaledGravity);
  56150. if (_this._isAnimationSheetEnabled) {
  56151. particle.updateCellIndex(_this._scaledUpdateSpeed);
  56152. }
  56153. }
  56154. }
  56155. };
  56156. }
  56157. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  56158. /**
  56159. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56160. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56161. */
  56162. get: function () {
  56163. if (this.particleEmitterType.direction1) {
  56164. return this.particleEmitterType.direction1;
  56165. }
  56166. return BABYLON.Vector3.Zero();
  56167. },
  56168. set: function (value) {
  56169. if (this.particleEmitterType.direction1) {
  56170. this.particleEmitterType.direction1 = value;
  56171. }
  56172. },
  56173. enumerable: true,
  56174. configurable: true
  56175. });
  56176. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  56177. /**
  56178. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56179. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56180. */
  56181. get: function () {
  56182. if (this.particleEmitterType.direction2) {
  56183. return this.particleEmitterType.direction2;
  56184. }
  56185. return BABYLON.Vector3.Zero();
  56186. },
  56187. set: function (value) {
  56188. if (this.particleEmitterType.direction2) {
  56189. this.particleEmitterType.direction2 = value;
  56190. }
  56191. },
  56192. enumerable: true,
  56193. configurable: true
  56194. });
  56195. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  56196. /**
  56197. * 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.
  56198. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56199. */
  56200. get: function () {
  56201. if (this.particleEmitterType.minEmitBox) {
  56202. return this.particleEmitterType.minEmitBox;
  56203. }
  56204. return BABYLON.Vector3.Zero();
  56205. },
  56206. set: function (value) {
  56207. if (this.particleEmitterType.minEmitBox) {
  56208. this.particleEmitterType.minEmitBox = value;
  56209. }
  56210. },
  56211. enumerable: true,
  56212. configurable: true
  56213. });
  56214. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  56215. /**
  56216. * 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.
  56217. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56218. */
  56219. get: function () {
  56220. if (this.particleEmitterType.maxEmitBox) {
  56221. return this.particleEmitterType.maxEmitBox;
  56222. }
  56223. return BABYLON.Vector3.Zero();
  56224. },
  56225. set: function (value) {
  56226. if (this.particleEmitterType.maxEmitBox) {
  56227. this.particleEmitterType.maxEmitBox = value;
  56228. }
  56229. },
  56230. enumerable: true,
  56231. configurable: true
  56232. });
  56233. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56234. /**
  56235. * Sets a callback that will be triggered when the system is disposed.
  56236. */
  56237. set: function (callback) {
  56238. if (this._onDisposeObserver) {
  56239. this.onDisposeObservable.remove(this._onDisposeObserver);
  56240. }
  56241. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56242. },
  56243. enumerable: true,
  56244. configurable: true
  56245. });
  56246. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  56247. /**
  56248. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  56249. */
  56250. get: function () {
  56251. return this._isAnimationSheetEnabled;
  56252. },
  56253. enumerable: true,
  56254. configurable: true
  56255. });
  56256. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56257. //end of Sub-emitter
  56258. /**
  56259. * Gets the current list of active particles
  56260. */
  56261. get: function () {
  56262. return this._particles;
  56263. },
  56264. enumerable: true,
  56265. configurable: true
  56266. });
  56267. /**
  56268. * Returns the string "ParticleSystem"
  56269. * @returns a string containing the class name
  56270. */
  56271. ParticleSystem.prototype.getClassName = function () {
  56272. return "ParticleSystem";
  56273. };
  56274. ParticleSystem.prototype._createIndexBuffer = function () {
  56275. var indices = [];
  56276. var index = 0;
  56277. for (var count = 0; count < this._capacity; count++) {
  56278. indices.push(index);
  56279. indices.push(index + 1);
  56280. indices.push(index + 2);
  56281. indices.push(index);
  56282. indices.push(index + 2);
  56283. indices.push(index + 3);
  56284. index += 4;
  56285. }
  56286. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56287. };
  56288. /**
  56289. * Gets the maximum number of particles active at the same time.
  56290. * @returns The max number of active particles.
  56291. */
  56292. ParticleSystem.prototype.getCapacity = function () {
  56293. return this._capacity;
  56294. };
  56295. /**
  56296. * Gets Wether there are still active particles in the system.
  56297. * @returns True if it is alive, otherwise false.
  56298. */
  56299. ParticleSystem.prototype.isAlive = function () {
  56300. return this._alive;
  56301. };
  56302. /**
  56303. * Gets Wether the system has been started.
  56304. * @returns True if it has been started, otherwise false.
  56305. */
  56306. ParticleSystem.prototype.isStarted = function () {
  56307. return this._started;
  56308. };
  56309. /**
  56310. * Starts the particle system and begins to emit.
  56311. */
  56312. ParticleSystem.prototype.start = function () {
  56313. this._started = true;
  56314. this._stopped = false;
  56315. this._actualFrame = 0;
  56316. if (this.subEmitters && this.subEmitters.length != 0) {
  56317. this.activeSubSystems = new Array();
  56318. }
  56319. };
  56320. /**
  56321. * Stops the particle system.
  56322. * @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.
  56323. */
  56324. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56325. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56326. this._stopped = true;
  56327. if (stopSubEmitters) {
  56328. this._stopSubEmitters();
  56329. }
  56330. };
  56331. // animation sheet
  56332. /**
  56333. * Remove all active particles
  56334. */
  56335. ParticleSystem.prototype.reset = function () {
  56336. this._stockParticles = [];
  56337. this._particles = [];
  56338. };
  56339. /**
  56340. * @hidden (for internal use only)
  56341. */
  56342. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56343. var offset = index * this._vertexBufferSize;
  56344. this._vertexData[offset] = particle.position.x;
  56345. this._vertexData[offset + 1] = particle.position.y;
  56346. this._vertexData[offset + 2] = particle.position.z;
  56347. this._vertexData[offset + 3] = particle.color.r;
  56348. this._vertexData[offset + 4] = particle.color.g;
  56349. this._vertexData[offset + 5] = particle.color.b;
  56350. this._vertexData[offset + 6] = particle.color.a;
  56351. this._vertexData[offset + 7] = particle.angle;
  56352. this._vertexData[offset + 8] = particle.size;
  56353. this._vertexData[offset + 9] = offsetX;
  56354. this._vertexData[offset + 10] = offsetY;
  56355. };
  56356. /**
  56357. * @hidden (for internal use only)
  56358. */
  56359. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56360. if (offsetX === 0)
  56361. offsetX = this._epsilon;
  56362. else if (offsetX === 1)
  56363. offsetX = 1 - this._epsilon;
  56364. if (offsetY === 0)
  56365. offsetY = this._epsilon;
  56366. else if (offsetY === 1)
  56367. offsetY = 1 - this._epsilon;
  56368. var offset = index * this._vertexBufferSize;
  56369. this._vertexData[offset] = particle.position.x;
  56370. this._vertexData[offset + 1] = particle.position.y;
  56371. this._vertexData[offset + 2] = particle.position.z;
  56372. this._vertexData[offset + 3] = particle.color.r;
  56373. this._vertexData[offset + 4] = particle.color.g;
  56374. this._vertexData[offset + 5] = particle.color.b;
  56375. this._vertexData[offset + 6] = particle.color.a;
  56376. this._vertexData[offset + 7] = particle.angle;
  56377. this._vertexData[offset + 8] = particle.size;
  56378. this._vertexData[offset + 9] = offsetX;
  56379. this._vertexData[offset + 10] = offsetY;
  56380. this._vertexData[offset + 11] = particle.cellIndex;
  56381. };
  56382. ParticleSystem.prototype._stopSubEmitters = function () {
  56383. if (!this.activeSubSystems) {
  56384. return;
  56385. }
  56386. this.activeSubSystems.forEach(function (subSystem) {
  56387. subSystem.stop(true);
  56388. });
  56389. this.activeSubSystems = new Array();
  56390. };
  56391. ParticleSystem.prototype._removeFromRoot = function () {
  56392. if (!this._rootParticleSystem) {
  56393. return;
  56394. }
  56395. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56396. if (index !== -1) {
  56397. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56398. }
  56399. };
  56400. // end of sub system methods
  56401. ParticleSystem.prototype._update = function (newParticles) {
  56402. // Update current
  56403. this._alive = this._particles.length > 0;
  56404. this.updateFunction(this._particles);
  56405. // Add new ones
  56406. var worldMatrix;
  56407. if (this.emitter.position) {
  56408. var emitterMesh = this.emitter;
  56409. worldMatrix = emitterMesh.getWorldMatrix();
  56410. }
  56411. else {
  56412. var emitterPosition = this.emitter;
  56413. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56414. }
  56415. var particle;
  56416. for (var index = 0; index < newParticles; index++) {
  56417. if (this._particles.length === this._capacity) {
  56418. break;
  56419. }
  56420. particle = this._createParticle();
  56421. this._particles.push(particle);
  56422. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56423. if (this.startPositionFunction) {
  56424. this.startPositionFunction(worldMatrix, particle.position, particle);
  56425. }
  56426. else {
  56427. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56428. }
  56429. if (this.startDirectionFunction) {
  56430. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56431. }
  56432. else {
  56433. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56434. }
  56435. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56436. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56437. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56438. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56439. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56440. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56441. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56442. }
  56443. };
  56444. ParticleSystem.prototype._getEffect = function () {
  56445. if (this._customEffect) {
  56446. return this._customEffect;
  56447. }
  56448. ;
  56449. var defines = [];
  56450. if (this._scene.clipPlane) {
  56451. defines.push("#define CLIPPLANE");
  56452. }
  56453. if (this._isAnimationSheetEnabled) {
  56454. defines.push("#define ANIMATESHEET");
  56455. }
  56456. // Effect
  56457. var join = defines.join("\n");
  56458. if (this._cachedDefines !== join) {
  56459. this._cachedDefines = join;
  56460. var attributesNamesOrOptions;
  56461. var effectCreationOption;
  56462. if (this._isAnimationSheetEnabled) {
  56463. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56464. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56465. }
  56466. else {
  56467. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56468. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56469. }
  56470. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56471. }
  56472. return this._effect;
  56473. };
  56474. /**
  56475. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56476. */
  56477. ParticleSystem.prototype.animate = function () {
  56478. if (!this._started)
  56479. return;
  56480. var effect = this._getEffect();
  56481. // Check
  56482. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56483. return;
  56484. if (this._currentRenderId === this._scene.getRenderId()) {
  56485. return;
  56486. }
  56487. this._currentRenderId = this._scene.getRenderId();
  56488. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56489. // determine the number of particles we need to create
  56490. var newParticles;
  56491. if (this.manualEmitCount > -1) {
  56492. newParticles = this.manualEmitCount;
  56493. this._newPartsExcess = 0;
  56494. this.manualEmitCount = 0;
  56495. }
  56496. else {
  56497. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56498. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56499. }
  56500. if (this._newPartsExcess > 1.0) {
  56501. newParticles += this._newPartsExcess >> 0;
  56502. this._newPartsExcess -= this._newPartsExcess >> 0;
  56503. }
  56504. this._alive = false;
  56505. if (!this._stopped) {
  56506. this._actualFrame += this._scaledUpdateSpeed;
  56507. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56508. this.stop();
  56509. }
  56510. else {
  56511. newParticles = 0;
  56512. }
  56513. this._update(newParticles);
  56514. // Stopped?
  56515. if (this._stopped) {
  56516. if (!this._alive) {
  56517. this._started = false;
  56518. if (this.onAnimationEnd) {
  56519. this.onAnimationEnd();
  56520. }
  56521. if (this.disposeOnStop) {
  56522. this._scene._toBeDisposed.push(this);
  56523. }
  56524. }
  56525. }
  56526. // Animation sheet
  56527. if (this._isAnimationSheetEnabled) {
  56528. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56529. }
  56530. else {
  56531. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56532. }
  56533. // Update VBO
  56534. var offset = 0;
  56535. for (var index = 0; index < this._particles.length; index++) {
  56536. var particle = this._particles[index];
  56537. this._appendParticleVertexes(offset, particle);
  56538. offset += 4;
  56539. }
  56540. if (this._vertexBuffer) {
  56541. this._vertexBuffer.update(this._vertexData);
  56542. }
  56543. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56544. this.stop();
  56545. }
  56546. };
  56547. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56548. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56549. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56550. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56551. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56552. };
  56553. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56554. this._appendParticleVertex(offset++, particle, 0, 0);
  56555. this._appendParticleVertex(offset++, particle, 1, 0);
  56556. this._appendParticleVertex(offset++, particle, 1, 1);
  56557. this._appendParticleVertex(offset++, particle, 0, 1);
  56558. };
  56559. /**
  56560. * Rebuilds the particle system.
  56561. */
  56562. ParticleSystem.prototype.rebuild = function () {
  56563. this._createIndexBuffer();
  56564. if (this._vertexBuffer) {
  56565. this._vertexBuffer._rebuild();
  56566. }
  56567. };
  56568. /**
  56569. * Is this system ready to be used/rendered
  56570. * @return true if the system is ready
  56571. */
  56572. ParticleSystem.prototype.isReady = function () {
  56573. var effect = this._getEffect();
  56574. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56575. return false;
  56576. }
  56577. return true;
  56578. };
  56579. /**
  56580. * Renders the particle system in its current state.
  56581. * @returns the current number of particles
  56582. */
  56583. ParticleSystem.prototype.render = function () {
  56584. var effect = this._getEffect();
  56585. // Check
  56586. if (!this.isReady() || !this._particles.length) {
  56587. return 0;
  56588. }
  56589. var engine = this._scene.getEngine();
  56590. // Render
  56591. engine.enableEffect(effect);
  56592. engine.setState(false);
  56593. var viewMatrix = this._scene.getViewMatrix();
  56594. effect.setTexture("diffuseSampler", this.particleTexture);
  56595. effect.setMatrix("view", viewMatrix);
  56596. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56597. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56598. var baseSize = this.particleTexture.getBaseSize();
  56599. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56600. }
  56601. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56602. if (this._scene.clipPlane) {
  56603. var clipPlane = this._scene.clipPlane;
  56604. var invView = viewMatrix.clone();
  56605. invView.invert();
  56606. effect.setMatrix("invView", invView);
  56607. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56608. }
  56609. // VBOs
  56610. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56611. // Draw order
  56612. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56613. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56614. }
  56615. else {
  56616. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56617. }
  56618. if (this.forceDepthWrite) {
  56619. engine.setDepthWrite(true);
  56620. }
  56621. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56622. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56623. return this._particles.length;
  56624. };
  56625. /**
  56626. * Disposes the particle system and free the associated resources
  56627. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56628. */
  56629. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56630. if (disposeTexture === void 0) { disposeTexture = true; }
  56631. if (this._vertexBuffer) {
  56632. this._vertexBuffer.dispose();
  56633. this._vertexBuffer = null;
  56634. }
  56635. if (this._indexBuffer) {
  56636. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56637. this._indexBuffer = null;
  56638. }
  56639. if (disposeTexture && this.particleTexture) {
  56640. this.particleTexture.dispose();
  56641. this.particleTexture = null;
  56642. }
  56643. this._removeFromRoot();
  56644. // Remove from scene
  56645. var index = this._scene.particleSystems.indexOf(this);
  56646. if (index > -1) {
  56647. this._scene.particleSystems.splice(index, 1);
  56648. }
  56649. // Callback
  56650. this.onDisposeObservable.notifyObservers(this);
  56651. this.onDisposeObservable.clear();
  56652. };
  56653. /**
  56654. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56655. * @param radius The radius of the sphere to emit from
  56656. * @returns the emitter
  56657. */
  56658. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56659. if (radius === void 0) { radius = 1; }
  56660. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56661. this.particleEmitterType = particleEmitter;
  56662. return particleEmitter;
  56663. };
  56664. /**
  56665. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56666. * @param radius The radius of the sphere to emit from
  56667. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56668. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56669. * @returns the emitter
  56670. */
  56671. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56672. if (radius === void 0) { radius = 1; }
  56673. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56674. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56675. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56676. this.particleEmitterType = particleEmitter;
  56677. return particleEmitter;
  56678. };
  56679. /**
  56680. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56681. * @param radius The radius of the cone to emit from
  56682. * @param angle The base angle of the cone
  56683. * @returns the emitter
  56684. */
  56685. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56686. if (radius === void 0) { radius = 1; }
  56687. if (angle === void 0) { angle = Math.PI / 4; }
  56688. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56689. this.particleEmitterType = particleEmitter;
  56690. return particleEmitter;
  56691. };
  56692. // 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.
  56693. /**
  56694. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56695. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56696. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56697. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56698. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56699. * @returns the emitter
  56700. */
  56701. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56702. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56703. this.particleEmitterType = particleEmitter;
  56704. this.direction1 = direction1;
  56705. this.direction2 = direction2;
  56706. this.minEmitBox = minEmitBox;
  56707. this.maxEmitBox = maxEmitBox;
  56708. return particleEmitter;
  56709. };
  56710. // Clone
  56711. /**
  56712. * Clones the particle system.
  56713. * @param name The name of the cloned object
  56714. * @param newEmitter The new emitter to use
  56715. * @returns the cloned particle system
  56716. */
  56717. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56718. var custom = null;
  56719. var program = null;
  56720. if (this.customShader != null) {
  56721. program = this.customShader;
  56722. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56723. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56724. }
  56725. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56726. result.customShader = program;
  56727. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56728. if (newEmitter === undefined) {
  56729. newEmitter = this.emitter;
  56730. }
  56731. result.emitter = newEmitter;
  56732. if (this.particleTexture) {
  56733. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56734. }
  56735. if (!this.preventAutoStart) {
  56736. result.start();
  56737. }
  56738. return result;
  56739. };
  56740. /**
  56741. * Serializes the particle system to a JSON object.
  56742. * @returns the JSON object
  56743. */
  56744. ParticleSystem.prototype.serialize = function () {
  56745. var serializationObject = {};
  56746. serializationObject.name = this.name;
  56747. serializationObject.id = this.id;
  56748. // Emitter
  56749. if (this.emitter.position) {
  56750. var emitterMesh = this.emitter;
  56751. serializationObject.emitterId = emitterMesh.id;
  56752. }
  56753. else {
  56754. var emitterPosition = this.emitter;
  56755. serializationObject.emitter = emitterPosition.asArray();
  56756. }
  56757. serializationObject.capacity = this.getCapacity();
  56758. if (this.particleTexture) {
  56759. serializationObject.textureName = this.particleTexture.name;
  56760. }
  56761. // Animations
  56762. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56763. // Particle system
  56764. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56765. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56766. serializationObject.minSize = this.minSize;
  56767. serializationObject.maxSize = this.maxSize;
  56768. serializationObject.minEmitPower = this.minEmitPower;
  56769. serializationObject.maxEmitPower = this.maxEmitPower;
  56770. serializationObject.minLifeTime = this.minLifeTime;
  56771. serializationObject.maxLifeTime = this.maxLifeTime;
  56772. serializationObject.emitRate = this.emitRate;
  56773. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56774. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56775. serializationObject.gravity = this.gravity.asArray();
  56776. serializationObject.direction1 = this.direction1.asArray();
  56777. serializationObject.direction2 = this.direction2.asArray();
  56778. serializationObject.color1 = this.color1.asArray();
  56779. serializationObject.color2 = this.color2.asArray();
  56780. serializationObject.colorDead = this.colorDead.asArray();
  56781. serializationObject.updateSpeed = this.updateSpeed;
  56782. serializationObject.targetStopDuration = this.targetStopDuration;
  56783. serializationObject.textureMask = this.textureMask.asArray();
  56784. serializationObject.blendMode = this.blendMode;
  56785. serializationObject.customShader = this.customShader;
  56786. serializationObject.preventAutoStart = this.preventAutoStart;
  56787. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56788. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56789. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56790. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56791. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56792. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56793. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56794. // Emitter
  56795. if (this.particleEmitterType) {
  56796. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56797. }
  56798. return serializationObject;
  56799. };
  56800. /**
  56801. * Parses a JSON object to create a particle system.
  56802. * @param parsedParticleSystem The JSON object to parse
  56803. * @param scene The scene to create the particle system in
  56804. * @param rootUrl The root url to use to load external dependencies like texture
  56805. * @returns the Parsed particle system
  56806. */
  56807. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56808. var name = parsedParticleSystem.name;
  56809. var custom = null;
  56810. var program = null;
  56811. if (parsedParticleSystem.customShader) {
  56812. program = parsedParticleSystem.customShader;
  56813. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56814. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56815. }
  56816. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56817. particleSystem.customShader = program;
  56818. if (parsedParticleSystem.id) {
  56819. particleSystem.id = parsedParticleSystem.id;
  56820. }
  56821. // Auto start
  56822. if (parsedParticleSystem.preventAutoStart) {
  56823. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56824. }
  56825. // Texture
  56826. if (parsedParticleSystem.textureName) {
  56827. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56828. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56829. }
  56830. // Emitter
  56831. if (parsedParticleSystem.emitterId) {
  56832. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56833. }
  56834. else {
  56835. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56836. }
  56837. // Animations
  56838. if (parsedParticleSystem.animations) {
  56839. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56840. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56841. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56842. }
  56843. }
  56844. if (parsedParticleSystem.autoAnimate) {
  56845. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56846. }
  56847. // Particle system
  56848. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56849. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56850. particleSystem.minSize = parsedParticleSystem.minSize;
  56851. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56852. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56853. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56854. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56855. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56856. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56857. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56858. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56859. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56860. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56861. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56862. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56863. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56864. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56865. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56866. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56867. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56868. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56869. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56870. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56871. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56872. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56873. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56874. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56875. if (!particleSystem.preventAutoStart) {
  56876. particleSystem.start();
  56877. }
  56878. return particleSystem;
  56879. };
  56880. /**
  56881. * Source color is added to the destination color without alpha affecting the result.
  56882. */
  56883. ParticleSystem.BLENDMODE_ONEONE = 0;
  56884. /**
  56885. * Blend current color and particle color using particle’s alpha.
  56886. */
  56887. ParticleSystem.BLENDMODE_STANDARD = 1;
  56888. return ParticleSystem;
  56889. }());
  56890. BABYLON.ParticleSystem = ParticleSystem;
  56891. })(BABYLON || (BABYLON = {}));
  56892. //# sourceMappingURL=babylon.particleSystem.js.map
  56893. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56894. var BABYLON;
  56895. (function (BABYLON) {
  56896. /**
  56897. * Particle emitter emitting particles from the inside of a box.
  56898. * It emits the particles randomly between 2 given directions.
  56899. */
  56900. var BoxParticleEmitter = /** @class */ (function () {
  56901. /**
  56902. * Creates a new instance BoxParticleEmitter
  56903. */
  56904. function BoxParticleEmitter() {
  56905. /**
  56906. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56907. */
  56908. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56909. /**
  56910. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56911. */
  56912. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56913. /**
  56914. * 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.
  56915. */
  56916. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56917. /**
  56918. * 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.
  56919. */
  56920. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56921. }
  56922. /**
  56923. * Called by the particle System when the direction is computed for the created particle.
  56924. * @param emitPower is the power of the particle (speed)
  56925. * @param worldMatrix is the world matrix of the particle system
  56926. * @param directionToUpdate is the direction vector to update with the result
  56927. * @param particle is the particle we are computed the direction for
  56928. */
  56929. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56930. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56931. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56932. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56933. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56934. };
  56935. /**
  56936. * Called by the particle System when the position is computed for the created particle.
  56937. * @param worldMatrix is the world matrix of the particle system
  56938. * @param positionToUpdate is the position vector to update with the result
  56939. * @param particle is the particle we are computed the position for
  56940. */
  56941. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56942. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56943. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56944. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56945. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56946. };
  56947. /**
  56948. * Clones the current emitter and returns a copy of it
  56949. * @returns the new emitter
  56950. */
  56951. BoxParticleEmitter.prototype.clone = function () {
  56952. var newOne = new BoxParticleEmitter();
  56953. BABYLON.Tools.DeepCopy(this, newOne);
  56954. return newOne;
  56955. };
  56956. /**
  56957. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56958. * @param effect defines the update shader
  56959. */
  56960. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56961. effect.setVector3("direction1", this.direction1);
  56962. effect.setVector3("direction2", this.direction2);
  56963. effect.setVector3("minEmitBox", this.minEmitBox);
  56964. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56965. };
  56966. /**
  56967. * Returns a string to use to update the GPU particles update shader
  56968. * @returns a string containng the defines string
  56969. */
  56970. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56971. return "#define BOXEMITTER";
  56972. };
  56973. /**
  56974. * Returns the string "BoxEmitter"
  56975. * @returns a string containing the class name
  56976. */
  56977. BoxParticleEmitter.prototype.getClassName = function () {
  56978. return "BoxEmitter";
  56979. };
  56980. /**
  56981. * Serializes the particle system to a JSON object.
  56982. * @returns the JSON object
  56983. */
  56984. BoxParticleEmitter.prototype.serialize = function () {
  56985. var serializationObject = {};
  56986. serializationObject.type = this.getClassName();
  56987. serializationObject.direction1 = this.direction1.asArray();
  56988. serializationObject.direction2 = this.direction2.asArray();
  56989. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56990. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56991. return serializationObject;
  56992. };
  56993. /**
  56994. * Parse properties from a JSON object
  56995. * @param serializationObject defines the JSON object
  56996. */
  56997. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56998. this.direction1.copyFrom(serializationObject.direction1);
  56999. this.direction2.copyFrom(serializationObject.direction2);
  57000. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  57001. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  57002. };
  57003. return BoxParticleEmitter;
  57004. }());
  57005. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57006. })(BABYLON || (BABYLON = {}));
  57007. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57008. var BABYLON;
  57009. (function (BABYLON) {
  57010. /**
  57011. * Particle emitter emitting particles from the inside of a cone.
  57012. * It emits the particles alongside the cone volume from the base to the particle.
  57013. * The emission direction might be randomized.
  57014. */
  57015. var ConeParticleEmitter = /** @class */ (function () {
  57016. /**
  57017. * Creates a new instance ConeParticleEmitter
  57018. * @param radius the radius of the emission cone (1 by default)
  57019. * @param angles the cone base angle (PI by default)
  57020. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57021. */
  57022. function ConeParticleEmitter(radius,
  57023. /**
  57024. * The radius of the emission cone.
  57025. */
  57026. angle,
  57027. /**
  57028. * The cone base angle.
  57029. */
  57030. directionRandomizer) {
  57031. if (radius === void 0) { radius = 1; }
  57032. if (angle === void 0) { angle = Math.PI; }
  57033. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57034. this.angle = angle;
  57035. this.directionRandomizer = directionRandomizer;
  57036. this.radius = radius;
  57037. }
  57038. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57039. /**
  57040. * Gets the radius of the emission cone.
  57041. */
  57042. get: function () {
  57043. return this._radius;
  57044. },
  57045. /**
  57046. * Sets the radius of the emission cone.
  57047. */
  57048. set: function (value) {
  57049. this._radius = value;
  57050. if (this.angle !== 0) {
  57051. this._height = value / Math.tan(this.angle / 2);
  57052. }
  57053. else {
  57054. this._height = 1;
  57055. }
  57056. },
  57057. enumerable: true,
  57058. configurable: true
  57059. });
  57060. /**
  57061. * Called by the particle System when the direction is computed for the created particle.
  57062. * @param emitPower is the power of the particle (speed)
  57063. * @param worldMatrix is the world matrix of the particle system
  57064. * @param directionToUpdate is the direction vector to update with the result
  57065. * @param particle is the particle we are computed the direction for
  57066. */
  57067. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57068. if (this.angle === 0) {
  57069. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  57070. }
  57071. else {
  57072. // measure the direction Vector from the emitter to the particle.
  57073. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57074. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57075. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57076. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57077. direction.x += randX;
  57078. direction.y += randY;
  57079. direction.z += randZ;
  57080. direction.normalize();
  57081. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57082. }
  57083. };
  57084. /**
  57085. * Called by the particle System when the position is computed for the created particle.
  57086. * @param worldMatrix is the world matrix of the particle system
  57087. * @param positionToUpdate is the position vector to update with the result
  57088. * @param particle is the particle we are computed the position for
  57089. */
  57090. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57091. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57092. var h = BABYLON.Scalar.RandomRange(0, 1);
  57093. // Better distribution in a cone at normal angles.
  57094. h = 1 - h * h;
  57095. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  57096. radius = radius * h;
  57097. var randX = radius * Math.sin(s);
  57098. var randZ = radius * Math.cos(s);
  57099. var randY = h * this._height;
  57100. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57101. };
  57102. /**
  57103. * Clones the current emitter and returns a copy of it
  57104. * @returns the new emitter
  57105. */
  57106. ConeParticleEmitter.prototype.clone = function () {
  57107. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  57108. BABYLON.Tools.DeepCopy(this, newOne);
  57109. return newOne;
  57110. };
  57111. /**
  57112. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57113. * @param effect defines the update shader
  57114. */
  57115. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57116. effect.setFloat("radius", this.radius);
  57117. effect.setFloat("coneAngle", this.angle);
  57118. effect.setFloat("height", this._height);
  57119. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57120. };
  57121. /**
  57122. * Returns a string to use to update the GPU particles update shader
  57123. * @returns a string containng the defines string
  57124. */
  57125. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57126. return "#define CONEEMITTER";
  57127. };
  57128. /**
  57129. * Returns the string "BoxEmitter"
  57130. * @returns a string containing the class name
  57131. */
  57132. ConeParticleEmitter.prototype.getClassName = function () {
  57133. return "ConeEmitter";
  57134. };
  57135. /**
  57136. * Serializes the particle system to a JSON object.
  57137. * @returns the JSON object
  57138. */
  57139. ConeParticleEmitter.prototype.serialize = function () {
  57140. var serializationObject = {};
  57141. serializationObject.type = this.getClassName();
  57142. serializationObject.radius = this.radius;
  57143. serializationObject.angle = this.angle;
  57144. serializationObject.directionRandomizer = this.directionRandomizer;
  57145. return serializationObject;
  57146. };
  57147. /**
  57148. * Parse properties from a JSON object
  57149. * @param serializationObject defines the JSON object
  57150. */
  57151. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57152. this.radius = serializationObject.radius;
  57153. this.angle = serializationObject.angle;
  57154. this.directionRandomizer = serializationObject.directionRandomizer;
  57155. };
  57156. return ConeParticleEmitter;
  57157. }());
  57158. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57159. })(BABYLON || (BABYLON = {}));
  57160. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57161. var BABYLON;
  57162. (function (BABYLON) {
  57163. /**
  57164. * Particle emitter emitting particles from the inside of a sphere.
  57165. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57166. */
  57167. var SphereParticleEmitter = /** @class */ (function () {
  57168. /**
  57169. * Creates a new instance SphereParticleEmitter
  57170. * @param radius the radius of the emission sphere (1 by default)
  57171. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57172. */
  57173. function SphereParticleEmitter(
  57174. /**
  57175. * The radius of the emission sphere.
  57176. */
  57177. radius,
  57178. /**
  57179. * How much to randomize the particle direction [0-1].
  57180. */
  57181. directionRandomizer) {
  57182. if (radius === void 0) { radius = 1; }
  57183. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57184. this.radius = radius;
  57185. this.directionRandomizer = directionRandomizer;
  57186. }
  57187. /**
  57188. * Called by the particle System when the direction is computed for the created particle.
  57189. * @param emitPower is the power of the particle (speed)
  57190. * @param worldMatrix is the world matrix of the particle system
  57191. * @param directionToUpdate is the direction vector to update with the result
  57192. * @param particle is the particle we are computed the direction for
  57193. */
  57194. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57195. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57196. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57197. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57198. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57199. direction.x += randX;
  57200. direction.y += randY;
  57201. direction.z += randZ;
  57202. direction.normalize();
  57203. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57204. };
  57205. /**
  57206. * Called by the particle System when the position is computed for the created particle.
  57207. * @param worldMatrix is the world matrix of the particle system
  57208. * @param positionToUpdate is the position vector to update with the result
  57209. * @param particle is the particle we are computed the position for
  57210. */
  57211. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57212. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57213. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  57214. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  57215. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57216. var randY = randRadius * Math.cos(theta);
  57217. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57218. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57219. };
  57220. /**
  57221. * Clones the current emitter and returns a copy of it
  57222. * @returns the new emitter
  57223. */
  57224. SphereParticleEmitter.prototype.clone = function () {
  57225. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57226. BABYLON.Tools.DeepCopy(this, newOne);
  57227. return newOne;
  57228. };
  57229. /**
  57230. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57231. * @param effect defines the update shader
  57232. */
  57233. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57234. effect.setFloat("radius", this.radius);
  57235. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57236. };
  57237. /**
  57238. * Returns a string to use to update the GPU particles update shader
  57239. * @returns a string containng the defines string
  57240. */
  57241. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57242. return "#define SPHEREEMITTER";
  57243. };
  57244. /**
  57245. * Returns the string "SphereParticleEmitter"
  57246. * @returns a string containing the class name
  57247. */
  57248. SphereParticleEmitter.prototype.getClassName = function () {
  57249. return "SphereParticleEmitter";
  57250. };
  57251. /**
  57252. * Serializes the particle system to a JSON object.
  57253. * @returns the JSON object
  57254. */
  57255. SphereParticleEmitter.prototype.serialize = function () {
  57256. var serializationObject = {};
  57257. serializationObject.type = this.getClassName();
  57258. serializationObject.radius = this.radius;
  57259. serializationObject.directionRandomizer = this.directionRandomizer;
  57260. return serializationObject;
  57261. };
  57262. /**
  57263. * Parse properties from a JSON object
  57264. * @param serializationObject defines the JSON object
  57265. */
  57266. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57267. this.radius = serializationObject.radius;
  57268. this.directionRandomizer = serializationObject.directionRandomizer;
  57269. };
  57270. return SphereParticleEmitter;
  57271. }());
  57272. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57273. /**
  57274. * Particle emitter emitting particles from the inside of a sphere.
  57275. * It emits the particles randomly between two vectors.
  57276. */
  57277. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57278. __extends(SphereDirectedParticleEmitter, _super);
  57279. /**
  57280. * Creates a new instance SphereDirectedParticleEmitter
  57281. * @param radius the radius of the emission sphere (1 by default)
  57282. * @param direction1 the min limit of the emission direction (up vector by default)
  57283. * @param direction2 the max limit of the emission direction (up vector by default)
  57284. */
  57285. function SphereDirectedParticleEmitter(radius,
  57286. /**
  57287. * The min limit of the emission direction.
  57288. */
  57289. direction1,
  57290. /**
  57291. * The max limit of the emission direction.
  57292. */
  57293. direction2) {
  57294. if (radius === void 0) { radius = 1; }
  57295. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57296. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57297. var _this = _super.call(this, radius) || this;
  57298. _this.direction1 = direction1;
  57299. _this.direction2 = direction2;
  57300. return _this;
  57301. }
  57302. /**
  57303. * Called by the particle System when the direction is computed for the created particle.
  57304. * @param emitPower is the power of the particle (speed)
  57305. * @param worldMatrix is the world matrix of the particle system
  57306. * @param directionToUpdate is the direction vector to update with the result
  57307. * @param particle is the particle we are computed the direction for
  57308. */
  57309. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57310. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57311. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57312. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57313. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57314. };
  57315. /**
  57316. * Clones the current emitter and returns a copy of it
  57317. * @returns the new emitter
  57318. */
  57319. SphereDirectedParticleEmitter.prototype.clone = function () {
  57320. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57321. BABYLON.Tools.DeepCopy(this, newOne);
  57322. return newOne;
  57323. };
  57324. /**
  57325. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57326. * @param effect defines the update shader
  57327. */
  57328. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57329. effect.setFloat("radius", this.radius);
  57330. effect.setVector3("direction1", this.direction1);
  57331. effect.setVector3("direction2", this.direction2);
  57332. };
  57333. /**
  57334. * Returns a string to use to update the GPU particles update shader
  57335. * @returns a string containng the defines string
  57336. */
  57337. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57338. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57339. };
  57340. /**
  57341. * Returns the string "SphereDirectedParticleEmitter"
  57342. * @returns a string containing the class name
  57343. */
  57344. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57345. return "SphereDirectedParticleEmitter";
  57346. };
  57347. /**
  57348. * Serializes the particle system to a JSON object.
  57349. * @returns the JSON object
  57350. */
  57351. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57352. var serializationObject = _super.prototype.serialize.call(this);
  57353. serializationObject.direction1 = this.direction1.asArray();
  57354. serializationObject.direction2 = this.direction2.asArray();
  57355. return serializationObject;
  57356. };
  57357. /**
  57358. * Parse properties from a JSON object
  57359. * @param serializationObject defines the JSON object
  57360. */
  57361. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57362. _super.prototype.parse.call(this, serializationObject);
  57363. this.direction1.copyFrom(serializationObject.direction1);
  57364. this.direction2.copyFrom(serializationObject.direction2);
  57365. };
  57366. return SphereDirectedParticleEmitter;
  57367. }(SphereParticleEmitter));
  57368. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57369. })(BABYLON || (BABYLON = {}));
  57370. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57371. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57372. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57373. s = arguments[i];
  57374. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57375. t[p] = s[p];
  57376. }
  57377. return t;
  57378. };
  57379. var BABYLON;
  57380. (function (BABYLON) {
  57381. /**
  57382. * This represents a GPU particle system in Babylon
  57383. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57384. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57385. */
  57386. var GPUParticleSystem = /** @class */ (function () {
  57387. /**
  57388. * Instantiates a GPU particle system.
  57389. * 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.
  57390. * @param name The name of the particle system
  57391. * @param capacity The max number of particles alive at the same time
  57392. * @param scene The scene the particle system belongs to
  57393. */
  57394. function GPUParticleSystem(name, options, scene) {
  57395. /**
  57396. * The emitter represents the Mesh or position we are attaching the particle system to.
  57397. */
  57398. this.emitter = null;
  57399. /**
  57400. * The rendering group used by the Particle system to chose when to render.
  57401. */
  57402. this.renderingGroupId = 0;
  57403. /**
  57404. * The layer mask we are rendering the particles through.
  57405. */
  57406. this.layerMask = 0x0FFFFFFF;
  57407. this._targetIndex = 0;
  57408. this._currentRenderId = -1;
  57409. this._started = false;
  57410. this._stopped = false;
  57411. this._timeDelta = 0;
  57412. this._attributesStrideSize = 16;
  57413. this._actualFrame = 0;
  57414. /**
  57415. * List of animations used by the particle system.
  57416. */
  57417. this.animations = [];
  57418. /**
  57419. * An event triggered when the system is disposed.
  57420. */
  57421. this.onDisposeObservable = new BABYLON.Observable();
  57422. /**
  57423. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57424. */
  57425. this.updateSpeed = 0.01;
  57426. /**
  57427. * The amount of time the particle system is running (depends of the overall update speed).
  57428. */
  57429. this.targetStopDuration = 0;
  57430. /**
  57431. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57432. */
  57433. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57434. /**
  57435. * Minimum life time of emitting particles.
  57436. */
  57437. this.minLifeTime = 1;
  57438. /**
  57439. * Maximum life time of emitting particles.
  57440. */
  57441. this.maxLifeTime = 1;
  57442. /**
  57443. * Minimum Size of emitting particles.
  57444. */
  57445. this.minSize = 1;
  57446. /**
  57447. * Maximum Size of emitting particles.
  57448. */
  57449. this.maxSize = 1;
  57450. /**
  57451. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57452. */
  57453. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57454. /**
  57455. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57456. */
  57457. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57458. /**
  57459. * Color the particle will have at the end of its lifetime.
  57460. */
  57461. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57462. /**
  57463. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57464. */
  57465. this.emitRate = 100;
  57466. /**
  57467. * You can use gravity if you want to give an orientation to your particles.
  57468. */
  57469. this.gravity = BABYLON.Vector3.Zero();
  57470. /**
  57471. * Minimum power of emitting particles.
  57472. */
  57473. this.minEmitPower = 1;
  57474. /**
  57475. * Maximum power of emitting particles.
  57476. */
  57477. this.maxEmitPower = 1;
  57478. /**
  57479. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57480. */
  57481. this.minAngularSpeed = 0;
  57482. /**
  57483. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57484. */
  57485. this.maxAngularSpeed = 0;
  57486. /**
  57487. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57488. * to override the particles.
  57489. */
  57490. this.forceDepthWrite = false;
  57491. this.id = name;
  57492. this.name = name;
  57493. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57494. this._engine = this._scene.getEngine();
  57495. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57496. this._capacity = fullOptions.capacity;
  57497. this._activeCount = fullOptions.capacity;
  57498. this._currentActiveCount = 0;
  57499. this._scene.particleSystems.push(this);
  57500. this._updateEffectOptions = {
  57501. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "angle"],
  57502. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57503. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57504. "angleRange"],
  57505. uniformBuffersNames: [],
  57506. samplers: ["randomSampler"],
  57507. defines: "",
  57508. fallbacks: null,
  57509. onCompiled: null,
  57510. onError: null,
  57511. indexParameters: null,
  57512. maxSimultaneousLights: 0,
  57513. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection", "outAngle"]
  57514. };
  57515. // Random data
  57516. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57517. var d = [];
  57518. for (var i = 0; i < maxTextureSize; ++i) {
  57519. d.push(Math.random());
  57520. d.push(Math.random());
  57521. d.push(Math.random());
  57522. d.push(Math.random());
  57523. }
  57524. 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);
  57525. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57526. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57527. this._randomTextureSize = maxTextureSize;
  57528. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57529. }
  57530. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57531. /**
  57532. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57533. */
  57534. get: function () {
  57535. if (!BABYLON.Engine.LastCreatedEngine) {
  57536. return false;
  57537. }
  57538. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57539. },
  57540. enumerable: true,
  57541. configurable: true
  57542. });
  57543. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57544. /**
  57545. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57546. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57547. */
  57548. get: function () {
  57549. if (this.particleEmitterType.direction1) {
  57550. return this.particleEmitterType.direction1;
  57551. }
  57552. return BABYLON.Vector3.Zero();
  57553. },
  57554. set: function (value) {
  57555. if (this.particleEmitterType.direction1) {
  57556. this.particleEmitterType.direction1 = value;
  57557. }
  57558. },
  57559. enumerable: true,
  57560. configurable: true
  57561. });
  57562. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57563. /**
  57564. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57565. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57566. */
  57567. get: function () {
  57568. if (this.particleEmitterType.direction2) {
  57569. return this.particleEmitterType.direction2;
  57570. }
  57571. return BABYLON.Vector3.Zero();
  57572. },
  57573. set: function (value) {
  57574. if (this.particleEmitterType.direction2) {
  57575. this.particleEmitterType.direction2 = value;
  57576. }
  57577. },
  57578. enumerable: true,
  57579. configurable: true
  57580. });
  57581. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57582. /**
  57583. * 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.
  57584. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57585. */
  57586. get: function () {
  57587. if (this.particleEmitterType.minEmitBox) {
  57588. return this.particleEmitterType.minEmitBox;
  57589. }
  57590. return BABYLON.Vector3.Zero();
  57591. },
  57592. set: function (value) {
  57593. if (this.particleEmitterType.minEmitBox) {
  57594. this.particleEmitterType.minEmitBox = value;
  57595. }
  57596. },
  57597. enumerable: true,
  57598. configurable: true
  57599. });
  57600. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57601. /**
  57602. * 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.
  57603. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57604. */
  57605. get: function () {
  57606. if (this.particleEmitterType.maxEmitBox) {
  57607. return this.particleEmitterType.maxEmitBox;
  57608. }
  57609. return BABYLON.Vector3.Zero();
  57610. },
  57611. set: function (value) {
  57612. if (this.particleEmitterType.maxEmitBox) {
  57613. this.particleEmitterType.maxEmitBox = value;
  57614. }
  57615. },
  57616. enumerable: true,
  57617. configurable: true
  57618. });
  57619. /**
  57620. * Gets the maximum number of particles active at the same time.
  57621. * @returns The max number of active particles.
  57622. */
  57623. GPUParticleSystem.prototype.getCapacity = function () {
  57624. return this._capacity;
  57625. };
  57626. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57627. /**
  57628. * Gets or set the number of active particles
  57629. */
  57630. get: function () {
  57631. return this._activeCount;
  57632. },
  57633. set: function (value) {
  57634. this._activeCount = Math.min(value, this._capacity);
  57635. },
  57636. enumerable: true,
  57637. configurable: true
  57638. });
  57639. /**
  57640. * Is this system ready to be used/rendered
  57641. * @return true if the system is ready
  57642. */
  57643. GPUParticleSystem.prototype.isReady = function () {
  57644. if (!this._updateEffect) {
  57645. this._recreateUpdateEffect();
  57646. this._recreateRenderEffect();
  57647. return false;
  57648. }
  57649. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57650. return false;
  57651. }
  57652. return true;
  57653. };
  57654. /**
  57655. * Gets Wether the system has been started.
  57656. * @returns True if it has been started, otherwise false.
  57657. */
  57658. GPUParticleSystem.prototype.isStarted = function () {
  57659. return this._started;
  57660. };
  57661. /**
  57662. * Starts the particle system and begins to emit.
  57663. */
  57664. GPUParticleSystem.prototype.start = function () {
  57665. this._started = true;
  57666. this._stopped = false;
  57667. };
  57668. /**
  57669. * Stops the particle system.
  57670. */
  57671. GPUParticleSystem.prototype.stop = function () {
  57672. this._stopped = true;
  57673. };
  57674. /**
  57675. * Remove all active particles
  57676. */
  57677. GPUParticleSystem.prototype.reset = function () {
  57678. this._releaseBuffers();
  57679. this._releaseVAOs();
  57680. this._currentActiveCount = 0;
  57681. this._targetIndex = 0;
  57682. };
  57683. /**
  57684. * Returns the string "GPUParticleSystem"
  57685. * @returns a string containing the class name
  57686. */
  57687. GPUParticleSystem.prototype.getClassName = function () {
  57688. return "GPUParticleSystem";
  57689. };
  57690. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57691. var updateVertexBuffers = {};
  57692. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57693. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57694. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57695. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57696. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57697. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57698. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57699. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2);
  57700. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57701. this._engine.bindArrayBuffer(null);
  57702. return vao;
  57703. };
  57704. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57705. var renderVertexBuffers = {};
  57706. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57707. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57708. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57709. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57710. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57711. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2, this._attributesStrideSize, true);
  57712. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57713. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57714. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57715. this._engine.bindArrayBuffer(null);
  57716. return vao;
  57717. };
  57718. GPUParticleSystem.prototype._initialize = function (force) {
  57719. if (force === void 0) { force = false; }
  57720. if (this._buffer0 && !force) {
  57721. return;
  57722. }
  57723. var engine = this._scene.getEngine();
  57724. var data = new Array();
  57725. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57726. // position
  57727. data.push(0.0);
  57728. data.push(0.0);
  57729. data.push(0.0);
  57730. // Age and life
  57731. data.push(0.0); // create the particle as a dead one to create a new one at start
  57732. data.push(0.0);
  57733. // Seed
  57734. data.push(Math.random());
  57735. // Size
  57736. data.push(0.0);
  57737. // color
  57738. data.push(0.0);
  57739. data.push(0.0);
  57740. data.push(0.0);
  57741. data.push(0.0);
  57742. // direction
  57743. data.push(0.0);
  57744. data.push(0.0);
  57745. data.push(0.0);
  57746. // angle
  57747. data.push(0.0);
  57748. data.push(0.0);
  57749. }
  57750. // Sprite data
  57751. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57752. -0.5, 0.5, 0, 1,
  57753. -0.5, -0.5, 0, 0,
  57754. 0.5, -0.5, 1, 0]);
  57755. // Buffers
  57756. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57757. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57758. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57759. // Update VAO
  57760. this._updateVAO = [];
  57761. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57762. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57763. // Render VAO
  57764. this._renderVAO = [];
  57765. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57766. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57767. // Links
  57768. this._sourceBuffer = this._buffer0;
  57769. this._targetBuffer = this._buffer1;
  57770. };
  57771. /** @hidden */
  57772. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57773. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57774. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57775. return;
  57776. }
  57777. this._updateEffectOptions.defines = defines;
  57778. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57779. };
  57780. /** @hidden */
  57781. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57782. var defines = "";
  57783. if (this._scene.clipPlane) {
  57784. defines = "\n#define CLIPPLANE";
  57785. }
  57786. if (this._renderEffect && this._renderEffect.defines === defines) {
  57787. return;
  57788. }
  57789. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57790. };
  57791. /**
  57792. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57793. */
  57794. GPUParticleSystem.prototype.animate = function () {
  57795. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57796. this._actualFrame += this._timeDelta;
  57797. if (!this._stopped) {
  57798. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57799. this.stop();
  57800. }
  57801. }
  57802. };
  57803. /**
  57804. * Renders the particle system in its current state.
  57805. * @returns the current number of particles
  57806. */
  57807. GPUParticleSystem.prototype.render = function () {
  57808. if (!this._started) {
  57809. return 0;
  57810. }
  57811. this._recreateUpdateEffect();
  57812. this._recreateRenderEffect();
  57813. if (!this.isReady()) {
  57814. return 0;
  57815. }
  57816. if (this._currentRenderId === this._scene.getRenderId()) {
  57817. return 0;
  57818. }
  57819. this._currentRenderId = this._scene.getRenderId();
  57820. // Get everything ready to render
  57821. this._initialize();
  57822. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57823. // Enable update effect
  57824. this._engine.enableEffect(this._updateEffect);
  57825. this._engine.setState(false);
  57826. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57827. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57828. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57829. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57830. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57831. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57832. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57833. this._updateEffect.setDirectColor4("color1", this.color1);
  57834. this._updateEffect.setDirectColor4("color2", this.color2);
  57835. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57836. this._updateEffect.setFloat2("angleRange", this.minAngularSpeed, this.maxAngularSpeed);
  57837. this._updateEffect.setVector3("gravity", this.gravity);
  57838. if (this.particleEmitterType) {
  57839. this.particleEmitterType.applyToShader(this._updateEffect);
  57840. }
  57841. var emitterWM;
  57842. if (this.emitter.position) {
  57843. var emitterMesh = this.emitter;
  57844. emitterWM = emitterMesh.getWorldMatrix();
  57845. }
  57846. else {
  57847. var emitterPosition = this.emitter;
  57848. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57849. }
  57850. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57851. // Bind source VAO
  57852. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57853. // Update
  57854. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57855. this._engine.setRasterizerState(false);
  57856. this._engine.beginTransformFeedback();
  57857. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57858. this._engine.endTransformFeedback();
  57859. this._engine.setRasterizerState(true);
  57860. this._engine.bindTransformFeedbackBuffer(null);
  57861. // Enable render effect
  57862. this._engine.enableEffect(this._renderEffect);
  57863. var viewMatrix = this._scene.getViewMatrix();
  57864. this._renderEffect.setMatrix("view", viewMatrix);
  57865. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57866. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57867. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57868. if (this._scene.clipPlane) {
  57869. var clipPlane = this._scene.clipPlane;
  57870. var invView = viewMatrix.clone();
  57871. invView.invert();
  57872. this._renderEffect.setMatrix("invView", invView);
  57873. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57874. }
  57875. // Draw order
  57876. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57877. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57878. }
  57879. else {
  57880. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57881. }
  57882. if (this.forceDepthWrite) {
  57883. this._engine.setDepthWrite(true);
  57884. }
  57885. // Bind source VAO
  57886. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57887. // Render
  57888. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57889. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57890. // Switch VAOs
  57891. this._targetIndex++;
  57892. if (this._targetIndex === 2) {
  57893. this._targetIndex = 0;
  57894. }
  57895. // Switch buffers
  57896. var tmpBuffer = this._sourceBuffer;
  57897. this._sourceBuffer = this._targetBuffer;
  57898. this._targetBuffer = tmpBuffer;
  57899. return this._currentActiveCount;
  57900. };
  57901. /**
  57902. * Rebuilds the particle system
  57903. */
  57904. GPUParticleSystem.prototype.rebuild = function () {
  57905. this._initialize(true);
  57906. };
  57907. GPUParticleSystem.prototype._releaseBuffers = function () {
  57908. if (this._buffer0) {
  57909. this._buffer0.dispose();
  57910. this._buffer0 = null;
  57911. }
  57912. if (this._buffer1) {
  57913. this._buffer1.dispose();
  57914. this._buffer1 = null;
  57915. }
  57916. if (this._spriteBuffer) {
  57917. this._spriteBuffer.dispose();
  57918. this._spriteBuffer = null;
  57919. }
  57920. };
  57921. GPUParticleSystem.prototype._releaseVAOs = function () {
  57922. if (!this._updateVAO) {
  57923. return;
  57924. }
  57925. for (var index = 0; index < this._updateVAO.length; index++) {
  57926. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57927. }
  57928. this._updateVAO = [];
  57929. for (var index = 0; index < this._renderVAO.length; index++) {
  57930. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57931. }
  57932. this._renderVAO = [];
  57933. };
  57934. /**
  57935. * Disposes the particle system and free the associated resources
  57936. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57937. */
  57938. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57939. if (disposeTexture === void 0) { disposeTexture = true; }
  57940. var index = this._scene.particleSystems.indexOf(this);
  57941. if (index > -1) {
  57942. this._scene.particleSystems.splice(index, 1);
  57943. }
  57944. this._releaseBuffers();
  57945. this._releaseVAOs();
  57946. if (this._randomTexture) {
  57947. this._randomTexture.dispose();
  57948. this._randomTexture = null;
  57949. }
  57950. if (disposeTexture && this.particleTexture) {
  57951. this.particleTexture.dispose();
  57952. this.particleTexture = null;
  57953. }
  57954. // Callback
  57955. this.onDisposeObservable.notifyObservers(this);
  57956. this.onDisposeObservable.clear();
  57957. };
  57958. /**
  57959. * Clones the particle system.
  57960. * @param name The name of the cloned object
  57961. * @param newEmitter The new emitter to use
  57962. * @returns the cloned particle system
  57963. */
  57964. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57965. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57966. BABYLON.Tools.DeepCopy(this, result);
  57967. if (newEmitter === undefined) {
  57968. newEmitter = this.emitter;
  57969. }
  57970. result.emitter = newEmitter;
  57971. if (this.particleTexture) {
  57972. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57973. }
  57974. return result;
  57975. };
  57976. /**
  57977. * Serializes the particle system to a JSON object.
  57978. * @returns the JSON object
  57979. */
  57980. GPUParticleSystem.prototype.serialize = function () {
  57981. var serializationObject = {};
  57982. serializationObject.name = this.name;
  57983. serializationObject.id = this.id;
  57984. // Emitter
  57985. if (this.emitter.position) {
  57986. var emitterMesh = this.emitter;
  57987. serializationObject.emitterId = emitterMesh.id;
  57988. }
  57989. else {
  57990. var emitterPosition = this.emitter;
  57991. serializationObject.emitter = emitterPosition.asArray();
  57992. }
  57993. serializationObject.capacity = this.getCapacity();
  57994. if (this.particleTexture) {
  57995. serializationObject.textureName = this.particleTexture.name;
  57996. }
  57997. // Animations
  57998. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57999. // Particle system
  58000. serializationObject.activeParticleCount = this.activeParticleCount;
  58001. serializationObject.randomTextureSize = this._randomTextureSize;
  58002. serializationObject.minSize = this.minSize;
  58003. serializationObject.maxSize = this.maxSize;
  58004. serializationObject.minEmitPower = this.minEmitPower;
  58005. serializationObject.maxEmitPower = this.maxEmitPower;
  58006. serializationObject.minLifeTime = this.minLifeTime;
  58007. serializationObject.maxLifeTime = this.maxLifeTime;
  58008. serializationObject.minAngularSpeed = this.minAngularSpeed;
  58009. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  58010. serializationObject.emitRate = this.emitRate;
  58011. serializationObject.gravity = this.gravity.asArray();
  58012. serializationObject.color1 = this.color1.asArray();
  58013. serializationObject.color2 = this.color2.asArray();
  58014. serializationObject.colorDead = this.colorDead.asArray();
  58015. serializationObject.updateSpeed = this.updateSpeed;
  58016. serializationObject.targetStopDuration = this.targetStopDuration;
  58017. serializationObject.blendMode = this.blendMode;
  58018. // Emitter
  58019. if (this.particleEmitterType) {
  58020. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  58021. }
  58022. return serializationObject;
  58023. };
  58024. /**
  58025. * Parses a JSON object to create a GPU particle system.
  58026. * @param parsedParticleSystem The JSON object to parse
  58027. * @param scene The scene to create the particle system in
  58028. * @param rootUrl The root url to use to load external dependencies like texture
  58029. * @returns the parsed GPU particle system
  58030. */
  58031. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58032. var name = parsedParticleSystem.name;
  58033. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  58034. if (parsedParticleSystem.id) {
  58035. particleSystem.id = parsedParticleSystem.id;
  58036. }
  58037. // Texture
  58038. if (parsedParticleSystem.textureName) {
  58039. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  58040. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  58041. }
  58042. // Emitter
  58043. if (parsedParticleSystem.emitterId) {
  58044. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  58045. }
  58046. else {
  58047. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  58048. }
  58049. // Animations
  58050. if (parsedParticleSystem.animations) {
  58051. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  58052. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  58053. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58054. }
  58055. }
  58056. // Particle system
  58057. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  58058. particleSystem.minSize = parsedParticleSystem.minSize;
  58059. particleSystem.maxSize = parsedParticleSystem.maxSize;
  58060. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  58061. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  58062. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  58063. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  58064. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  58065. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  58066. particleSystem.emitRate = parsedParticleSystem.emitRate;
  58067. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  58068. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  58069. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  58070. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  58071. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  58072. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  58073. particleSystem.blendMode = parsedParticleSystem.blendMode;
  58074. // Emitter
  58075. if (parsedParticleSystem.particleEmitterType) {
  58076. var emitterType = void 0;
  58077. switch (parsedParticleSystem.particleEmitterType.type) {
  58078. case "SphereEmitter":
  58079. emitterType = new BABYLON.SphereParticleEmitter();
  58080. break;
  58081. case "SphereDirectedParticleEmitter":
  58082. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  58083. break;
  58084. case "ConeEmitter":
  58085. emitterType = new BABYLON.ConeParticleEmitter();
  58086. break;
  58087. case "BoxEmitter":
  58088. default:
  58089. emitterType = new BABYLON.BoxParticleEmitter();
  58090. break;
  58091. }
  58092. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58093. particleSystem.particleEmitterType = emitterType;
  58094. }
  58095. return particleSystem;
  58096. };
  58097. return GPUParticleSystem;
  58098. }());
  58099. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58100. })(BABYLON || (BABYLON = {}));
  58101. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58102. var BABYLON;
  58103. (function (BABYLON) {
  58104. /**
  58105. * Represents one particle of a solid particle system.
  58106. */
  58107. var SolidParticle = /** @class */ (function () {
  58108. /**
  58109. * Creates a Solid Particle object.
  58110. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58111. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58112. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58113. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58114. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58115. * @param shapeId (integer) is the model shape identifier in the SPS.
  58116. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58117. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58118. */
  58119. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58120. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58121. /**
  58122. * particle global index
  58123. */
  58124. this.idx = 0;
  58125. /**
  58126. * The color of the particle
  58127. */
  58128. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58129. /**
  58130. * The world space position of the particle.
  58131. */
  58132. this.position = BABYLON.Vector3.Zero();
  58133. /**
  58134. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58135. */
  58136. this.rotation = BABYLON.Vector3.Zero();
  58137. /**
  58138. * The scaling of the particle.
  58139. */
  58140. this.scaling = BABYLON.Vector3.One();
  58141. /**
  58142. * The uvs of the particle.
  58143. */
  58144. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58145. /**
  58146. * The current speed of the particle.
  58147. */
  58148. this.velocity = BABYLON.Vector3.Zero();
  58149. /**
  58150. * The pivot point in the particle local space.
  58151. */
  58152. this.pivot = BABYLON.Vector3.Zero();
  58153. /**
  58154. * Must the particle be translated from its pivot point in its local space ?
  58155. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58156. * Default : false
  58157. */
  58158. this.translateFromPivot = false;
  58159. /**
  58160. * Is the particle active or not ?
  58161. */
  58162. this.alive = true;
  58163. /**
  58164. * Is the particle visible or not ?
  58165. */
  58166. this.isVisible = true;
  58167. /**
  58168. * Index of this particle in the global "positions" array (Internal use)
  58169. */
  58170. this._pos = 0;
  58171. /**
  58172. * Index of this particle in the global "indices" array (Internal use)
  58173. */
  58174. this._ind = 0;
  58175. /**
  58176. * ModelShape id of this particle
  58177. */
  58178. this.shapeId = 0;
  58179. /**
  58180. * Index of the particle in its shape id (Internal use)
  58181. */
  58182. this.idxInShape = 0;
  58183. /**
  58184. * Still set as invisible in order to skip useless computations (Internal use)
  58185. */
  58186. this._stillInvisible = false;
  58187. /**
  58188. * Last computed particle rotation matrix
  58189. */
  58190. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58191. /**
  58192. * Parent particle Id, if any.
  58193. * Default null.
  58194. */
  58195. this.parentId = null;
  58196. /**
  58197. * Internal global position in the SPS.
  58198. */
  58199. this._globalPosition = BABYLON.Vector3.Zero();
  58200. this.idx = particleIndex;
  58201. this._pos = positionIndex;
  58202. this._ind = indiceIndex;
  58203. this._model = model;
  58204. this.shapeId = shapeId;
  58205. this.idxInShape = idxInShape;
  58206. this._sps = sps;
  58207. if (modelBoundingInfo) {
  58208. this._modelBoundingInfo = modelBoundingInfo;
  58209. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58210. }
  58211. }
  58212. Object.defineProperty(SolidParticle.prototype, "scale", {
  58213. /**
  58214. * Legacy support, changed scale to scaling
  58215. */
  58216. get: function () {
  58217. return this.scaling;
  58218. },
  58219. /**
  58220. * Legacy support, changed scale to scaling
  58221. */
  58222. set: function (scale) {
  58223. this.scaling = scale;
  58224. },
  58225. enumerable: true,
  58226. configurable: true
  58227. });
  58228. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58229. /**
  58230. * Legacy support, changed quaternion to rotationQuaternion
  58231. */
  58232. get: function () {
  58233. return this.rotationQuaternion;
  58234. },
  58235. /**
  58236. * Legacy support, changed quaternion to rotationQuaternion
  58237. */
  58238. set: function (q) {
  58239. this.rotationQuaternion = q;
  58240. },
  58241. enumerable: true,
  58242. configurable: true
  58243. });
  58244. /**
  58245. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58246. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58247. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58248. * @returns true if it intersects
  58249. */
  58250. SolidParticle.prototype.intersectsMesh = function (target) {
  58251. if (!this._boundingInfo || !target._boundingInfo) {
  58252. return false;
  58253. }
  58254. if (this._sps._bSphereOnly) {
  58255. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58256. }
  58257. return this._boundingInfo.intersects(target._boundingInfo, false);
  58258. };
  58259. return SolidParticle;
  58260. }());
  58261. BABYLON.SolidParticle = SolidParticle;
  58262. /**
  58263. * Represents the shape of the model used by one particle of a solid particle system.
  58264. * SPS internal tool, don't use it manually.
  58265. */
  58266. var ModelShape = /** @class */ (function () {
  58267. /**
  58268. * 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.
  58269. * SPS internal tool, don't use it manually.
  58270. * @hidden
  58271. */
  58272. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58273. /**
  58274. * length of the shape in the model indices array (internal use)
  58275. */
  58276. this._indicesLength = 0;
  58277. this.shapeID = id;
  58278. this._shape = shape;
  58279. this._indicesLength = indicesLength;
  58280. this._shapeUV = shapeUV;
  58281. this._positionFunction = posFunction;
  58282. this._vertexFunction = vtxFunction;
  58283. }
  58284. return ModelShape;
  58285. }());
  58286. BABYLON.ModelShape = ModelShape;
  58287. /**
  58288. * Represents a Depth Sorted Particle in the solid particle system.
  58289. */
  58290. var DepthSortedParticle = /** @class */ (function () {
  58291. function DepthSortedParticle() {
  58292. /**
  58293. * Index of the particle in the "indices" array
  58294. */
  58295. this.ind = 0;
  58296. /**
  58297. * Length of the particle shape in the "indices" array
  58298. */
  58299. this.indicesLength = 0;
  58300. /**
  58301. * Squared distance from the particle to the camera
  58302. */
  58303. this.sqDistance = 0.0;
  58304. }
  58305. return DepthSortedParticle;
  58306. }());
  58307. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58308. })(BABYLON || (BABYLON = {}));
  58309. //# sourceMappingURL=babylon.solidParticle.js.map
  58310. var BABYLON;
  58311. (function (BABYLON) {
  58312. /**
  58313. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58314. *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.
  58315. * The SPS is also a particle system. It provides some methods to manage the particles.
  58316. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58317. *
  58318. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58319. */
  58320. var SolidParticleSystem = /** @class */ (function () {
  58321. /**
  58322. * Creates a SPS (Solid Particle System) object.
  58323. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58324. * @param scene (Scene) is the scene in which the SPS is added.
  58325. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58326. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58327. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58328. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58329. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58330. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58331. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58332. */
  58333. function SolidParticleSystem(name, scene, options) {
  58334. /**
  58335. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58336. * Example : var p = SPS.particles[i];
  58337. */
  58338. this.particles = new Array();
  58339. /**
  58340. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58341. */
  58342. this.nbParticles = 0;
  58343. /**
  58344. * If the particles must ever face the camera (default false). Useful for planar particles.
  58345. */
  58346. this.billboard = false;
  58347. /**
  58348. * Recompute normals when adding a shape
  58349. */
  58350. this.recomputeNormals = true;
  58351. /**
  58352. * This a counter ofr your own usage. It's not set by any SPS functions.
  58353. */
  58354. this.counter = 0;
  58355. /**
  58356. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58357. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58358. */
  58359. this.vars = {};
  58360. /**
  58361. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58362. */
  58363. this._bSphereOnly = false;
  58364. /**
  58365. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58366. */
  58367. this._bSphereRadiusFactor = 1.0;
  58368. this._positions = new Array();
  58369. this._indices = new Array();
  58370. this._normals = new Array();
  58371. this._colors = new Array();
  58372. this._uvs = new Array();
  58373. this._index = 0; // indices index
  58374. this._updatable = true;
  58375. this._pickable = false;
  58376. this._isVisibilityBoxLocked = false;
  58377. this._alwaysVisible = false;
  58378. this._depthSort = false;
  58379. this._shapeCounter = 0;
  58380. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58381. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58382. this._computeParticleColor = true;
  58383. this._computeParticleTexture = true;
  58384. this._computeParticleRotation = true;
  58385. this._computeParticleVertex = false;
  58386. this._computeBoundingBox = false;
  58387. this._depthSortParticles = true;
  58388. this._cam_axisZ = BABYLON.Vector3.Zero();
  58389. this._cam_axisY = BABYLON.Vector3.Zero();
  58390. this._cam_axisX = BABYLON.Vector3.Zero();
  58391. this._axisZ = BABYLON.Axis.Z;
  58392. this._camDir = BABYLON.Vector3.Zero();
  58393. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58394. this._rotMatrix = new BABYLON.Matrix();
  58395. this._invertMatrix = new BABYLON.Matrix();
  58396. this._rotated = BABYLON.Vector3.Zero();
  58397. this._quaternion = new BABYLON.Quaternion();
  58398. this._vertex = BABYLON.Vector3.Zero();
  58399. this._normal = BABYLON.Vector3.Zero();
  58400. this._yaw = 0.0;
  58401. this._pitch = 0.0;
  58402. this._roll = 0.0;
  58403. this._halfroll = 0.0;
  58404. this._halfpitch = 0.0;
  58405. this._halfyaw = 0.0;
  58406. this._sinRoll = 0.0;
  58407. this._cosRoll = 0.0;
  58408. this._sinPitch = 0.0;
  58409. this._cosPitch = 0.0;
  58410. this._sinYaw = 0.0;
  58411. this._cosYaw = 0.0;
  58412. this._mustUnrotateFixedNormals = false;
  58413. this._minimum = BABYLON.Vector3.Zero();
  58414. this._maximum = BABYLON.Vector3.Zero();
  58415. this._minBbox = BABYLON.Vector3.Zero();
  58416. this._maxBbox = BABYLON.Vector3.Zero();
  58417. this._particlesIntersect = false;
  58418. this._depthSortFunction = function (p1, p2) {
  58419. return (p2.sqDistance - p1.sqDistance);
  58420. };
  58421. this._needs32Bits = false;
  58422. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58423. this._scaledPivot = BABYLON.Vector3.Zero();
  58424. this._particleHasParent = false;
  58425. this.name = name;
  58426. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58427. this._camera = scene.activeCamera;
  58428. this._pickable = options ? options.isPickable : false;
  58429. this._depthSort = options ? options.enableDepthSort : false;
  58430. this._particlesIntersect = options ? options.particleIntersection : false;
  58431. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58432. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58433. if (options && options.updatable) {
  58434. this._updatable = options.updatable;
  58435. }
  58436. else {
  58437. this._updatable = true;
  58438. }
  58439. if (this._pickable) {
  58440. this.pickedParticles = [];
  58441. }
  58442. if (this._depthSort) {
  58443. this.depthSortedParticles = [];
  58444. }
  58445. }
  58446. /**
  58447. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58448. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58449. * @returns the created mesh
  58450. */
  58451. SolidParticleSystem.prototype.buildMesh = function () {
  58452. if (this.nbParticles === 0) {
  58453. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58454. this.addShape(triangle, 1);
  58455. triangle.dispose();
  58456. }
  58457. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58458. this._positions32 = new Float32Array(this._positions);
  58459. this._uvs32 = new Float32Array(this._uvs);
  58460. this._colors32 = new Float32Array(this._colors);
  58461. if (this.recomputeNormals) {
  58462. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58463. }
  58464. this._normals32 = new Float32Array(this._normals);
  58465. this._fixedNormal32 = new Float32Array(this._normals);
  58466. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58467. this._unrotateFixedNormals();
  58468. }
  58469. var vertexData = new BABYLON.VertexData();
  58470. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58471. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58472. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58473. if (this._uvs32.length > 0) {
  58474. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58475. }
  58476. if (this._colors32.length > 0) {
  58477. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58478. }
  58479. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58480. vertexData.applyToMesh(mesh, this._updatable);
  58481. this.mesh = mesh;
  58482. this.mesh.isPickable = this._pickable;
  58483. // free memory
  58484. if (!this._depthSort) {
  58485. this._indices = null;
  58486. }
  58487. this._positions = null;
  58488. this._normals = null;
  58489. this._uvs = null;
  58490. this._colors = null;
  58491. if (!this._updatable) {
  58492. this.particles.length = 0;
  58493. }
  58494. return mesh;
  58495. };
  58496. /**
  58497. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58498. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58499. * Thus the particles generated from `digest()` have their property `position` set yet.
  58500. * @param mesh ( Mesh ) is the mesh to be digested
  58501. * @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
  58502. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58503. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58504. * @returns the current SPS
  58505. */
  58506. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58507. var size = (options && options.facetNb) || 1;
  58508. var number = (options && options.number) || 0;
  58509. var delta = (options && options.delta) || 0;
  58510. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58511. var meshInd = mesh.getIndices();
  58512. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58513. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58514. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58515. var f = 0; // facet counter
  58516. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58517. // compute size from number
  58518. if (number) {
  58519. number = (number > totalFacets) ? totalFacets : number;
  58520. size = Math.round(totalFacets / number);
  58521. delta = 0;
  58522. }
  58523. else {
  58524. size = (size > totalFacets) ? totalFacets : size;
  58525. }
  58526. var facetPos = []; // submesh positions
  58527. var facetInd = []; // submesh indices
  58528. var facetUV = []; // submesh UV
  58529. var facetCol = []; // submesh colors
  58530. var barycenter = BABYLON.Vector3.Zero();
  58531. var sizeO = size;
  58532. while (f < totalFacets) {
  58533. size = sizeO + Math.floor((1 + delta) * Math.random());
  58534. if (f > totalFacets - size) {
  58535. size = totalFacets - f;
  58536. }
  58537. // reset temp arrays
  58538. facetPos.length = 0;
  58539. facetInd.length = 0;
  58540. facetUV.length = 0;
  58541. facetCol.length = 0;
  58542. // iterate over "size" facets
  58543. var fi = 0;
  58544. for (var j = f * 3; j < (f + size) * 3; j++) {
  58545. facetInd.push(fi);
  58546. var i = meshInd[j];
  58547. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58548. if (meshUV) {
  58549. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58550. }
  58551. if (meshCol) {
  58552. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58553. }
  58554. fi++;
  58555. }
  58556. // create a model shape for each single particle
  58557. var idx = this.nbParticles;
  58558. var shape = this._posToShape(facetPos);
  58559. var shapeUV = this._uvsToShapeUV(facetUV);
  58560. // compute the barycenter of the shape
  58561. var v;
  58562. for (v = 0; v < shape.length; v++) {
  58563. barycenter.addInPlace(shape[v]);
  58564. }
  58565. barycenter.scaleInPlace(1 / shape.length);
  58566. // shift the shape from its barycenter to the origin
  58567. for (v = 0; v < shape.length; v++) {
  58568. shape[v].subtractInPlace(barycenter);
  58569. }
  58570. var bInfo;
  58571. if (this._particlesIntersect) {
  58572. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58573. }
  58574. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58575. // add the particle in the SPS
  58576. var currentPos = this._positions.length;
  58577. var currentInd = this._indices.length;
  58578. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58579. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58580. // initialize the particle position
  58581. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58582. this._index += shape.length;
  58583. idx++;
  58584. this.nbParticles++;
  58585. this._shapeCounter++;
  58586. f += size;
  58587. }
  58588. return this;
  58589. };
  58590. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58591. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58592. var index = 0;
  58593. var idx = 0;
  58594. for (var p = 0; p < this.particles.length; p++) {
  58595. this._particle = this.particles[p];
  58596. this._shape = this._particle._model._shape;
  58597. if (this._particle.rotationQuaternion) {
  58598. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58599. }
  58600. else {
  58601. this._yaw = this._particle.rotation.y;
  58602. this._pitch = this._particle.rotation.x;
  58603. this._roll = this._particle.rotation.z;
  58604. this._quaternionRotationYPR();
  58605. }
  58606. this._quaternionToRotationMatrix();
  58607. this._rotMatrix.invertToRef(this._invertMatrix);
  58608. for (var pt = 0; pt < this._shape.length; pt++) {
  58609. idx = index + pt * 3;
  58610. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58611. this._fixedNormal32[idx] = this._normal.x;
  58612. this._fixedNormal32[idx + 1] = this._normal.y;
  58613. this._fixedNormal32[idx + 2] = this._normal.z;
  58614. }
  58615. index = idx + 3;
  58616. }
  58617. };
  58618. //reset copy
  58619. SolidParticleSystem.prototype._resetCopy = function () {
  58620. this._copy.position.x = 0;
  58621. this._copy.position.y = 0;
  58622. this._copy.position.z = 0;
  58623. this._copy.rotation.x = 0;
  58624. this._copy.rotation.y = 0;
  58625. this._copy.rotation.z = 0;
  58626. this._copy.rotationQuaternion = null;
  58627. this._copy.scaling.x = 1.0;
  58628. this._copy.scaling.y = 1.0;
  58629. this._copy.scaling.z = 1.0;
  58630. this._copy.uvs.x = 0;
  58631. this._copy.uvs.y = 0;
  58632. this._copy.uvs.z = 1.0;
  58633. this._copy.uvs.w = 1.0;
  58634. this._copy.color = null;
  58635. this._copy.translateFromPivot = false;
  58636. };
  58637. // _meshBuilder : inserts the shape model in the global SPS mesh
  58638. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58639. var i;
  58640. var u = 0;
  58641. var c = 0;
  58642. var n = 0;
  58643. this._resetCopy();
  58644. if (options && options.positionFunction) { // call to custom positionFunction
  58645. options.positionFunction(this._copy, idx, idxInShape);
  58646. this._mustUnrotateFixedNormals = true;
  58647. }
  58648. if (this._copy.rotationQuaternion) {
  58649. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58650. }
  58651. else {
  58652. this._yaw = this._copy.rotation.y;
  58653. this._pitch = this._copy.rotation.x;
  58654. this._roll = this._copy.rotation.z;
  58655. this._quaternionRotationYPR();
  58656. }
  58657. this._quaternionToRotationMatrix();
  58658. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58659. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58660. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58661. if (this._copy.translateFromPivot) {
  58662. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58663. }
  58664. else {
  58665. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58666. }
  58667. for (i = 0; i < shape.length; i++) {
  58668. this._vertex.x = shape[i].x;
  58669. this._vertex.y = shape[i].y;
  58670. this._vertex.z = shape[i].z;
  58671. if (options && options.vertexFunction) {
  58672. options.vertexFunction(this._copy, this._vertex, i);
  58673. }
  58674. this._vertex.x *= this._copy.scaling.x;
  58675. this._vertex.y *= this._copy.scaling.y;
  58676. this._vertex.z *= this._copy.scaling.z;
  58677. this._vertex.x -= this._scaledPivot.x;
  58678. this._vertex.y -= this._scaledPivot.y;
  58679. this._vertex.z -= this._scaledPivot.z;
  58680. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58681. this._rotated.addInPlace(this._pivotBackTranslation);
  58682. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58683. if (meshUV) {
  58684. 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);
  58685. u += 2;
  58686. }
  58687. if (this._copy.color) {
  58688. this._color = this._copy.color;
  58689. }
  58690. else if (meshCol && meshCol[c] !== undefined) {
  58691. this._color.r = meshCol[c];
  58692. this._color.g = meshCol[c + 1];
  58693. this._color.b = meshCol[c + 2];
  58694. this._color.a = meshCol[c + 3];
  58695. }
  58696. else {
  58697. this._color.r = 1.0;
  58698. this._color.g = 1.0;
  58699. this._color.b = 1.0;
  58700. this._color.a = 1.0;
  58701. }
  58702. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58703. c += 4;
  58704. if (!this.recomputeNormals && meshNor) {
  58705. this._normal.x = meshNor[n];
  58706. this._normal.y = meshNor[n + 1];
  58707. this._normal.z = meshNor[n + 2];
  58708. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58709. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58710. n += 3;
  58711. }
  58712. }
  58713. for (i = 0; i < meshInd.length; i++) {
  58714. var current_ind = p + meshInd[i];
  58715. indices.push(current_ind);
  58716. if (current_ind > 65535) {
  58717. this._needs32Bits = true;
  58718. }
  58719. }
  58720. if (this._pickable) {
  58721. var nbfaces = meshInd.length / 3;
  58722. for (i = 0; i < nbfaces; i++) {
  58723. this.pickedParticles.push({ idx: idx, faceId: i });
  58724. }
  58725. }
  58726. if (this._depthSort) {
  58727. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58728. }
  58729. return this._copy;
  58730. };
  58731. // returns a shape array from positions array
  58732. SolidParticleSystem.prototype._posToShape = function (positions) {
  58733. var shape = [];
  58734. for (var i = 0; i < positions.length; i += 3) {
  58735. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58736. }
  58737. return shape;
  58738. };
  58739. // returns a shapeUV array from a Vector4 uvs
  58740. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58741. var shapeUV = [];
  58742. if (uvs) {
  58743. for (var i = 0; i < uvs.length; i++)
  58744. shapeUV.push(uvs[i]);
  58745. }
  58746. return shapeUV;
  58747. };
  58748. // adds a new particle object in the particles array
  58749. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58750. if (bInfo === void 0) { bInfo = null; }
  58751. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58752. this.particles.push(sp);
  58753. return sp;
  58754. };
  58755. /**
  58756. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58757. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58758. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58759. * @param nb (positive integer) the number of particles to be created from this model
  58760. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58761. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58762. * @returns the number of shapes in the system
  58763. */
  58764. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58765. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58766. var meshInd = mesh.getIndices();
  58767. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58768. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58769. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58770. var bbInfo;
  58771. if (this._particlesIntersect) {
  58772. bbInfo = mesh.getBoundingInfo();
  58773. }
  58774. var shape = this._posToShape(meshPos);
  58775. var shapeUV = this._uvsToShapeUV(meshUV);
  58776. var posfunc = options ? options.positionFunction : null;
  58777. var vtxfunc = options ? options.vertexFunction : null;
  58778. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58779. // particles
  58780. var sp;
  58781. var currentCopy;
  58782. var idx = this.nbParticles;
  58783. for (var i = 0; i < nb; i++) {
  58784. var currentPos = this._positions.length;
  58785. var currentInd = this._indices.length;
  58786. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58787. if (this._updatable) {
  58788. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58789. sp.position.copyFrom(currentCopy.position);
  58790. sp.rotation.copyFrom(currentCopy.rotation);
  58791. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58792. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58793. }
  58794. if (currentCopy.color && sp.color) {
  58795. sp.color.copyFrom(currentCopy.color);
  58796. }
  58797. sp.scaling.copyFrom(currentCopy.scaling);
  58798. sp.uvs.copyFrom(currentCopy.uvs);
  58799. }
  58800. this._index += shape.length;
  58801. idx++;
  58802. }
  58803. this.nbParticles += nb;
  58804. this._shapeCounter++;
  58805. return this._shapeCounter - 1;
  58806. };
  58807. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58808. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58809. this._resetCopy();
  58810. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58811. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58812. }
  58813. if (this._copy.rotationQuaternion) {
  58814. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58815. }
  58816. else {
  58817. this._yaw = this._copy.rotation.y;
  58818. this._pitch = this._copy.rotation.x;
  58819. this._roll = this._copy.rotation.z;
  58820. this._quaternionRotationYPR();
  58821. }
  58822. this._quaternionToRotationMatrix();
  58823. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58824. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58825. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58826. if (this._copy.translateFromPivot) {
  58827. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58828. }
  58829. else {
  58830. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58831. }
  58832. this._shape = particle._model._shape;
  58833. for (var pt = 0; pt < this._shape.length; pt++) {
  58834. this._vertex.x = this._shape[pt].x;
  58835. this._vertex.y = this._shape[pt].y;
  58836. this._vertex.z = this._shape[pt].z;
  58837. if (particle._model._vertexFunction) {
  58838. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58839. }
  58840. this._vertex.x *= this._copy.scaling.x;
  58841. this._vertex.y *= this._copy.scaling.y;
  58842. this._vertex.z *= this._copy.scaling.z;
  58843. this._vertex.x -= this._scaledPivot.x;
  58844. this._vertex.y -= this._scaledPivot.y;
  58845. this._vertex.z -= this._scaledPivot.z;
  58846. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58847. this._rotated.addInPlace(this._pivotBackTranslation);
  58848. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58849. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58850. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58851. }
  58852. particle.position.x = 0.0;
  58853. particle.position.y = 0.0;
  58854. particle.position.z = 0.0;
  58855. particle.rotation.x = 0.0;
  58856. particle.rotation.y = 0.0;
  58857. particle.rotation.z = 0.0;
  58858. particle.rotationQuaternion = null;
  58859. particle.scaling.x = 1.0;
  58860. particle.scaling.y = 1.0;
  58861. particle.scaling.z = 1.0;
  58862. particle.uvs.x = 0.0;
  58863. particle.uvs.y = 0.0;
  58864. particle.uvs.z = 1.0;
  58865. particle.uvs.w = 1.0;
  58866. particle.pivot.x = 0.0;
  58867. particle.pivot.y = 0.0;
  58868. particle.pivot.z = 0.0;
  58869. particle.translateFromPivot = false;
  58870. particle.parentId = null;
  58871. };
  58872. /**
  58873. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58874. * @returns the SPS.
  58875. */
  58876. SolidParticleSystem.prototype.rebuildMesh = function () {
  58877. for (var p = 0; p < this.particles.length; p++) {
  58878. this._rebuildParticle(this.particles[p]);
  58879. }
  58880. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58881. return this;
  58882. };
  58883. /**
  58884. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58885. * This method calls `updateParticle()` for each particle of the SPS.
  58886. * For an animated SPS, it is usually called within the render loop.
  58887. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58888. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58889. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58890. * @returns the SPS.
  58891. */
  58892. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58893. if (start === void 0) { start = 0; }
  58894. if (end === void 0) { end = this.nbParticles - 1; }
  58895. if (update === void 0) { update = true; }
  58896. if (!this._updatable) {
  58897. return this;
  58898. }
  58899. // custom beforeUpdate
  58900. this.beforeUpdateParticles(start, end, update);
  58901. this._cam_axisX.x = 1.0;
  58902. this._cam_axisX.y = 0.0;
  58903. this._cam_axisX.z = 0.0;
  58904. this._cam_axisY.x = 0.0;
  58905. this._cam_axisY.y = 1.0;
  58906. this._cam_axisY.z = 0.0;
  58907. this._cam_axisZ.x = 0.0;
  58908. this._cam_axisZ.y = 0.0;
  58909. this._cam_axisZ.z = 1.0;
  58910. // cases when the World Matrix is to be computed first
  58911. if (this.billboard || this._depthSort) {
  58912. this.mesh.computeWorldMatrix(true);
  58913. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58914. }
  58915. // if the particles will always face the camera
  58916. if (this.billboard) {
  58917. // compute the camera position and un-rotate it by the current mesh rotation
  58918. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58919. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58920. this._cam_axisZ.normalize();
  58921. // same for camera up vector extracted from the cam view matrix
  58922. var view = this._camera.getViewMatrix(true);
  58923. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58924. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58925. this._cam_axisY.normalize();
  58926. this._cam_axisX.normalize();
  58927. }
  58928. // if depthSort, compute the camera global position in the mesh local system
  58929. if (this._depthSort) {
  58930. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58931. }
  58932. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58933. var idx = 0; // current position index in the global array positions32
  58934. var index = 0; // position start index in the global array positions32 of the current particle
  58935. var colidx = 0; // current color index in the global array colors32
  58936. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58937. var uvidx = 0; // current uv index in the global array uvs32
  58938. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58939. var pt = 0; // current index in the particle model shape
  58940. if (this.mesh.isFacetDataEnabled) {
  58941. this._computeBoundingBox = true;
  58942. }
  58943. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58944. if (this._computeBoundingBox) {
  58945. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58946. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58947. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58948. }
  58949. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58950. if (this.mesh._boundingInfo) {
  58951. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58952. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58953. }
  58954. }
  58955. }
  58956. // particle loop
  58957. index = this.particles[start]._pos;
  58958. var vpos = (index / 3) | 0;
  58959. colorIndex = vpos * 4;
  58960. uvIndex = vpos * 2;
  58961. for (var p = start; p <= end; p++) {
  58962. this._particle = this.particles[p];
  58963. this._shape = this._particle._model._shape;
  58964. this._shapeUV = this._particle._model._shapeUV;
  58965. // call to custom user function to update the particle properties
  58966. this.updateParticle(this._particle);
  58967. // camera-particle distance for depth sorting
  58968. if (this._depthSort && this._depthSortParticles) {
  58969. var dsp = this.depthSortedParticles[p];
  58970. dsp.ind = this._particle._ind;
  58971. dsp.indicesLength = this._particle._model._indicesLength;
  58972. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58973. }
  58974. // skip the computations for inactive or already invisible particles
  58975. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58976. // increment indexes for the next particle
  58977. pt = this._shape.length;
  58978. index += pt * 3;
  58979. colorIndex += pt * 4;
  58980. uvIndex += pt * 2;
  58981. continue;
  58982. }
  58983. if (this._particle.isVisible) {
  58984. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58985. this._particleHasParent = (this._particle.parentId !== null);
  58986. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58987. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58988. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58989. // particle rotation matrix
  58990. if (this.billboard) {
  58991. this._particle.rotation.x = 0.0;
  58992. this._particle.rotation.y = 0.0;
  58993. }
  58994. if (this._computeParticleRotation || this.billboard) {
  58995. if (this._particle.rotationQuaternion) {
  58996. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58997. }
  58998. else {
  58999. this._yaw = this._particle.rotation.y;
  59000. this._pitch = this._particle.rotation.x;
  59001. this._roll = this._particle.rotation.z;
  59002. this._quaternionRotationYPR();
  59003. }
  59004. this._quaternionToRotationMatrix();
  59005. }
  59006. if (this._particleHasParent) {
  59007. this._parent = this.particles[this._particle.parentId];
  59008. 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];
  59009. 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];
  59010. 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];
  59011. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  59012. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  59013. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  59014. if (this._computeParticleRotation || this.billboard) {
  59015. 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];
  59016. 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];
  59017. 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];
  59018. 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];
  59019. 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];
  59020. 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];
  59021. 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];
  59022. 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];
  59023. 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];
  59024. }
  59025. }
  59026. else {
  59027. this._particle._globalPosition.x = this._particle.position.x;
  59028. this._particle._globalPosition.y = this._particle.position.y;
  59029. this._particle._globalPosition.z = this._particle.position.z;
  59030. if (this._computeParticleRotation || this.billboard) {
  59031. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  59032. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  59033. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  59034. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  59035. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  59036. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  59037. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  59038. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  59039. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  59040. }
  59041. }
  59042. if (this._particle.translateFromPivot) {
  59043. this._pivotBackTranslation.x = 0.0;
  59044. this._pivotBackTranslation.y = 0.0;
  59045. this._pivotBackTranslation.z = 0.0;
  59046. }
  59047. else {
  59048. this._pivotBackTranslation.x = this._scaledPivot.x;
  59049. this._pivotBackTranslation.y = this._scaledPivot.y;
  59050. this._pivotBackTranslation.z = this._scaledPivot.z;
  59051. }
  59052. // particle vertex loop
  59053. for (pt = 0; pt < this._shape.length; pt++) {
  59054. idx = index + pt * 3;
  59055. colidx = colorIndex + pt * 4;
  59056. uvidx = uvIndex + pt * 2;
  59057. this._vertex.x = this._shape[pt].x;
  59058. this._vertex.y = this._shape[pt].y;
  59059. this._vertex.z = this._shape[pt].z;
  59060. if (this._computeParticleVertex) {
  59061. this.updateParticleVertex(this._particle, this._vertex, pt);
  59062. }
  59063. // positions
  59064. this._vertex.x *= this._particle.scaling.x;
  59065. this._vertex.y *= this._particle.scaling.y;
  59066. this._vertex.z *= this._particle.scaling.z;
  59067. this._vertex.x -= this._scaledPivot.x;
  59068. this._vertex.y -= this._scaledPivot.y;
  59069. this._vertex.z -= this._scaledPivot.z;
  59070. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59071. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59072. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59073. this._rotated.x += this._pivotBackTranslation.x;
  59074. this._rotated.y += this._pivotBackTranslation.y;
  59075. this._rotated.z += this._pivotBackTranslation.z;
  59076. 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;
  59077. 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;
  59078. 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;
  59079. if (this._computeBoundingBox) {
  59080. if (this._positions32[idx] < this._minimum.x) {
  59081. this._minimum.x = this._positions32[idx];
  59082. }
  59083. if (this._positions32[idx] > this._maximum.x) {
  59084. this._maximum.x = this._positions32[idx];
  59085. }
  59086. if (this._positions32[idx + 1] < this._minimum.y) {
  59087. this._minimum.y = this._positions32[idx + 1];
  59088. }
  59089. if (this._positions32[idx + 1] > this._maximum.y) {
  59090. this._maximum.y = this._positions32[idx + 1];
  59091. }
  59092. if (this._positions32[idx + 2] < this._minimum.z) {
  59093. this._minimum.z = this._positions32[idx + 2];
  59094. }
  59095. if (this._positions32[idx + 2] > this._maximum.z) {
  59096. this._maximum.z = this._positions32[idx + 2];
  59097. }
  59098. }
  59099. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59100. if (!this._computeParticleVertex) {
  59101. this._normal.x = this._fixedNormal32[idx];
  59102. this._normal.y = this._fixedNormal32[idx + 1];
  59103. this._normal.z = this._fixedNormal32[idx + 2];
  59104. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59105. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59106. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59107. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59108. 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;
  59109. 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;
  59110. }
  59111. if (this._computeParticleColor && this._particle.color) {
  59112. this._colors32[colidx] = this._particle.color.r;
  59113. this._colors32[colidx + 1] = this._particle.color.g;
  59114. this._colors32[colidx + 2] = this._particle.color.b;
  59115. this._colors32[colidx + 3] = this._particle.color.a;
  59116. }
  59117. if (this._computeParticleTexture) {
  59118. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59119. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59120. }
  59121. }
  59122. }
  59123. // particle just set invisible : scaled to zero and positioned at the origin
  59124. else {
  59125. this._particle._stillInvisible = true; // mark the particle as invisible
  59126. for (pt = 0; pt < this._shape.length; pt++) {
  59127. idx = index + pt * 3;
  59128. colidx = colorIndex + pt * 4;
  59129. uvidx = uvIndex + pt * 2;
  59130. this._positions32[idx] = 0.0;
  59131. this._positions32[idx + 1] = 0.0;
  59132. this._positions32[idx + 2] = 0.0;
  59133. this._normals32[idx] = 0.0;
  59134. this._normals32[idx + 1] = 0.0;
  59135. this._normals32[idx + 2] = 0.0;
  59136. if (this._computeParticleColor && this._particle.color) {
  59137. this._colors32[colidx] = this._particle.color.r;
  59138. this._colors32[colidx + 1] = this._particle.color.g;
  59139. this._colors32[colidx + 2] = this._particle.color.b;
  59140. this._colors32[colidx + 3] = this._particle.color.a;
  59141. }
  59142. if (this._computeParticleTexture) {
  59143. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59144. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59145. }
  59146. }
  59147. }
  59148. // if the particle intersections must be computed : update the bbInfo
  59149. if (this._particlesIntersect) {
  59150. var bInfo = this._particle._boundingInfo;
  59151. var bBox = bInfo.boundingBox;
  59152. var bSphere = bInfo.boundingSphere;
  59153. if (!this._bSphereOnly) {
  59154. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59155. for (var b = 0; b < bBox.vectors.length; b++) {
  59156. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59157. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59158. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59159. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59160. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59161. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59162. 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;
  59163. 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;
  59164. 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;
  59165. }
  59166. bBox._update(this.mesh._worldMatrix);
  59167. }
  59168. // place and scale the particle bouding sphere in the SPS local system, then update it
  59169. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59170. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59171. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59172. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59173. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59174. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59175. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59176. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59177. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59178. 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));
  59179. bSphere._update(this.mesh._worldMatrix);
  59180. }
  59181. // increment indexes for the next particle
  59182. index = idx + 3;
  59183. colorIndex = colidx + 4;
  59184. uvIndex = uvidx + 2;
  59185. }
  59186. // if the VBO must be updated
  59187. if (update) {
  59188. if (this._computeParticleColor) {
  59189. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59190. }
  59191. if (this._computeParticleTexture) {
  59192. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59193. }
  59194. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59195. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59196. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59197. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59198. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59199. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59200. for (var i = 0; i < this._normals32.length; i++) {
  59201. this._fixedNormal32[i] = this._normals32[i];
  59202. }
  59203. }
  59204. if (!this.mesh.areNormalsFrozen) {
  59205. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59206. }
  59207. }
  59208. if (this._depthSort && this._depthSortParticles) {
  59209. this.depthSortedParticles.sort(this._depthSortFunction);
  59210. var dspl = this.depthSortedParticles.length;
  59211. var sorted = 0;
  59212. var lind = 0;
  59213. var sind = 0;
  59214. var sid = 0;
  59215. for (sorted = 0; sorted < dspl; sorted++) {
  59216. lind = this.depthSortedParticles[sorted].indicesLength;
  59217. sind = this.depthSortedParticles[sorted].ind;
  59218. for (var i = 0; i < lind; i++) {
  59219. this._indices32[sid] = this._indices[sind + i];
  59220. sid++;
  59221. }
  59222. }
  59223. this.mesh.updateIndices(this._indices32);
  59224. }
  59225. }
  59226. if (this._computeBoundingBox) {
  59227. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59228. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59229. }
  59230. this.afterUpdateParticles(start, end, update);
  59231. return this;
  59232. };
  59233. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59234. this._halfroll = this._roll * 0.5;
  59235. this._halfpitch = this._pitch * 0.5;
  59236. this._halfyaw = this._yaw * 0.5;
  59237. this._sinRoll = Math.sin(this._halfroll);
  59238. this._cosRoll = Math.cos(this._halfroll);
  59239. this._sinPitch = Math.sin(this._halfpitch);
  59240. this._cosPitch = Math.cos(this._halfpitch);
  59241. this._sinYaw = Math.sin(this._halfyaw);
  59242. this._cosYaw = Math.cos(this._halfyaw);
  59243. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59244. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59245. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59246. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59247. };
  59248. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59249. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59250. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59251. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59252. this._rotMatrix.m[3] = 0;
  59253. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59254. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59255. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59256. this._rotMatrix.m[7] = 0;
  59257. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59258. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59259. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59260. this._rotMatrix.m[11] = 0;
  59261. this._rotMatrix.m[12] = 0;
  59262. this._rotMatrix.m[13] = 0;
  59263. this._rotMatrix.m[14] = 0;
  59264. this._rotMatrix.m[15] = 1.0;
  59265. };
  59266. /**
  59267. * Disposes the SPS.
  59268. */
  59269. SolidParticleSystem.prototype.dispose = function () {
  59270. this.mesh.dispose();
  59271. this.vars = null;
  59272. // drop references to internal big arrays for the GC
  59273. this._positions = null;
  59274. this._indices = null;
  59275. this._normals = null;
  59276. this._uvs = null;
  59277. this._colors = null;
  59278. this._indices32 = null;
  59279. this._positions32 = null;
  59280. this._normals32 = null;
  59281. this._fixedNormal32 = null;
  59282. this._uvs32 = null;
  59283. this._colors32 = null;
  59284. this.pickedParticles = null;
  59285. };
  59286. /**
  59287. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59288. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59289. * @returns the SPS.
  59290. */
  59291. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59292. if (!this._isVisibilityBoxLocked) {
  59293. this.mesh.refreshBoundingInfo();
  59294. }
  59295. return this;
  59296. };
  59297. /**
  59298. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59299. * @param size the size (float) of the visibility box
  59300. * note : this doesn't lock the SPS mesh bounding box.
  59301. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59302. */
  59303. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59304. var vis = size / 2;
  59305. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59306. };
  59307. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59308. /**
  59309. * Gets whether the SPS as always visible or not
  59310. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59311. */
  59312. get: function () {
  59313. return this._alwaysVisible;
  59314. },
  59315. /**
  59316. * Sets the SPS as always visible or not
  59317. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59318. */
  59319. set: function (val) {
  59320. this._alwaysVisible = val;
  59321. this.mesh.alwaysSelectAsActiveMesh = val;
  59322. },
  59323. enumerable: true,
  59324. configurable: true
  59325. });
  59326. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59327. /**
  59328. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59329. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59330. */
  59331. get: function () {
  59332. return this._isVisibilityBoxLocked;
  59333. },
  59334. /**
  59335. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59336. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59337. */
  59338. set: function (val) {
  59339. this._isVisibilityBoxLocked = val;
  59340. var boundingInfo = this.mesh.getBoundingInfo();
  59341. boundingInfo.isLocked = val;
  59342. },
  59343. enumerable: true,
  59344. configurable: true
  59345. });
  59346. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59347. /**
  59348. * Gets if `setParticles()` computes the particle rotations or not.
  59349. * Default value : true. The SPS is faster when it's set to false.
  59350. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59351. */
  59352. get: function () {
  59353. return this._computeParticleRotation;
  59354. },
  59355. /**
  59356. * Tells to `setParticles()` to compute the particle rotations or not.
  59357. * Default value : true. The SPS is faster when it's set to false.
  59358. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59359. */
  59360. set: function (val) {
  59361. this._computeParticleRotation = val;
  59362. },
  59363. enumerable: true,
  59364. configurable: true
  59365. });
  59366. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59367. /**
  59368. * Gets if `setParticles()` computes the particle colors or not.
  59369. * Default value : true. The SPS is faster when it's set to false.
  59370. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59371. */
  59372. get: function () {
  59373. return this._computeParticleColor;
  59374. },
  59375. /**
  59376. * Tells to `setParticles()` to compute the particle colors or not.
  59377. * Default value : true. The SPS is faster when it's set to false.
  59378. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59379. */
  59380. set: function (val) {
  59381. this._computeParticleColor = val;
  59382. },
  59383. enumerable: true,
  59384. configurable: true
  59385. });
  59386. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59387. /**
  59388. * Gets if `setParticles()` computes the particle textures or not.
  59389. * Default value : true. The SPS is faster when it's set to false.
  59390. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59391. */
  59392. get: function () {
  59393. return this._computeParticleTexture;
  59394. },
  59395. set: function (val) {
  59396. this._computeParticleTexture = val;
  59397. },
  59398. enumerable: true,
  59399. configurable: true
  59400. });
  59401. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59402. /**
  59403. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59404. * Default value : false. The SPS is faster when it's set to false.
  59405. * Note : the particle custom vertex positions aren't stored values.
  59406. */
  59407. get: function () {
  59408. return this._computeParticleVertex;
  59409. },
  59410. /**
  59411. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59412. * Default value : false. The SPS is faster when it's set to false.
  59413. * Note : the particle custom vertex positions aren't stored values.
  59414. */
  59415. set: function (val) {
  59416. this._computeParticleVertex = val;
  59417. },
  59418. enumerable: true,
  59419. configurable: true
  59420. });
  59421. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59422. /**
  59423. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59424. */
  59425. get: function () {
  59426. return this._computeBoundingBox;
  59427. },
  59428. /**
  59429. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59430. */
  59431. set: function (val) {
  59432. this._computeBoundingBox = val;
  59433. },
  59434. enumerable: true,
  59435. configurable: true
  59436. });
  59437. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59438. /**
  59439. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59440. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59441. * Default : `true`
  59442. */
  59443. get: function () {
  59444. return this._depthSortParticles;
  59445. },
  59446. /**
  59447. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59448. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59449. * Default : `true`
  59450. */
  59451. set: function (val) {
  59452. this._depthSortParticles = val;
  59453. },
  59454. enumerable: true,
  59455. configurable: true
  59456. });
  59457. // =======================================================================
  59458. // Particle behavior logic
  59459. // these following methods may be overwritten by the user to fit his needs
  59460. /**
  59461. * This function does nothing. It may be overwritten to set all the particle first values.
  59462. * The SPS doesn't call this function, you may have to call it by your own.
  59463. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59464. */
  59465. SolidParticleSystem.prototype.initParticles = function () {
  59466. };
  59467. /**
  59468. * This function does nothing. It may be overwritten to recycle a particle.
  59469. * The SPS doesn't call this function, you may have to call it by your own.
  59470. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59471. * @param particle The particle to recycle
  59472. * @returns the recycled particle
  59473. */
  59474. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59475. return particle;
  59476. };
  59477. /**
  59478. * Updates a particle : this function should be overwritten by the user.
  59479. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59480. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59481. * @example : just set a particle position or velocity and recycle conditions
  59482. * @param particle The particle to update
  59483. * @returns the updated particle
  59484. */
  59485. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59486. return particle;
  59487. };
  59488. /**
  59489. * Updates a vertex of a particle : it can be overwritten by the user.
  59490. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59491. * @param particle the current particle
  59492. * @param vertex the current index of the current particle
  59493. * @param pt the index of the current vertex in the particle shape
  59494. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59495. * @example : just set a vertex particle position
  59496. * @returns the updated vertex
  59497. */
  59498. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59499. return vertex;
  59500. };
  59501. /**
  59502. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59503. * This does nothing and may be overwritten by the user.
  59504. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59505. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59506. * @param update the boolean update value actually passed to setParticles()
  59507. */
  59508. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59509. };
  59510. /**
  59511. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59512. * This will be passed three parameters.
  59513. * This does nothing and may be overwritten by the user.
  59514. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59515. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59516. * @param update the boolean update value actually passed to setParticles()
  59517. */
  59518. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59519. };
  59520. return SolidParticleSystem;
  59521. }());
  59522. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59523. })(BABYLON || (BABYLON = {}));
  59524. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59525. var BABYLON;
  59526. (function (BABYLON) {
  59527. var ShaderMaterial = /** @class */ (function (_super) {
  59528. __extends(ShaderMaterial, _super);
  59529. function ShaderMaterial(name, scene, shaderPath, options) {
  59530. var _this = _super.call(this, name, scene) || this;
  59531. _this._textures = {};
  59532. _this._textureArrays = {};
  59533. _this._floats = {};
  59534. _this._ints = {};
  59535. _this._floatsArrays = {};
  59536. _this._colors3 = {};
  59537. _this._colors3Arrays = {};
  59538. _this._colors4 = {};
  59539. _this._vectors2 = {};
  59540. _this._vectors3 = {};
  59541. _this._vectors4 = {};
  59542. _this._matrices = {};
  59543. _this._matrices3x3 = {};
  59544. _this._matrices2x2 = {};
  59545. _this._vectors2Arrays = {};
  59546. _this._vectors3Arrays = {};
  59547. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59548. _this._shaderPath = shaderPath;
  59549. options.needAlphaBlending = options.needAlphaBlending || false;
  59550. options.needAlphaTesting = options.needAlphaTesting || false;
  59551. options.attributes = options.attributes || ["position", "normal", "uv"];
  59552. options.uniforms = options.uniforms || ["worldViewProjection"];
  59553. options.uniformBuffers = options.uniformBuffers || [];
  59554. options.samplers = options.samplers || [];
  59555. options.defines = options.defines || [];
  59556. _this._options = options;
  59557. return _this;
  59558. }
  59559. ShaderMaterial.prototype.getClassName = function () {
  59560. return "ShaderMaterial";
  59561. };
  59562. ShaderMaterial.prototype.needAlphaBlending = function () {
  59563. return this._options.needAlphaBlending;
  59564. };
  59565. ShaderMaterial.prototype.needAlphaTesting = function () {
  59566. return this._options.needAlphaTesting;
  59567. };
  59568. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59569. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59570. this._options.uniforms.push(uniformName);
  59571. }
  59572. };
  59573. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59574. if (this._options.samplers.indexOf(name) === -1) {
  59575. this._options.samplers.push(name);
  59576. }
  59577. this._textures[name] = texture;
  59578. return this;
  59579. };
  59580. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59581. if (this._options.samplers.indexOf(name) === -1) {
  59582. this._options.samplers.push(name);
  59583. }
  59584. this._checkUniform(name);
  59585. this._textureArrays[name] = textures;
  59586. return this;
  59587. };
  59588. ShaderMaterial.prototype.setFloat = function (name, value) {
  59589. this._checkUniform(name);
  59590. this._floats[name] = value;
  59591. return this;
  59592. };
  59593. ShaderMaterial.prototype.setInt = function (name, value) {
  59594. this._checkUniform(name);
  59595. this._ints[name] = value;
  59596. return this;
  59597. };
  59598. ShaderMaterial.prototype.setFloats = function (name, value) {
  59599. this._checkUniform(name);
  59600. this._floatsArrays[name] = value;
  59601. return this;
  59602. };
  59603. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59604. this._checkUniform(name);
  59605. this._colors3[name] = value;
  59606. return this;
  59607. };
  59608. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59609. this._checkUniform(name);
  59610. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59611. color.toArray(arr, arr.length);
  59612. return arr;
  59613. }, []);
  59614. return this;
  59615. };
  59616. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59617. this._checkUniform(name);
  59618. this._colors4[name] = value;
  59619. return this;
  59620. };
  59621. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59622. this._checkUniform(name);
  59623. this._vectors2[name] = value;
  59624. return this;
  59625. };
  59626. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59627. this._checkUniform(name);
  59628. this._vectors3[name] = value;
  59629. return this;
  59630. };
  59631. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59632. this._checkUniform(name);
  59633. this._vectors4[name] = value;
  59634. return this;
  59635. };
  59636. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59637. this._checkUniform(name);
  59638. this._matrices[name] = value;
  59639. return this;
  59640. };
  59641. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59642. this._checkUniform(name);
  59643. this._matrices3x3[name] = value;
  59644. return this;
  59645. };
  59646. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59647. this._checkUniform(name);
  59648. this._matrices2x2[name] = value;
  59649. return this;
  59650. };
  59651. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59652. this._checkUniform(name);
  59653. this._vectors2Arrays[name] = value;
  59654. return this;
  59655. };
  59656. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59657. this._checkUniform(name);
  59658. this._vectors3Arrays[name] = value;
  59659. return this;
  59660. };
  59661. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59662. if (!mesh) {
  59663. return true;
  59664. }
  59665. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59666. return false;
  59667. }
  59668. return false;
  59669. };
  59670. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59671. var scene = this.getScene();
  59672. var engine = scene.getEngine();
  59673. if (!this.checkReadyOnEveryCall) {
  59674. if (this._renderId === scene.getRenderId()) {
  59675. if (this._checkCache(scene, mesh, useInstances)) {
  59676. return true;
  59677. }
  59678. }
  59679. }
  59680. // Instances
  59681. var defines = [];
  59682. var attribs = [];
  59683. var fallbacks = new BABYLON.EffectFallbacks();
  59684. if (useInstances) {
  59685. defines.push("#define INSTANCES");
  59686. }
  59687. for (var index = 0; index < this._options.defines.length; index++) {
  59688. defines.push(this._options.defines[index]);
  59689. }
  59690. for (var index = 0; index < this._options.attributes.length; index++) {
  59691. attribs.push(this._options.attributes[index]);
  59692. }
  59693. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59694. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59695. defines.push("#define VERTEXCOLOR");
  59696. }
  59697. // Bones
  59698. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59699. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59700. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59701. if (mesh.numBoneInfluencers > 4) {
  59702. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59703. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59704. }
  59705. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59706. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59707. fallbacks.addCPUSkinningFallback(0, mesh);
  59708. if (this._options.uniforms.indexOf("mBones") === -1) {
  59709. this._options.uniforms.push("mBones");
  59710. }
  59711. }
  59712. else {
  59713. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59714. }
  59715. // Textures
  59716. for (var name in this._textures) {
  59717. if (!this._textures[name].isReady()) {
  59718. return false;
  59719. }
  59720. }
  59721. // Alpha test
  59722. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59723. defines.push("#define ALPHATEST");
  59724. }
  59725. var previousEffect = this._effect;
  59726. var join = defines.join("\n");
  59727. this._effect = engine.createEffect(this._shaderPath, {
  59728. attributes: attribs,
  59729. uniformsNames: this._options.uniforms,
  59730. uniformBuffersNames: this._options.uniformBuffers,
  59731. samplers: this._options.samplers,
  59732. defines: join,
  59733. fallbacks: fallbacks,
  59734. onCompiled: this.onCompiled,
  59735. onError: this.onError
  59736. }, engine);
  59737. if (!this._effect.isReady()) {
  59738. return false;
  59739. }
  59740. if (previousEffect !== this._effect) {
  59741. scene.resetCachedMaterial();
  59742. }
  59743. this._renderId = scene.getRenderId();
  59744. return true;
  59745. };
  59746. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59747. var scene = this.getScene();
  59748. if (!this._effect) {
  59749. return;
  59750. }
  59751. if (this._options.uniforms.indexOf("world") !== -1) {
  59752. this._effect.setMatrix("world", world);
  59753. }
  59754. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59755. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59756. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59757. }
  59758. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59759. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59760. }
  59761. };
  59762. ShaderMaterial.prototype.bind = function (world, mesh) {
  59763. // Std values
  59764. this.bindOnlyWorldMatrix(world);
  59765. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59766. if (this._options.uniforms.indexOf("view") !== -1) {
  59767. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59768. }
  59769. if (this._options.uniforms.indexOf("projection") !== -1) {
  59770. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59771. }
  59772. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59773. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59774. }
  59775. // Bones
  59776. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59777. var name;
  59778. // Texture
  59779. for (name in this._textures) {
  59780. this._effect.setTexture(name, this._textures[name]);
  59781. }
  59782. // Texture arrays
  59783. for (name in this._textureArrays) {
  59784. this._effect.setTextureArray(name, this._textureArrays[name]);
  59785. }
  59786. // Int
  59787. for (name in this._ints) {
  59788. this._effect.setInt(name, this._ints[name]);
  59789. }
  59790. // Float
  59791. for (name in this._floats) {
  59792. this._effect.setFloat(name, this._floats[name]);
  59793. }
  59794. // Floats
  59795. for (name in this._floatsArrays) {
  59796. this._effect.setArray(name, this._floatsArrays[name]);
  59797. }
  59798. // Color3
  59799. for (name in this._colors3) {
  59800. this._effect.setColor3(name, this._colors3[name]);
  59801. }
  59802. for (name in this._colors3Arrays) {
  59803. this._effect.setArray3(name, this._colors3Arrays[name]);
  59804. }
  59805. // Color4
  59806. for (name in this._colors4) {
  59807. var color = this._colors4[name];
  59808. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59809. }
  59810. // Vector2
  59811. for (name in this._vectors2) {
  59812. this._effect.setVector2(name, this._vectors2[name]);
  59813. }
  59814. // Vector3
  59815. for (name in this._vectors3) {
  59816. this._effect.setVector3(name, this._vectors3[name]);
  59817. }
  59818. // Vector4
  59819. for (name in this._vectors4) {
  59820. this._effect.setVector4(name, this._vectors4[name]);
  59821. }
  59822. // Matrix
  59823. for (name in this._matrices) {
  59824. this._effect.setMatrix(name, this._matrices[name]);
  59825. }
  59826. // Matrix 3x3
  59827. for (name in this._matrices3x3) {
  59828. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59829. }
  59830. // Matrix 2x2
  59831. for (name in this._matrices2x2) {
  59832. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59833. }
  59834. // Vector2Array
  59835. for (name in this._vectors2Arrays) {
  59836. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59837. }
  59838. // Vector3Array
  59839. for (name in this._vectors3Arrays) {
  59840. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59841. }
  59842. }
  59843. this._afterBind(mesh);
  59844. };
  59845. ShaderMaterial.prototype.getActiveTextures = function () {
  59846. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59847. for (var name in this._textures) {
  59848. activeTextures.push(this._textures[name]);
  59849. }
  59850. for (var name in this._textureArrays) {
  59851. var array = this._textureArrays[name];
  59852. for (var index = 0; index < array.length; index++) {
  59853. activeTextures.push(array[index]);
  59854. }
  59855. }
  59856. return activeTextures;
  59857. };
  59858. ShaderMaterial.prototype.hasTexture = function (texture) {
  59859. if (_super.prototype.hasTexture.call(this, texture)) {
  59860. return true;
  59861. }
  59862. for (var name in this._textures) {
  59863. if (this._textures[name] === texture) {
  59864. return true;
  59865. }
  59866. }
  59867. for (var name in this._textureArrays) {
  59868. var array = this._textureArrays[name];
  59869. for (var index = 0; index < array.length; index++) {
  59870. if (array[index] === texture) {
  59871. return true;
  59872. }
  59873. }
  59874. }
  59875. return false;
  59876. };
  59877. ShaderMaterial.prototype.clone = function (name) {
  59878. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59879. return newShaderMaterial;
  59880. };
  59881. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59882. if (forceDisposeTextures) {
  59883. var name;
  59884. for (name in this._textures) {
  59885. this._textures[name].dispose();
  59886. }
  59887. for (name in this._textureArrays) {
  59888. var array = this._textureArrays[name];
  59889. for (var index = 0; index < array.length; index++) {
  59890. array[index].dispose();
  59891. }
  59892. }
  59893. }
  59894. this._textures = {};
  59895. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59896. };
  59897. ShaderMaterial.prototype.serialize = function () {
  59898. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59899. serializationObject.customType = "BABYLON.ShaderMaterial";
  59900. serializationObject.options = this._options;
  59901. serializationObject.shaderPath = this._shaderPath;
  59902. var name;
  59903. // Texture
  59904. serializationObject.textures = {};
  59905. for (name in this._textures) {
  59906. serializationObject.textures[name] = this._textures[name].serialize();
  59907. }
  59908. // Texture arrays
  59909. serializationObject.textureArrays = {};
  59910. for (name in this._textureArrays) {
  59911. serializationObject.textureArrays[name] = [];
  59912. var array = this._textureArrays[name];
  59913. for (var index = 0; index < array.length; index++) {
  59914. serializationObject.textureArrays[name].push(array[index].serialize());
  59915. }
  59916. }
  59917. // Float
  59918. serializationObject.floats = {};
  59919. for (name in this._floats) {
  59920. serializationObject.floats[name] = this._floats[name];
  59921. }
  59922. // Float s
  59923. serializationObject.FloatArrays = {};
  59924. for (name in this._floatsArrays) {
  59925. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59926. }
  59927. // Color3
  59928. serializationObject.colors3 = {};
  59929. for (name in this._colors3) {
  59930. serializationObject.colors3[name] = this._colors3[name].asArray();
  59931. }
  59932. // Color3 array
  59933. serializationObject.colors3Arrays = {};
  59934. for (name in this._colors3Arrays) {
  59935. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59936. }
  59937. // Color4
  59938. serializationObject.colors4 = {};
  59939. for (name in this._colors4) {
  59940. serializationObject.colors4[name] = this._colors4[name].asArray();
  59941. }
  59942. // Vector2
  59943. serializationObject.vectors2 = {};
  59944. for (name in this._vectors2) {
  59945. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59946. }
  59947. // Vector3
  59948. serializationObject.vectors3 = {};
  59949. for (name in this._vectors3) {
  59950. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59951. }
  59952. // Vector4
  59953. serializationObject.vectors4 = {};
  59954. for (name in this._vectors4) {
  59955. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59956. }
  59957. // Matrix
  59958. serializationObject.matrices = {};
  59959. for (name in this._matrices) {
  59960. serializationObject.matrices[name] = this._matrices[name].asArray();
  59961. }
  59962. // Matrix 3x3
  59963. serializationObject.matrices3x3 = {};
  59964. for (name in this._matrices3x3) {
  59965. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59966. }
  59967. // Matrix 2x2
  59968. serializationObject.matrices2x2 = {};
  59969. for (name in this._matrices2x2) {
  59970. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59971. }
  59972. // Vector2Array
  59973. serializationObject.vectors2Arrays = {};
  59974. for (name in this._vectors2Arrays) {
  59975. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59976. }
  59977. // Vector3Array
  59978. serializationObject.vectors3Arrays = {};
  59979. for (name in this._vectors3Arrays) {
  59980. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59981. }
  59982. return serializationObject;
  59983. };
  59984. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59985. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59986. var name;
  59987. // Texture
  59988. for (name in source.textures) {
  59989. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59990. }
  59991. // Texture arrays
  59992. for (name in source.textureArrays) {
  59993. var array = source.textureArrays[name];
  59994. var textureArray = new Array();
  59995. for (var index = 0; index < array.length; index++) {
  59996. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59997. }
  59998. material.setTextureArray(name, textureArray);
  59999. }
  60000. // Float
  60001. for (name in source.floats) {
  60002. material.setFloat(name, source.floats[name]);
  60003. }
  60004. // Float s
  60005. for (name in source.floatsArrays) {
  60006. material.setFloats(name, source.floatsArrays[name]);
  60007. }
  60008. // Color3
  60009. for (name in source.colors3) {
  60010. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60011. }
  60012. // Color3 arrays
  60013. for (name in source.colors3Arrays) {
  60014. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60015. if (i % 3 === 0) {
  60016. arr.push([num]);
  60017. }
  60018. else {
  60019. arr[arr.length - 1].push(num);
  60020. }
  60021. return arr;
  60022. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60023. material.setColor3Array(name, colors);
  60024. }
  60025. // Color4
  60026. for (name in source.colors4) {
  60027. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60028. }
  60029. // Vector2
  60030. for (name in source.vectors2) {
  60031. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60032. }
  60033. // Vector3
  60034. for (name in source.vectors3) {
  60035. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60036. }
  60037. // Vector4
  60038. for (name in source.vectors4) {
  60039. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60040. }
  60041. // Matrix
  60042. for (name in source.matrices) {
  60043. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60044. }
  60045. // Matrix 3x3
  60046. for (name in source.matrices3x3) {
  60047. material.setMatrix3x3(name, source.matrices3x3[name]);
  60048. }
  60049. // Matrix 2x2
  60050. for (name in source.matrices2x2) {
  60051. material.setMatrix2x2(name, source.matrices2x2[name]);
  60052. }
  60053. // Vector2Array
  60054. for (name in source.vectors2Arrays) {
  60055. material.setArray2(name, source.vectors2Arrays[name]);
  60056. }
  60057. // Vector3Array
  60058. for (name in source.vectors3Arrays) {
  60059. material.setArray3(name, source.vectors3Arrays[name]);
  60060. }
  60061. return material;
  60062. };
  60063. return ShaderMaterial;
  60064. }(BABYLON.Material));
  60065. BABYLON.ShaderMaterial = ShaderMaterial;
  60066. })(BABYLON || (BABYLON = {}));
  60067. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60068. var BABYLON;
  60069. (function (BABYLON) {
  60070. var GroundMesh = /** @class */ (function (_super) {
  60071. __extends(GroundMesh, _super);
  60072. function GroundMesh(name, scene) {
  60073. var _this = _super.call(this, name, scene) || this;
  60074. _this.generateOctree = false;
  60075. return _this;
  60076. }
  60077. GroundMesh.prototype.getClassName = function () {
  60078. return "GroundMesh";
  60079. };
  60080. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60081. get: function () {
  60082. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60083. },
  60084. enumerable: true,
  60085. configurable: true
  60086. });
  60087. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60088. get: function () {
  60089. return this._subdivisionsX;
  60090. },
  60091. enumerable: true,
  60092. configurable: true
  60093. });
  60094. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60095. get: function () {
  60096. return this._subdivisionsY;
  60097. },
  60098. enumerable: true,
  60099. configurable: true
  60100. });
  60101. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60102. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60103. this._subdivisionsX = chunksCount;
  60104. this._subdivisionsY = chunksCount;
  60105. this.subdivide(chunksCount);
  60106. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60107. };
  60108. /**
  60109. * Returns a height (y) value in the Worl system :
  60110. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60111. * Returns the ground y position if (x, z) are outside the ground surface.
  60112. */
  60113. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60114. var world = this.getWorldMatrix();
  60115. var invMat = BABYLON.Tmp.Matrix[5];
  60116. world.invertToRef(invMat);
  60117. var tmpVect = BABYLON.Tmp.Vector3[8];
  60118. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60119. x = tmpVect.x;
  60120. z = tmpVect.z;
  60121. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60122. return this.position.y;
  60123. }
  60124. if (!this._heightQuads || this._heightQuads.length == 0) {
  60125. this._initHeightQuads();
  60126. this._computeHeightQuads();
  60127. }
  60128. var facet = this._getFacetAt(x, z);
  60129. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60130. // return y in the World system
  60131. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60132. return tmpVect.y;
  60133. };
  60134. /**
  60135. * Returns a normalized vector (Vector3) orthogonal to the ground
  60136. * at the ground coordinates (x, z) expressed in the World system.
  60137. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60138. */
  60139. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60140. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60141. this.getNormalAtCoordinatesToRef(x, z, normal);
  60142. return normal;
  60143. };
  60144. /**
  60145. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60146. * at the ground coordinates (x, z) expressed in the World system.
  60147. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60148. * Returns the GroundMesh.
  60149. */
  60150. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60151. var world = this.getWorldMatrix();
  60152. var tmpMat = BABYLON.Tmp.Matrix[5];
  60153. world.invertToRef(tmpMat);
  60154. var tmpVect = BABYLON.Tmp.Vector3[8];
  60155. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60156. x = tmpVect.x;
  60157. z = tmpVect.z;
  60158. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60159. return this;
  60160. }
  60161. if (!this._heightQuads || this._heightQuads.length == 0) {
  60162. this._initHeightQuads();
  60163. this._computeHeightQuads();
  60164. }
  60165. var facet = this._getFacetAt(x, z);
  60166. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60167. return this;
  60168. };
  60169. /**
  60170. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60171. * if the ground has been updated.
  60172. * This can be used in the render loop.
  60173. * Returns the GroundMesh.
  60174. */
  60175. GroundMesh.prototype.updateCoordinateHeights = function () {
  60176. if (!this._heightQuads || this._heightQuads.length == 0) {
  60177. this._initHeightQuads();
  60178. }
  60179. this._computeHeightQuads();
  60180. return this;
  60181. };
  60182. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60183. GroundMesh.prototype._getFacetAt = function (x, z) {
  60184. // retrieve col and row from x, z coordinates in the ground local system
  60185. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60186. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60187. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60188. var facet;
  60189. if (z < quad.slope.x * x + quad.slope.y) {
  60190. facet = quad.facet1;
  60191. }
  60192. else {
  60193. facet = quad.facet2;
  60194. }
  60195. return facet;
  60196. };
  60197. // Creates and populates the heightMap array with "facet" elements :
  60198. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60199. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60200. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60201. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60202. // Returns the GroundMesh.
  60203. GroundMesh.prototype._initHeightQuads = function () {
  60204. var subdivisionsX = this._subdivisionsX;
  60205. var subdivisionsY = this._subdivisionsY;
  60206. this._heightQuads = new Array();
  60207. for (var row = 0; row < subdivisionsY; row++) {
  60208. for (var col = 0; col < subdivisionsX; col++) {
  60209. 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) };
  60210. this._heightQuads[row * subdivisionsX + col] = quad;
  60211. }
  60212. }
  60213. return this;
  60214. };
  60215. // Compute each quad element values and update the the heightMap array :
  60216. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60217. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60218. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60219. // Returns the GroundMesh.
  60220. GroundMesh.prototype._computeHeightQuads = function () {
  60221. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60222. if (!positions) {
  60223. return this;
  60224. }
  60225. var v1 = BABYLON.Tmp.Vector3[3];
  60226. var v2 = BABYLON.Tmp.Vector3[2];
  60227. var v3 = BABYLON.Tmp.Vector3[1];
  60228. var v4 = BABYLON.Tmp.Vector3[0];
  60229. var v1v2 = BABYLON.Tmp.Vector3[4];
  60230. var v1v3 = BABYLON.Tmp.Vector3[5];
  60231. var v1v4 = BABYLON.Tmp.Vector3[6];
  60232. var norm1 = BABYLON.Tmp.Vector3[7];
  60233. var norm2 = BABYLON.Tmp.Vector3[8];
  60234. var i = 0;
  60235. var j = 0;
  60236. var k = 0;
  60237. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60238. var h = 0;
  60239. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60240. var d2 = 0;
  60241. var subdivisionsX = this._subdivisionsX;
  60242. var subdivisionsY = this._subdivisionsY;
  60243. for (var row = 0; row < subdivisionsY; row++) {
  60244. for (var col = 0; col < subdivisionsX; col++) {
  60245. i = col * 3;
  60246. j = row * (subdivisionsX + 1) * 3;
  60247. k = (row + 1) * (subdivisionsX + 1) * 3;
  60248. v1.x = positions[j + i];
  60249. v1.y = positions[j + i + 1];
  60250. v1.z = positions[j + i + 2];
  60251. v2.x = positions[j + i + 3];
  60252. v2.y = positions[j + i + 4];
  60253. v2.z = positions[j + i + 5];
  60254. v3.x = positions[k + i];
  60255. v3.y = positions[k + i + 1];
  60256. v3.z = positions[k + i + 2];
  60257. v4.x = positions[k + i + 3];
  60258. v4.y = positions[k + i + 4];
  60259. v4.z = positions[k + i + 5];
  60260. // 2D slope V1V4
  60261. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60262. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60263. // facet equations :
  60264. // we compute each facet normal vector
  60265. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60266. // we compute the value d by applying the equation to v1 which belongs to the plane
  60267. // then we store the facet equation in a Vector4
  60268. v2.subtractToRef(v1, v1v2);
  60269. v3.subtractToRef(v1, v1v3);
  60270. v4.subtractToRef(v1, v1v4);
  60271. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60272. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60273. norm1.normalize();
  60274. norm2.normalize();
  60275. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60276. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60277. var quad = this._heightQuads[row * subdivisionsX + col];
  60278. quad.slope.copyFromFloats(cd, h);
  60279. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60280. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60281. }
  60282. }
  60283. return this;
  60284. };
  60285. GroundMesh.prototype.serialize = function (serializationObject) {
  60286. _super.prototype.serialize.call(this, serializationObject);
  60287. serializationObject.subdivisionsX = this._subdivisionsX;
  60288. serializationObject.subdivisionsY = this._subdivisionsY;
  60289. serializationObject.minX = this._minX;
  60290. serializationObject.maxX = this._maxX;
  60291. serializationObject.minZ = this._minZ;
  60292. serializationObject.maxZ = this._maxZ;
  60293. serializationObject.width = this._width;
  60294. serializationObject.height = this._height;
  60295. };
  60296. GroundMesh.Parse = function (parsedMesh, scene) {
  60297. var result = new GroundMesh(parsedMesh.name, scene);
  60298. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60299. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60300. result._minX = parsedMesh.minX;
  60301. result._maxX = parsedMesh.maxX;
  60302. result._minZ = parsedMesh.minZ;
  60303. result._maxZ = parsedMesh.maxZ;
  60304. result._width = parsedMesh.width;
  60305. result._height = parsedMesh.height;
  60306. return result;
  60307. };
  60308. return GroundMesh;
  60309. }(BABYLON.Mesh));
  60310. BABYLON.GroundMesh = GroundMesh;
  60311. })(BABYLON || (BABYLON = {}));
  60312. //# sourceMappingURL=babylon.groundMesh.js.map
  60313. var BABYLON;
  60314. (function (BABYLON) {
  60315. /**
  60316. * Creates an instance based on a source mesh.
  60317. */
  60318. var InstancedMesh = /** @class */ (function (_super) {
  60319. __extends(InstancedMesh, _super);
  60320. function InstancedMesh(name, source) {
  60321. var _this = _super.call(this, name, source.getScene()) || this;
  60322. source.instances.push(_this);
  60323. _this._sourceMesh = source;
  60324. _this.position.copyFrom(source.position);
  60325. _this.rotation.copyFrom(source.rotation);
  60326. _this.scaling.copyFrom(source.scaling);
  60327. if (source.rotationQuaternion) {
  60328. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60329. }
  60330. _this.infiniteDistance = source.infiniteDistance;
  60331. _this.setPivotMatrix(source.getPivotMatrix());
  60332. _this.refreshBoundingInfo();
  60333. _this._syncSubMeshes();
  60334. return _this;
  60335. }
  60336. /**
  60337. * Returns the string "InstancedMesh".
  60338. */
  60339. InstancedMesh.prototype.getClassName = function () {
  60340. return "InstancedMesh";
  60341. };
  60342. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60343. // Methods
  60344. get: function () {
  60345. return this._sourceMesh.receiveShadows;
  60346. },
  60347. enumerable: true,
  60348. configurable: true
  60349. });
  60350. Object.defineProperty(InstancedMesh.prototype, "material", {
  60351. get: function () {
  60352. return this._sourceMesh.material;
  60353. },
  60354. enumerable: true,
  60355. configurable: true
  60356. });
  60357. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60358. get: function () {
  60359. return this._sourceMesh.visibility;
  60360. },
  60361. enumerable: true,
  60362. configurable: true
  60363. });
  60364. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60365. get: function () {
  60366. return this._sourceMesh.skeleton;
  60367. },
  60368. enumerable: true,
  60369. configurable: true
  60370. });
  60371. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60372. get: function () {
  60373. return this._sourceMesh.renderingGroupId;
  60374. },
  60375. set: function (value) {
  60376. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60377. return;
  60378. }
  60379. //no-op with warning
  60380. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60381. },
  60382. enumerable: true,
  60383. configurable: true
  60384. });
  60385. /**
  60386. * Returns the total number of vertices (integer).
  60387. */
  60388. InstancedMesh.prototype.getTotalVertices = function () {
  60389. return this._sourceMesh.getTotalVertices();
  60390. };
  60391. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60392. get: function () {
  60393. return this._sourceMesh;
  60394. },
  60395. enumerable: true,
  60396. configurable: true
  60397. });
  60398. /**
  60399. * Is this node ready to be used/rendered
  60400. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60401. * @return {boolean} is it ready
  60402. */
  60403. InstancedMesh.prototype.isReady = function (completeCheck) {
  60404. if (completeCheck === void 0) { completeCheck = false; }
  60405. return this._sourceMesh.isReady(completeCheck, true);
  60406. };
  60407. /**
  60408. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60409. */
  60410. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60411. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60412. };
  60413. /**
  60414. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60415. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60416. * The `data` are either a numeric array either a Float32Array.
  60417. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60418. * 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).
  60419. * Note that a new underlying VertexBuffer object is created each call.
  60420. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60421. *
  60422. * Possible `kind` values :
  60423. * - BABYLON.VertexBuffer.PositionKind
  60424. * - BABYLON.VertexBuffer.UVKind
  60425. * - BABYLON.VertexBuffer.UV2Kind
  60426. * - BABYLON.VertexBuffer.UV3Kind
  60427. * - BABYLON.VertexBuffer.UV4Kind
  60428. * - BABYLON.VertexBuffer.UV5Kind
  60429. * - BABYLON.VertexBuffer.UV6Kind
  60430. * - BABYLON.VertexBuffer.ColorKind
  60431. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60432. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60433. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60434. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60435. *
  60436. * Returns the Mesh.
  60437. */
  60438. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60439. if (this.sourceMesh) {
  60440. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60441. }
  60442. return this.sourceMesh;
  60443. };
  60444. /**
  60445. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60446. * If the mesh has no geometry, it is simply returned as it is.
  60447. * The `data` are either a numeric array either a Float32Array.
  60448. * No new underlying VertexBuffer object is created.
  60449. * 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.
  60450. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60451. *
  60452. * Possible `kind` values :
  60453. * - BABYLON.VertexBuffer.PositionKind
  60454. * - BABYLON.VertexBuffer.UVKind
  60455. * - BABYLON.VertexBuffer.UV2Kind
  60456. * - BABYLON.VertexBuffer.UV3Kind
  60457. * - BABYLON.VertexBuffer.UV4Kind
  60458. * - BABYLON.VertexBuffer.UV5Kind
  60459. * - BABYLON.VertexBuffer.UV6Kind
  60460. * - BABYLON.VertexBuffer.ColorKind
  60461. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60462. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60463. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60464. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60465. *
  60466. * Returns the Mesh.
  60467. */
  60468. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60469. if (this.sourceMesh) {
  60470. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60471. }
  60472. return this.sourceMesh;
  60473. };
  60474. /**
  60475. * Sets the mesh indices.
  60476. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60477. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60478. * This method creates a new index buffer each call.
  60479. * Returns the Mesh.
  60480. */
  60481. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60482. if (totalVertices === void 0) { totalVertices = null; }
  60483. if (this.sourceMesh) {
  60484. this.sourceMesh.setIndices(indices, totalVertices);
  60485. }
  60486. return this.sourceMesh;
  60487. };
  60488. /**
  60489. * Boolean : True if the mesh owns the requested kind of data.
  60490. */
  60491. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60492. return this._sourceMesh.isVerticesDataPresent(kind);
  60493. };
  60494. /**
  60495. * Returns an array of indices (IndicesArray).
  60496. */
  60497. InstancedMesh.prototype.getIndices = function () {
  60498. return this._sourceMesh.getIndices();
  60499. };
  60500. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60501. get: function () {
  60502. return this._sourceMesh._positions;
  60503. },
  60504. enumerable: true,
  60505. configurable: true
  60506. });
  60507. /**
  60508. * Sets a new updated BoundingInfo to the mesh.
  60509. * Returns the mesh.
  60510. */
  60511. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60512. var meshBB = this._sourceMesh.getBoundingInfo();
  60513. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60514. this._updateBoundingInfo();
  60515. return this;
  60516. };
  60517. InstancedMesh.prototype._preActivate = function () {
  60518. if (this._currentLOD) {
  60519. this._currentLOD._preActivate();
  60520. }
  60521. return this;
  60522. };
  60523. InstancedMesh.prototype._activate = function (renderId) {
  60524. if (this._currentLOD) {
  60525. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60526. }
  60527. return this;
  60528. };
  60529. /**
  60530. * Returns the current associated LOD AbstractMesh.
  60531. */
  60532. InstancedMesh.prototype.getLOD = function (camera) {
  60533. if (!camera) {
  60534. return this;
  60535. }
  60536. var boundingInfo = this.getBoundingInfo();
  60537. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60538. if (this._currentLOD === this.sourceMesh) {
  60539. return this;
  60540. }
  60541. return this._currentLOD;
  60542. };
  60543. InstancedMesh.prototype._syncSubMeshes = function () {
  60544. this.releaseSubMeshes();
  60545. if (this._sourceMesh.subMeshes) {
  60546. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60547. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60548. }
  60549. }
  60550. return this;
  60551. };
  60552. InstancedMesh.prototype._generatePointsArray = function () {
  60553. return this._sourceMesh._generatePointsArray();
  60554. };
  60555. /**
  60556. * Creates a new InstancedMesh from the current mesh.
  60557. * - name (string) : the cloned mesh name
  60558. * - newParent (optional Node) : the optional Node to parent the clone to.
  60559. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60560. *
  60561. * Returns the clone.
  60562. */
  60563. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60564. var result = this._sourceMesh.createInstance(name);
  60565. // Deep copy
  60566. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60567. // Bounding info
  60568. this.refreshBoundingInfo();
  60569. // Parent
  60570. if (newParent) {
  60571. result.parent = newParent;
  60572. }
  60573. if (!doNotCloneChildren) {
  60574. // Children
  60575. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60576. var mesh = this.getScene().meshes[index];
  60577. if (mesh.parent === this) {
  60578. mesh.clone(mesh.name, result);
  60579. }
  60580. }
  60581. }
  60582. result.computeWorldMatrix(true);
  60583. return result;
  60584. };
  60585. /**
  60586. * Disposes the InstancedMesh.
  60587. * Returns nothing.
  60588. */
  60589. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60590. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60591. // Remove from mesh
  60592. var index = this._sourceMesh.instances.indexOf(this);
  60593. this._sourceMesh.instances.splice(index, 1);
  60594. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60595. };
  60596. return InstancedMesh;
  60597. }(BABYLON.AbstractMesh));
  60598. BABYLON.InstancedMesh = InstancedMesh;
  60599. })(BABYLON || (BABYLON = {}));
  60600. //# sourceMappingURL=babylon.instancedMesh.js.map
  60601. var BABYLON;
  60602. (function (BABYLON) {
  60603. var LinesMesh = /** @class */ (function (_super) {
  60604. __extends(LinesMesh, _super);
  60605. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60606. if (scene === void 0) { scene = null; }
  60607. if (parent === void 0) { parent = null; }
  60608. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60609. _this.useVertexColor = useVertexColor;
  60610. _this.useVertexAlpha = useVertexAlpha;
  60611. _this.color = new BABYLON.Color3(1, 1, 1);
  60612. _this.alpha = 1;
  60613. if (source) {
  60614. _this.color = source.color.clone();
  60615. _this.alpha = source.alpha;
  60616. _this.useVertexColor = source.useVertexColor;
  60617. _this.useVertexAlpha = source.useVertexAlpha;
  60618. }
  60619. _this._intersectionThreshold = 0.1;
  60620. var defines = [];
  60621. var options = {
  60622. attributes: [BABYLON.VertexBuffer.PositionKind],
  60623. uniforms: ["world", "viewProjection"],
  60624. needAlphaBlending: true,
  60625. defines: defines
  60626. };
  60627. if (useVertexAlpha === false) {
  60628. options.needAlphaBlending = false;
  60629. }
  60630. if (!useVertexColor) {
  60631. options.uniforms.push("color");
  60632. }
  60633. else {
  60634. options.defines.push("#define VERTEXCOLOR");
  60635. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60636. }
  60637. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60638. return _this;
  60639. }
  60640. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60641. /**
  60642. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60643. * This margin is expressed in world space coordinates, so its value may vary.
  60644. * Default value is 0.1
  60645. * @returns the intersection Threshold value.
  60646. */
  60647. get: function () {
  60648. return this._intersectionThreshold;
  60649. },
  60650. /**
  60651. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60652. * This margin is expressed in world space coordinates, so its value may vary.
  60653. * @param value the new threshold to apply
  60654. */
  60655. set: function (value) {
  60656. if (this._intersectionThreshold === value) {
  60657. return;
  60658. }
  60659. this._intersectionThreshold = value;
  60660. if (this.geometry) {
  60661. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60662. }
  60663. },
  60664. enumerable: true,
  60665. configurable: true
  60666. });
  60667. /**
  60668. * Returns the string "LineMesh"
  60669. */
  60670. LinesMesh.prototype.getClassName = function () {
  60671. return "LinesMesh";
  60672. };
  60673. Object.defineProperty(LinesMesh.prototype, "material", {
  60674. get: function () {
  60675. return this._colorShader;
  60676. },
  60677. set: function (value) {
  60678. // Do nothing
  60679. },
  60680. enumerable: true,
  60681. configurable: true
  60682. });
  60683. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60684. get: function () {
  60685. return false;
  60686. },
  60687. enumerable: true,
  60688. configurable: true
  60689. });
  60690. LinesMesh.prototype.createInstance = function (name) {
  60691. throw new Error("LinesMeshes do not support createInstance.");
  60692. };
  60693. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60694. if (!this._geometry) {
  60695. return this;
  60696. }
  60697. // VBOs
  60698. this._geometry._bind(this._colorShader.getEffect());
  60699. // Color
  60700. if (!this.useVertexColor) {
  60701. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60702. }
  60703. return this;
  60704. };
  60705. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60706. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60707. return this;
  60708. }
  60709. var engine = this.getScene().getEngine();
  60710. // Draw order
  60711. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60712. return this;
  60713. };
  60714. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60715. this._colorShader.dispose();
  60716. _super.prototype.dispose.call(this, doNotRecurse);
  60717. };
  60718. /**
  60719. * Returns a new LineMesh object cloned from the current one.
  60720. */
  60721. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60722. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60723. };
  60724. return LinesMesh;
  60725. }(BABYLON.Mesh));
  60726. BABYLON.LinesMesh = LinesMesh;
  60727. })(BABYLON || (BABYLON = {}));
  60728. //# sourceMappingURL=babylon.linesMesh.js.map
  60729. var BABYLON;
  60730. (function (BABYLON) {
  60731. /**
  60732. * Class containing static functions to help procedurally build meshes
  60733. */
  60734. var MeshBuilder = /** @class */ (function () {
  60735. function MeshBuilder() {
  60736. }
  60737. MeshBuilder.updateSideOrientation = function (orientation) {
  60738. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60739. return BABYLON.Mesh.DOUBLESIDE;
  60740. }
  60741. if (orientation === undefined || orientation === null) {
  60742. return BABYLON.Mesh.FRONTSIDE;
  60743. }
  60744. return orientation;
  60745. };
  60746. /**
  60747. * Creates a box mesh
  60748. * * The parameter `size` sets the size (float) of each box side (default 1)
  60749. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60750. * * 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)
  60751. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60752. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60753. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60754. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60755. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60756. * @param name defines the name of the mesh
  60757. * @param options defines the options used to create the mesh
  60758. * @param scene defines the hosting scene
  60759. * @returns the box mesh
  60760. */
  60761. MeshBuilder.CreateBox = function (name, options, scene) {
  60762. if (scene === void 0) { scene = null; }
  60763. var box = new BABYLON.Mesh(name, scene);
  60764. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60765. box._originalBuilderSideOrientation = options.sideOrientation;
  60766. var vertexData = BABYLON.VertexData.CreateBox(options);
  60767. vertexData.applyToMesh(box, options.updatable);
  60768. return box;
  60769. };
  60770. /**
  60771. * Creates a sphere mesh
  60772. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60773. * * 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`)
  60774. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60775. * * 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
  60776. * * 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)
  60777. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60778. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60779. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60780. * @param name defines the name of the mesh
  60781. * @param options defines the options used to create the mesh
  60782. * @param scene defines the hosting scene
  60783. * @returns the sphere mesh
  60784. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60785. */
  60786. MeshBuilder.CreateSphere = function (name, options, scene) {
  60787. var sphere = new BABYLON.Mesh(name, scene);
  60788. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60789. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60790. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60791. vertexData.applyToMesh(sphere, options.updatable);
  60792. return sphere;
  60793. };
  60794. /**
  60795. * Creates a plane polygonal mesh. By default, this is a disc
  60796. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60797. * * 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
  60798. * * 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
  60799. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60800. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60801. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60802. * @param name defines the name of the mesh
  60803. * @param options defines the options used to create the mesh
  60804. * @param scene defines the hosting scene
  60805. * @returns the plane polygonal mesh
  60806. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60807. */
  60808. MeshBuilder.CreateDisc = function (name, options, scene) {
  60809. if (scene === void 0) { scene = null; }
  60810. var disc = new BABYLON.Mesh(name, scene);
  60811. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60812. disc._originalBuilderSideOrientation = options.sideOrientation;
  60813. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60814. vertexData.applyToMesh(disc, options.updatable);
  60815. return disc;
  60816. };
  60817. /**
  60818. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60819. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60820. * * 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`)
  60821. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60822. * * 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
  60823. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60824. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60825. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60826. * @param name defines the name of the mesh
  60827. * @param options defines the options used to create the mesh
  60828. * @param scene defines the hosting scene
  60829. * @returns the icosahedron mesh
  60830. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60831. */
  60832. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60833. var sphere = new BABYLON.Mesh(name, scene);
  60834. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60835. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60836. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60837. vertexData.applyToMesh(sphere, options.updatable);
  60838. return sphere;
  60839. };
  60840. ;
  60841. /**
  60842. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60843. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60844. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60845. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60846. * * 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
  60847. * * 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
  60848. * * 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
  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/babylon101/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 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
  60853. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60854. * * 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
  60855. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60856. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60857. * @param name defines the name of the mesh
  60858. * @param options defines the options used to create the mesh
  60859. * @param scene defines the hosting scene
  60860. * @returns the ribbon mesh
  60861. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60862. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60863. */
  60864. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60865. if (scene === void 0) { scene = null; }
  60866. var pathArray = options.pathArray;
  60867. var closeArray = options.closeArray;
  60868. var closePath = options.closePath;
  60869. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60870. var instance = options.instance;
  60871. var updatable = options.updatable;
  60872. if (instance) { // existing ribbon instance update
  60873. // positionFunction : ribbon case
  60874. // only pathArray and sideOrientation parameters are taken into account for positions update
  60875. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60876. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60877. var positionFunction = function (positions) {
  60878. var minlg = pathArray[0].length;
  60879. var i = 0;
  60880. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60881. for (var si = 1; si <= ns; si++) {
  60882. for (var p = 0; p < pathArray.length; p++) {
  60883. var path = pathArray[p];
  60884. var l = path.length;
  60885. minlg = (minlg < l) ? minlg : l;
  60886. var j = 0;
  60887. while (j < minlg) {
  60888. positions[i] = path[j].x;
  60889. positions[i + 1] = path[j].y;
  60890. positions[i + 2] = path[j].z;
  60891. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60892. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60893. }
  60894. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60895. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60896. }
  60897. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60898. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60899. }
  60900. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60901. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60902. }
  60903. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60904. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60905. }
  60906. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60907. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60908. }
  60909. j++;
  60910. i += 3;
  60911. }
  60912. if (instance._closePath) {
  60913. positions[i] = path[0].x;
  60914. positions[i + 1] = path[0].y;
  60915. positions[i + 2] = path[0].z;
  60916. i += 3;
  60917. }
  60918. }
  60919. }
  60920. };
  60921. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60922. positionFunction(positions);
  60923. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60924. instance._boundingInfo.update(instance._worldMatrix);
  60925. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60926. if (options.colors) {
  60927. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60928. for (var c = 0; c < options.colors.length; c++) {
  60929. colors[c * 4] = options.colors[c].r;
  60930. colors[c * 4 + 1] = options.colors[c].g;
  60931. colors[c * 4 + 2] = options.colors[c].b;
  60932. colors[c * 4 + 3] = options.colors[c].a;
  60933. }
  60934. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60935. }
  60936. if (options.uvs) {
  60937. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60938. for (var i = 0; i < options.uvs.length; i++) {
  60939. uvs[i * 2] = options.uvs[i].x;
  60940. uvs[i * 2 + 1] = options.uvs[i].y;
  60941. }
  60942. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60943. }
  60944. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60945. var indices = instance.getIndices();
  60946. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60947. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60948. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60949. if (instance._closePath) {
  60950. var indexFirst = 0;
  60951. var indexLast = 0;
  60952. for (var p = 0; p < pathArray.length; p++) {
  60953. indexFirst = instance._idx[p] * 3;
  60954. if (p + 1 < pathArray.length) {
  60955. indexLast = (instance._idx[p + 1] - 1) * 3;
  60956. }
  60957. else {
  60958. indexLast = normals.length - 3;
  60959. }
  60960. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60961. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60962. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60963. normals[indexLast] = normals[indexFirst];
  60964. normals[indexLast + 1] = normals[indexFirst + 1];
  60965. normals[indexLast + 2] = normals[indexFirst + 2];
  60966. }
  60967. }
  60968. if (!(instance.areNormalsFrozen)) {
  60969. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60970. }
  60971. }
  60972. return instance;
  60973. }
  60974. else { // new ribbon creation
  60975. var ribbon = new BABYLON.Mesh(name, scene);
  60976. ribbon._originalBuilderSideOrientation = sideOrientation;
  60977. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60978. if (closePath) {
  60979. ribbon._idx = vertexData._idx;
  60980. }
  60981. ribbon._closePath = closePath;
  60982. ribbon._closeArray = closeArray;
  60983. vertexData.applyToMesh(ribbon, updatable);
  60984. return ribbon;
  60985. }
  60986. };
  60987. /**
  60988. * Creates a cylinder or a cone mesh
  60989. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60990. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60991. * * 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.
  60992. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60993. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60994. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60995. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60996. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60997. * * 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).
  60998. * * 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
  60999. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61000. * * 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
  61001. * * 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.
  61002. * * If `enclose` is false, a ring surface is one element.
  61003. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61004. * * 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
  61005. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61006. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61007. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61008. * @param name defines the name of the mesh
  61009. * @param options defines the options used to create the mesh
  61010. * @param scene defines the hosting scene
  61011. * @returns the cylinder mesh
  61012. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61013. */
  61014. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61015. var cylinder = new BABYLON.Mesh(name, scene);
  61016. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61017. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61018. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61019. vertexData.applyToMesh(cylinder, options.updatable);
  61020. return cylinder;
  61021. };
  61022. /**
  61023. * Creates a torus mesh
  61024. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61025. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61026. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61027. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61028. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61029. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61030. * @param name defines the name of the mesh
  61031. * @param options defines the options used to create the mesh
  61032. * @param scene defines the hosting scene
  61033. * @returns the torus mesh
  61034. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61035. */
  61036. MeshBuilder.CreateTorus = function (name, options, scene) {
  61037. var torus = new BABYLON.Mesh(name, scene);
  61038. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61039. torus._originalBuilderSideOrientation = options.sideOrientation;
  61040. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61041. vertexData.applyToMesh(torus, options.updatable);
  61042. return torus;
  61043. };
  61044. /**
  61045. * Creates a torus knot mesh
  61046. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61047. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61048. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61049. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61050. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61051. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61052. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61053. * @param name defines the name of the mesh
  61054. * @param options defines the options used to create the mesh
  61055. * @param scene defines the hosting scene
  61056. * @returns the torus knot mesh
  61057. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61058. */
  61059. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61060. var torusKnot = new BABYLON.Mesh(name, scene);
  61061. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61062. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61063. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61064. vertexData.applyToMesh(torusKnot, options.updatable);
  61065. return torusKnot;
  61066. };
  61067. /**
  61068. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61069. * * 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
  61070. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61071. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61072. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61073. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61074. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61075. * * 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
  61076. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61077. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61078. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61079. * @param name defines the name of the new line system
  61080. * @param options defines the options used to create the line system
  61081. * @param scene defines the hosting scene
  61082. * @returns a new line system mesh
  61083. */
  61084. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61085. var instance = options.instance;
  61086. var lines = options.lines;
  61087. var colors = options.colors;
  61088. if (instance) { // lines update
  61089. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61090. var vertexColor;
  61091. var lineColors;
  61092. if (colors) {
  61093. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61094. }
  61095. var i = 0;
  61096. var c = 0;
  61097. for (var l = 0; l < lines.length; l++) {
  61098. var points = lines[l];
  61099. for (var p = 0; p < points.length; p++) {
  61100. positions[i] = points[p].x;
  61101. positions[i + 1] = points[p].y;
  61102. positions[i + 2] = points[p].z;
  61103. if (colors && vertexColor) {
  61104. lineColors = colors[l];
  61105. vertexColor[c] = lineColors[p].r;
  61106. vertexColor[c + 1] = lineColors[p].g;
  61107. vertexColor[c + 2] = lineColors[p].b;
  61108. vertexColor[c + 3] = lineColors[p].a;
  61109. c += 4;
  61110. }
  61111. i += 3;
  61112. }
  61113. }
  61114. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61115. if (colors && vertexColor) {
  61116. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61117. }
  61118. return instance;
  61119. }
  61120. // line system creation
  61121. var useVertexColor = (colors) ? true : false;
  61122. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61123. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61124. vertexData.applyToMesh(lineSystem, options.updatable);
  61125. return lineSystem;
  61126. };
  61127. /**
  61128. * Creates a line mesh
  61129. * 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
  61130. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61131. * * The parameter `points` is an array successive Vector3
  61132. * * 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
  61133. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61134. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61135. * * When updating an instance, remember that only point positions can change, not the number of points
  61136. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61137. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61138. * @param name defines the name of the new line system
  61139. * @param options defines the options used to create the line system
  61140. * @param scene defines the hosting scene
  61141. * @returns a new line mesh
  61142. */
  61143. MeshBuilder.CreateLines = function (name, options, scene) {
  61144. if (scene === void 0) { scene = null; }
  61145. var colors = (options.colors) ? [options.colors] : null;
  61146. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61147. return lines;
  61148. };
  61149. /**
  61150. * Creates a dashed line mesh
  61151. * * 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
  61152. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61153. * * The parameter `points` is an array successive Vector3
  61154. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61155. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61156. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61157. * * 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
  61158. * * When updating an instance, remember that only point positions can change, not the number of points
  61159. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61160. * @param name defines the name of the mesh
  61161. * @param options defines the options used to create the mesh
  61162. * @param scene defines the hosting scene
  61163. * @returns the dashed line mesh
  61164. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61165. */
  61166. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61167. if (scene === void 0) { scene = null; }
  61168. var points = options.points;
  61169. var instance = options.instance;
  61170. var gapSize = options.gapSize || 1;
  61171. var dashSize = options.dashSize || 3;
  61172. if (instance) { // dashed lines update
  61173. var positionFunction = function (positions) {
  61174. var curvect = BABYLON.Vector3.Zero();
  61175. var nbSeg = positions.length / 6;
  61176. var lg = 0;
  61177. var nb = 0;
  61178. var shft = 0;
  61179. var dashshft = 0;
  61180. var curshft = 0;
  61181. var p = 0;
  61182. var i = 0;
  61183. var j = 0;
  61184. for (i = 0; i < points.length - 1; i++) {
  61185. points[i + 1].subtractToRef(points[i], curvect);
  61186. lg += curvect.length();
  61187. }
  61188. shft = lg / nbSeg;
  61189. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61190. for (i = 0; i < points.length - 1; i++) {
  61191. points[i + 1].subtractToRef(points[i], curvect);
  61192. nb = Math.floor(curvect.length() / shft);
  61193. curvect.normalize();
  61194. j = 0;
  61195. while (j < nb && p < positions.length) {
  61196. curshft = shft * j;
  61197. positions[p] = points[i].x + curshft * curvect.x;
  61198. positions[p + 1] = points[i].y + curshft * curvect.y;
  61199. positions[p + 2] = points[i].z + curshft * curvect.z;
  61200. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61201. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61202. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61203. p += 6;
  61204. j++;
  61205. }
  61206. }
  61207. while (p < positions.length) {
  61208. positions[p] = points[i].x;
  61209. positions[p + 1] = points[i].y;
  61210. positions[p + 2] = points[i].z;
  61211. p += 3;
  61212. }
  61213. };
  61214. instance.updateMeshPositions(positionFunction, false);
  61215. return instance;
  61216. }
  61217. // dashed lines creation
  61218. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61219. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61220. vertexData.applyToMesh(dashedLines, options.updatable);
  61221. dashedLines.dashSize = dashSize;
  61222. dashedLines.gapSize = gapSize;
  61223. return dashedLines;
  61224. };
  61225. /**
  61226. * 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.
  61227. * * 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.
  61228. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61229. * * 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.
  61230. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61231. * * 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
  61232. * * 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
  61233. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61234. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61235. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61236. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61237. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61238. * @param name defines the name of the mesh
  61239. * @param options defines the options used to create the mesh
  61240. * @param scene defines the hosting scene
  61241. * @returns the extruded shape mesh
  61242. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61243. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61244. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61245. */
  61246. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61247. if (scene === void 0) { scene = null; }
  61248. var path = options.path;
  61249. var shape = options.shape;
  61250. var scale = options.scale || 1;
  61251. var rotation = options.rotation || 0;
  61252. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61253. var updatable = options.updatable;
  61254. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61255. var instance = options.instance || null;
  61256. var invertUV = options.invertUV || false;
  61257. 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);
  61258. };
  61259. /**
  61260. * Creates an custom extruded shape mesh.
  61261. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61262. * * 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.
  61263. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61264. * * 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
  61265. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61266. * * 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
  61267. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61268. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61269. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61270. * * 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
  61271. * * 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
  61272. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61273. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61274. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61275. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61276. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61277. * @param name defines the name of the mesh
  61278. * @param options defines the options used to create the mesh
  61279. * @param scene defines the hosting scene
  61280. * @returns the custom extruded shape mesh
  61281. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61282. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61283. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61284. */
  61285. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61286. var path = options.path;
  61287. var shape = options.shape;
  61288. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61289. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61290. var ribbonCloseArray = options.ribbonCloseArray || false;
  61291. var ribbonClosePath = options.ribbonClosePath || false;
  61292. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61293. var updatable = options.updatable;
  61294. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61295. var instance = options.instance;
  61296. var invertUV = options.invertUV || false;
  61297. 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);
  61298. };
  61299. /**
  61300. * Creates lathe mesh.
  61301. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61302. * * 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
  61303. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61304. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61305. * * 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
  61306. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61307. * * 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
  61308. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61309. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61310. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61311. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61312. * @param name defines the name of the mesh
  61313. * @param options defines the options used to create the mesh
  61314. * @param scene defines the hosting scene
  61315. * @returns the lathe mesh
  61316. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61317. */
  61318. MeshBuilder.CreateLathe = function (name, options, scene) {
  61319. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61320. var closed = (options.closed === undefined) ? true : options.closed;
  61321. var shape = options.shape;
  61322. var radius = options.radius || 1;
  61323. var tessellation = options.tessellation || 64;
  61324. var updatable = options.updatable;
  61325. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61326. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61327. var pi2 = Math.PI * 2;
  61328. var paths = new Array();
  61329. var invertUV = options.invertUV || false;
  61330. var i = 0;
  61331. var p = 0;
  61332. var step = pi2 / tessellation * arc;
  61333. var rotated;
  61334. var path = new Array();
  61335. for (i = 0; i <= tessellation; i++) {
  61336. var path = [];
  61337. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61338. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61339. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61340. }
  61341. for (p = 0; p < shape.length; p++) {
  61342. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61343. path.push(rotated);
  61344. }
  61345. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61346. 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));
  61347. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61348. }
  61349. paths.push(path);
  61350. }
  61351. // lathe ribbon
  61352. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61353. return lathe;
  61354. };
  61355. /**
  61356. * Creates a plane mesh
  61357. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61358. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61359. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61360. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61361. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61362. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61363. * @param name defines the name of the mesh
  61364. * @param options defines the options used to create the mesh
  61365. * @param scene defines the hosting scene
  61366. * @returns the plane mesh
  61367. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61368. */
  61369. MeshBuilder.CreatePlane = function (name, options, scene) {
  61370. var plane = new BABYLON.Mesh(name, scene);
  61371. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61372. plane._originalBuilderSideOrientation = options.sideOrientation;
  61373. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61374. vertexData.applyToMesh(plane, options.updatable);
  61375. if (options.sourcePlane) {
  61376. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61377. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61378. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61379. plane.rotate(vectorProduct, product);
  61380. }
  61381. return plane;
  61382. };
  61383. /**
  61384. * Creates a ground mesh
  61385. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61386. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61387. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61388. * @param name defines the name of the mesh
  61389. * @param options defines the options used to create the mesh
  61390. * @param scene defines the hosting scene
  61391. * @returns the ground mesh
  61392. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61393. */
  61394. MeshBuilder.CreateGround = function (name, options, scene) {
  61395. var ground = new BABYLON.GroundMesh(name, scene);
  61396. ground._setReady(false);
  61397. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61398. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61399. ground._width = options.width || 1;
  61400. ground._height = options.height || 1;
  61401. ground._maxX = ground._width / 2;
  61402. ground._maxZ = ground._height / 2;
  61403. ground._minX = -ground._maxX;
  61404. ground._minZ = -ground._maxZ;
  61405. var vertexData = BABYLON.VertexData.CreateGround(options);
  61406. vertexData.applyToMesh(ground, options.updatable);
  61407. ground._setReady(true);
  61408. return ground;
  61409. };
  61410. /**
  61411. * Creates a tiled ground mesh
  61412. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61413. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61414. * * 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
  61415. * * 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
  61416. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61417. * @param name defines the name of the mesh
  61418. * @param options defines the options used to create the mesh
  61419. * @param scene defines the hosting scene
  61420. * @returns the tiled ground mesh
  61421. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61422. */
  61423. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61424. var tiledGround = new BABYLON.Mesh(name, scene);
  61425. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61426. vertexData.applyToMesh(tiledGround, options.updatable);
  61427. return tiledGround;
  61428. };
  61429. /**
  61430. * Creates a ground mesh from a height map
  61431. * * The parameter `url` sets the URL of the height map image resource.
  61432. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61433. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61434. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61435. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61436. * * 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.
  61437. * * 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).
  61438. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61439. * @param name defines the name of the mesh
  61440. * @param url defines the url to the height map
  61441. * @param options defines the options used to create the mesh
  61442. * @param scene defines the hosting scene
  61443. * @returns the ground mesh
  61444. * @see http://doc.babylonjs.com/babylon101/height_map
  61445. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61446. */
  61447. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61448. var width = options.width || 10.0;
  61449. var height = options.height || 10.0;
  61450. var subdivisions = options.subdivisions || 1 | 0;
  61451. var minHeight = options.minHeight || 0.0;
  61452. var maxHeight = options.maxHeight || 1.0;
  61453. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61454. var updatable = options.updatable;
  61455. var onReady = options.onReady;
  61456. var ground = new BABYLON.GroundMesh(name, scene);
  61457. ground._subdivisionsX = subdivisions;
  61458. ground._subdivisionsY = subdivisions;
  61459. ground._width = width;
  61460. ground._height = height;
  61461. ground._maxX = ground._width / 2.0;
  61462. ground._maxZ = ground._height / 2.0;
  61463. ground._minX = -ground._maxX;
  61464. ground._minZ = -ground._maxZ;
  61465. ground._setReady(false);
  61466. var onload = function (img) {
  61467. // Getting height map data
  61468. var canvas = document.createElement("canvas");
  61469. var context = canvas.getContext("2d");
  61470. if (!context) {
  61471. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61472. }
  61473. if (scene.isDisposed) {
  61474. return;
  61475. }
  61476. var bufferWidth = img.width;
  61477. var bufferHeight = img.height;
  61478. canvas.width = bufferWidth;
  61479. canvas.height = bufferHeight;
  61480. context.drawImage(img, 0, 0);
  61481. // Create VertexData from map data
  61482. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61483. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61484. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61485. width: width, height: height,
  61486. subdivisions: subdivisions,
  61487. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61488. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61489. });
  61490. vertexData.applyToMesh(ground, updatable);
  61491. //execute ready callback, if set
  61492. if (onReady) {
  61493. onReady(ground);
  61494. }
  61495. ground._setReady(true);
  61496. };
  61497. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61498. return ground;
  61499. };
  61500. /**
  61501. * Creates a polygon mesh
  61502. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61503. * * 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
  61504. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61505. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61506. * * 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)
  61507. * * Remember you can only change the shape positions, not their number when updating a polygon
  61508. * @param name defines the name of the mesh
  61509. * @param options defines the options used to create the mesh
  61510. * @param scene defines the hosting scene
  61511. * @returns the polygon mesh
  61512. */
  61513. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61514. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61515. var shape = options.shape;
  61516. var holes = options.holes || [];
  61517. var depth = options.depth || 0;
  61518. var contours = [];
  61519. var hole = [];
  61520. for (var i = 0; i < shape.length; i++) {
  61521. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61522. }
  61523. var epsilon = 0.00000001;
  61524. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61525. contours.pop();
  61526. }
  61527. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61528. for (var hNb = 0; hNb < holes.length; hNb++) {
  61529. hole = [];
  61530. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61531. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61532. }
  61533. polygonTriangulation.addHole(hole);
  61534. }
  61535. var polygon = polygonTriangulation.build(options.updatable, depth);
  61536. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61537. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61538. vertexData.applyToMesh(polygon, options.updatable);
  61539. return polygon;
  61540. };
  61541. ;
  61542. /**
  61543. * Creates an extruded polygon mesh, with depth in the Y direction.
  61544. * * 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)
  61545. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61546. * @param name defines the name of the mesh
  61547. * @param options defines the options used to create the mesh
  61548. * @param scene defines the hosting scene
  61549. * @returns the polygon mesh
  61550. */
  61551. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61552. return MeshBuilder.CreatePolygon(name, options, scene);
  61553. };
  61554. ;
  61555. /**
  61556. * Creates a tube mesh.
  61557. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61558. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61559. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61560. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61561. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61562. * * 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)
  61563. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61564. * * 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
  61565. * * 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
  61566. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61567. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61568. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61569. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61570. * @param name defines the name of the mesh
  61571. * @param options defines the options used to create the mesh
  61572. * @param scene defines the hosting scene
  61573. * @returns the tube mesh
  61574. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61575. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61576. */
  61577. MeshBuilder.CreateTube = function (name, options, scene) {
  61578. var path = options.path;
  61579. var instance = options.instance;
  61580. var radius = 1.0;
  61581. if (instance) {
  61582. radius = instance.radius;
  61583. }
  61584. if (options.radius !== undefined) {
  61585. radius = options.radius;
  61586. }
  61587. ;
  61588. var tessellation = options.tessellation || 64 | 0;
  61589. var radiusFunction = options.radiusFunction || null;
  61590. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61591. var invertUV = options.invertUV || false;
  61592. var updatable = options.updatable;
  61593. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61594. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61595. // tube geometry
  61596. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61597. var tangents = path3D.getTangents();
  61598. var normals = path3D.getNormals();
  61599. var distances = path3D.getDistances();
  61600. var pi2 = Math.PI * 2;
  61601. var step = pi2 / tessellation * arc;
  61602. var returnRadius = function () { return radius; };
  61603. var radiusFunctionFinal = radiusFunction || returnRadius;
  61604. var circlePath;
  61605. var rad;
  61606. var normal;
  61607. var rotated;
  61608. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61609. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61610. for (var i = 0; i < path.length; i++) {
  61611. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61612. circlePath = Array(); // current circle array
  61613. normal = normals[i]; // current normal
  61614. for (var t = 0; t < tessellation; t++) {
  61615. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61616. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61617. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61618. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61619. circlePath[t] = rotated;
  61620. }
  61621. circlePaths[index] = circlePath;
  61622. index++;
  61623. }
  61624. // cap
  61625. var capPath = function (nbPoints, pathIndex) {
  61626. var pointCap = Array();
  61627. for (var i = 0; i < nbPoints; i++) {
  61628. pointCap.push(path[pathIndex]);
  61629. }
  61630. return pointCap;
  61631. };
  61632. switch (cap) {
  61633. case BABYLON.Mesh.NO_CAP:
  61634. break;
  61635. case BABYLON.Mesh.CAP_START:
  61636. circlePaths[0] = capPath(tessellation, 0);
  61637. circlePaths[1] = circlePaths[2].slice(0);
  61638. break;
  61639. case BABYLON.Mesh.CAP_END:
  61640. circlePaths[index] = circlePaths[index - 1].slice(0);
  61641. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61642. break;
  61643. case BABYLON.Mesh.CAP_ALL:
  61644. circlePaths[0] = capPath(tessellation, 0);
  61645. circlePaths[1] = circlePaths[2].slice(0);
  61646. circlePaths[index] = circlePaths[index - 1].slice(0);
  61647. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61648. break;
  61649. default:
  61650. break;
  61651. }
  61652. return circlePaths;
  61653. };
  61654. var path3D;
  61655. var pathArray;
  61656. if (instance) { // tube update
  61657. var arc = options.arc || instance.arc;
  61658. path3D = (instance.path3D).update(path);
  61659. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61660. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61661. instance.path3D = path3D;
  61662. instance.pathArray = pathArray;
  61663. instance.arc = arc;
  61664. instance.radius = radius;
  61665. return instance;
  61666. }
  61667. // tube creation
  61668. path3D = new BABYLON.Path3D(path);
  61669. var newPathArray = new Array();
  61670. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61671. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61672. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61673. tube.pathArray = pathArray;
  61674. tube.path3D = path3D;
  61675. tube.tessellation = tessellation;
  61676. tube.cap = cap;
  61677. tube.arc = options.arc;
  61678. tube.radius = radius;
  61679. return tube;
  61680. };
  61681. /**
  61682. * Creates a polyhedron mesh
  61683. * * 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
  61684. * * The parameter `size` (positive float, default 1) sets the polygon size
  61685. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61686. * * 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`
  61687. * * 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
  61688. * * 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)`)
  61689. * * 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
  61690. * * 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
  61691. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61692. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61693. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61694. * @param name defines the name of the mesh
  61695. * @param options defines the options used to create the mesh
  61696. * @param scene defines the hosting scene
  61697. * @returns the polyhedron mesh
  61698. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61699. */
  61700. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61701. var polyhedron = new BABYLON.Mesh(name, scene);
  61702. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61703. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61704. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61705. vertexData.applyToMesh(polyhedron, options.updatable);
  61706. return polyhedron;
  61707. };
  61708. /**
  61709. * Creates a decal mesh.
  61710. * 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
  61711. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61712. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61713. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61714. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61715. * @param name defines the name of the mesh
  61716. * @param sourceMesh defines the mesh where the decal must be applied
  61717. * @param options defines the options used to create the mesh
  61718. * @param scene defines the hosting scene
  61719. * @returns the decal mesh
  61720. * @see http://doc.babylonjs.com/how_to/decals
  61721. */
  61722. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61723. var indices = sourceMesh.getIndices();
  61724. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61725. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61726. var position = options.position || BABYLON.Vector3.Zero();
  61727. var normal = options.normal || BABYLON.Vector3.Up();
  61728. var size = options.size || BABYLON.Vector3.One();
  61729. var angle = options.angle || 0;
  61730. // Getting correct rotation
  61731. if (!normal) {
  61732. var target = new BABYLON.Vector3(0, 0, 1);
  61733. var camera = sourceMesh.getScene().activeCamera;
  61734. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61735. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61736. }
  61737. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61738. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61739. var pitch = Math.atan2(normal.y, len);
  61740. // Matrix
  61741. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61742. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61743. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61744. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61745. var vertexData = new BABYLON.VertexData();
  61746. vertexData.indices = [];
  61747. vertexData.positions = [];
  61748. vertexData.normals = [];
  61749. vertexData.uvs = [];
  61750. var currentVertexDataIndex = 0;
  61751. var extractDecalVector3 = function (indexId) {
  61752. var result = new BABYLON.PositionNormalVertex();
  61753. if (!indices || !positions || !normals) {
  61754. return result;
  61755. }
  61756. var vertexId = indices[indexId];
  61757. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61758. // Send vector to decal local world
  61759. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61760. // Get normal
  61761. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61762. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61763. return result;
  61764. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61765. var clip = function (vertices, axis) {
  61766. if (vertices.length === 0) {
  61767. return vertices;
  61768. }
  61769. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61770. var clipVertices = function (v0, v1) {
  61771. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61772. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61773. };
  61774. var result = new Array();
  61775. for (var index = 0; index < vertices.length; index += 3) {
  61776. var v1Out;
  61777. var v2Out;
  61778. var v3Out;
  61779. var total = 0;
  61780. var nV1 = null;
  61781. var nV2 = null;
  61782. var nV3 = null;
  61783. var nV4 = null;
  61784. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61785. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61786. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61787. v1Out = d1 > 0;
  61788. v2Out = d2 > 0;
  61789. v3Out = d3 > 0;
  61790. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61791. switch (total) {
  61792. case 0:
  61793. result.push(vertices[index]);
  61794. result.push(vertices[index + 1]);
  61795. result.push(vertices[index + 2]);
  61796. break;
  61797. case 1:
  61798. if (v1Out) {
  61799. nV1 = vertices[index + 1];
  61800. nV2 = vertices[index + 2];
  61801. nV3 = clipVertices(vertices[index], nV1);
  61802. nV4 = clipVertices(vertices[index], nV2);
  61803. }
  61804. if (v2Out) {
  61805. nV1 = vertices[index];
  61806. nV2 = vertices[index + 2];
  61807. nV3 = clipVertices(vertices[index + 1], nV1);
  61808. nV4 = clipVertices(vertices[index + 1], nV2);
  61809. result.push(nV3);
  61810. result.push(nV2.clone());
  61811. result.push(nV1.clone());
  61812. result.push(nV2.clone());
  61813. result.push(nV3.clone());
  61814. result.push(nV4);
  61815. break;
  61816. }
  61817. if (v3Out) {
  61818. nV1 = vertices[index];
  61819. nV2 = vertices[index + 1];
  61820. nV3 = clipVertices(vertices[index + 2], nV1);
  61821. nV4 = clipVertices(vertices[index + 2], nV2);
  61822. }
  61823. if (nV1 && nV2 && nV3 && nV4) {
  61824. result.push(nV1.clone());
  61825. result.push(nV2.clone());
  61826. result.push(nV3);
  61827. result.push(nV4);
  61828. result.push(nV3.clone());
  61829. result.push(nV2.clone());
  61830. }
  61831. break;
  61832. case 2:
  61833. if (!v1Out) {
  61834. nV1 = vertices[index].clone();
  61835. nV2 = clipVertices(nV1, vertices[index + 1]);
  61836. nV3 = clipVertices(nV1, vertices[index + 2]);
  61837. result.push(nV1);
  61838. result.push(nV2);
  61839. result.push(nV3);
  61840. }
  61841. if (!v2Out) {
  61842. nV1 = vertices[index + 1].clone();
  61843. nV2 = clipVertices(nV1, vertices[index + 2]);
  61844. nV3 = clipVertices(nV1, vertices[index]);
  61845. result.push(nV1);
  61846. result.push(nV2);
  61847. result.push(nV3);
  61848. }
  61849. if (!v3Out) {
  61850. nV1 = vertices[index + 2].clone();
  61851. nV2 = clipVertices(nV1, vertices[index]);
  61852. nV3 = clipVertices(nV1, vertices[index + 1]);
  61853. result.push(nV1);
  61854. result.push(nV2);
  61855. result.push(nV3);
  61856. }
  61857. break;
  61858. case 3:
  61859. break;
  61860. }
  61861. }
  61862. return result;
  61863. };
  61864. for (var index = 0; index < indices.length; index += 3) {
  61865. var faceVertices = new Array();
  61866. faceVertices.push(extractDecalVector3(index));
  61867. faceVertices.push(extractDecalVector3(index + 1));
  61868. faceVertices.push(extractDecalVector3(index + 2));
  61869. // Clip
  61870. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61871. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61872. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61873. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61874. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61875. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61876. if (faceVertices.length === 0) {
  61877. continue;
  61878. }
  61879. // Add UVs and get back to world
  61880. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61881. var vertex = faceVertices[vIndex];
  61882. //TODO check for Int32Array | Uint32Array | Uint16Array
  61883. vertexData.indices.push(currentVertexDataIndex);
  61884. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61885. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61886. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61887. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61888. currentVertexDataIndex++;
  61889. }
  61890. }
  61891. // Return mesh
  61892. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61893. vertexData.applyToMesh(decal);
  61894. decal.position = position.clone();
  61895. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61896. return decal;
  61897. };
  61898. // Privates
  61899. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61900. // extrusion geometry
  61901. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61902. var tangents = path3D.getTangents();
  61903. var normals = path3D.getNormals();
  61904. var binormals = path3D.getBinormals();
  61905. var distances = path3D.getDistances();
  61906. var angle = 0;
  61907. var returnScale = function () { return scale !== null ? scale : 1; };
  61908. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61909. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61910. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61911. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61912. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61913. for (var i = 0; i < curve.length; i++) {
  61914. var shapePath = new Array();
  61915. var angleStep = rotate(i, distances[i]);
  61916. var scaleRatio = scl(i, distances[i]);
  61917. for (var p = 0; p < shape.length; p++) {
  61918. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61919. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61920. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61921. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61922. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61923. shapePath[p] = rotated;
  61924. }
  61925. shapePaths[index] = shapePath;
  61926. angle += angleStep;
  61927. index++;
  61928. }
  61929. // cap
  61930. var capPath = function (shapePath) {
  61931. var pointCap = Array();
  61932. var barycenter = BABYLON.Vector3.Zero();
  61933. var i;
  61934. for (i = 0; i < shapePath.length; i++) {
  61935. barycenter.addInPlace(shapePath[i]);
  61936. }
  61937. barycenter.scaleInPlace(1.0 / shapePath.length);
  61938. for (i = 0; i < shapePath.length; i++) {
  61939. pointCap.push(barycenter);
  61940. }
  61941. return pointCap;
  61942. };
  61943. switch (cap) {
  61944. case BABYLON.Mesh.NO_CAP:
  61945. break;
  61946. case BABYLON.Mesh.CAP_START:
  61947. shapePaths[0] = capPath(shapePaths[2]);
  61948. shapePaths[1] = shapePaths[2];
  61949. break;
  61950. case BABYLON.Mesh.CAP_END:
  61951. shapePaths[index] = shapePaths[index - 1];
  61952. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61953. break;
  61954. case BABYLON.Mesh.CAP_ALL:
  61955. shapePaths[0] = capPath(shapePaths[2]);
  61956. shapePaths[1] = shapePaths[2];
  61957. shapePaths[index] = shapePaths[index - 1];
  61958. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61959. break;
  61960. default:
  61961. break;
  61962. }
  61963. return shapePaths;
  61964. };
  61965. var path3D;
  61966. var pathArray;
  61967. if (instance) { // instance update
  61968. path3D = (instance.path3D).update(curve);
  61969. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61970. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61971. return instance;
  61972. }
  61973. // extruded shape creation
  61974. path3D = new BABYLON.Path3D(curve);
  61975. var newShapePaths = new Array();
  61976. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61977. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61978. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61979. extrudedGeneric.pathArray = pathArray;
  61980. extrudedGeneric.path3D = path3D;
  61981. extrudedGeneric.cap = cap;
  61982. return extrudedGeneric;
  61983. };
  61984. return MeshBuilder;
  61985. }());
  61986. BABYLON.MeshBuilder = MeshBuilder;
  61987. })(BABYLON || (BABYLON = {}));
  61988. //# sourceMappingURL=babylon.meshBuilder.js.map
  61989. var BABYLON;
  61990. (function (BABYLON) {
  61991. /**
  61992. * Draco compression (https://google.github.io/draco/)
  61993. *
  61994. * This class wraps the Draco module.
  61995. *
  61996. * **Encoder**
  61997. *
  61998. * The encoder is not currently implemented.
  61999. *
  62000. * **Decoder**
  62001. *
  62002. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62003. *
  62004. * To update the configuration, use the following code:
  62005. * ```javascript
  62006. * BABYLON.DracoCompression.Configuration = {
  62007. * decoder: {
  62008. * wasmUrl: "<url to the WebAssembly library>",
  62009. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62010. * fallbackUrl: "<url to the fallback JavaScript library>",
  62011. * }
  62012. * };
  62013. * ```
  62014. *
  62015. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  62016. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62017. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62018. *
  62019. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62020. * ```javascript
  62021. * var dracoCompression = new BABYLON.DracoCompression();
  62022. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62023. * [BABYLON.VertexBuffer.PositionKind]: 0
  62024. * });
  62025. * ```
  62026. *
  62027. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62028. */
  62029. var DracoCompression = /** @class */ (function () {
  62030. /**
  62031. * Constructor
  62032. */
  62033. function DracoCompression() {
  62034. }
  62035. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62036. /**
  62037. * Returns true if the decoder is available.
  62038. */
  62039. get: function () {
  62040. if (typeof DracoDecoderModule !== "undefined") {
  62041. return true;
  62042. }
  62043. var decoder = DracoCompression.Configuration.decoder;
  62044. if (decoder) {
  62045. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62046. return true;
  62047. }
  62048. if (decoder.fallbackUrl) {
  62049. return true;
  62050. }
  62051. }
  62052. return false;
  62053. },
  62054. enumerable: true,
  62055. configurable: true
  62056. });
  62057. /**
  62058. * Stop all async operations and release resources.
  62059. */
  62060. DracoCompression.prototype.dispose = function () {
  62061. };
  62062. /**
  62063. * Decode Draco compressed mesh data to vertex data.
  62064. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62065. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62066. * @returns A promise that resolves with the decoded vertex data
  62067. */
  62068. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62069. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62070. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62071. var module = wrappedModule.module;
  62072. var vertexData = new BABYLON.VertexData();
  62073. var buffer = new module.DecoderBuffer();
  62074. buffer.Init(dataView, dataView.byteLength);
  62075. var decoder = new module.Decoder();
  62076. var geometry;
  62077. var status;
  62078. try {
  62079. var type = decoder.GetEncodedGeometryType(buffer);
  62080. switch (type) {
  62081. case module.TRIANGULAR_MESH:
  62082. geometry = new module.Mesh();
  62083. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62084. break;
  62085. case module.POINT_CLOUD:
  62086. geometry = new module.PointCloud();
  62087. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62088. break;
  62089. default:
  62090. throw new Error("Invalid geometry type " + type);
  62091. }
  62092. if (!status.ok() || !geometry.ptr) {
  62093. throw new Error(status.error_msg());
  62094. }
  62095. var numPoints = geometry.num_points();
  62096. if (type === module.TRIANGULAR_MESH) {
  62097. var numFaces = geometry.num_faces();
  62098. var faceIndices = new module.DracoInt32Array();
  62099. try {
  62100. var indices = new Uint32Array(numFaces * 3);
  62101. for (var i = 0; i < numFaces; i++) {
  62102. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62103. var offset = i * 3;
  62104. indices[offset + 0] = faceIndices.GetValue(0);
  62105. indices[offset + 1] = faceIndices.GetValue(1);
  62106. indices[offset + 2] = faceIndices.GetValue(2);
  62107. }
  62108. vertexData.indices = indices;
  62109. }
  62110. finally {
  62111. module.destroy(faceIndices);
  62112. }
  62113. }
  62114. for (var kind in attributes) {
  62115. var uniqueId = attributes[kind];
  62116. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62117. var dracoData = new module.DracoFloat32Array();
  62118. try {
  62119. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62120. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62121. for (var i = 0; i < babylonData.length; i++) {
  62122. babylonData[i] = dracoData.GetValue(i);
  62123. }
  62124. vertexData.set(babylonData, kind);
  62125. }
  62126. finally {
  62127. module.destroy(dracoData);
  62128. }
  62129. }
  62130. }
  62131. finally {
  62132. if (geometry) {
  62133. module.destroy(geometry);
  62134. }
  62135. module.destroy(decoder);
  62136. module.destroy(buffer);
  62137. }
  62138. return vertexData;
  62139. });
  62140. };
  62141. DracoCompression._GetDecoderModule = function () {
  62142. if (!DracoCompression._DecoderModulePromise) {
  62143. var promise = null;
  62144. var config_1 = {};
  62145. if (typeof DracoDecoderModule !== "undefined") {
  62146. promise = Promise.resolve();
  62147. }
  62148. else {
  62149. var decoder = DracoCompression.Configuration.decoder;
  62150. if (decoder) {
  62151. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62152. promise = Promise.all([
  62153. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62154. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62155. config_1.wasmBinary = data;
  62156. })
  62157. ]);
  62158. }
  62159. else if (decoder.fallbackUrl) {
  62160. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62161. }
  62162. }
  62163. }
  62164. if (!promise) {
  62165. throw new Error("Draco decoder module is not available");
  62166. }
  62167. DracoCompression._DecoderModulePromise = promise.then(function () {
  62168. return new Promise(function (resolve) {
  62169. config_1.onModuleLoaded = function (decoderModule) {
  62170. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62171. resolve({ module: decoderModule });
  62172. };
  62173. DracoDecoderModule(config_1);
  62174. });
  62175. });
  62176. }
  62177. return DracoCompression._DecoderModulePromise;
  62178. };
  62179. DracoCompression._LoadScriptAsync = function (url) {
  62180. return new Promise(function (resolve, reject) {
  62181. BABYLON.Tools.LoadScript(url, function () {
  62182. resolve();
  62183. }, function (message) {
  62184. reject(new Error(message));
  62185. });
  62186. });
  62187. };
  62188. DracoCompression._LoadFileAsync = function (url) {
  62189. return new Promise(function (resolve, reject) {
  62190. BABYLON.Tools.LoadFile(url, function (data) {
  62191. resolve(data);
  62192. }, undefined, undefined, true, function (request, exception) {
  62193. reject(exception);
  62194. });
  62195. });
  62196. };
  62197. /**
  62198. * The configuration. Defaults to the following urls:
  62199. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62200. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62201. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62202. */
  62203. DracoCompression.Configuration = {
  62204. decoder: {
  62205. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62206. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62207. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62208. }
  62209. };
  62210. return DracoCompression;
  62211. }());
  62212. BABYLON.DracoCompression = DracoCompression;
  62213. })(BABYLON || (BABYLON = {}));
  62214. //# sourceMappingURL=babylon.dracoCompression.js.map
  62215. var BABYLON;
  62216. (function (BABYLON) {
  62217. var AudioEngine = /** @class */ (function () {
  62218. function AudioEngine() {
  62219. this._audioContext = null;
  62220. this._audioContextInitialized = false;
  62221. this.canUseWebAudio = false;
  62222. this.WarnedWebAudioUnsupported = false;
  62223. this.unlocked = false;
  62224. this.isMP3supported = false;
  62225. this.isOGGsupported = false;
  62226. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62227. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62228. this.canUseWebAudio = true;
  62229. }
  62230. var audioElem = document.createElement('audio');
  62231. try {
  62232. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62233. this.isMP3supported = true;
  62234. }
  62235. }
  62236. catch (e) {
  62237. // protect error during capability check.
  62238. }
  62239. try {
  62240. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62241. this.isOGGsupported = true;
  62242. }
  62243. }
  62244. catch (e) {
  62245. // protect error during capability check.
  62246. }
  62247. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62248. this._unlockiOSaudio();
  62249. }
  62250. else {
  62251. this.unlocked = true;
  62252. }
  62253. }
  62254. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62255. get: function () {
  62256. if (!this._audioContextInitialized) {
  62257. this._initializeAudioContext();
  62258. }
  62259. return this._audioContext;
  62260. },
  62261. enumerable: true,
  62262. configurable: true
  62263. });
  62264. AudioEngine.prototype._unlockiOSaudio = function () {
  62265. var _this = this;
  62266. var unlockaudio = function () {
  62267. if (!_this.audioContext) {
  62268. return;
  62269. }
  62270. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62271. var source = _this.audioContext.createBufferSource();
  62272. source.buffer = buffer;
  62273. source.connect(_this.audioContext.destination);
  62274. source.start(0);
  62275. setTimeout(function () {
  62276. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62277. _this.unlocked = true;
  62278. window.removeEventListener('touchend', unlockaudio, false);
  62279. if (_this.onAudioUnlocked) {
  62280. _this.onAudioUnlocked();
  62281. }
  62282. }
  62283. }, 0);
  62284. };
  62285. window.addEventListener('touchend', unlockaudio, false);
  62286. };
  62287. AudioEngine.prototype._initializeAudioContext = function () {
  62288. try {
  62289. if (this.canUseWebAudio) {
  62290. this._audioContext = new AudioContext();
  62291. // create a global volume gain node
  62292. this.masterGain = this._audioContext.createGain();
  62293. this.masterGain.gain.value = 1;
  62294. this.masterGain.connect(this._audioContext.destination);
  62295. this._audioContextInitialized = true;
  62296. }
  62297. }
  62298. catch (e) {
  62299. this.canUseWebAudio = false;
  62300. BABYLON.Tools.Error("Web Audio: " + e.message);
  62301. }
  62302. };
  62303. AudioEngine.prototype.dispose = function () {
  62304. if (this.canUseWebAudio && this._audioContextInitialized) {
  62305. if (this._connectedAnalyser && this._audioContext) {
  62306. this._connectedAnalyser.stopDebugCanvas();
  62307. this._connectedAnalyser.dispose();
  62308. this.masterGain.disconnect();
  62309. this.masterGain.connect(this._audioContext.destination);
  62310. this._connectedAnalyser = null;
  62311. }
  62312. this.masterGain.gain.value = 1;
  62313. }
  62314. this.WarnedWebAudioUnsupported = false;
  62315. };
  62316. AudioEngine.prototype.getGlobalVolume = function () {
  62317. if (this.canUseWebAudio && this._audioContextInitialized) {
  62318. return this.masterGain.gain.value;
  62319. }
  62320. else {
  62321. return -1;
  62322. }
  62323. };
  62324. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62325. if (this.canUseWebAudio && this._audioContextInitialized) {
  62326. this.masterGain.gain.value = newVolume;
  62327. }
  62328. };
  62329. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62330. if (this._connectedAnalyser) {
  62331. this._connectedAnalyser.stopDebugCanvas();
  62332. }
  62333. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62334. this._connectedAnalyser = analyser;
  62335. this.masterGain.disconnect();
  62336. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62337. }
  62338. };
  62339. return AudioEngine;
  62340. }());
  62341. BABYLON.AudioEngine = AudioEngine;
  62342. })(BABYLON || (BABYLON = {}));
  62343. //# sourceMappingURL=babylon.audioEngine.js.map
  62344. var BABYLON;
  62345. (function (BABYLON) {
  62346. var Sound = /** @class */ (function () {
  62347. /**
  62348. * Create a sound and attach it to a scene
  62349. * @param name Name of your sound
  62350. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62351. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62352. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62353. */
  62354. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62355. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62356. var _this = this;
  62357. this.autoplay = false;
  62358. this.loop = false;
  62359. this.useCustomAttenuation = false;
  62360. this.spatialSound = false;
  62361. this.refDistance = 1;
  62362. this.rolloffFactor = 1;
  62363. this.maxDistance = 100;
  62364. this.distanceModel = "linear";
  62365. this._panningModel = "equalpower";
  62366. this._playbackRate = 1;
  62367. this._streaming = false;
  62368. this._startTime = 0;
  62369. this._startOffset = 0;
  62370. this._position = BABYLON.Vector3.Zero();
  62371. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62372. this._volume = 1;
  62373. this._isReadyToPlay = false;
  62374. this.isPlaying = false;
  62375. this.isPaused = false;
  62376. this._isDirectional = false;
  62377. // Used if you'd like to create a directional sound.
  62378. // If not set, the sound will be omnidirectional
  62379. this._coneInnerAngle = 360;
  62380. this._coneOuterAngle = 360;
  62381. this._coneOuterGain = 0;
  62382. this._isOutputConnected = false;
  62383. this._urlType = "Unknown";
  62384. this.name = name;
  62385. this._scene = scene;
  62386. this._readyToPlayCallback = readyToPlayCallback;
  62387. // Default custom attenuation function is a linear attenuation
  62388. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62389. if (currentDistance < maxDistance) {
  62390. return currentVolume * (1 - currentDistance / maxDistance);
  62391. }
  62392. else {
  62393. return 0;
  62394. }
  62395. };
  62396. if (options) {
  62397. this.autoplay = options.autoplay || false;
  62398. this.loop = options.loop || false;
  62399. // if volume === 0, we need another way to check this option
  62400. if (options.volume !== undefined) {
  62401. this._volume = options.volume;
  62402. }
  62403. this.spatialSound = options.spatialSound || false;
  62404. this.maxDistance = options.maxDistance || 100;
  62405. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62406. this.rolloffFactor = options.rolloffFactor || 1;
  62407. this.refDistance = options.refDistance || 1;
  62408. this.distanceModel = options.distanceModel || "linear";
  62409. this._playbackRate = options.playbackRate || 1;
  62410. this._streaming = options.streaming || false;
  62411. }
  62412. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62413. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62414. this._soundGain.gain.value = this._volume;
  62415. this._inputAudioNode = this._soundGain;
  62416. this._ouputAudioNode = this._soundGain;
  62417. if (this.spatialSound) {
  62418. this._createSpatialParameters();
  62419. }
  62420. this._scene.mainSoundTrack.AddSound(this);
  62421. var validParameter = true;
  62422. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62423. if (urlOrArrayBuffer) {
  62424. try {
  62425. if (typeof (urlOrArrayBuffer) === "string")
  62426. this._urlType = "String";
  62427. if (Array.isArray(urlOrArrayBuffer))
  62428. this._urlType = "Array";
  62429. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62430. this._urlType = "ArrayBuffer";
  62431. var urls = [];
  62432. var codecSupportedFound = false;
  62433. switch (this._urlType) {
  62434. case "ArrayBuffer":
  62435. if (urlOrArrayBuffer.byteLength > 0) {
  62436. codecSupportedFound = true;
  62437. this._soundLoaded(urlOrArrayBuffer);
  62438. }
  62439. break;
  62440. case "String":
  62441. urls.push(urlOrArrayBuffer);
  62442. case "Array":
  62443. if (urls.length === 0)
  62444. urls = urlOrArrayBuffer;
  62445. // If we found a supported format, we load it immediately and stop the loop
  62446. for (var i = 0; i < urls.length; i++) {
  62447. var url = urls[i];
  62448. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62449. codecSupportedFound = true;
  62450. }
  62451. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62452. codecSupportedFound = true;
  62453. }
  62454. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62455. codecSupportedFound = true;
  62456. }
  62457. if (url.indexOf("blob:") !== -1) {
  62458. codecSupportedFound = true;
  62459. }
  62460. if (codecSupportedFound) {
  62461. // Loading sound using XHR2
  62462. if (!this._streaming) {
  62463. this._scene._loadFile(url, function (data) {
  62464. _this._soundLoaded(data);
  62465. }, undefined, true, true, function (exception) {
  62466. if (exception) {
  62467. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62468. }
  62469. BABYLON.Tools.Error("Sound creation aborted.");
  62470. _this._scene.mainSoundTrack.RemoveSound(_this);
  62471. });
  62472. }
  62473. // Streaming sound using HTML5 Audio tag
  62474. else {
  62475. this._htmlAudioElement = new Audio(url);
  62476. this._htmlAudioElement.controls = false;
  62477. this._htmlAudioElement.loop = this.loop;
  62478. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62479. this._htmlAudioElement.preload = "auto";
  62480. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62481. _this._isReadyToPlay = true;
  62482. if (_this.autoplay) {
  62483. _this.play();
  62484. }
  62485. if (_this._readyToPlayCallback) {
  62486. _this._readyToPlayCallback();
  62487. }
  62488. });
  62489. document.body.appendChild(this._htmlAudioElement);
  62490. }
  62491. break;
  62492. }
  62493. }
  62494. break;
  62495. default:
  62496. validParameter = false;
  62497. break;
  62498. }
  62499. if (!validParameter) {
  62500. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62501. }
  62502. else {
  62503. if (!codecSupportedFound) {
  62504. this._isReadyToPlay = true;
  62505. // Simulating a ready to play event to avoid breaking code path
  62506. if (this._readyToPlayCallback) {
  62507. window.setTimeout(function () {
  62508. if (_this._readyToPlayCallback) {
  62509. _this._readyToPlayCallback();
  62510. }
  62511. }, 1000);
  62512. }
  62513. }
  62514. }
  62515. }
  62516. catch (ex) {
  62517. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62518. this._scene.mainSoundTrack.RemoveSound(this);
  62519. }
  62520. }
  62521. }
  62522. else {
  62523. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62524. this._scene.mainSoundTrack.AddSound(this);
  62525. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62526. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62527. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62528. }
  62529. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62530. if (this._readyToPlayCallback) {
  62531. window.setTimeout(function () {
  62532. if (_this._readyToPlayCallback) {
  62533. _this._readyToPlayCallback();
  62534. }
  62535. }, 1000);
  62536. }
  62537. }
  62538. }
  62539. Sound.prototype.dispose = function () {
  62540. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62541. if (this.isPlaying) {
  62542. this.stop();
  62543. }
  62544. this._isReadyToPlay = false;
  62545. if (this.soundTrackId === -1) {
  62546. this._scene.mainSoundTrack.RemoveSound(this);
  62547. }
  62548. else {
  62549. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62550. }
  62551. if (this._soundGain) {
  62552. this._soundGain.disconnect();
  62553. this._soundGain = null;
  62554. }
  62555. if (this._soundPanner) {
  62556. this._soundPanner.disconnect();
  62557. this._soundPanner = null;
  62558. }
  62559. if (this._soundSource) {
  62560. this._soundSource.disconnect();
  62561. this._soundSource = null;
  62562. }
  62563. this._audioBuffer = null;
  62564. if (this._htmlAudioElement) {
  62565. this._htmlAudioElement.pause();
  62566. this._htmlAudioElement.src = "";
  62567. document.body.removeChild(this._htmlAudioElement);
  62568. }
  62569. if (this._connectedMesh && this._registerFunc) {
  62570. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62571. this._connectedMesh = null;
  62572. }
  62573. }
  62574. };
  62575. Sound.prototype.isReady = function () {
  62576. return this._isReadyToPlay;
  62577. };
  62578. Sound.prototype._soundLoaded = function (audioData) {
  62579. var _this = this;
  62580. if (!BABYLON.Engine.audioEngine.audioContext) {
  62581. return;
  62582. }
  62583. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62584. _this._audioBuffer = buffer;
  62585. _this._isReadyToPlay = true;
  62586. if (_this.autoplay) {
  62587. _this.play();
  62588. }
  62589. if (_this._readyToPlayCallback) {
  62590. _this._readyToPlayCallback();
  62591. }
  62592. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62593. };
  62594. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62595. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62596. this._audioBuffer = audioBuffer;
  62597. this._isReadyToPlay = true;
  62598. }
  62599. };
  62600. Sound.prototype.updateOptions = function (options) {
  62601. if (options) {
  62602. this.loop = options.loop || this.loop;
  62603. this.maxDistance = options.maxDistance || this.maxDistance;
  62604. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62605. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62606. this.refDistance = options.refDistance || this.refDistance;
  62607. this.distanceModel = options.distanceModel || this.distanceModel;
  62608. this._playbackRate = options.playbackRate || this._playbackRate;
  62609. this._updateSpatialParameters();
  62610. if (this.isPlaying) {
  62611. if (this._streaming) {
  62612. this._htmlAudioElement.playbackRate = this._playbackRate;
  62613. }
  62614. else {
  62615. if (this._soundSource) {
  62616. this._soundSource.playbackRate.value = this._playbackRate;
  62617. }
  62618. }
  62619. }
  62620. }
  62621. };
  62622. Sound.prototype._createSpatialParameters = function () {
  62623. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62624. if (this._scene.headphone) {
  62625. this._panningModel = "HRTF";
  62626. }
  62627. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62628. this._updateSpatialParameters();
  62629. this._soundPanner.connect(this._ouputAudioNode);
  62630. this._inputAudioNode = this._soundPanner;
  62631. }
  62632. };
  62633. Sound.prototype._updateSpatialParameters = function () {
  62634. if (this.spatialSound && this._soundPanner) {
  62635. if (this.useCustomAttenuation) {
  62636. // Tricks to disable in a way embedded Web Audio attenuation
  62637. this._soundPanner.distanceModel = "linear";
  62638. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62639. this._soundPanner.refDistance = 1;
  62640. this._soundPanner.rolloffFactor = 1;
  62641. this._soundPanner.panningModel = this._panningModel;
  62642. }
  62643. else {
  62644. this._soundPanner.distanceModel = this.distanceModel;
  62645. this._soundPanner.maxDistance = this.maxDistance;
  62646. this._soundPanner.refDistance = this.refDistance;
  62647. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62648. this._soundPanner.panningModel = this._panningModel;
  62649. }
  62650. }
  62651. };
  62652. Sound.prototype.switchPanningModelToHRTF = function () {
  62653. this._panningModel = "HRTF";
  62654. this._switchPanningModel();
  62655. };
  62656. Sound.prototype.switchPanningModelToEqualPower = function () {
  62657. this._panningModel = "equalpower";
  62658. this._switchPanningModel();
  62659. };
  62660. Sound.prototype._switchPanningModel = function () {
  62661. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62662. this._soundPanner.panningModel = this._panningModel;
  62663. }
  62664. };
  62665. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62666. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62667. if (this._isOutputConnected) {
  62668. this._ouputAudioNode.disconnect();
  62669. }
  62670. this._ouputAudioNode.connect(soundTrackAudioNode);
  62671. this._isOutputConnected = true;
  62672. }
  62673. };
  62674. /**
  62675. * Transform this sound into a directional source
  62676. * @param coneInnerAngle Size of the inner cone in degree
  62677. * @param coneOuterAngle Size of the outer cone in degree
  62678. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62679. */
  62680. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62681. if (coneOuterAngle < coneInnerAngle) {
  62682. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62683. return;
  62684. }
  62685. this._coneInnerAngle = coneInnerAngle;
  62686. this._coneOuterAngle = coneOuterAngle;
  62687. this._coneOuterGain = coneOuterGain;
  62688. this._isDirectional = true;
  62689. if (this.isPlaying && this.loop) {
  62690. this.stop();
  62691. this.play();
  62692. }
  62693. };
  62694. Sound.prototype.setPosition = function (newPosition) {
  62695. this._position = newPosition;
  62696. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62697. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62698. }
  62699. };
  62700. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62701. this._localDirection = newLocalDirection;
  62702. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62703. this._updateDirection();
  62704. }
  62705. };
  62706. Sound.prototype._updateDirection = function () {
  62707. if (!this._connectedMesh || !this._soundPanner) {
  62708. return;
  62709. }
  62710. var mat = this._connectedMesh.getWorldMatrix();
  62711. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62712. direction.normalize();
  62713. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62714. };
  62715. Sound.prototype.updateDistanceFromListener = function () {
  62716. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62717. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62718. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62719. }
  62720. };
  62721. Sound.prototype.setAttenuationFunction = function (callback) {
  62722. this._customAttenuationFunction = callback;
  62723. };
  62724. /**
  62725. * Play the sound
  62726. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62727. * @param offset (optional) Start the sound setting it at a specific time
  62728. */
  62729. Sound.prototype.play = function (time, offset) {
  62730. var _this = this;
  62731. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62732. try {
  62733. if (this._startOffset < 0) {
  62734. time = -this._startOffset;
  62735. this._startOffset = 0;
  62736. }
  62737. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62738. if (!this._soundSource || !this._streamingSource) {
  62739. if (this.spatialSound && this._soundPanner) {
  62740. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62741. if (this._isDirectional) {
  62742. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62743. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62744. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62745. if (this._connectedMesh) {
  62746. this._updateDirection();
  62747. }
  62748. else {
  62749. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62750. }
  62751. }
  62752. }
  62753. }
  62754. if (this._streaming) {
  62755. if (!this._streamingSource) {
  62756. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62757. this._htmlAudioElement.onended = function () { _this._onended(); };
  62758. this._htmlAudioElement.playbackRate = this._playbackRate;
  62759. }
  62760. this._streamingSource.disconnect();
  62761. this._streamingSource.connect(this._inputAudioNode);
  62762. this._htmlAudioElement.play();
  62763. }
  62764. else {
  62765. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62766. this._soundSource.buffer = this._audioBuffer;
  62767. this._soundSource.connect(this._inputAudioNode);
  62768. this._soundSource.loop = this.loop;
  62769. this._soundSource.playbackRate.value = this._playbackRate;
  62770. this._soundSource.onended = function () { _this._onended(); };
  62771. if (this._soundSource.buffer) {
  62772. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62773. }
  62774. }
  62775. this._startTime = startTime;
  62776. this.isPlaying = true;
  62777. this.isPaused = false;
  62778. }
  62779. catch (ex) {
  62780. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62781. }
  62782. }
  62783. };
  62784. Sound.prototype._onended = function () {
  62785. this.isPlaying = false;
  62786. if (this.onended) {
  62787. this.onended();
  62788. }
  62789. };
  62790. /**
  62791. * Stop the sound
  62792. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62793. */
  62794. Sound.prototype.stop = function (time) {
  62795. if (this.isPlaying) {
  62796. if (this._streaming) {
  62797. this._htmlAudioElement.pause();
  62798. // Test needed for Firefox or it will generate an Invalid State Error
  62799. if (this._htmlAudioElement.currentTime > 0) {
  62800. this._htmlAudioElement.currentTime = 0;
  62801. }
  62802. }
  62803. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62804. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62805. this._soundSource.stop(stopTime);
  62806. this._soundSource.onended = function () { };
  62807. if (!this.isPaused) {
  62808. this._startOffset = 0;
  62809. }
  62810. }
  62811. this.isPlaying = false;
  62812. }
  62813. };
  62814. Sound.prototype.pause = function () {
  62815. if (this.isPlaying) {
  62816. this.isPaused = true;
  62817. if (this._streaming) {
  62818. this._htmlAudioElement.pause();
  62819. }
  62820. else if (BABYLON.Engine.audioEngine.audioContext) {
  62821. this.stop(0);
  62822. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62823. }
  62824. }
  62825. };
  62826. Sound.prototype.setVolume = function (newVolume, time) {
  62827. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62828. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62829. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62830. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62831. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62832. }
  62833. else {
  62834. this._soundGain.gain.value = newVolume;
  62835. }
  62836. }
  62837. this._volume = newVolume;
  62838. };
  62839. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62840. this._playbackRate = newPlaybackRate;
  62841. if (this.isPlaying) {
  62842. if (this._streaming) {
  62843. this._htmlAudioElement.playbackRate = this._playbackRate;
  62844. }
  62845. else if (this._soundSource) {
  62846. this._soundSource.playbackRate.value = this._playbackRate;
  62847. }
  62848. }
  62849. };
  62850. Sound.prototype.getVolume = function () {
  62851. return this._volume;
  62852. };
  62853. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62854. var _this = this;
  62855. if (this._connectedMesh && this._registerFunc) {
  62856. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62857. this._registerFunc = null;
  62858. }
  62859. this._connectedMesh = meshToConnectTo;
  62860. if (!this.spatialSound) {
  62861. this.spatialSound = true;
  62862. this._createSpatialParameters();
  62863. if (this.isPlaying && this.loop) {
  62864. this.stop();
  62865. this.play();
  62866. }
  62867. }
  62868. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62869. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62870. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62871. };
  62872. Sound.prototype.detachFromMesh = function () {
  62873. if (this._connectedMesh && this._registerFunc) {
  62874. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62875. this._registerFunc = null;
  62876. this._connectedMesh = null;
  62877. }
  62878. };
  62879. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62880. if (!node.getBoundingInfo) {
  62881. return;
  62882. }
  62883. var mesh = node;
  62884. var boundingInfo = mesh.getBoundingInfo();
  62885. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62886. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62887. this._updateDirection();
  62888. }
  62889. };
  62890. Sound.prototype.clone = function () {
  62891. var _this = this;
  62892. if (!this._streaming) {
  62893. var setBufferAndRun = function () {
  62894. if (_this._isReadyToPlay) {
  62895. clonedSound._audioBuffer = _this.getAudioBuffer();
  62896. clonedSound._isReadyToPlay = true;
  62897. if (clonedSound.autoplay) {
  62898. clonedSound.play();
  62899. }
  62900. }
  62901. else {
  62902. window.setTimeout(setBufferAndRun, 300);
  62903. }
  62904. };
  62905. var currentOptions = {
  62906. autoplay: this.autoplay, loop: this.loop,
  62907. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62908. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62909. refDistance: this.refDistance, distanceModel: this.distanceModel
  62910. };
  62911. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62912. if (this.useCustomAttenuation) {
  62913. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62914. }
  62915. clonedSound.setPosition(this._position);
  62916. clonedSound.setPlaybackRate(this._playbackRate);
  62917. setBufferAndRun();
  62918. return clonedSound;
  62919. }
  62920. // Can't clone a streaming sound
  62921. else {
  62922. return null;
  62923. }
  62924. };
  62925. Sound.prototype.getAudioBuffer = function () {
  62926. return this._audioBuffer;
  62927. };
  62928. Sound.prototype.serialize = function () {
  62929. var serializationObject = {
  62930. name: this.name,
  62931. url: this.name,
  62932. autoplay: this.autoplay,
  62933. loop: this.loop,
  62934. volume: this._volume,
  62935. spatialSound: this.spatialSound,
  62936. maxDistance: this.maxDistance,
  62937. rolloffFactor: this.rolloffFactor,
  62938. refDistance: this.refDistance,
  62939. distanceModel: this.distanceModel,
  62940. playbackRate: this._playbackRate,
  62941. panningModel: this._panningModel,
  62942. soundTrackId: this.soundTrackId
  62943. };
  62944. if (this.spatialSound) {
  62945. if (this._connectedMesh)
  62946. serializationObject.connectedMeshId = this._connectedMesh.id;
  62947. serializationObject.position = this._position.asArray();
  62948. serializationObject.refDistance = this.refDistance;
  62949. serializationObject.distanceModel = this.distanceModel;
  62950. serializationObject.isDirectional = this._isDirectional;
  62951. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62952. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62953. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62954. serializationObject.coneOuterGain = this._coneOuterGain;
  62955. }
  62956. return serializationObject;
  62957. };
  62958. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62959. var soundName = parsedSound.name;
  62960. var soundUrl;
  62961. if (parsedSound.url) {
  62962. soundUrl = rootUrl + parsedSound.url;
  62963. }
  62964. else {
  62965. soundUrl = rootUrl + soundName;
  62966. }
  62967. var options = {
  62968. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62969. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62970. rolloffFactor: parsedSound.rolloffFactor,
  62971. refDistance: parsedSound.refDistance,
  62972. distanceModel: parsedSound.distanceModel,
  62973. playbackRate: parsedSound.playbackRate
  62974. };
  62975. var newSound;
  62976. if (!sourceSound) {
  62977. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62978. scene._addPendingData(newSound);
  62979. }
  62980. else {
  62981. var setBufferAndRun = function () {
  62982. if (sourceSound._isReadyToPlay) {
  62983. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62984. newSound._isReadyToPlay = true;
  62985. if (newSound.autoplay) {
  62986. newSound.play();
  62987. }
  62988. }
  62989. else {
  62990. window.setTimeout(setBufferAndRun, 300);
  62991. }
  62992. };
  62993. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62994. setBufferAndRun();
  62995. }
  62996. if (parsedSound.position) {
  62997. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62998. newSound.setPosition(soundPosition);
  62999. }
  63000. if (parsedSound.isDirectional) {
  63001. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63002. if (parsedSound.localDirectionToMesh) {
  63003. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63004. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63005. }
  63006. }
  63007. if (parsedSound.connectedMeshId) {
  63008. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63009. if (connectedMesh) {
  63010. newSound.attachToMesh(connectedMesh);
  63011. }
  63012. }
  63013. return newSound;
  63014. };
  63015. return Sound;
  63016. }());
  63017. BABYLON.Sound = Sound;
  63018. })(BABYLON || (BABYLON = {}));
  63019. //# sourceMappingURL=babylon.sound.js.map
  63020. var BABYLON;
  63021. (function (BABYLON) {
  63022. var SoundTrack = /** @class */ (function () {
  63023. function SoundTrack(scene, options) {
  63024. this.id = -1;
  63025. this._isMainTrack = false;
  63026. this._isInitialized = false;
  63027. this._scene = scene;
  63028. this.soundCollection = new Array();
  63029. this._options = options;
  63030. if (!this._isMainTrack) {
  63031. this._scene.soundTracks.push(this);
  63032. this.id = this._scene.soundTracks.length - 1;
  63033. }
  63034. }
  63035. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63036. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63037. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63038. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63039. if (this._options) {
  63040. if (this._options.volume) {
  63041. this._outputAudioNode.gain.value = this._options.volume;
  63042. }
  63043. if (this._options.mainTrack) {
  63044. this._isMainTrack = this._options.mainTrack;
  63045. }
  63046. }
  63047. this._isInitialized = true;
  63048. }
  63049. };
  63050. SoundTrack.prototype.dispose = function () {
  63051. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63052. if (this._connectedAnalyser) {
  63053. this._connectedAnalyser.stopDebugCanvas();
  63054. }
  63055. while (this.soundCollection.length) {
  63056. this.soundCollection[0].dispose();
  63057. }
  63058. if (this._outputAudioNode) {
  63059. this._outputAudioNode.disconnect();
  63060. }
  63061. this._outputAudioNode = null;
  63062. }
  63063. };
  63064. SoundTrack.prototype.AddSound = function (sound) {
  63065. if (!this._isInitialized) {
  63066. this._initializeSoundTrackAudioGraph();
  63067. }
  63068. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63069. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63070. }
  63071. if (sound.soundTrackId) {
  63072. if (sound.soundTrackId === -1) {
  63073. this._scene.mainSoundTrack.RemoveSound(sound);
  63074. }
  63075. else {
  63076. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63077. }
  63078. }
  63079. this.soundCollection.push(sound);
  63080. sound.soundTrackId = this.id;
  63081. };
  63082. SoundTrack.prototype.RemoveSound = function (sound) {
  63083. var index = this.soundCollection.indexOf(sound);
  63084. if (index !== -1) {
  63085. this.soundCollection.splice(index, 1);
  63086. }
  63087. };
  63088. SoundTrack.prototype.setVolume = function (newVolume) {
  63089. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63090. this._outputAudioNode.gain.value = newVolume;
  63091. }
  63092. };
  63093. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63094. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63095. for (var i = 0; i < this.soundCollection.length; i++) {
  63096. this.soundCollection[i].switchPanningModelToHRTF();
  63097. }
  63098. }
  63099. };
  63100. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63101. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63102. for (var i = 0; i < this.soundCollection.length; i++) {
  63103. this.soundCollection[i].switchPanningModelToEqualPower();
  63104. }
  63105. }
  63106. };
  63107. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63108. if (this._connectedAnalyser) {
  63109. this._connectedAnalyser.stopDebugCanvas();
  63110. }
  63111. this._connectedAnalyser = analyser;
  63112. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63113. this._outputAudioNode.disconnect();
  63114. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63115. }
  63116. };
  63117. return SoundTrack;
  63118. }());
  63119. BABYLON.SoundTrack = SoundTrack;
  63120. })(BABYLON || (BABYLON = {}));
  63121. //# sourceMappingURL=babylon.soundtrack.js.map
  63122. var BABYLON;
  63123. (function (BABYLON) {
  63124. /**
  63125. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63126. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63127. */
  63128. var Analyser = /** @class */ (function () {
  63129. /**
  63130. * Creates a new analyser
  63131. * @param scene defines hosting scene
  63132. */
  63133. function Analyser(scene) {
  63134. /**
  63135. * Gets or sets the smoothing
  63136. * @ignorenaming
  63137. */
  63138. this.SMOOTHING = 0.75;
  63139. /**
  63140. * Gets or sets the FFT table size
  63141. * @ignorenaming
  63142. */
  63143. this.FFT_SIZE = 512;
  63144. /**
  63145. * Gets or sets the bar graph amplitude
  63146. * @ignorenaming
  63147. */
  63148. this.BARGRAPHAMPLITUDE = 256;
  63149. /**
  63150. * Gets or sets the position of the debug canvas
  63151. * @ignorenaming
  63152. */
  63153. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63154. /**
  63155. * Gets or sets the debug canvas size
  63156. * @ignorenaming
  63157. */
  63158. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63159. this._scene = scene;
  63160. this._audioEngine = BABYLON.Engine.audioEngine;
  63161. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63162. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63163. this._webAudioAnalyser.minDecibels = -140;
  63164. this._webAudioAnalyser.maxDecibels = 0;
  63165. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63166. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63167. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63168. }
  63169. }
  63170. /**
  63171. * Get the number of data values you will have to play with for the visualization
  63172. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63173. * @returns a number
  63174. */
  63175. Analyser.prototype.getFrequencyBinCount = function () {
  63176. if (this._audioEngine.canUseWebAudio) {
  63177. return this._webAudioAnalyser.frequencyBinCount;
  63178. }
  63179. else {
  63180. return 0;
  63181. }
  63182. };
  63183. /**
  63184. * Gets the current frequency data as a byte array
  63185. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63186. * @returns a Uint8Array
  63187. */
  63188. Analyser.prototype.getByteFrequencyData = function () {
  63189. if (this._audioEngine.canUseWebAudio) {
  63190. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63191. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63192. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63193. }
  63194. return this._byteFreqs;
  63195. };
  63196. /**
  63197. * Gets the current waveform as a byte array
  63198. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63199. * @returns a Uint8Array
  63200. */
  63201. Analyser.prototype.getByteTimeDomainData = function () {
  63202. if (this._audioEngine.canUseWebAudio) {
  63203. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63204. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63205. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63206. }
  63207. return this._byteTime;
  63208. };
  63209. /**
  63210. * Gets the current frequency data as a float array
  63211. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63212. * @returns a Float32Array
  63213. */
  63214. Analyser.prototype.getFloatFrequencyData = function () {
  63215. if (this._audioEngine.canUseWebAudio) {
  63216. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63217. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63218. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63219. }
  63220. return this._floatFreqs;
  63221. };
  63222. /**
  63223. * Renders the debug canvas
  63224. */
  63225. Analyser.prototype.drawDebugCanvas = function () {
  63226. var _this = this;
  63227. if (this._audioEngine.canUseWebAudio) {
  63228. if (!this._debugCanvas) {
  63229. this._debugCanvas = document.createElement("canvas");
  63230. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63231. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63232. this._debugCanvas.style.position = "absolute";
  63233. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63234. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63235. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63236. document.body.appendChild(this._debugCanvas);
  63237. this._registerFunc = function () {
  63238. _this.drawDebugCanvas();
  63239. };
  63240. this._scene.registerBeforeRender(this._registerFunc);
  63241. }
  63242. if (this._registerFunc && this._debugCanvasContext) {
  63243. var workingArray = this.getByteFrequencyData();
  63244. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63245. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63246. // Draw the frequency domain chart.
  63247. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63248. var value = workingArray[i];
  63249. var percent = value / this.BARGRAPHAMPLITUDE;
  63250. var height = this.DEBUGCANVASSIZE.height * percent;
  63251. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63252. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63253. var hue = i / this.getFrequencyBinCount() * 360;
  63254. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63255. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63256. }
  63257. }
  63258. }
  63259. };
  63260. /**
  63261. * Stops rendering the debug canvas and removes it
  63262. */
  63263. Analyser.prototype.stopDebugCanvas = function () {
  63264. if (this._debugCanvas) {
  63265. if (this._registerFunc) {
  63266. this._scene.unregisterBeforeRender(this._registerFunc);
  63267. this._registerFunc = null;
  63268. }
  63269. document.body.removeChild(this._debugCanvas);
  63270. this._debugCanvas = null;
  63271. this._debugCanvasContext = null;
  63272. }
  63273. };
  63274. /**
  63275. * Connects two audio nodes
  63276. * @param inputAudioNode defines first node to connect
  63277. * @param outputAudioNode defines second node to connect
  63278. */
  63279. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63280. if (this._audioEngine.canUseWebAudio) {
  63281. inputAudioNode.connect(this._webAudioAnalyser);
  63282. this._webAudioAnalyser.connect(outputAudioNode);
  63283. }
  63284. };
  63285. /**
  63286. * Releases all associated resources
  63287. */
  63288. Analyser.prototype.dispose = function () {
  63289. if (this._audioEngine.canUseWebAudio) {
  63290. this._webAudioAnalyser.disconnect();
  63291. }
  63292. };
  63293. return Analyser;
  63294. }());
  63295. BABYLON.Analyser = Analyser;
  63296. })(BABYLON || (BABYLON = {}));
  63297. //# sourceMappingURL=babylon.analyser.js.map
  63298. var BABYLON;
  63299. (function (BABYLON) {
  63300. var CubeTexture = /** @class */ (function (_super) {
  63301. __extends(CubeTexture, _super);
  63302. /**
  63303. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63304. * as prefiltered data.
  63305. * @param rootUrl defines the url of the texture or the root name of the six images
  63306. * @param scene defines the scene the texture is attached to
  63307. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63308. * @param noMipmap defines if mipmaps should be created or not
  63309. * @param files defines the six files to load for the different faces
  63310. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63311. * @param onError defines a callback triggered in case of error during load
  63312. * @param format defines the internal format to use for the texture once loaded
  63313. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63314. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63315. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63316. * @return the cube texture
  63317. */
  63318. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials) {
  63319. if (extensions === void 0) { extensions = null; }
  63320. if (noMipmap === void 0) { noMipmap = false; }
  63321. if (files === void 0) { files = null; }
  63322. if (onLoad === void 0) { onLoad = null; }
  63323. if (onError === void 0) { onError = null; }
  63324. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63325. if (prefiltered === void 0) { prefiltered = false; }
  63326. if (forcedExtension === void 0) { forcedExtension = null; }
  63327. if (createPolynomials === void 0) { createPolynomials = false; }
  63328. var _this = _super.call(this, scene) || this;
  63329. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63330. /**
  63331. * Gets or sets the center of the bounding box associated with the cube texture
  63332. * It must define where the camera used to render the texture was set
  63333. */
  63334. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63335. _this._rotationY = 0;
  63336. _this.name = rootUrl;
  63337. _this.url = rootUrl;
  63338. _this._noMipmap = noMipmap;
  63339. _this.hasAlpha = false;
  63340. _this._format = format;
  63341. _this._prefiltered = prefiltered;
  63342. _this.isCube = true;
  63343. _this._textureMatrix = BABYLON.Matrix.Identity();
  63344. _this._createPolynomials = createPolynomials;
  63345. if (prefiltered) {
  63346. _this.gammaSpace = false;
  63347. }
  63348. if (!rootUrl && !files) {
  63349. return _this;
  63350. }
  63351. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63352. var lastDot = rootUrl.lastIndexOf(".");
  63353. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63354. var isDDS = (extension === ".dds");
  63355. if (!files) {
  63356. if (!isDDS && !extensions) {
  63357. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63358. }
  63359. files = [];
  63360. if (extensions) {
  63361. for (var index = 0; index < extensions.length; index++) {
  63362. files.push(rootUrl + extensions[index]);
  63363. }
  63364. }
  63365. }
  63366. _this._files = files;
  63367. if (!_this._texture) {
  63368. if (!scene.useDelayedTextureLoading) {
  63369. if (prefiltered) {
  63370. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63371. }
  63372. else {
  63373. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  63374. }
  63375. }
  63376. else {
  63377. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63378. }
  63379. }
  63380. else if (onLoad) {
  63381. if (_this._texture.isReady) {
  63382. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63383. }
  63384. else {
  63385. _this._texture.onLoadedObservable.add(onLoad);
  63386. }
  63387. }
  63388. return _this;
  63389. }
  63390. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63391. get: function () {
  63392. return this._boundingBoxSize;
  63393. },
  63394. /**
  63395. * Gets or sets the size of the bounding box associated with the cube texture
  63396. * When defined, the cubemap will switch to local mode
  63397. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63398. * @example https://www.babylonjs-playground.com/#RNASML
  63399. */
  63400. set: function (value) {
  63401. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63402. return;
  63403. }
  63404. this._boundingBoxSize = value;
  63405. var scene = this.getScene();
  63406. if (scene) {
  63407. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63408. }
  63409. },
  63410. enumerable: true,
  63411. configurable: true
  63412. });
  63413. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63414. /**
  63415. * Gets texture matrix rotation angle around Y axis radians.
  63416. */
  63417. get: function () {
  63418. return this._rotationY;
  63419. },
  63420. /**
  63421. * Sets texture matrix rotation angle around Y axis in radians.
  63422. */
  63423. set: function (value) {
  63424. this._rotationY = value;
  63425. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63426. },
  63427. enumerable: true,
  63428. configurable: true
  63429. });
  63430. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63431. var rootUrlKey = "";
  63432. files.forEach(function (url) { return rootUrlKey += url; });
  63433. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63434. };
  63435. /**
  63436. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63437. * @param url defines the url of the prefiltered texture
  63438. * @param scene defines the scene the texture is attached to
  63439. * @param forcedExtension defines the extension of the file if different from the url
  63440. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63441. * @return the prefiltered texture
  63442. */
  63443. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63444. if (forcedExtension === void 0) { forcedExtension = null; }
  63445. if (createPolynomials === void 0) { createPolynomials = true; }
  63446. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63447. };
  63448. // Methods
  63449. CubeTexture.prototype.delayLoad = function () {
  63450. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63451. return;
  63452. }
  63453. var scene = this.getScene();
  63454. if (!scene) {
  63455. return;
  63456. }
  63457. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63458. this._texture = this._getFromCache(this.url, this._noMipmap);
  63459. if (!this._texture) {
  63460. if (this._prefiltered) {
  63461. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63462. }
  63463. else {
  63464. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63465. }
  63466. }
  63467. };
  63468. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63469. return this._textureMatrix;
  63470. };
  63471. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63472. this._textureMatrix = value;
  63473. };
  63474. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63475. var texture = BABYLON.SerializationHelper.Parse(function () {
  63476. var prefiltered = false;
  63477. if (parsedTexture.prefiltered) {
  63478. prefiltered = parsedTexture.prefiltered;
  63479. }
  63480. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63481. }, parsedTexture, scene);
  63482. // Local Cubemaps
  63483. if (parsedTexture.boundingBoxPosition) {
  63484. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63485. }
  63486. if (parsedTexture.boundingBoxSize) {
  63487. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63488. }
  63489. // Animations
  63490. if (parsedTexture.animations) {
  63491. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63492. var parsedAnimation = parsedTexture.animations[animationIndex];
  63493. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63494. }
  63495. }
  63496. return texture;
  63497. };
  63498. CubeTexture.prototype.clone = function () {
  63499. var _this = this;
  63500. return BABYLON.SerializationHelper.Clone(function () {
  63501. var scene = _this.getScene();
  63502. if (!scene) {
  63503. return _this;
  63504. }
  63505. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63506. }, this);
  63507. };
  63508. __decorate([
  63509. BABYLON.serialize("rotationY")
  63510. ], CubeTexture.prototype, "_rotationY", void 0);
  63511. return CubeTexture;
  63512. }(BABYLON.BaseTexture));
  63513. BABYLON.CubeTexture = CubeTexture;
  63514. })(BABYLON || (BABYLON = {}));
  63515. //# sourceMappingURL=babylon.cubeTexture.js.map
  63516. var BABYLON;
  63517. (function (BABYLON) {
  63518. var RenderTargetTexture = /** @class */ (function (_super) {
  63519. __extends(RenderTargetTexture, _super);
  63520. /**
  63521. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63522. * or used a shadow, depth texture...
  63523. * @param name The friendly name of the texture
  63524. * @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)
  63525. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63526. * @param generateMipMaps True if mip maps need to be generated after render.
  63527. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63528. * @param type The type of the buffer in the RTT (int, half float, float...)
  63529. * @param isCube True if a cube texture needs to be created
  63530. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63531. * @param generateDepthBuffer True to generate a depth buffer
  63532. * @param generateStencilBuffer True to generate a stencil buffer
  63533. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63534. */
  63535. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63536. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63537. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63538. if (isCube === void 0) { isCube = false; }
  63539. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63540. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63541. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63542. if (isMulti === void 0) { isMulti = false; }
  63543. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63544. _this.isCube = isCube;
  63545. /**
  63546. * Use this list to define the list of mesh you want to render.
  63547. */
  63548. _this.renderList = new Array();
  63549. _this.renderParticles = true;
  63550. _this.renderSprites = false;
  63551. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63552. _this.ignoreCameraViewport = false;
  63553. // Events
  63554. /**
  63555. * An event triggered when the texture is unbind.
  63556. */
  63557. _this.onBeforeBindObservable = new BABYLON.Observable();
  63558. /**
  63559. * An event triggered when the texture is unbind.
  63560. */
  63561. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63562. /**
  63563. * An event triggered before rendering the texture
  63564. */
  63565. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63566. /**
  63567. * An event triggered after rendering the texture
  63568. */
  63569. _this.onAfterRenderObservable = new BABYLON.Observable();
  63570. /**
  63571. * An event triggered after the texture clear
  63572. */
  63573. _this.onClearObservable = new BABYLON.Observable();
  63574. _this._currentRefreshId = -1;
  63575. _this._refreshRate = 1;
  63576. _this._samples = 1;
  63577. /**
  63578. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63579. * It must define where the camera used to render the texture is set
  63580. */
  63581. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63582. scene = _this.getScene();
  63583. if (!scene) {
  63584. return _this;
  63585. }
  63586. _this._engine = scene.getEngine();
  63587. _this.name = name;
  63588. _this.isRenderTarget = true;
  63589. _this._initialSizeParameter = size;
  63590. _this._processSizeParameter(size);
  63591. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63592. });
  63593. _this._generateMipMaps = generateMipMaps ? true : false;
  63594. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63595. // Rendering groups
  63596. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63597. if (isMulti) {
  63598. return _this;
  63599. }
  63600. _this._renderTargetOptions = {
  63601. generateMipMaps: generateMipMaps,
  63602. type: type,
  63603. samplingMode: samplingMode,
  63604. generateDepthBuffer: generateDepthBuffer,
  63605. generateStencilBuffer: generateStencilBuffer
  63606. };
  63607. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63608. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63609. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63610. }
  63611. if (isCube) {
  63612. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63613. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63614. _this._textureMatrix = BABYLON.Matrix.Identity();
  63615. }
  63616. else {
  63617. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63618. }
  63619. return _this;
  63620. }
  63621. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63622. get: function () {
  63623. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63624. },
  63625. enumerable: true,
  63626. configurable: true
  63627. });
  63628. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63629. get: function () {
  63630. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63631. },
  63632. enumerable: true,
  63633. configurable: true
  63634. });
  63635. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63636. get: function () {
  63637. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63638. },
  63639. enumerable: true,
  63640. configurable: true
  63641. });
  63642. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63643. set: function (callback) {
  63644. if (this._onAfterUnbindObserver) {
  63645. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63646. }
  63647. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63648. },
  63649. enumerable: true,
  63650. configurable: true
  63651. });
  63652. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63653. set: function (callback) {
  63654. if (this._onBeforeRenderObserver) {
  63655. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63656. }
  63657. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63658. },
  63659. enumerable: true,
  63660. configurable: true
  63661. });
  63662. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63663. set: function (callback) {
  63664. if (this._onAfterRenderObserver) {
  63665. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63666. }
  63667. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63668. },
  63669. enumerable: true,
  63670. configurable: true
  63671. });
  63672. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63673. set: function (callback) {
  63674. if (this._onClearObserver) {
  63675. this.onClearObservable.remove(this._onClearObserver);
  63676. }
  63677. this._onClearObserver = this.onClearObservable.add(callback);
  63678. },
  63679. enumerable: true,
  63680. configurable: true
  63681. });
  63682. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63683. get: function () {
  63684. return this._renderTargetOptions;
  63685. },
  63686. enumerable: true,
  63687. configurable: true
  63688. });
  63689. RenderTargetTexture.prototype._onRatioRescale = function () {
  63690. if (this._sizeRatio) {
  63691. this.resize(this._initialSizeParameter);
  63692. }
  63693. };
  63694. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63695. get: function () {
  63696. return this._boundingBoxSize;
  63697. },
  63698. /**
  63699. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63700. * When defined, the cubemap will switch to local mode
  63701. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63702. * @example https://www.babylonjs-playground.com/#RNASML
  63703. */
  63704. set: function (value) {
  63705. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63706. return;
  63707. }
  63708. this._boundingBoxSize = value;
  63709. var scene = this.getScene();
  63710. if (scene) {
  63711. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63712. }
  63713. },
  63714. enumerable: true,
  63715. configurable: true
  63716. });
  63717. /**
  63718. * Creates a depth stencil texture.
  63719. * This is only available in WebGL 2 or with the depth texture extension available.
  63720. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63721. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63722. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63723. */
  63724. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63725. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63726. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63727. if (generateStencil === void 0) { generateStencil = false; }
  63728. if (!this.getScene()) {
  63729. return;
  63730. }
  63731. var engine = this.getScene().getEngine();
  63732. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63733. bilinearFiltering: bilinearFiltering,
  63734. comparisonFunction: comparisonFunction,
  63735. generateStencil: generateStencil,
  63736. isCube: this.isCube
  63737. });
  63738. engine.setFrameBufferDepthStencilTexture(this);
  63739. };
  63740. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63741. if (size.ratio) {
  63742. this._sizeRatio = size.ratio;
  63743. this._size = {
  63744. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63745. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63746. };
  63747. }
  63748. else {
  63749. this._size = size;
  63750. }
  63751. };
  63752. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63753. get: function () {
  63754. return this._samples;
  63755. },
  63756. set: function (value) {
  63757. if (this._samples === value) {
  63758. return;
  63759. }
  63760. var scene = this.getScene();
  63761. if (!scene) {
  63762. return;
  63763. }
  63764. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63765. },
  63766. enumerable: true,
  63767. configurable: true
  63768. });
  63769. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63770. this._currentRefreshId = -1;
  63771. };
  63772. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63773. get: function () {
  63774. return this._refreshRate;
  63775. },
  63776. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63777. set: function (value) {
  63778. this._refreshRate = value;
  63779. this.resetRefreshCounter();
  63780. },
  63781. enumerable: true,
  63782. configurable: true
  63783. });
  63784. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63785. if (!this._postProcessManager) {
  63786. var scene = this.getScene();
  63787. if (!scene) {
  63788. return;
  63789. }
  63790. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63791. this._postProcesses = new Array();
  63792. }
  63793. this._postProcesses.push(postProcess);
  63794. this._postProcesses[0].autoClear = false;
  63795. };
  63796. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63797. if (!this._postProcesses) {
  63798. return;
  63799. }
  63800. if (dispose) {
  63801. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63802. var postProcess = _a[_i];
  63803. postProcess.dispose();
  63804. }
  63805. }
  63806. this._postProcesses = [];
  63807. };
  63808. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63809. if (!this._postProcesses) {
  63810. return;
  63811. }
  63812. var index = this._postProcesses.indexOf(postProcess);
  63813. if (index === -1) {
  63814. return;
  63815. }
  63816. this._postProcesses.splice(index, 1);
  63817. if (this._postProcesses.length > 0) {
  63818. this._postProcesses[0].autoClear = false;
  63819. }
  63820. };
  63821. RenderTargetTexture.prototype._shouldRender = function () {
  63822. if (this._currentRefreshId === -1) { // At least render once
  63823. this._currentRefreshId = 1;
  63824. return true;
  63825. }
  63826. if (this.refreshRate === this._currentRefreshId) {
  63827. this._currentRefreshId = 1;
  63828. return true;
  63829. }
  63830. this._currentRefreshId++;
  63831. return false;
  63832. };
  63833. RenderTargetTexture.prototype.getRenderSize = function () {
  63834. if (this._size.width) {
  63835. return this._size.width;
  63836. }
  63837. return this._size;
  63838. };
  63839. RenderTargetTexture.prototype.getRenderWidth = function () {
  63840. if (this._size.width) {
  63841. return this._size.width;
  63842. }
  63843. return this._size;
  63844. };
  63845. RenderTargetTexture.prototype.getRenderHeight = function () {
  63846. if (this._size.width) {
  63847. return this._size.height;
  63848. }
  63849. return this._size;
  63850. };
  63851. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63852. get: function () {
  63853. return true;
  63854. },
  63855. enumerable: true,
  63856. configurable: true
  63857. });
  63858. RenderTargetTexture.prototype.scale = function (ratio) {
  63859. var newSize = this.getRenderSize() * ratio;
  63860. this.resize(newSize);
  63861. };
  63862. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63863. if (this.isCube) {
  63864. return this._textureMatrix;
  63865. }
  63866. return _super.prototype.getReflectionTextureMatrix.call(this);
  63867. };
  63868. RenderTargetTexture.prototype.resize = function (size) {
  63869. this.releaseInternalTexture();
  63870. var scene = this.getScene();
  63871. if (!scene) {
  63872. return;
  63873. }
  63874. this._processSizeParameter(size);
  63875. if (this.isCube) {
  63876. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63877. }
  63878. else {
  63879. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63880. }
  63881. };
  63882. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63883. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63884. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63885. var scene = this.getScene();
  63886. if (!scene) {
  63887. return;
  63888. }
  63889. var engine = scene.getEngine();
  63890. if (this.useCameraPostProcesses !== undefined) {
  63891. useCameraPostProcess = this.useCameraPostProcesses;
  63892. }
  63893. if (this._waitingRenderList) {
  63894. this.renderList = [];
  63895. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63896. var id = this._waitingRenderList[index];
  63897. var mesh_1 = scene.getMeshByID(id);
  63898. if (mesh_1) {
  63899. this.renderList.push(mesh_1);
  63900. }
  63901. }
  63902. delete this._waitingRenderList;
  63903. }
  63904. // Is predicate defined?
  63905. if (this.renderListPredicate) {
  63906. if (this.renderList) {
  63907. this.renderList.splice(0); // Clear previous renderList
  63908. }
  63909. else {
  63910. this.renderList = [];
  63911. }
  63912. var scene = this.getScene();
  63913. if (!scene) {
  63914. return;
  63915. }
  63916. var sceneMeshes = scene.meshes;
  63917. for (var index = 0; index < sceneMeshes.length; index++) {
  63918. var mesh = sceneMeshes[index];
  63919. if (this.renderListPredicate(mesh)) {
  63920. this.renderList.push(mesh);
  63921. }
  63922. }
  63923. }
  63924. this.onBeforeBindObservable.notifyObservers(this);
  63925. // Set custom projection.
  63926. // Needs to be before binding to prevent changing the aspect ratio.
  63927. var camera;
  63928. if (this.activeCamera) {
  63929. camera = this.activeCamera;
  63930. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63931. if (this.activeCamera !== scene.activeCamera) {
  63932. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63933. }
  63934. }
  63935. else {
  63936. camera = scene.activeCamera;
  63937. if (camera) {
  63938. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63939. }
  63940. }
  63941. // Prepare renderingManager
  63942. this._renderingManager.reset();
  63943. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63944. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63945. var sceneRenderId = scene.getRenderId();
  63946. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63947. var mesh = currentRenderList[meshIndex];
  63948. if (mesh) {
  63949. if (!mesh.isReady(this.refreshRate === 0)) {
  63950. this.resetRefreshCounter();
  63951. continue;
  63952. }
  63953. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63954. var isMasked = void 0;
  63955. if (!this.renderList && camera) {
  63956. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63957. }
  63958. else {
  63959. isMasked = false;
  63960. }
  63961. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63962. mesh._activate(sceneRenderId);
  63963. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63964. var subMesh = mesh.subMeshes[subIndex];
  63965. scene._activeIndices.addCount(subMesh.indexCount, false);
  63966. this._renderingManager.dispatch(subMesh, mesh);
  63967. }
  63968. }
  63969. }
  63970. }
  63971. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63972. var particleSystem = scene.particleSystems[particleIndex];
  63973. var emitter = particleSystem.emitter;
  63974. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63975. continue;
  63976. }
  63977. if (currentRenderList.indexOf(emitter) >= 0) {
  63978. this._renderingManager.dispatchParticles(particleSystem);
  63979. }
  63980. }
  63981. if (this.isCube) {
  63982. for (var face = 0; face < 6; face++) {
  63983. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63984. scene.incrementRenderId();
  63985. scene.resetCachedMaterial();
  63986. }
  63987. }
  63988. else {
  63989. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63990. }
  63991. this.onAfterUnbindObservable.notifyObservers(this);
  63992. if (scene.activeCamera) {
  63993. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63994. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63995. }
  63996. engine.setViewport(scene.activeCamera.viewport);
  63997. }
  63998. scene.resetCachedMaterial();
  63999. };
  64000. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  64001. var minimum = 128;
  64002. var x = renderDimension * scale;
  64003. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  64004. // Ensure we don't exceed the render dimension (while staying POT)
  64005. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  64006. };
  64007. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64008. var _this = this;
  64009. if (!this._texture) {
  64010. return;
  64011. }
  64012. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  64013. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64014. });
  64015. };
  64016. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  64017. var scene = this.getScene();
  64018. if (!scene) {
  64019. return;
  64020. }
  64021. var engine = scene.getEngine();
  64022. if (!this._texture) {
  64023. return;
  64024. }
  64025. // Bind
  64026. if (this._postProcessManager) {
  64027. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  64028. }
  64029. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  64030. if (this._texture) {
  64031. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  64032. }
  64033. }
  64034. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  64035. // Clear
  64036. if (this.onClearObservable.hasObservers()) {
  64037. this.onClearObservable.notifyObservers(engine);
  64038. }
  64039. else {
  64040. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64041. }
  64042. if (!this._doNotChangeAspectRatio) {
  64043. scene.updateTransformMatrix(true);
  64044. }
  64045. // Render
  64046. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64047. if (this._postProcessManager) {
  64048. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64049. }
  64050. else if (useCameraPostProcess) {
  64051. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64052. }
  64053. if (!this._doNotChangeAspectRatio) {
  64054. scene.updateTransformMatrix(true);
  64055. }
  64056. // Dump ?
  64057. if (dumpForDebug) {
  64058. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64059. }
  64060. // Unbind
  64061. if (!this.isCube || faceIndex === 5) {
  64062. if (this.isCube) {
  64063. if (faceIndex === 5) {
  64064. engine.generateMipMapsForCubemap(this._texture);
  64065. }
  64066. }
  64067. this.unbindFrameBuffer(engine, faceIndex);
  64068. }
  64069. else {
  64070. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64071. }
  64072. };
  64073. /**
  64074. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64075. * This allowed control for front to back rendering or reversly depending of the special needs.
  64076. *
  64077. * @param renderingGroupId The rendering group id corresponding to its index
  64078. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64079. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64080. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64081. */
  64082. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64083. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64084. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64085. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64086. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64087. };
  64088. /**
  64089. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64090. *
  64091. * @param renderingGroupId The rendering group id corresponding to its index
  64092. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64093. */
  64094. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64095. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64096. };
  64097. RenderTargetTexture.prototype.clone = function () {
  64098. var textureSize = this.getSize();
  64099. 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);
  64100. // Base texture
  64101. newTexture.hasAlpha = this.hasAlpha;
  64102. newTexture.level = this.level;
  64103. // RenderTarget Texture
  64104. newTexture.coordinatesMode = this.coordinatesMode;
  64105. if (this.renderList) {
  64106. newTexture.renderList = this.renderList.slice(0);
  64107. }
  64108. return newTexture;
  64109. };
  64110. RenderTargetTexture.prototype.serialize = function () {
  64111. if (!this.name) {
  64112. return null;
  64113. }
  64114. var serializationObject = _super.prototype.serialize.call(this);
  64115. serializationObject.renderTargetSize = this.getRenderSize();
  64116. serializationObject.renderList = [];
  64117. if (this.renderList) {
  64118. for (var index = 0; index < this.renderList.length; index++) {
  64119. serializationObject.renderList.push(this.renderList[index].id);
  64120. }
  64121. }
  64122. return serializationObject;
  64123. };
  64124. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64125. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64126. var objBuffer = this.getInternalTexture();
  64127. var scene = this.getScene();
  64128. if (objBuffer && scene) {
  64129. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64130. }
  64131. };
  64132. RenderTargetTexture.prototype.dispose = function () {
  64133. if (this._postProcessManager) {
  64134. this._postProcessManager.dispose();
  64135. this._postProcessManager = null;
  64136. }
  64137. this.clearPostProcesses(true);
  64138. if (this._resizeObserver) {
  64139. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64140. this._resizeObserver = null;
  64141. }
  64142. this.renderList = null;
  64143. // Remove from custom render targets
  64144. var scene = this.getScene();
  64145. if (!scene) {
  64146. return;
  64147. }
  64148. var index = scene.customRenderTargets.indexOf(this);
  64149. if (index >= 0) {
  64150. scene.customRenderTargets.splice(index, 1);
  64151. }
  64152. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64153. var camera = _a[_i];
  64154. index = camera.customRenderTargets.indexOf(this);
  64155. if (index >= 0) {
  64156. camera.customRenderTargets.splice(index, 1);
  64157. }
  64158. }
  64159. _super.prototype.dispose.call(this);
  64160. };
  64161. RenderTargetTexture.prototype._rebuild = function () {
  64162. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64163. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64164. }
  64165. if (this._postProcessManager) {
  64166. this._postProcessManager._rebuild();
  64167. }
  64168. };
  64169. /**
  64170. * Clear the info related to rendering groups preventing retention point in material dispose.
  64171. */
  64172. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64173. if (this._renderingManager) {
  64174. this._renderingManager.freeRenderingGroups();
  64175. }
  64176. };
  64177. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64178. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64179. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64180. return RenderTargetTexture;
  64181. }(BABYLON.Texture));
  64182. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64183. })(BABYLON || (BABYLON = {}));
  64184. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64185. var BABYLON;
  64186. (function (BABYLON) {
  64187. ;
  64188. var MultiRenderTarget = /** @class */ (function (_super) {
  64189. __extends(MultiRenderTarget, _super);
  64190. function MultiRenderTarget(name, size, count, scene, options) {
  64191. var _this = this;
  64192. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64193. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64194. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64195. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64196. _this._engine = scene.getEngine();
  64197. if (!_this.isSupported) {
  64198. _this.dispose();
  64199. return;
  64200. }
  64201. var types = [];
  64202. var samplingModes = [];
  64203. for (var i = 0; i < count; i++) {
  64204. if (options && options.types && options.types[i] !== undefined) {
  64205. types.push(options.types[i]);
  64206. }
  64207. else {
  64208. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64209. }
  64210. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64211. samplingModes.push(options.samplingModes[i]);
  64212. }
  64213. else {
  64214. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64215. }
  64216. }
  64217. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64218. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64219. _this._size = size;
  64220. _this._multiRenderTargetOptions = {
  64221. samplingModes: samplingModes,
  64222. generateMipMaps: generateMipMaps,
  64223. generateDepthBuffer: generateDepthBuffer,
  64224. generateStencilBuffer: generateStencilBuffer,
  64225. generateDepthTexture: generateDepthTexture,
  64226. types: types,
  64227. textureCount: count
  64228. };
  64229. _this._createInternalTextures();
  64230. _this._createTextures();
  64231. return _this;
  64232. }
  64233. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64234. get: function () {
  64235. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64236. },
  64237. enumerable: true,
  64238. configurable: true
  64239. });
  64240. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64241. get: function () {
  64242. return this._textures;
  64243. },
  64244. enumerable: true,
  64245. configurable: true
  64246. });
  64247. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64248. get: function () {
  64249. return this._textures[this._textures.length - 1];
  64250. },
  64251. enumerable: true,
  64252. configurable: true
  64253. });
  64254. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64255. set: function (wrap) {
  64256. if (this._textures) {
  64257. for (var i = 0; i < this._textures.length; i++) {
  64258. this._textures[i].wrapU = wrap;
  64259. }
  64260. }
  64261. },
  64262. enumerable: true,
  64263. configurable: true
  64264. });
  64265. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64266. set: function (wrap) {
  64267. if (this._textures) {
  64268. for (var i = 0; i < this._textures.length; i++) {
  64269. this._textures[i].wrapV = wrap;
  64270. }
  64271. }
  64272. },
  64273. enumerable: true,
  64274. configurable: true
  64275. });
  64276. MultiRenderTarget.prototype._rebuild = function () {
  64277. this.releaseInternalTextures();
  64278. this._createInternalTextures();
  64279. for (var i = 0; i < this._internalTextures.length; i++) {
  64280. var texture = this._textures[i];
  64281. texture._texture = this._internalTextures[i];
  64282. }
  64283. // Keeps references to frame buffer and stencil/depth buffer
  64284. this._texture = this._internalTextures[0];
  64285. };
  64286. MultiRenderTarget.prototype._createInternalTextures = function () {
  64287. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64288. };
  64289. MultiRenderTarget.prototype._createTextures = function () {
  64290. this._textures = [];
  64291. for (var i = 0; i < this._internalTextures.length; i++) {
  64292. var texture = new BABYLON.Texture(null, this.getScene());
  64293. texture._texture = this._internalTextures[i];
  64294. this._textures.push(texture);
  64295. }
  64296. // Keeps references to frame buffer and stencil/depth buffer
  64297. this._texture = this._internalTextures[0];
  64298. };
  64299. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64300. get: function () {
  64301. return this._samples;
  64302. },
  64303. set: function (value) {
  64304. if (this._samples === value) {
  64305. return;
  64306. }
  64307. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64308. },
  64309. enumerable: true,
  64310. configurable: true
  64311. });
  64312. MultiRenderTarget.prototype.resize = function (size) {
  64313. this.releaseInternalTextures();
  64314. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64315. this._createInternalTextures();
  64316. };
  64317. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64318. var _this = this;
  64319. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64320. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64321. });
  64322. };
  64323. MultiRenderTarget.prototype.dispose = function () {
  64324. this.releaseInternalTextures();
  64325. _super.prototype.dispose.call(this);
  64326. };
  64327. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64328. if (!this._internalTextures) {
  64329. return;
  64330. }
  64331. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64332. if (this._internalTextures[i] !== undefined) {
  64333. this._internalTextures[i].dispose();
  64334. this._internalTextures.splice(i, 1);
  64335. }
  64336. }
  64337. };
  64338. return MultiRenderTarget;
  64339. }(BABYLON.RenderTargetTexture));
  64340. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64341. })(BABYLON || (BABYLON = {}));
  64342. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64343. var BABYLON;
  64344. (function (BABYLON) {
  64345. var MirrorTexture = /** @class */ (function (_super) {
  64346. __extends(MirrorTexture, _super);
  64347. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64348. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64349. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64350. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64351. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64352. _this.scene = scene;
  64353. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64354. _this._transformMatrix = BABYLON.Matrix.Zero();
  64355. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64356. _this._adaptiveBlurKernel = 0;
  64357. _this._blurKernelX = 0;
  64358. _this._blurKernelY = 0;
  64359. _this._blurRatio = 1.0;
  64360. _this.ignoreCameraViewport = true;
  64361. _this._updateGammaSpace();
  64362. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64363. _this._updateGammaSpace;
  64364. });
  64365. _this.onBeforeRenderObservable.add(function () {
  64366. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64367. _this._savedViewMatrix = scene.getViewMatrix();
  64368. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64369. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64370. scene.clipPlane = _this.mirrorPlane;
  64371. scene.getEngine().cullBackFaces = false;
  64372. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64373. });
  64374. _this.onAfterRenderObservable.add(function () {
  64375. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64376. scene.getEngine().cullBackFaces = true;
  64377. scene._mirroredCameraPosition = null;
  64378. delete scene.clipPlane;
  64379. });
  64380. return _this;
  64381. }
  64382. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64383. get: function () {
  64384. return this._blurRatio;
  64385. },
  64386. set: function (value) {
  64387. if (this._blurRatio === value) {
  64388. return;
  64389. }
  64390. this._blurRatio = value;
  64391. this._preparePostProcesses();
  64392. },
  64393. enumerable: true,
  64394. configurable: true
  64395. });
  64396. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64397. set: function (value) {
  64398. this._adaptiveBlurKernel = value;
  64399. this._autoComputeBlurKernel();
  64400. },
  64401. enumerable: true,
  64402. configurable: true
  64403. });
  64404. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64405. set: function (value) {
  64406. this.blurKernelX = value;
  64407. this.blurKernelY = value;
  64408. },
  64409. enumerable: true,
  64410. configurable: true
  64411. });
  64412. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64413. get: function () {
  64414. return this._blurKernelX;
  64415. },
  64416. set: function (value) {
  64417. if (this._blurKernelX === value) {
  64418. return;
  64419. }
  64420. this._blurKernelX = value;
  64421. this._preparePostProcesses();
  64422. },
  64423. enumerable: true,
  64424. configurable: true
  64425. });
  64426. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64427. get: function () {
  64428. return this._blurKernelY;
  64429. },
  64430. set: function (value) {
  64431. if (this._blurKernelY === value) {
  64432. return;
  64433. }
  64434. this._blurKernelY = value;
  64435. this._preparePostProcesses();
  64436. },
  64437. enumerable: true,
  64438. configurable: true
  64439. });
  64440. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64441. var engine = this.getScene().getEngine();
  64442. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64443. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64444. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64445. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64446. };
  64447. MirrorTexture.prototype._onRatioRescale = function () {
  64448. if (this._sizeRatio) {
  64449. this.resize(this._initialSizeParameter);
  64450. if (!this._adaptiveBlurKernel) {
  64451. this._preparePostProcesses();
  64452. }
  64453. }
  64454. if (this._adaptiveBlurKernel) {
  64455. this._autoComputeBlurKernel();
  64456. }
  64457. };
  64458. MirrorTexture.prototype._updateGammaSpace = function () {
  64459. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64460. };
  64461. MirrorTexture.prototype._preparePostProcesses = function () {
  64462. this.clearPostProcesses(true);
  64463. if (this._blurKernelX && this._blurKernelY) {
  64464. var engine = this.getScene().getEngine();
  64465. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64466. 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);
  64467. this._blurX.autoClear = false;
  64468. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64469. this._blurX.inputTexture = this._texture;
  64470. }
  64471. else {
  64472. this._blurX.alwaysForcePOT = true;
  64473. }
  64474. 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);
  64475. this._blurY.autoClear = false;
  64476. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64477. this.addPostProcess(this._blurX);
  64478. this.addPostProcess(this._blurY);
  64479. }
  64480. else {
  64481. if (this._blurY) {
  64482. this.removePostProcess(this._blurY);
  64483. this._blurY.dispose();
  64484. this._blurY = null;
  64485. }
  64486. if (this._blurX) {
  64487. this.removePostProcess(this._blurX);
  64488. this._blurX.dispose();
  64489. this._blurX = null;
  64490. }
  64491. }
  64492. };
  64493. MirrorTexture.prototype.clone = function () {
  64494. var scene = this.getScene();
  64495. if (!scene) {
  64496. return this;
  64497. }
  64498. var textureSize = this.getSize();
  64499. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64500. // Base texture
  64501. newTexture.hasAlpha = this.hasAlpha;
  64502. newTexture.level = this.level;
  64503. // Mirror Texture
  64504. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64505. if (this.renderList) {
  64506. newTexture.renderList = this.renderList.slice(0);
  64507. }
  64508. return newTexture;
  64509. };
  64510. MirrorTexture.prototype.serialize = function () {
  64511. if (!this.name) {
  64512. return null;
  64513. }
  64514. var serializationObject = _super.prototype.serialize.call(this);
  64515. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64516. return serializationObject;
  64517. };
  64518. MirrorTexture.prototype.dispose = function () {
  64519. _super.prototype.dispose.call(this);
  64520. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64521. };
  64522. return MirrorTexture;
  64523. }(BABYLON.RenderTargetTexture));
  64524. BABYLON.MirrorTexture = MirrorTexture;
  64525. })(BABYLON || (BABYLON = {}));
  64526. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64527. var BABYLON;
  64528. (function (BABYLON) {
  64529. /**
  64530. * Creates a refraction texture used by refraction channel of the standard material.
  64531. * @param name the texture name
  64532. * @param size size of the underlying texture
  64533. * @param scene root scene
  64534. */
  64535. var RefractionTexture = /** @class */ (function (_super) {
  64536. __extends(RefractionTexture, _super);
  64537. function RefractionTexture(name, size, scene, generateMipMaps) {
  64538. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64539. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64540. _this.depth = 2.0;
  64541. _this.onBeforeRenderObservable.add(function () {
  64542. scene.clipPlane = _this.refractionPlane;
  64543. });
  64544. _this.onAfterRenderObservable.add(function () {
  64545. delete scene.clipPlane;
  64546. });
  64547. return _this;
  64548. }
  64549. RefractionTexture.prototype.clone = function () {
  64550. var scene = this.getScene();
  64551. if (!scene) {
  64552. return this;
  64553. }
  64554. var textureSize = this.getSize();
  64555. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64556. // Base texture
  64557. newTexture.hasAlpha = this.hasAlpha;
  64558. newTexture.level = this.level;
  64559. // Refraction Texture
  64560. newTexture.refractionPlane = this.refractionPlane.clone();
  64561. if (this.renderList) {
  64562. newTexture.renderList = this.renderList.slice(0);
  64563. }
  64564. newTexture.depth = this.depth;
  64565. return newTexture;
  64566. };
  64567. RefractionTexture.prototype.serialize = function () {
  64568. if (!this.name) {
  64569. return null;
  64570. }
  64571. var serializationObject = _super.prototype.serialize.call(this);
  64572. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64573. serializationObject.depth = this.depth;
  64574. return serializationObject;
  64575. };
  64576. return RefractionTexture;
  64577. }(BABYLON.RenderTargetTexture));
  64578. BABYLON.RefractionTexture = RefractionTexture;
  64579. })(BABYLON || (BABYLON = {}));
  64580. //# sourceMappingURL=babylon.refractionTexture.js.map
  64581. var BABYLON;
  64582. (function (BABYLON) {
  64583. /**
  64584. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64585. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64586. */
  64587. var DynamicTexture = /** @class */ (function (_super) {
  64588. __extends(DynamicTexture, _super);
  64589. /**
  64590. * Creates a {BABYLON.DynamicTexture}
  64591. * @param name defines the name of the texture
  64592. * @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
  64593. * @param scene defines the scene where you want the texture
  64594. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64595. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64596. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64597. */
  64598. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64599. if (scene === void 0) { scene = null; }
  64600. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64601. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64602. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64603. _this.name = name;
  64604. _this._engine = _this.getScene().getEngine();
  64605. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64606. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64607. _this._generateMipMaps = generateMipMaps;
  64608. if (options.getContext) {
  64609. _this._canvas = options;
  64610. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64611. }
  64612. else {
  64613. _this._canvas = document.createElement("canvas");
  64614. if (options.width || options.width === 0) {
  64615. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64616. }
  64617. else {
  64618. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64619. }
  64620. }
  64621. var textureSize = _this.getSize();
  64622. _this._canvas.width = textureSize.width;
  64623. _this._canvas.height = textureSize.height;
  64624. _this._context = _this._canvas.getContext("2d");
  64625. return _this;
  64626. }
  64627. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64628. /**
  64629. * Gets the current state of canRescale
  64630. */
  64631. get: function () {
  64632. return true;
  64633. },
  64634. enumerable: true,
  64635. configurable: true
  64636. });
  64637. DynamicTexture.prototype._recreate = function (textureSize) {
  64638. this._canvas.width = textureSize.width;
  64639. this._canvas.height = textureSize.height;
  64640. this.releaseInternalTexture();
  64641. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64642. };
  64643. /**
  64644. * Scales the texture
  64645. * @param ratio the scale factor to apply to both width and height
  64646. */
  64647. DynamicTexture.prototype.scale = function (ratio) {
  64648. var textureSize = this.getSize();
  64649. textureSize.width *= ratio;
  64650. textureSize.height *= ratio;
  64651. this._recreate(textureSize);
  64652. };
  64653. /**
  64654. * Resizes the texture
  64655. * @param width the new width
  64656. * @param height the new height
  64657. */
  64658. DynamicTexture.prototype.scaleTo = function (width, height) {
  64659. var textureSize = this.getSize();
  64660. textureSize.width = width;
  64661. textureSize.height = height;
  64662. this._recreate(textureSize);
  64663. };
  64664. /**
  64665. * Gets the context of the canvas used by the texture
  64666. * @returns the canvas context of the dynamic texture
  64667. */
  64668. DynamicTexture.prototype.getContext = function () {
  64669. return this._context;
  64670. };
  64671. /**
  64672. * Clears the texture
  64673. */
  64674. DynamicTexture.prototype.clear = function () {
  64675. var size = this.getSize();
  64676. this._context.fillRect(0, 0, size.width, size.height);
  64677. };
  64678. /**
  64679. * Updates the texture
  64680. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64681. */
  64682. DynamicTexture.prototype.update = function (invertY) {
  64683. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  64684. };
  64685. /**
  64686. * Draws text onto the texture
  64687. * @param text defines the text to be drawn
  64688. * @param x defines the placement of the text from the left
  64689. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64690. * @param font defines the font to be used with font-style, font-size, font-name
  64691. * @param color defines the color used for the text
  64692. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64693. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64694. * @param update defines whether texture is immediately update (default is true)
  64695. */
  64696. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64697. if (update === void 0) { update = true; }
  64698. var size = this.getSize();
  64699. if (clearColor) {
  64700. this._context.fillStyle = clearColor;
  64701. this._context.fillRect(0, 0, size.width, size.height);
  64702. }
  64703. this._context.font = font;
  64704. if (x === null || x === undefined) {
  64705. var textSize = this._context.measureText(text);
  64706. x = (size.width - textSize.width) / 2;
  64707. }
  64708. if (y === null || y === undefined) {
  64709. var fontSize = parseInt((font.replace(/\D/g, '')));
  64710. y = (size.height / 2) + (fontSize / 3.65);
  64711. }
  64712. this._context.fillStyle = color;
  64713. this._context.fillText(text, x, y);
  64714. if (update) {
  64715. this.update(invertY);
  64716. }
  64717. };
  64718. /**
  64719. * Clones the texture
  64720. * @returns the clone of the texture.
  64721. */
  64722. DynamicTexture.prototype.clone = function () {
  64723. var scene = this.getScene();
  64724. if (!scene) {
  64725. return this;
  64726. }
  64727. var textureSize = this.getSize();
  64728. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64729. // Base texture
  64730. newTexture.hasAlpha = this.hasAlpha;
  64731. newTexture.level = this.level;
  64732. // Dynamic Texture
  64733. newTexture.wrapU = this.wrapU;
  64734. newTexture.wrapV = this.wrapV;
  64735. return newTexture;
  64736. };
  64737. /** @hidden */
  64738. DynamicTexture.prototype._rebuild = function () {
  64739. this.update();
  64740. };
  64741. return DynamicTexture;
  64742. }(BABYLON.Texture));
  64743. BABYLON.DynamicTexture = DynamicTexture;
  64744. })(BABYLON || (BABYLON = {}));
  64745. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64746. var BABYLON;
  64747. (function (BABYLON) {
  64748. var VideoTexture = /** @class */ (function (_super) {
  64749. __extends(VideoTexture, _super);
  64750. /**
  64751. * Creates a video texture.
  64752. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64753. * @param {string | null} name optional name, will detect from video source, if not defined
  64754. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64755. * @param {BABYLON.Scene} scene is obviously the current scene.
  64756. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64757. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64758. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64759. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64760. */
  64761. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64762. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64763. if (invertY === void 0) { invertY = false; }
  64764. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64765. if (settings === void 0) { settings = {
  64766. autoPlay: true,
  64767. loop: true,
  64768. autoUpdateTexture: true,
  64769. }; }
  64770. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64771. _this._stillImageCaptured = false;
  64772. _this._createInternalTexture = function () {
  64773. if (_this._texture != null) {
  64774. return;
  64775. }
  64776. if (!_this._engine.needPOTTextures ||
  64777. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64778. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64779. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64780. }
  64781. else {
  64782. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64783. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64784. _this._generateMipMaps = false;
  64785. }
  64786. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64787. if (!_this.video.autoplay) {
  64788. var oldHandler_1 = _this.video.onplaying;
  64789. _this.video.onplaying = function () {
  64790. _this.video.onplaying = oldHandler_1;
  64791. _this._texture.isReady = true;
  64792. _this._updateInternalTexture();
  64793. _this.video.pause();
  64794. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64795. _this.onLoadObservable.notifyObservers(_this);
  64796. }
  64797. };
  64798. _this.video.play();
  64799. }
  64800. else {
  64801. _this._texture.isReady = true;
  64802. _this._updateInternalTexture();
  64803. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64804. _this.onLoadObservable.notifyObservers(_this);
  64805. }
  64806. }
  64807. };
  64808. _this.reset = function () {
  64809. if (_this._texture == null) {
  64810. return;
  64811. }
  64812. _this._texture.dispose();
  64813. _this._texture = null;
  64814. };
  64815. _this._updateInternalTexture = function (e) {
  64816. if (_this._texture == null || !_this._texture.isReady) {
  64817. return;
  64818. }
  64819. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64820. return;
  64821. }
  64822. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64823. };
  64824. _this._engine = _this.getScene().getEngine();
  64825. _this._generateMipMaps = generateMipMaps;
  64826. _this._samplingMode = samplingMode;
  64827. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64828. _this.name = name || _this._getName(src);
  64829. _this.video = _this._getVideo(src);
  64830. if (settings.autoPlay !== undefined) {
  64831. _this.video.autoplay = settings.autoPlay;
  64832. }
  64833. if (settings.loop !== undefined) {
  64834. _this.video.loop = settings.loop;
  64835. }
  64836. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64837. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64838. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64839. _this.video.addEventListener("emptied", _this.reset);
  64840. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64841. _this._createInternalTexture();
  64842. }
  64843. return _this;
  64844. }
  64845. VideoTexture.prototype._getName = function (src) {
  64846. if (src instanceof HTMLVideoElement) {
  64847. return src.currentSrc;
  64848. }
  64849. if (typeof src === "object") {
  64850. return src.toString();
  64851. }
  64852. return src;
  64853. };
  64854. ;
  64855. VideoTexture.prototype._getVideo = function (src) {
  64856. if (src instanceof HTMLVideoElement) {
  64857. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64858. return src;
  64859. }
  64860. var video = document.createElement("video");
  64861. if (typeof src === "string") {
  64862. BABYLON.Tools.SetCorsBehavior(src, video);
  64863. video.src = src;
  64864. }
  64865. else {
  64866. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64867. src.forEach(function (url) {
  64868. var source = document.createElement("source");
  64869. source.src = url;
  64870. video.appendChild(source);
  64871. });
  64872. }
  64873. return video;
  64874. };
  64875. ;
  64876. /**
  64877. * Internal method to initiate `update`.
  64878. */
  64879. VideoTexture.prototype._rebuild = function () {
  64880. this.update();
  64881. };
  64882. /**
  64883. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64884. */
  64885. VideoTexture.prototype.update = function () {
  64886. if (!this.autoUpdateTexture) {
  64887. // Expecting user to call `updateTexture` manually
  64888. return;
  64889. }
  64890. this.updateTexture(true);
  64891. };
  64892. /**
  64893. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64894. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64895. */
  64896. VideoTexture.prototype.updateTexture = function (isVisible) {
  64897. if (!isVisible) {
  64898. return;
  64899. }
  64900. if (this.video.paused && this._stillImageCaptured) {
  64901. return;
  64902. }
  64903. this._stillImageCaptured = true;
  64904. this._updateInternalTexture();
  64905. };
  64906. /**
  64907. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64908. * @param url New url.
  64909. */
  64910. VideoTexture.prototype.updateURL = function (url) {
  64911. this.video.src = url;
  64912. };
  64913. VideoTexture.prototype.dispose = function () {
  64914. _super.prototype.dispose.call(this);
  64915. this.video.removeEventListener("canplay", this._createInternalTexture);
  64916. this.video.removeEventListener("paused", this._updateInternalTexture);
  64917. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64918. this.video.removeEventListener("emptied", this.reset);
  64919. this.video.pause();
  64920. };
  64921. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64922. var video = document.createElement("video");
  64923. var constraintsDeviceId;
  64924. if (constraints && constraints.deviceId) {
  64925. constraintsDeviceId = {
  64926. exact: constraints.deviceId,
  64927. };
  64928. }
  64929. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64930. if (navigator.mediaDevices) {
  64931. navigator.mediaDevices.getUserMedia({ video: constraints })
  64932. .then(function (stream) {
  64933. if (video.mozSrcObject !== undefined) {
  64934. // hack for Firefox < 19
  64935. video.mozSrcObject = stream;
  64936. }
  64937. else {
  64938. video.srcObject = stream;
  64939. }
  64940. var onPlaying = function () {
  64941. if (onReady) {
  64942. onReady(new VideoTexture("video", video, scene, true, true));
  64943. }
  64944. video.removeEventListener("playing", onPlaying);
  64945. };
  64946. video.addEventListener("playing", onPlaying);
  64947. video.play();
  64948. })
  64949. .catch(function (err) {
  64950. BABYLON.Tools.Error(err.name);
  64951. });
  64952. }
  64953. else {
  64954. navigator.getUserMedia =
  64955. navigator.getUserMedia ||
  64956. navigator.webkitGetUserMedia ||
  64957. navigator.mozGetUserMedia ||
  64958. navigator.msGetUserMedia;
  64959. if (navigator.getUserMedia) {
  64960. navigator.getUserMedia({
  64961. video: {
  64962. deviceId: constraintsDeviceId,
  64963. width: {
  64964. min: (constraints && constraints.minWidth) || 256,
  64965. max: (constraints && constraints.maxWidth) || 640,
  64966. },
  64967. height: {
  64968. min: (constraints && constraints.minHeight) || 256,
  64969. max: (constraints && constraints.maxHeight) || 480,
  64970. },
  64971. },
  64972. }, function (stream) {
  64973. if (video.mozSrcObject !== undefined) {
  64974. // hack for Firefox < 19
  64975. video.mozSrcObject = stream;
  64976. }
  64977. else {
  64978. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64979. }
  64980. video.play();
  64981. if (onReady) {
  64982. onReady(new VideoTexture("video", video, scene, true, true));
  64983. }
  64984. }, function (e) {
  64985. BABYLON.Tools.Error(e.name);
  64986. });
  64987. }
  64988. }
  64989. };
  64990. return VideoTexture;
  64991. }(BABYLON.Texture));
  64992. BABYLON.VideoTexture = VideoTexture;
  64993. })(BABYLON || (BABYLON = {}));
  64994. //# sourceMappingURL=babylon.videoTexture.js.map
  64995. var BABYLON;
  64996. (function (BABYLON) {
  64997. var RawTexture = /** @class */ (function (_super) {
  64998. __extends(RawTexture, _super);
  64999. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65000. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65001. if (invertY === void 0) { invertY = false; }
  65002. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65003. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65004. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65005. _this.format = format;
  65006. _this._engine = scene.getEngine();
  65007. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65008. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65009. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65010. return _this;
  65011. }
  65012. RawTexture.prototype.update = function (data) {
  65013. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65014. };
  65015. // Statics
  65016. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65017. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65018. if (invertY === void 0) { invertY = false; }
  65019. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65020. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65021. };
  65022. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65023. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65024. if (invertY === void 0) { invertY = false; }
  65025. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65026. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65027. };
  65028. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65029. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65030. if (invertY === void 0) { invertY = false; }
  65031. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65032. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65033. };
  65034. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65035. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65036. if (invertY === void 0) { invertY = false; }
  65037. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65038. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65039. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65040. };
  65041. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65042. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65043. if (invertY === void 0) { invertY = false; }
  65044. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65045. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65046. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65047. };
  65048. return RawTexture;
  65049. }(BABYLON.Texture));
  65050. BABYLON.RawTexture = RawTexture;
  65051. })(BABYLON || (BABYLON = {}));
  65052. //# sourceMappingURL=babylon.rawTexture.js.map
  65053. var BABYLON;
  65054. (function (BABYLON) {
  65055. /**
  65056. * Class used to store 3D textures containing user data
  65057. */
  65058. var RawTexture3D = /** @class */ (function (_super) {
  65059. __extends(RawTexture3D, _super);
  65060. /**
  65061. * Create a new RawTexture3D
  65062. * @param data defines the data of the texture
  65063. * @param width defines the width of the texture
  65064. * @param height defines the height of the texture
  65065. * @param depth defines the depth of the texture
  65066. * @param format defines the texture format to use
  65067. * @param scene defines the hosting scene
  65068. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65069. * @param invertY defines if texture must be stored with Y axis inverted
  65070. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65071. */
  65072. function RawTexture3D(data, width, height, depth,
  65073. /** Gets or sets the texture format to use*/
  65074. format, scene, generateMipMaps, invertY, samplingMode) {
  65075. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65076. if (invertY === void 0) { invertY = false; }
  65077. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65078. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65079. _this.format = format;
  65080. _this._engine = scene.getEngine();
  65081. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  65082. _this.is3D = true;
  65083. return _this;
  65084. }
  65085. /**
  65086. * Update the texture with new data
  65087. * @param data defines the data to store in the texture
  65088. */
  65089. RawTexture3D.prototype.update = function (data) {
  65090. if (!this._texture) {
  65091. return;
  65092. }
  65093. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  65094. };
  65095. return RawTexture3D;
  65096. }(BABYLON.Texture));
  65097. BABYLON.RawTexture3D = RawTexture3D;
  65098. })(BABYLON || (BABYLON = {}));
  65099. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65100. var BABYLON;
  65101. (function (BABYLON) {
  65102. /**
  65103. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65104. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65105. */
  65106. var PostProcess = /** @class */ (function () {
  65107. /**
  65108. * Creates a new instance PostProcess
  65109. * @param name The name of the PostProcess.
  65110. * @param fragmentUrl The url of the fragment shader to be used.
  65111. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65112. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65113. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65114. * @param camera The camera to apply the render pass to.
  65115. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65116. * @param engine The engine which the post process will be applied. (default: current engine)
  65117. * @param reusable If the post process can be reused on the same frame. (default: false)
  65118. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65119. * @param textureType Type of textures used when performing the post process. (default: 0)
  65120. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65121. * @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
  65122. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65123. */
  65124. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65125. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65126. if (defines === void 0) { defines = null; }
  65127. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65128. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65129. if (blockCompilation === void 0) { blockCompilation = false; }
  65130. this.name = name;
  65131. /**
  65132. * Width of the texture to apply the post process on
  65133. */
  65134. this.width = -1;
  65135. /**
  65136. * Height of the texture to apply the post process on
  65137. */
  65138. this.height = -1;
  65139. /**
  65140. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65141. */
  65142. this._outputTexture = null;
  65143. /**
  65144. * If the buffer needs to be cleared before applying the post process. (default: true)
  65145. * Should be set to false if shader will overwrite all previous pixels.
  65146. */
  65147. this.autoClear = true;
  65148. /**
  65149. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65150. */
  65151. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65152. /**
  65153. * Animations to be used for the post processing
  65154. */
  65155. this.animations = new Array();
  65156. /**
  65157. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65158. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65159. */
  65160. this.enablePixelPerfectMode = false;
  65161. /**
  65162. * Force the postprocess to be applied without taking in account viewport
  65163. */
  65164. this.forceFullscreenViewport = true;
  65165. /**
  65166. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65167. */
  65168. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65169. /**
  65170. * Force textures to be a power of two (default: false)
  65171. */
  65172. this.alwaysForcePOT = false;
  65173. /**
  65174. * Number of sample textures (default: 1)
  65175. */
  65176. this.samples = 1;
  65177. /**
  65178. * Modify the scale of the post process to be the same as the viewport (default: false)
  65179. */
  65180. this.adaptScaleToCurrentViewport = false;
  65181. this._reusable = false;
  65182. /**
  65183. * Smart array of input and output textures for the post process.
  65184. */
  65185. this._textures = new BABYLON.SmartArray(2);
  65186. /**
  65187. * The index in _textures that corresponds to the output texture.
  65188. */
  65189. this._currentRenderTextureInd = 0;
  65190. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65191. this._texelSize = BABYLON.Vector2.Zero();
  65192. // Events
  65193. /**
  65194. * An event triggered when the postprocess is activated.
  65195. */
  65196. this.onActivateObservable = new BABYLON.Observable();
  65197. /**
  65198. * An event triggered when the postprocess changes its size.
  65199. */
  65200. this.onSizeChangedObservable = new BABYLON.Observable();
  65201. /**
  65202. * An event triggered when the postprocess applies its effect.
  65203. */
  65204. this.onApplyObservable = new BABYLON.Observable();
  65205. /**
  65206. * An event triggered before rendering the postprocess
  65207. */
  65208. this.onBeforeRenderObservable = new BABYLON.Observable();
  65209. /**
  65210. * An event triggered after rendering the postprocess
  65211. */
  65212. this.onAfterRenderObservable = new BABYLON.Observable();
  65213. if (camera != null) {
  65214. this._camera = camera;
  65215. this._scene = camera.getScene();
  65216. camera.attachPostProcess(this);
  65217. this._engine = this._scene.getEngine();
  65218. this._scene.postProcesses.push(this);
  65219. }
  65220. else if (engine) {
  65221. this._engine = engine;
  65222. this._engine.postProcesses.push(this);
  65223. }
  65224. this._options = options;
  65225. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65226. this._reusable = reusable || false;
  65227. this._textureType = textureType;
  65228. this._samplers = samplers || [];
  65229. this._samplers.push("textureSampler");
  65230. this._fragmentUrl = fragmentUrl;
  65231. this._vertexUrl = vertexUrl;
  65232. this._parameters = parameters || [];
  65233. this._parameters.push("scale");
  65234. this._indexParameters = indexParameters;
  65235. if (!blockCompilation) {
  65236. this.updateEffect(defines);
  65237. }
  65238. }
  65239. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65240. /**
  65241. * A function that is added to the onActivateObservable
  65242. */
  65243. set: function (callback) {
  65244. if (this._onActivateObserver) {
  65245. this.onActivateObservable.remove(this._onActivateObserver);
  65246. }
  65247. if (callback) {
  65248. this._onActivateObserver = this.onActivateObservable.add(callback);
  65249. }
  65250. },
  65251. enumerable: true,
  65252. configurable: true
  65253. });
  65254. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65255. /**
  65256. * A function that is added to the onSizeChangedObservable
  65257. */
  65258. set: function (callback) {
  65259. if (this._onSizeChangedObserver) {
  65260. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65261. }
  65262. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65263. },
  65264. enumerable: true,
  65265. configurable: true
  65266. });
  65267. Object.defineProperty(PostProcess.prototype, "onApply", {
  65268. /**
  65269. * A function that is added to the onApplyObservable
  65270. */
  65271. set: function (callback) {
  65272. if (this._onApplyObserver) {
  65273. this.onApplyObservable.remove(this._onApplyObserver);
  65274. }
  65275. this._onApplyObserver = this.onApplyObservable.add(callback);
  65276. },
  65277. enumerable: true,
  65278. configurable: true
  65279. });
  65280. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65281. /**
  65282. * A function that is added to the onBeforeRenderObservable
  65283. */
  65284. set: function (callback) {
  65285. if (this._onBeforeRenderObserver) {
  65286. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65287. }
  65288. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65289. },
  65290. enumerable: true,
  65291. configurable: true
  65292. });
  65293. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65294. /**
  65295. * A function that is added to the onAfterRenderObservable
  65296. */
  65297. set: function (callback) {
  65298. if (this._onAfterRenderObserver) {
  65299. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65300. }
  65301. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65302. },
  65303. enumerable: true,
  65304. configurable: true
  65305. });
  65306. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65307. /**
  65308. * 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
  65309. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65310. */
  65311. get: function () {
  65312. return this._textures.data[this._currentRenderTextureInd];
  65313. },
  65314. set: function (value) {
  65315. this._forcedOutputTexture = value;
  65316. },
  65317. enumerable: true,
  65318. configurable: true
  65319. });
  65320. /**
  65321. * Gets the camera which post process is applied to.
  65322. * @returns The camera the post process is applied to.
  65323. */
  65324. PostProcess.prototype.getCamera = function () {
  65325. return this._camera;
  65326. };
  65327. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65328. /**
  65329. * Gets the texel size of the postprocess.
  65330. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65331. */
  65332. get: function () {
  65333. if (this._shareOutputWithPostProcess) {
  65334. return this._shareOutputWithPostProcess.texelSize;
  65335. }
  65336. if (this._forcedOutputTexture) {
  65337. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65338. }
  65339. return this._texelSize;
  65340. },
  65341. enumerable: true,
  65342. configurable: true
  65343. });
  65344. /**
  65345. * Gets the engine which this post process belongs to.
  65346. * @returns The engine the post process was enabled with.
  65347. */
  65348. PostProcess.prototype.getEngine = function () {
  65349. return this._engine;
  65350. };
  65351. /**
  65352. * The effect that is created when initializing the post process.
  65353. * @returns The created effect corrisponding the the postprocess.
  65354. */
  65355. PostProcess.prototype.getEffect = function () {
  65356. return this._effect;
  65357. };
  65358. /**
  65359. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65360. * @param postProcess The post process to share the output with.
  65361. * @returns This post process.
  65362. */
  65363. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65364. this._disposeTextures();
  65365. this._shareOutputWithPostProcess = postProcess;
  65366. return this;
  65367. };
  65368. /**
  65369. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65370. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65371. */
  65372. PostProcess.prototype.useOwnOutput = function () {
  65373. if (this._textures.length == 0) {
  65374. this._textures = new BABYLON.SmartArray(2);
  65375. }
  65376. this._shareOutputWithPostProcess = null;
  65377. };
  65378. /**
  65379. * Updates the effect with the current post process compile time values and recompiles the shader.
  65380. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65381. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65382. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65383. * @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
  65384. * @param onCompiled Called when the shader has been compiled.
  65385. * @param onError Called if there is an error when compiling a shader.
  65386. */
  65387. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65388. if (defines === void 0) { defines = null; }
  65389. if (uniforms === void 0) { uniforms = null; }
  65390. if (samplers === void 0) { samplers = null; }
  65391. 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);
  65392. };
  65393. /**
  65394. * The post process is reusable if it can be used multiple times within one frame.
  65395. * @returns If the post process is reusable
  65396. */
  65397. PostProcess.prototype.isReusable = function () {
  65398. return this._reusable;
  65399. };
  65400. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65401. PostProcess.prototype.markTextureDirty = function () {
  65402. this.width = -1;
  65403. };
  65404. /**
  65405. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65406. * 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.
  65407. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65408. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65409. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65410. * @returns The target texture that was bound to be written to.
  65411. */
  65412. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65413. var _this = this;
  65414. if (sourceTexture === void 0) { sourceTexture = null; }
  65415. camera = camera || this._camera;
  65416. var scene = camera.getScene();
  65417. var engine = scene.getEngine();
  65418. var maxSize = engine.getCaps().maxTextureSize;
  65419. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65420. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65421. // 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
  65422. var webVRCamera = camera.parent;
  65423. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65424. requiredWidth /= 2;
  65425. }
  65426. var desiredWidth = (this._options.width || requiredWidth);
  65427. var desiredHeight = this._options.height || requiredHeight;
  65428. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65429. if (this.adaptScaleToCurrentViewport) {
  65430. var currentViewport = engine.currentViewport;
  65431. if (currentViewport) {
  65432. desiredWidth *= currentViewport.width;
  65433. desiredHeight *= currentViewport.height;
  65434. }
  65435. }
  65436. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65437. if (!this._options.width) {
  65438. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65439. }
  65440. if (!this._options.height) {
  65441. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65442. }
  65443. }
  65444. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65445. if (this._textures.length > 0) {
  65446. for (var i = 0; i < this._textures.length; i++) {
  65447. this._engine._releaseTexture(this._textures.data[i]);
  65448. }
  65449. this._textures.reset();
  65450. }
  65451. this.width = desiredWidth;
  65452. this.height = desiredHeight;
  65453. var textureSize = { width: this.width, height: this.height };
  65454. var textureOptions = {
  65455. generateMipMaps: false,
  65456. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65457. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65458. samplingMode: this.renderTargetSamplingMode,
  65459. type: this._textureType
  65460. };
  65461. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65462. if (this._reusable) {
  65463. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65464. }
  65465. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65466. this.onSizeChangedObservable.notifyObservers(this);
  65467. }
  65468. this._textures.forEach(function (texture) {
  65469. if (texture.samples !== _this.samples) {
  65470. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65471. }
  65472. });
  65473. }
  65474. var target;
  65475. if (this._shareOutputWithPostProcess) {
  65476. target = this._shareOutputWithPostProcess.inputTexture;
  65477. }
  65478. else if (this._forcedOutputTexture) {
  65479. target = this._forcedOutputTexture;
  65480. this.width = this._forcedOutputTexture.width;
  65481. this.height = this._forcedOutputTexture.height;
  65482. }
  65483. else {
  65484. target = this.inputTexture;
  65485. }
  65486. // Bind the input of this post process to be used as the output of the previous post process.
  65487. if (this.enablePixelPerfectMode) {
  65488. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65489. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65490. }
  65491. else {
  65492. this._scaleRatio.copyFromFloats(1, 1);
  65493. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65494. }
  65495. this.onActivateObservable.notifyObservers(camera);
  65496. // Clear
  65497. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65498. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65499. }
  65500. if (this._reusable) {
  65501. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65502. }
  65503. return target;
  65504. };
  65505. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65506. /**
  65507. * If the post process is supported.
  65508. */
  65509. get: function () {
  65510. return this._effect.isSupported;
  65511. },
  65512. enumerable: true,
  65513. configurable: true
  65514. });
  65515. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65516. /**
  65517. * The aspect ratio of the output texture.
  65518. */
  65519. get: function () {
  65520. if (this._shareOutputWithPostProcess) {
  65521. return this._shareOutputWithPostProcess.aspectRatio;
  65522. }
  65523. if (this._forcedOutputTexture) {
  65524. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65525. }
  65526. return this.width / this.height;
  65527. },
  65528. enumerable: true,
  65529. configurable: true
  65530. });
  65531. /**
  65532. * Get a value indicating if the post-process is ready to be used
  65533. * @returns true if the post-process is ready (shader is compiled)
  65534. */
  65535. PostProcess.prototype.isReady = function () {
  65536. return this._effect && this._effect.isReady();
  65537. };
  65538. /**
  65539. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65540. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65541. */
  65542. PostProcess.prototype.apply = function () {
  65543. // Check
  65544. if (!this._effect || !this._effect.isReady())
  65545. return null;
  65546. // States
  65547. this._engine.enableEffect(this._effect);
  65548. this._engine.setState(false);
  65549. this._engine.setDepthBuffer(false);
  65550. this._engine.setDepthWrite(false);
  65551. // Alpha
  65552. this._engine.setAlphaMode(this.alphaMode);
  65553. if (this.alphaConstants) {
  65554. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65555. }
  65556. // Bind the output texture of the preivous post process as the input to this post process.
  65557. var source;
  65558. if (this._shareOutputWithPostProcess) {
  65559. source = this._shareOutputWithPostProcess.inputTexture;
  65560. }
  65561. else if (this._forcedOutputTexture) {
  65562. source = this._forcedOutputTexture;
  65563. }
  65564. else {
  65565. source = this.inputTexture;
  65566. }
  65567. this._effect._bindTexture("textureSampler", source);
  65568. // Parameters
  65569. this._effect.setVector2("scale", this._scaleRatio);
  65570. this.onApplyObservable.notifyObservers(this._effect);
  65571. return this._effect;
  65572. };
  65573. PostProcess.prototype._disposeTextures = function () {
  65574. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65575. return;
  65576. }
  65577. if (this._textures.length > 0) {
  65578. for (var i = 0; i < this._textures.length; i++) {
  65579. this._engine._releaseTexture(this._textures.data[i]);
  65580. }
  65581. }
  65582. this._textures.dispose();
  65583. };
  65584. /**
  65585. * Disposes the post process.
  65586. * @param camera The camera to dispose the post process on.
  65587. */
  65588. PostProcess.prototype.dispose = function (camera) {
  65589. camera = camera || this._camera;
  65590. this._disposeTextures();
  65591. if (this._scene) {
  65592. var index_1 = this._scene.postProcesses.indexOf(this);
  65593. if (index_1 !== -1) {
  65594. this._scene.postProcesses.splice(index_1, 1);
  65595. }
  65596. }
  65597. else {
  65598. var index_2 = this._engine.postProcesses.indexOf(this);
  65599. if (index_2 !== -1) {
  65600. this._engine.postProcesses.splice(index_2, 1);
  65601. }
  65602. }
  65603. if (!camera) {
  65604. return;
  65605. }
  65606. camera.detachPostProcess(this);
  65607. var index = camera._postProcesses.indexOf(this);
  65608. if (index === 0 && camera._postProcesses.length > 0) {
  65609. var firstPostProcess = this._camera._getFirstPostProcess();
  65610. if (firstPostProcess) {
  65611. firstPostProcess.markTextureDirty();
  65612. }
  65613. }
  65614. this.onActivateObservable.clear();
  65615. this.onAfterRenderObservable.clear();
  65616. this.onApplyObservable.clear();
  65617. this.onBeforeRenderObservable.clear();
  65618. this.onSizeChangedObservable.clear();
  65619. };
  65620. return PostProcess;
  65621. }());
  65622. BABYLON.PostProcess = PostProcess;
  65623. })(BABYLON || (BABYLON = {}));
  65624. //# sourceMappingURL=babylon.postProcess.js.map
  65625. var BABYLON;
  65626. (function (BABYLON) {
  65627. var PassPostProcess = /** @class */ (function (_super) {
  65628. __extends(PassPostProcess, _super);
  65629. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65630. if (camera === void 0) { camera = null; }
  65631. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65632. if (blockCompilation === void 0) { blockCompilation = false; }
  65633. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65634. }
  65635. return PassPostProcess;
  65636. }(BABYLON.PostProcess));
  65637. BABYLON.PassPostProcess = PassPostProcess;
  65638. })(BABYLON || (BABYLON = {}));
  65639. //# sourceMappingURL=babylon.passPostProcess.js.map
  65640. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65641. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65642. s = arguments[i];
  65643. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65644. t[p] = s[p];
  65645. }
  65646. return t;
  65647. };
  65648. var BABYLON;
  65649. (function (BABYLON) {
  65650. /**
  65651. * Default implementation IShadowGenerator.
  65652. * This is the main object responsible of generating shadows in the framework.
  65653. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65654. */
  65655. var ShadowGenerator = /** @class */ (function () {
  65656. /**
  65657. * Creates a ShadowGenerator object.
  65658. * A ShadowGenerator is the required tool to use the shadows.
  65659. * Each light casting shadows needs to use its own ShadowGenerator.
  65660. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65661. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65662. * @param light The light object generating the shadows.
  65663. * @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.
  65664. */
  65665. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65666. this._bias = 0.00005;
  65667. this._normalBias = 0;
  65668. this._blurBoxOffset = 1;
  65669. this._blurScale = 2;
  65670. this._blurKernel = 1;
  65671. this._useKernelBlur = false;
  65672. this._filter = ShadowGenerator.FILTER_NONE;
  65673. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65674. this._contactHardeningLightSizeUVRatio = 0.1;
  65675. this._darkness = 0;
  65676. this._transparencyShadow = false;
  65677. /**
  65678. * Controls the extent to which the shadows fade out at the edge of the frustum
  65679. * Used only by directionals and spots
  65680. */
  65681. this.frustumEdgeFalloff = 0;
  65682. /**
  65683. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65684. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65685. * It might on the other hand introduce peter panning.
  65686. */
  65687. this.forceBackFacesOnly = false;
  65688. this._lightDirection = BABYLON.Vector3.Zero();
  65689. this._viewMatrix = BABYLON.Matrix.Zero();
  65690. this._projectionMatrix = BABYLON.Matrix.Zero();
  65691. this._transformMatrix = BABYLON.Matrix.Zero();
  65692. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65693. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65694. this._currentFaceIndex = 0;
  65695. this._currentFaceIndexCache = 0;
  65696. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65697. this._mapSize = mapSize;
  65698. this._light = light;
  65699. this._scene = light.getScene();
  65700. light._shadowGenerator = this;
  65701. // Texture type fallback from float to int if not supported.
  65702. var caps = this._scene.getEngine().getCaps();
  65703. if (!useFullFloatFirst) {
  65704. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65705. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65706. }
  65707. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65708. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65709. }
  65710. else {
  65711. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65712. }
  65713. }
  65714. else {
  65715. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65716. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65717. }
  65718. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65719. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65720. }
  65721. else {
  65722. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65723. }
  65724. }
  65725. this._initializeGenerator();
  65726. this._applyFilterValues();
  65727. }
  65728. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65729. /**
  65730. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65731. */
  65732. get: function () {
  65733. return this._bias;
  65734. },
  65735. /**
  65736. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65737. */
  65738. set: function (bias) {
  65739. this._bias = bias;
  65740. },
  65741. enumerable: true,
  65742. configurable: true
  65743. });
  65744. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65745. /**
  65746. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65747. */
  65748. get: function () {
  65749. return this._normalBias;
  65750. },
  65751. /**
  65752. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65753. */
  65754. set: function (normalBias) {
  65755. this._normalBias = normalBias;
  65756. },
  65757. enumerable: true,
  65758. configurable: true
  65759. });
  65760. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65761. /**
  65762. * Gets the blur box offset: offset applied during the blur pass.
  65763. * Only usefull if useKernelBlur = false
  65764. */
  65765. get: function () {
  65766. return this._blurBoxOffset;
  65767. },
  65768. /**
  65769. * Sets the blur box offset: offset applied during the blur pass.
  65770. * Only usefull if useKernelBlur = false
  65771. */
  65772. set: function (value) {
  65773. if (this._blurBoxOffset === value) {
  65774. return;
  65775. }
  65776. this._blurBoxOffset = value;
  65777. this._disposeBlurPostProcesses();
  65778. },
  65779. enumerable: true,
  65780. configurable: true
  65781. });
  65782. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65783. /**
  65784. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65785. * 2 means half of the size.
  65786. */
  65787. get: function () {
  65788. return this._blurScale;
  65789. },
  65790. /**
  65791. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65792. * 2 means half of the size.
  65793. */
  65794. set: function (value) {
  65795. if (this._blurScale === value) {
  65796. return;
  65797. }
  65798. this._blurScale = value;
  65799. this._disposeBlurPostProcesses();
  65800. },
  65801. enumerable: true,
  65802. configurable: true
  65803. });
  65804. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65805. /**
  65806. * Gets the blur kernel: kernel size of the blur pass.
  65807. * Only usefull if useKernelBlur = true
  65808. */
  65809. get: function () {
  65810. return this._blurKernel;
  65811. },
  65812. /**
  65813. * Sets the blur kernel: kernel size of the blur pass.
  65814. * Only usefull if useKernelBlur = true
  65815. */
  65816. set: function (value) {
  65817. if (this._blurKernel === value) {
  65818. return;
  65819. }
  65820. this._blurKernel = value;
  65821. this._disposeBlurPostProcesses();
  65822. },
  65823. enumerable: true,
  65824. configurable: true
  65825. });
  65826. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65827. /**
  65828. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65829. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65830. */
  65831. get: function () {
  65832. return this._useKernelBlur;
  65833. },
  65834. /**
  65835. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65836. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65837. */
  65838. set: function (value) {
  65839. if (this._useKernelBlur === value) {
  65840. return;
  65841. }
  65842. this._useKernelBlur = value;
  65843. this._disposeBlurPostProcesses();
  65844. },
  65845. enumerable: true,
  65846. configurable: true
  65847. });
  65848. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65849. /**
  65850. * Gets the depth scale used in ESM mode.
  65851. */
  65852. get: function () {
  65853. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65854. },
  65855. /**
  65856. * Sets the depth scale used in ESM mode.
  65857. * This can override the scale stored on the light.
  65858. */
  65859. set: function (value) {
  65860. this._depthScale = value;
  65861. },
  65862. enumerable: true,
  65863. configurable: true
  65864. });
  65865. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65866. /**
  65867. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65868. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65869. */
  65870. get: function () {
  65871. return this._filter;
  65872. },
  65873. /**
  65874. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65875. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65876. */
  65877. set: function (value) {
  65878. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65879. if (this._light.needCube()) {
  65880. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65881. this.useExponentialShadowMap = true;
  65882. return;
  65883. }
  65884. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65885. this.useCloseExponentialShadowMap = true;
  65886. return;
  65887. }
  65888. // PCF on cubemap would also be expensive
  65889. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65890. this.usePoissonSampling = true;
  65891. return;
  65892. }
  65893. }
  65894. // Weblg1 fallback for PCF.
  65895. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65896. if (this._scene.getEngine().webGLVersion === 1) {
  65897. this.usePoissonSampling = true;
  65898. return;
  65899. }
  65900. }
  65901. if (this._filter === value) {
  65902. return;
  65903. }
  65904. this._filter = value;
  65905. this._disposeBlurPostProcesses();
  65906. this._applyFilterValues();
  65907. this._light._markMeshesAsLightDirty();
  65908. },
  65909. enumerable: true,
  65910. configurable: true
  65911. });
  65912. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65913. /**
  65914. * Gets if the current filter is set to Poisson Sampling.
  65915. */
  65916. get: function () {
  65917. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65918. },
  65919. /**
  65920. * Sets the current filter to Poisson Sampling.
  65921. */
  65922. set: function (value) {
  65923. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65924. return;
  65925. }
  65926. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65927. },
  65928. enumerable: true,
  65929. configurable: true
  65930. });
  65931. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65932. /**
  65933. * Gets if the current filter is set to VSM.
  65934. * DEPRECATED. Should use useExponentialShadowMap instead.
  65935. */
  65936. get: function () {
  65937. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65938. return this.useExponentialShadowMap;
  65939. },
  65940. /**
  65941. * Sets the current filter is to VSM.
  65942. * DEPRECATED. Should use useExponentialShadowMap instead.
  65943. */
  65944. set: function (value) {
  65945. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65946. this.useExponentialShadowMap = value;
  65947. },
  65948. enumerable: true,
  65949. configurable: true
  65950. });
  65951. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65952. /**
  65953. * Gets if the current filter is set to blurred VSM.
  65954. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65955. */
  65956. get: function () {
  65957. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65958. return this.useBlurExponentialShadowMap;
  65959. },
  65960. /**
  65961. * Sets the current filter is to blurred VSM.
  65962. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65963. */
  65964. set: function (value) {
  65965. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65966. this.useBlurExponentialShadowMap = value;
  65967. },
  65968. enumerable: true,
  65969. configurable: true
  65970. });
  65971. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65972. /**
  65973. * Gets if the current filter is set to ESM.
  65974. */
  65975. get: function () {
  65976. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65977. },
  65978. /**
  65979. * Sets the current filter is to ESM.
  65980. */
  65981. set: function (value) {
  65982. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65983. return;
  65984. }
  65985. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65986. },
  65987. enumerable: true,
  65988. configurable: true
  65989. });
  65990. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65991. /**
  65992. * Gets if the current filter is set to filtered ESM.
  65993. */
  65994. get: function () {
  65995. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65996. },
  65997. /**
  65998. * Gets if the current filter is set to filtered ESM.
  65999. */
  66000. set: function (value) {
  66001. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66002. return;
  66003. }
  66004. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66005. },
  66006. enumerable: true,
  66007. configurable: true
  66008. });
  66009. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66010. /**
  66011. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66012. * exponential to prevent steep falloff artifacts).
  66013. */
  66014. get: function () {
  66015. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66016. },
  66017. /**
  66018. * Sets the current filter to "close ESM" (using the inverse of the
  66019. * exponential to prevent steep falloff artifacts).
  66020. */
  66021. set: function (value) {
  66022. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66023. return;
  66024. }
  66025. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66026. },
  66027. enumerable: true,
  66028. configurable: true
  66029. });
  66030. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66031. /**
  66032. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66033. * exponential to prevent steep falloff artifacts).
  66034. */
  66035. get: function () {
  66036. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66037. },
  66038. /**
  66039. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66040. * exponential to prevent steep falloff artifacts).
  66041. */
  66042. set: function (value) {
  66043. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66044. return;
  66045. }
  66046. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66047. },
  66048. enumerable: true,
  66049. configurable: true
  66050. });
  66051. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66052. /**
  66053. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66054. */
  66055. get: function () {
  66056. return this.filter === ShadowGenerator.FILTER_PCF;
  66057. },
  66058. /**
  66059. * Sets the current filter to "PCF" (percentage closer filtering).
  66060. */
  66061. set: function (value) {
  66062. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66063. return;
  66064. }
  66065. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66066. },
  66067. enumerable: true,
  66068. configurable: true
  66069. });
  66070. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66071. /**
  66072. * Gets the PCF or PCSS Quality.
  66073. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66074. */
  66075. get: function () {
  66076. return this._filteringQuality;
  66077. },
  66078. /**
  66079. * Sets the PCF or PCSS Quality.
  66080. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66081. */
  66082. set: function (filteringQuality) {
  66083. this._filteringQuality = filteringQuality;
  66084. },
  66085. enumerable: true,
  66086. configurable: true
  66087. });
  66088. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66089. /**
  66090. * Gets if the current filter is set to "PCSS" (contact hardening).
  66091. */
  66092. get: function () {
  66093. return this.filter === ShadowGenerator.FILTER_PCSS;
  66094. },
  66095. /**
  66096. * Sets the current filter to "PCSS" (contact hardening).
  66097. */
  66098. set: function (value) {
  66099. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66100. return;
  66101. }
  66102. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66103. },
  66104. enumerable: true,
  66105. configurable: true
  66106. });
  66107. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66108. /**
  66109. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66110. * Using a ratio helps keeping shape stability independently of the map size.
  66111. *
  66112. * It does not account for the light projection as it was having too much
  66113. * instability during the light setup or during light position changes.
  66114. *
  66115. * Only valid if useContactHardeningShadow is true.
  66116. */
  66117. get: function () {
  66118. return this._contactHardeningLightSizeUVRatio;
  66119. },
  66120. /**
  66121. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66122. * Using a ratio helps keeping shape stability independently of the map size.
  66123. *
  66124. * It does not account for the light projection as it was having too much
  66125. * instability during the light setup or during light position changes.
  66126. *
  66127. * Only valid if useContactHardeningShadow is true.
  66128. */
  66129. set: function (contactHardeningLightSizeUVRatio) {
  66130. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66131. },
  66132. enumerable: true,
  66133. configurable: true
  66134. });
  66135. /**
  66136. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66137. * 0 means strongest and 1 would means no shadow.
  66138. * @returns the darkness.
  66139. */
  66140. ShadowGenerator.prototype.getDarkness = function () {
  66141. return this._darkness;
  66142. };
  66143. /**
  66144. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66145. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66146. * @returns the shadow generator allowing fluent coding.
  66147. */
  66148. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66149. if (darkness >= 1.0)
  66150. this._darkness = 1.0;
  66151. else if (darkness <= 0.0)
  66152. this._darkness = 0.0;
  66153. else
  66154. this._darkness = darkness;
  66155. return this;
  66156. };
  66157. /**
  66158. * Sets the ability to have transparent shadow (boolean).
  66159. * @param transparent True if transparent else False
  66160. * @returns the shadow generator allowing fluent coding
  66161. */
  66162. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66163. this._transparencyShadow = transparent;
  66164. return this;
  66165. };
  66166. /**
  66167. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66168. * @returns The render target texture if present otherwise, null
  66169. */
  66170. ShadowGenerator.prototype.getShadowMap = function () {
  66171. return this._shadowMap;
  66172. };
  66173. /**
  66174. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66175. * @returns The render target texture if the shadow map is present otherwise, null
  66176. */
  66177. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66178. if (this._shadowMap2) {
  66179. return this._shadowMap2;
  66180. }
  66181. return this._shadowMap;
  66182. };
  66183. /**
  66184. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66185. * @param mesh Mesh to add
  66186. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66187. * @returns the Shadow Generator itself
  66188. */
  66189. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66190. if (includeDescendants === void 0) { includeDescendants = true; }
  66191. if (!this._shadowMap) {
  66192. return this;
  66193. }
  66194. if (!this._shadowMap.renderList) {
  66195. this._shadowMap.renderList = [];
  66196. }
  66197. this._shadowMap.renderList.push(mesh);
  66198. if (includeDescendants) {
  66199. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66200. }
  66201. return this;
  66202. var _a;
  66203. };
  66204. /**
  66205. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66206. * @param mesh Mesh to remove
  66207. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66208. * @returns the Shadow Generator itself
  66209. */
  66210. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66211. if (includeDescendants === void 0) { includeDescendants = true; }
  66212. if (!this._shadowMap || !this._shadowMap.renderList) {
  66213. return this;
  66214. }
  66215. var index = this._shadowMap.renderList.indexOf(mesh);
  66216. if (index !== -1) {
  66217. this._shadowMap.renderList.splice(index, 1);
  66218. }
  66219. if (includeDescendants) {
  66220. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66221. var child = _a[_i];
  66222. this.removeShadowCaster(child);
  66223. }
  66224. }
  66225. return this;
  66226. };
  66227. /**
  66228. * Returns the associated light object.
  66229. * @returns the light generating the shadow
  66230. */
  66231. ShadowGenerator.prototype.getLight = function () {
  66232. return this._light;
  66233. };
  66234. ShadowGenerator.prototype._initializeGenerator = function () {
  66235. this._light._markMeshesAsLightDirty();
  66236. this._initializeShadowMap();
  66237. };
  66238. ShadowGenerator.prototype._initializeShadowMap = function () {
  66239. var _this = this;
  66240. // Render target
  66241. var engine = this._scene.getEngine();
  66242. if (engine.webGLVersion > 1) {
  66243. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66244. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66245. }
  66246. else {
  66247. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66248. }
  66249. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66250. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66251. this._shadowMap.anisotropicFilteringLevel = 1;
  66252. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66253. this._shadowMap.renderParticles = false;
  66254. this._shadowMap.ignoreCameraViewport = true;
  66255. // Record Face Index before render.
  66256. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66257. _this._currentFaceIndex = faceIndex;
  66258. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66259. engine.setColorWrite(false);
  66260. }
  66261. });
  66262. // Custom render function.
  66263. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66264. // Blur if required afer render.
  66265. this._shadowMap.onAfterUnbindObservable.add(function () {
  66266. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66267. engine.setColorWrite(true);
  66268. }
  66269. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66270. return;
  66271. }
  66272. var shadowMap = _this.getShadowMapForRendering();
  66273. if (shadowMap) {
  66274. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66275. }
  66276. });
  66277. // Clear according to the chosen filter.
  66278. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66279. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66280. this._shadowMap.onClearObservable.add(function (engine) {
  66281. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66282. engine.clear(clearOne, false, true, false);
  66283. }
  66284. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66285. engine.clear(clearZero, true, true, false);
  66286. }
  66287. else {
  66288. engine.clear(clearOne, true, true, false);
  66289. }
  66290. });
  66291. };
  66292. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66293. var _this = this;
  66294. var engine = this._scene.getEngine();
  66295. var targetSize = this._mapSize / this.blurScale;
  66296. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66297. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66298. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66299. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66300. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66301. }
  66302. if (this.useKernelBlur) {
  66303. 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);
  66304. this._kernelBlurXPostprocess.width = targetSize;
  66305. this._kernelBlurXPostprocess.height = targetSize;
  66306. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66307. effect.setTexture("textureSampler", _this._shadowMap);
  66308. });
  66309. 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);
  66310. this._kernelBlurXPostprocess.autoClear = false;
  66311. this._kernelBlurYPostprocess.autoClear = false;
  66312. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66313. this._kernelBlurXPostprocess.packedFloat = true;
  66314. this._kernelBlurYPostprocess.packedFloat = true;
  66315. }
  66316. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66317. }
  66318. else {
  66319. 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);
  66320. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66321. effect.setFloat2("screenSize", targetSize, targetSize);
  66322. effect.setTexture("textureSampler", _this._shadowMap);
  66323. });
  66324. this._boxBlurPostprocess.autoClear = false;
  66325. this._blurPostProcesses = [this._boxBlurPostprocess];
  66326. }
  66327. };
  66328. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66329. var index;
  66330. var engine = this._scene.getEngine();
  66331. if (depthOnlySubMeshes.length) {
  66332. engine.setColorWrite(false);
  66333. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66334. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66335. }
  66336. engine.setColorWrite(true);
  66337. }
  66338. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66339. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66340. }
  66341. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66342. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66343. }
  66344. if (this._transparencyShadow) {
  66345. for (index = 0; index < transparentSubMeshes.length; index++) {
  66346. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66347. }
  66348. }
  66349. };
  66350. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66351. var _this = this;
  66352. var mesh = subMesh.getRenderingMesh();
  66353. var scene = this._scene;
  66354. var engine = scene.getEngine();
  66355. var material = subMesh.getMaterial();
  66356. if (!material) {
  66357. return;
  66358. }
  66359. // Culling
  66360. engine.setState(material.backFaceCulling);
  66361. // Managing instances
  66362. var batch = mesh._getInstancesRenderList(subMesh._id);
  66363. if (batch.mustReturn) {
  66364. return;
  66365. }
  66366. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66367. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66368. engine.enableEffect(this._effect);
  66369. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66370. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66371. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66372. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66373. this._effect.setVector3("lightData", this._cachedDirection);
  66374. }
  66375. else {
  66376. this._effect.setVector3("lightData", this._cachedPosition);
  66377. }
  66378. if (scene.activeCamera) {
  66379. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66380. }
  66381. // Alpha test
  66382. if (material && material.needAlphaTesting()) {
  66383. var alphaTexture = material.getAlphaTestTexture();
  66384. if (alphaTexture) {
  66385. this._effect.setTexture("diffuseSampler", alphaTexture);
  66386. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66387. }
  66388. }
  66389. // Bones
  66390. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66391. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66392. }
  66393. // Morph targets
  66394. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66395. if (this.forceBackFacesOnly) {
  66396. engine.setState(true, 0, false, true);
  66397. }
  66398. // Draw
  66399. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66400. if (this.forceBackFacesOnly) {
  66401. engine.setState(true, 0, false, false);
  66402. }
  66403. }
  66404. else {
  66405. // Need to reset refresh rate of the shadowMap
  66406. if (this._shadowMap) {
  66407. this._shadowMap.resetRefreshCounter();
  66408. }
  66409. }
  66410. };
  66411. ShadowGenerator.prototype._applyFilterValues = function () {
  66412. if (!this._shadowMap) {
  66413. return;
  66414. }
  66415. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66416. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66417. }
  66418. else {
  66419. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66420. }
  66421. };
  66422. /**
  66423. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66424. * @param onCompiled Callback triggered at the and of the effects compilation
  66425. * @param options Sets of optional options forcing the compilation with different modes
  66426. */
  66427. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66428. var _this = this;
  66429. var localOptions = __assign({ useInstances: false }, options);
  66430. var shadowMap = this.getShadowMap();
  66431. if (!shadowMap) {
  66432. if (onCompiled) {
  66433. onCompiled(this);
  66434. }
  66435. return;
  66436. }
  66437. var renderList = shadowMap.renderList;
  66438. if (!renderList) {
  66439. if (onCompiled) {
  66440. onCompiled(this);
  66441. }
  66442. return;
  66443. }
  66444. var subMeshes = new Array();
  66445. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66446. var mesh = renderList_1[_i];
  66447. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66448. }
  66449. if (subMeshes.length === 0) {
  66450. if (onCompiled) {
  66451. onCompiled(this);
  66452. }
  66453. return;
  66454. }
  66455. var currentIndex = 0;
  66456. var checkReady = function () {
  66457. if (!_this._scene || !_this._scene.getEngine()) {
  66458. return;
  66459. }
  66460. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66461. currentIndex++;
  66462. if (currentIndex >= subMeshes.length) {
  66463. if (onCompiled) {
  66464. onCompiled(_this);
  66465. }
  66466. return;
  66467. }
  66468. }
  66469. setTimeout(checkReady, 16);
  66470. };
  66471. checkReady();
  66472. };
  66473. /**
  66474. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66475. * @param options Sets of optional options forcing the compilation with different modes
  66476. * @returns A promise that resolves when the compilation completes
  66477. */
  66478. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66479. var _this = this;
  66480. return new Promise(function (resolve) {
  66481. _this.forceCompilation(function () {
  66482. resolve();
  66483. }, options);
  66484. });
  66485. };
  66486. /**
  66487. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66488. * @param subMesh The submesh we want to render in the shadow map
  66489. * @param useInstances Defines wether will draw in the map using instances
  66490. * @returns true if ready otherwise, false
  66491. */
  66492. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66493. var defines = [];
  66494. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66495. defines.push("#define FLOAT");
  66496. }
  66497. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66498. defines.push("#define ESM");
  66499. }
  66500. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66501. defines.push("#define DEPTHTEXTURE");
  66502. }
  66503. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66504. var mesh = subMesh.getMesh();
  66505. var material = subMesh.getMaterial();
  66506. // Normal bias.
  66507. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66508. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66509. defines.push("#define NORMAL");
  66510. if (mesh.nonUniformScaling) {
  66511. defines.push("#define NONUNIFORMSCALING");
  66512. }
  66513. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66514. defines.push("#define DIRECTIONINLIGHTDATA");
  66515. }
  66516. }
  66517. // Alpha test
  66518. if (material && material.needAlphaTesting()) {
  66519. var alphaTexture = material.getAlphaTestTexture();
  66520. if (alphaTexture) {
  66521. defines.push("#define ALPHATEST");
  66522. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66523. attribs.push(BABYLON.VertexBuffer.UVKind);
  66524. defines.push("#define UV1");
  66525. }
  66526. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66527. if (alphaTexture.coordinatesIndex === 1) {
  66528. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66529. defines.push("#define UV2");
  66530. }
  66531. }
  66532. }
  66533. }
  66534. // Bones
  66535. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66536. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66537. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66538. if (mesh.numBoneInfluencers > 4) {
  66539. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66540. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66541. }
  66542. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66543. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66544. }
  66545. else {
  66546. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66547. }
  66548. // Morph targets
  66549. var manager = mesh.morphTargetManager;
  66550. var morphInfluencers = 0;
  66551. if (manager) {
  66552. if (manager.numInfluencers > 0) {
  66553. defines.push("#define MORPHTARGETS");
  66554. morphInfluencers = manager.numInfluencers;
  66555. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66556. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66557. }
  66558. }
  66559. // Instances
  66560. if (useInstances) {
  66561. defines.push("#define INSTANCES");
  66562. attribs.push("world0");
  66563. attribs.push("world1");
  66564. attribs.push("world2");
  66565. attribs.push("world3");
  66566. }
  66567. // Get correct effect
  66568. var join = defines.join("\n");
  66569. if (this._cachedDefines !== join) {
  66570. this._cachedDefines = join;
  66571. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66572. }
  66573. if (!this._effect.isReady()) {
  66574. return false;
  66575. }
  66576. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66577. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66578. this._initializeBlurRTTAndPostProcesses();
  66579. }
  66580. }
  66581. return this.arePostProcessesReady();
  66582. };
  66583. /**
  66584. * Returns true if all post processes required to render the shadow map are ready
  66585. * @returns true if the shadow map can be rendered with all post-processes
  66586. */
  66587. ShadowGenerator.prototype.arePostProcessesReady = function () {
  66588. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66589. return false;
  66590. }
  66591. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66592. return false;
  66593. }
  66594. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66595. return false;
  66596. }
  66597. return true;
  66598. };
  66599. /**
  66600. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66601. * @param defines Defines of the material we want to update
  66602. * @param lightIndex Index of the light in the enabled light list of the material
  66603. */
  66604. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66605. var scene = this._scene;
  66606. var light = this._light;
  66607. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66608. return;
  66609. }
  66610. defines["SHADOW" + lightIndex] = true;
  66611. if (this.useContactHardeningShadow) {
  66612. defines["SHADOWPCSS" + lightIndex] = true;
  66613. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66614. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66615. }
  66616. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66617. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66618. }
  66619. // else default to high.
  66620. }
  66621. if (this.usePercentageCloserFiltering) {
  66622. defines["SHADOWPCF" + lightIndex] = true;
  66623. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66624. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66625. }
  66626. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66627. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66628. }
  66629. // else default to high.
  66630. }
  66631. else if (this.usePoissonSampling) {
  66632. defines["SHADOWPOISSON" + lightIndex] = true;
  66633. }
  66634. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66635. defines["SHADOWESM" + lightIndex] = true;
  66636. }
  66637. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66638. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66639. }
  66640. if (light.needCube()) {
  66641. defines["SHADOWCUBE" + lightIndex] = true;
  66642. }
  66643. };
  66644. /**
  66645. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66646. * defined in the generator but impacting the effect).
  66647. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66648. * @param effect The effect we are binfing the information for
  66649. */
  66650. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66651. var light = this._light;
  66652. var scene = this._scene;
  66653. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66654. return;
  66655. }
  66656. var camera = scene.activeCamera;
  66657. if (!camera) {
  66658. return;
  66659. }
  66660. var shadowMap = this.getShadowMap();
  66661. if (!shadowMap) {
  66662. return;
  66663. }
  66664. if (!light.needCube()) {
  66665. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66666. }
  66667. // Only PCF uses depth stencil texture.
  66668. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66669. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66670. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66671. }
  66672. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66673. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66674. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66675. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66676. }
  66677. else {
  66678. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66679. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66680. }
  66681. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66682. };
  66683. /**
  66684. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66685. * (eq to shadow prjection matrix * light transform matrix)
  66686. * @returns The transform matrix used to create the shadow map
  66687. */
  66688. ShadowGenerator.prototype.getTransformMatrix = function () {
  66689. var scene = this._scene;
  66690. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66691. return this._transformMatrix;
  66692. }
  66693. this._currentRenderID = scene.getRenderId();
  66694. this._currentFaceIndexCache = this._currentFaceIndex;
  66695. var lightPosition = this._light.position;
  66696. if (this._light.computeTransformedInformation()) {
  66697. lightPosition = this._light.transformedPosition;
  66698. }
  66699. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66700. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66701. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66702. }
  66703. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66704. this._cachedPosition.copyFrom(lightPosition);
  66705. this._cachedDirection.copyFrom(this._lightDirection);
  66706. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66707. var shadowMap = this.getShadowMap();
  66708. if (shadowMap) {
  66709. var renderList = shadowMap.renderList;
  66710. if (renderList) {
  66711. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66712. }
  66713. }
  66714. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66715. }
  66716. return this._transformMatrix;
  66717. };
  66718. /**
  66719. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66720. * Cube and 2D textures for instance.
  66721. */
  66722. ShadowGenerator.prototype.recreateShadowMap = function () {
  66723. var shadowMap = this._shadowMap;
  66724. if (!shadowMap) {
  66725. return;
  66726. }
  66727. // Track render list.
  66728. var renderList = shadowMap.renderList;
  66729. // Clean up existing data.
  66730. this._disposeRTTandPostProcesses();
  66731. // Reinitializes.
  66732. this._initializeGenerator();
  66733. // Reaffect the filter to ensure a correct fallback if necessary.
  66734. this.filter = this.filter;
  66735. // Reaffect the filter.
  66736. this._applyFilterValues();
  66737. // Reaffect Render List.
  66738. this._shadowMap.renderList = renderList;
  66739. };
  66740. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66741. if (this._shadowMap2) {
  66742. this._shadowMap2.dispose();
  66743. this._shadowMap2 = null;
  66744. }
  66745. if (this._boxBlurPostprocess) {
  66746. this._boxBlurPostprocess.dispose();
  66747. this._boxBlurPostprocess = null;
  66748. }
  66749. if (this._kernelBlurXPostprocess) {
  66750. this._kernelBlurXPostprocess.dispose();
  66751. this._kernelBlurXPostprocess = null;
  66752. }
  66753. if (this._kernelBlurYPostprocess) {
  66754. this._kernelBlurYPostprocess.dispose();
  66755. this._kernelBlurYPostprocess = null;
  66756. }
  66757. this._blurPostProcesses = [];
  66758. };
  66759. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66760. if (this._shadowMap) {
  66761. this._shadowMap.dispose();
  66762. this._shadowMap = null;
  66763. }
  66764. this._disposeBlurPostProcesses();
  66765. };
  66766. /**
  66767. * Disposes the ShadowGenerator.
  66768. * Returns nothing.
  66769. */
  66770. ShadowGenerator.prototype.dispose = function () {
  66771. this._disposeRTTandPostProcesses();
  66772. if (this._light) {
  66773. this._light._shadowGenerator = null;
  66774. this._light._markMeshesAsLightDirty();
  66775. }
  66776. };
  66777. /**
  66778. * Serializes the shadow generator setup to a json object.
  66779. * @returns The serialized JSON object
  66780. */
  66781. ShadowGenerator.prototype.serialize = function () {
  66782. var serializationObject = {};
  66783. var shadowMap = this.getShadowMap();
  66784. if (!shadowMap) {
  66785. return serializationObject;
  66786. }
  66787. serializationObject.lightId = this._light.id;
  66788. serializationObject.mapSize = shadowMap.getRenderSize();
  66789. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66790. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66791. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66792. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66793. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66794. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66795. serializationObject.depthScale = this.depthScale;
  66796. serializationObject.darkness = this.getDarkness();
  66797. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66798. serializationObject.blurKernel = this.blurKernel;
  66799. serializationObject.blurScale = this.blurScale;
  66800. serializationObject.useKernelBlur = this.useKernelBlur;
  66801. serializationObject.transparencyShadow = this._transparencyShadow;
  66802. serializationObject.bias = this.bias;
  66803. serializationObject.normalBias = this.normalBias;
  66804. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66805. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66806. serializationObject.filteringQuality = this.filteringQuality;
  66807. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66808. serializationObject.renderList = [];
  66809. if (shadowMap.renderList) {
  66810. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66811. var mesh = shadowMap.renderList[meshIndex];
  66812. serializationObject.renderList.push(mesh.id);
  66813. }
  66814. }
  66815. return serializationObject;
  66816. };
  66817. /**
  66818. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66819. * @param parsedShadowGenerator The JSON object to parse
  66820. * @param scene The scene to create the shadow map for
  66821. * @returns The parsed shadow generator
  66822. */
  66823. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66824. //casting to point light, as light is missing the position attr and typescript complains.
  66825. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66826. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66827. var shadowMap = shadowGenerator.getShadowMap();
  66828. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66829. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66830. meshes.forEach(function (mesh) {
  66831. if (!shadowMap) {
  66832. return;
  66833. }
  66834. if (!shadowMap.renderList) {
  66835. shadowMap.renderList = [];
  66836. }
  66837. shadowMap.renderList.push(mesh);
  66838. });
  66839. }
  66840. if (parsedShadowGenerator.usePoissonSampling) {
  66841. shadowGenerator.usePoissonSampling = true;
  66842. }
  66843. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66844. shadowGenerator.useExponentialShadowMap = true;
  66845. }
  66846. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66847. shadowGenerator.useBlurExponentialShadowMap = true;
  66848. }
  66849. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66850. shadowGenerator.useCloseExponentialShadowMap = true;
  66851. }
  66852. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66853. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66854. }
  66855. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66856. shadowGenerator.usePercentageCloserFiltering = true;
  66857. }
  66858. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66859. shadowGenerator.useContactHardeningShadow = true;
  66860. }
  66861. if (parsedShadowGenerator.filteringQuality) {
  66862. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66863. }
  66864. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66865. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66866. }
  66867. // Backward compat
  66868. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66869. shadowGenerator.useExponentialShadowMap = true;
  66870. }
  66871. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66872. shadowGenerator.useBlurExponentialShadowMap = true;
  66873. }
  66874. if (parsedShadowGenerator.depthScale) {
  66875. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66876. }
  66877. if (parsedShadowGenerator.blurScale) {
  66878. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66879. }
  66880. if (parsedShadowGenerator.blurBoxOffset) {
  66881. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66882. }
  66883. if (parsedShadowGenerator.useKernelBlur) {
  66884. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66885. }
  66886. if (parsedShadowGenerator.blurKernel) {
  66887. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66888. }
  66889. if (parsedShadowGenerator.bias !== undefined) {
  66890. shadowGenerator.bias = parsedShadowGenerator.bias;
  66891. }
  66892. if (parsedShadowGenerator.normalBias !== undefined) {
  66893. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66894. }
  66895. if (parsedShadowGenerator.darkness) {
  66896. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66897. }
  66898. if (parsedShadowGenerator.transparencyShadow) {
  66899. shadowGenerator.setTransparencyShadow(true);
  66900. }
  66901. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66902. return shadowGenerator;
  66903. };
  66904. /**
  66905. * Shadow generator mode None: no filtering applied.
  66906. */
  66907. ShadowGenerator.FILTER_NONE = 0;
  66908. /**
  66909. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66910. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66911. */
  66912. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66913. /**
  66914. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66915. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66916. */
  66917. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66918. /**
  66919. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66920. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66921. */
  66922. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66923. /**
  66924. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66925. * edge artifacts on steep falloff.
  66926. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66927. */
  66928. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66929. /**
  66930. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66931. * edge artifacts on steep falloff.
  66932. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66933. */
  66934. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66935. /**
  66936. * Shadow generator mode PCF: Percentage Closer Filtering
  66937. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66938. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66939. */
  66940. ShadowGenerator.FILTER_PCF = 6;
  66941. /**
  66942. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66943. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66944. * Contact Hardening
  66945. */
  66946. ShadowGenerator.FILTER_PCSS = 7;
  66947. /**
  66948. * Reserved for PCF and PCSS
  66949. * Highest Quality.
  66950. *
  66951. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66952. *
  66953. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66954. */
  66955. ShadowGenerator.QUALITY_HIGH = 0;
  66956. /**
  66957. * Reserved for PCF and PCSS
  66958. * Good tradeoff for quality/perf cross devices
  66959. *
  66960. * Execute PCF on a 3*3 kernel.
  66961. *
  66962. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66963. */
  66964. ShadowGenerator.QUALITY_MEDIUM = 1;
  66965. /**
  66966. * Reserved for PCF and PCSS
  66967. * The lowest quality but the fastest.
  66968. *
  66969. * Execute PCF on a 1*1 kernel.
  66970. *
  66971. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66972. */
  66973. ShadowGenerator.QUALITY_LOW = 2;
  66974. return ShadowGenerator;
  66975. }());
  66976. BABYLON.ShadowGenerator = ShadowGenerator;
  66977. })(BABYLON || (BABYLON = {}));
  66978. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66979. var BABYLON;
  66980. (function (BABYLON) {
  66981. var DefaultLoadingScreen = /** @class */ (function () {
  66982. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66983. if (_loadingText === void 0) { _loadingText = ""; }
  66984. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66985. var _this = this;
  66986. this._renderingCanvas = _renderingCanvas;
  66987. this._loadingText = _loadingText;
  66988. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66989. // Resize
  66990. this._resizeLoadingUI = function () {
  66991. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66992. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66993. if (!_this._loadingDiv) {
  66994. return;
  66995. }
  66996. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66997. _this._loadingDiv.style.left = canvasRect.left + "px";
  66998. _this._loadingDiv.style.top = canvasRect.top + "px";
  66999. _this._loadingDiv.style.width = canvasRect.width + "px";
  67000. _this._loadingDiv.style.height = canvasRect.height + "px";
  67001. };
  67002. }
  67003. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67004. if (this._loadingDiv) {
  67005. // Do not add a loading screen if there is already one
  67006. return;
  67007. }
  67008. this._loadingDiv = document.createElement("div");
  67009. this._loadingDiv.id = "babylonjsLoadingDiv";
  67010. this._loadingDiv.style.opacity = "0";
  67011. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67012. this._loadingDiv.style.pointerEvents = "none";
  67013. // Loading text
  67014. this._loadingTextDiv = document.createElement("div");
  67015. this._loadingTextDiv.style.position = "absolute";
  67016. this._loadingTextDiv.style.left = "0";
  67017. this._loadingTextDiv.style.top = "50%";
  67018. this._loadingTextDiv.style.marginTop = "80px";
  67019. this._loadingTextDiv.style.width = "100%";
  67020. this._loadingTextDiv.style.height = "20px";
  67021. this._loadingTextDiv.style.fontFamily = "Arial";
  67022. this._loadingTextDiv.style.fontSize = "14px";
  67023. this._loadingTextDiv.style.color = "white";
  67024. this._loadingTextDiv.style.textAlign = "center";
  67025. this._loadingTextDiv.innerHTML = "Loading";
  67026. this._loadingDiv.appendChild(this._loadingTextDiv);
  67027. //set the predefined text
  67028. this._loadingTextDiv.innerHTML = this._loadingText;
  67029. // Generating keyframes
  67030. var style = document.createElement('style');
  67031. style.type = 'text/css';
  67032. 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 }";
  67033. style.innerHTML = keyFrames;
  67034. document.getElementsByTagName('head')[0].appendChild(style);
  67035. // Loading img
  67036. var imgBack = new Image();
  67037. 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";
  67038. imgBack.style.position = "absolute";
  67039. imgBack.style.left = "50%";
  67040. imgBack.style.top = "50%";
  67041. imgBack.style.marginLeft = "-60px";
  67042. imgBack.style.marginTop = "-60px";
  67043. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67044. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67045. imgBack.style.transformOrigin = "50% 50%";
  67046. imgBack.style.webkitTransformOrigin = "50% 50%";
  67047. this._loadingDiv.appendChild(imgBack);
  67048. this._resizeLoadingUI();
  67049. window.addEventListener("resize", this._resizeLoadingUI);
  67050. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67051. document.body.appendChild(this._loadingDiv);
  67052. this._loadingDiv.style.opacity = "1";
  67053. };
  67054. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67055. var _this = this;
  67056. if (!this._loadingDiv) {
  67057. return;
  67058. }
  67059. var onTransitionEnd = function () {
  67060. if (!_this._loadingDiv) {
  67061. return;
  67062. }
  67063. document.body.removeChild(_this._loadingDiv);
  67064. window.removeEventListener("resize", _this._resizeLoadingUI);
  67065. _this._loadingDiv = null;
  67066. };
  67067. this._loadingDiv.style.opacity = "0";
  67068. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67069. };
  67070. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67071. set: function (text) {
  67072. this._loadingText = text;
  67073. if (this._loadingTextDiv) {
  67074. this._loadingTextDiv.innerHTML = this._loadingText;
  67075. }
  67076. },
  67077. enumerable: true,
  67078. configurable: true
  67079. });
  67080. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67081. get: function () {
  67082. return this._loadingDivBackgroundColor;
  67083. },
  67084. set: function (color) {
  67085. this._loadingDivBackgroundColor = color;
  67086. if (!this._loadingDiv) {
  67087. return;
  67088. }
  67089. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67090. },
  67091. enumerable: true,
  67092. configurable: true
  67093. });
  67094. return DefaultLoadingScreen;
  67095. }());
  67096. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67097. })(BABYLON || (BABYLON = {}));
  67098. //# sourceMappingURL=babylon.loadingScreen.js.map
  67099. var BABYLON;
  67100. (function (BABYLON) {
  67101. var SceneLoaderProgressEvent = /** @class */ (function () {
  67102. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67103. this.lengthComputable = lengthComputable;
  67104. this.loaded = loaded;
  67105. this.total = total;
  67106. }
  67107. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67108. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67109. };
  67110. return SceneLoaderProgressEvent;
  67111. }());
  67112. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67113. var SceneLoader = /** @class */ (function () {
  67114. function SceneLoader() {
  67115. }
  67116. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67117. get: function () {
  67118. return 0;
  67119. },
  67120. enumerable: true,
  67121. configurable: true
  67122. });
  67123. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67124. get: function () {
  67125. return 1;
  67126. },
  67127. enumerable: true,
  67128. configurable: true
  67129. });
  67130. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67131. get: function () {
  67132. return 2;
  67133. },
  67134. enumerable: true,
  67135. configurable: true
  67136. });
  67137. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67138. get: function () {
  67139. return 3;
  67140. },
  67141. enumerable: true,
  67142. configurable: true
  67143. });
  67144. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67145. get: function () {
  67146. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67147. },
  67148. set: function (value) {
  67149. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67150. },
  67151. enumerable: true,
  67152. configurable: true
  67153. });
  67154. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67155. get: function () {
  67156. return SceneLoader._ShowLoadingScreen;
  67157. },
  67158. set: function (value) {
  67159. SceneLoader._ShowLoadingScreen = value;
  67160. },
  67161. enumerable: true,
  67162. configurable: true
  67163. });
  67164. Object.defineProperty(SceneLoader, "loggingLevel", {
  67165. get: function () {
  67166. return SceneLoader._loggingLevel;
  67167. },
  67168. set: function (value) {
  67169. SceneLoader._loggingLevel = value;
  67170. },
  67171. enumerable: true,
  67172. configurable: true
  67173. });
  67174. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67175. get: function () {
  67176. return SceneLoader._CleanBoneMatrixWeights;
  67177. },
  67178. set: function (value) {
  67179. SceneLoader._CleanBoneMatrixWeights = value;
  67180. },
  67181. enumerable: true,
  67182. configurable: true
  67183. });
  67184. SceneLoader._getDefaultPlugin = function () {
  67185. return SceneLoader._registeredPlugins[".babylon"];
  67186. };
  67187. SceneLoader._getPluginForExtension = function (extension) {
  67188. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67189. if (registeredPlugin) {
  67190. return registeredPlugin;
  67191. }
  67192. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  67193. return SceneLoader._getDefaultPlugin();
  67194. };
  67195. SceneLoader._getPluginForDirectLoad = function (data) {
  67196. for (var extension in SceneLoader._registeredPlugins) {
  67197. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67198. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67199. return SceneLoader._registeredPlugins[extension];
  67200. }
  67201. }
  67202. return SceneLoader._getDefaultPlugin();
  67203. };
  67204. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67205. if (sceneFilename.name) {
  67206. sceneFilename = sceneFilename.name;
  67207. }
  67208. var queryStringPosition = sceneFilename.indexOf("?");
  67209. if (queryStringPosition !== -1) {
  67210. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67211. }
  67212. var dotPosition = sceneFilename.lastIndexOf(".");
  67213. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67214. return SceneLoader._getPluginForExtension(extension);
  67215. };
  67216. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67217. SceneLoader._getDirectLoad = function (sceneFilename) {
  67218. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67219. return sceneFilename.substr(5);
  67220. }
  67221. return null;
  67222. };
  67223. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67224. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67225. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67226. var plugin;
  67227. if (registeredPlugin.plugin.createPlugin) {
  67228. plugin = registeredPlugin.plugin.createPlugin();
  67229. }
  67230. else {
  67231. plugin = registeredPlugin.plugin;
  67232. }
  67233. var useArrayBuffer = registeredPlugin.isBinary;
  67234. var database;
  67235. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67236. var dataCallback = function (data, responseURL) {
  67237. if (scene.isDisposed) {
  67238. onError("Scene has been disposed");
  67239. return;
  67240. }
  67241. scene.database = database;
  67242. onSuccess(plugin, data, responseURL);
  67243. };
  67244. var request = null;
  67245. var pluginDisposed = false;
  67246. var onDisposeObservable = plugin.onDisposeObservable;
  67247. if (onDisposeObservable) {
  67248. onDisposeObservable.add(function () {
  67249. pluginDisposed = true;
  67250. if (request) {
  67251. request.abort();
  67252. request = null;
  67253. }
  67254. onDispose();
  67255. });
  67256. }
  67257. var manifestChecked = function () {
  67258. if (pluginDisposed) {
  67259. return;
  67260. }
  67261. var url = rootUrl + sceneFilename;
  67262. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67263. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67264. } : undefined, database, useArrayBuffer, function (request, exception) {
  67265. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67266. });
  67267. };
  67268. if (directLoad) {
  67269. dataCallback(directLoad);
  67270. return plugin;
  67271. }
  67272. if (rootUrl.indexOf("file:") === -1) {
  67273. var engine = scene.getEngine();
  67274. var canUseOfflineSupport = engine.enableOfflineSupport;
  67275. if (canUseOfflineSupport) {
  67276. // Also check for exceptions
  67277. var exceptionFound = false;
  67278. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67279. var regex = _a[_i];
  67280. if (regex.test(rootUrl + sceneFilename)) {
  67281. exceptionFound = true;
  67282. break;
  67283. }
  67284. }
  67285. canUseOfflineSupport = !exceptionFound;
  67286. }
  67287. if (canUseOfflineSupport) {
  67288. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67289. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67290. }
  67291. else {
  67292. manifestChecked();
  67293. }
  67294. }
  67295. // Loading file from disk via input file or drag'n'drop
  67296. else {
  67297. var fileOrString = sceneFilename;
  67298. if (fileOrString.name) { // File
  67299. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67300. }
  67301. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67302. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67303. }
  67304. else {
  67305. onError("Unable to find file named " + sceneFilename);
  67306. }
  67307. }
  67308. return plugin;
  67309. };
  67310. // Public functions
  67311. SceneLoader.GetPluginForExtension = function (extension) {
  67312. return SceneLoader._getPluginForExtension(extension).plugin;
  67313. };
  67314. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67315. return !!SceneLoader._registeredPlugins[extension];
  67316. };
  67317. SceneLoader.RegisterPlugin = function (plugin) {
  67318. if (typeof plugin.extensions === "string") {
  67319. var extension = plugin.extensions;
  67320. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67321. plugin: plugin,
  67322. isBinary: false
  67323. };
  67324. }
  67325. else {
  67326. var extensions = plugin.extensions;
  67327. Object.keys(extensions).forEach(function (extension) {
  67328. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67329. plugin: plugin,
  67330. isBinary: extensions[extension].isBinary
  67331. };
  67332. });
  67333. }
  67334. };
  67335. /**
  67336. * Import meshes into a scene
  67337. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67338. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67339. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67340. * @param scene the instance of BABYLON.Scene to append to
  67341. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67342. * @param onProgress a callback with a progress event for each file being loaded
  67343. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67344. * @param pluginExtension the extension used to determine the plugin
  67345. * @returns The loaded plugin
  67346. */
  67347. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67348. if (sceneFilename === void 0) { sceneFilename = ""; }
  67349. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67350. if (onSuccess === void 0) { onSuccess = null; }
  67351. if (onProgress === void 0) { onProgress = null; }
  67352. if (onError === void 0) { onError = null; }
  67353. if (pluginExtension === void 0) { pluginExtension = null; }
  67354. if (!scene) {
  67355. BABYLON.Tools.Error("No scene available to import mesh to");
  67356. return null;
  67357. }
  67358. if (!sceneFilename) {
  67359. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67360. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67361. }
  67362. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67363. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67364. return null;
  67365. }
  67366. var loadingToken = {};
  67367. scene._addPendingData(loadingToken);
  67368. var disposeHandler = function () {
  67369. scene._removePendingData(loadingToken);
  67370. };
  67371. var errorHandler = function (message, exception) {
  67372. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67373. if (onError) {
  67374. onError(scene, errorMessage, exception);
  67375. }
  67376. else {
  67377. BABYLON.Tools.Error(errorMessage);
  67378. // should the exception be thrown?
  67379. }
  67380. disposeHandler();
  67381. };
  67382. var progressHandler = onProgress ? function (event) {
  67383. try {
  67384. onProgress(event);
  67385. }
  67386. catch (e) {
  67387. errorHandler("Error in onProgress callback", e);
  67388. }
  67389. } : undefined;
  67390. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67391. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67392. if (onSuccess) {
  67393. try {
  67394. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67395. }
  67396. catch (e) {
  67397. errorHandler("Error in onSuccess callback", e);
  67398. }
  67399. }
  67400. scene._removePendingData(loadingToken);
  67401. };
  67402. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67403. if (plugin.rewriteRootURL) {
  67404. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67405. }
  67406. if (sceneFilename === "") {
  67407. if (sceneFilename === "") {
  67408. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67409. }
  67410. }
  67411. if (plugin.importMesh) {
  67412. var syncedPlugin = plugin;
  67413. var meshes = new Array();
  67414. var particleSystems = new Array();
  67415. var skeletons = new Array();
  67416. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67417. return;
  67418. }
  67419. scene.loadingPluginName = plugin.name;
  67420. successHandler(meshes, particleSystems, skeletons, []);
  67421. }
  67422. else {
  67423. var asyncedPlugin = plugin;
  67424. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67425. scene.loadingPluginName = plugin.name;
  67426. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67427. }).catch(function (error) {
  67428. errorHandler(error.message, error);
  67429. });
  67430. }
  67431. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67432. };
  67433. /**
  67434. * Import meshes into a scene
  67435. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67436. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67437. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67438. * @param scene the instance of BABYLON.Scene to append to
  67439. * @param onProgress a callback with a progress event for each file being loaded
  67440. * @param pluginExtension the extension used to determine the plugin
  67441. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67442. */
  67443. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67444. if (sceneFilename === void 0) { sceneFilename = ""; }
  67445. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67446. if (onProgress === void 0) { onProgress = null; }
  67447. if (pluginExtension === void 0) { pluginExtension = null; }
  67448. return new Promise(function (resolve, reject) {
  67449. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67450. resolve({
  67451. meshes: meshes,
  67452. particleSystems: particleSystems,
  67453. skeletons: skeletons,
  67454. animationGroups: animationGroups
  67455. });
  67456. }, onProgress, function (scene, message, exception) {
  67457. reject(exception || new Error(message));
  67458. }, pluginExtension);
  67459. });
  67460. };
  67461. /**
  67462. * Load a scene
  67463. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67464. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67465. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67466. * @param onSuccess a callback with the scene when import succeeds
  67467. * @param onProgress a callback with a progress event for each file being loaded
  67468. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67469. * @param pluginExtension the extension used to determine the plugin
  67470. * @returns The loaded plugin
  67471. */
  67472. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67473. if (onSuccess === void 0) { onSuccess = null; }
  67474. if (onProgress === void 0) { onProgress = null; }
  67475. if (onError === void 0) { onError = null; }
  67476. if (pluginExtension === void 0) { pluginExtension = null; }
  67477. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67478. };
  67479. /**
  67480. * Load a scene
  67481. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67482. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67483. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67484. * @param onProgress a callback with a progress event for each file being loaded
  67485. * @param pluginExtension the extension used to determine the plugin
  67486. * @returns The loaded scene
  67487. */
  67488. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67489. if (onProgress === void 0) { onProgress = null; }
  67490. if (pluginExtension === void 0) { pluginExtension = null; }
  67491. return new Promise(function (resolve, reject) {
  67492. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67493. resolve(scene);
  67494. }, onProgress, function (scene, message, exception) {
  67495. reject(exception || new Error(message));
  67496. }, pluginExtension);
  67497. });
  67498. };
  67499. /**
  67500. * Append a scene
  67501. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67502. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67503. * @param scene is the instance of BABYLON.Scene to append to
  67504. * @param onSuccess a callback with the scene when import succeeds
  67505. * @param onProgress a callback with a progress event for each file being loaded
  67506. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67507. * @param pluginExtension the extension used to determine the plugin
  67508. * @returns The loaded plugin
  67509. */
  67510. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67511. if (sceneFilename === void 0) { sceneFilename = ""; }
  67512. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67513. if (onSuccess === void 0) { onSuccess = null; }
  67514. if (onProgress === void 0) { onProgress = null; }
  67515. if (onError === void 0) { onError = null; }
  67516. if (pluginExtension === void 0) { pluginExtension = null; }
  67517. if (!scene) {
  67518. BABYLON.Tools.Error("No scene available to append to");
  67519. return null;
  67520. }
  67521. if (!sceneFilename) {
  67522. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67523. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67524. }
  67525. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67526. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67527. return null;
  67528. }
  67529. if (SceneLoader.ShowLoadingScreen) {
  67530. scene.getEngine().displayLoadingUI();
  67531. }
  67532. var loadingToken = {};
  67533. scene._addPendingData(loadingToken);
  67534. var disposeHandler = function () {
  67535. scene._removePendingData(loadingToken);
  67536. scene.getEngine().hideLoadingUI();
  67537. };
  67538. var errorHandler = function (message, exception) {
  67539. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67540. if (onError) {
  67541. onError(scene, errorMessage, exception);
  67542. }
  67543. else {
  67544. BABYLON.Tools.Error(errorMessage);
  67545. // should the exception be thrown?
  67546. }
  67547. disposeHandler();
  67548. };
  67549. var progressHandler = onProgress ? function (event) {
  67550. try {
  67551. onProgress(event);
  67552. }
  67553. catch (e) {
  67554. errorHandler("Error in onProgress callback", e);
  67555. }
  67556. } : undefined;
  67557. var successHandler = function () {
  67558. if (onSuccess) {
  67559. try {
  67560. onSuccess(scene);
  67561. }
  67562. catch (e) {
  67563. errorHandler("Error in onSuccess callback", e);
  67564. }
  67565. }
  67566. scene._removePendingData(loadingToken);
  67567. };
  67568. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67569. if (sceneFilename === "") {
  67570. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67571. }
  67572. if (plugin.load) {
  67573. var syncedPlugin = plugin;
  67574. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67575. return;
  67576. }
  67577. scene.loadingPluginName = plugin.name;
  67578. successHandler();
  67579. }
  67580. else {
  67581. var asyncedPlugin = plugin;
  67582. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67583. scene.loadingPluginName = plugin.name;
  67584. successHandler();
  67585. }).catch(function (error) {
  67586. errorHandler(error.message, error);
  67587. });
  67588. }
  67589. if (SceneLoader.ShowLoadingScreen) {
  67590. scene.executeWhenReady(function () {
  67591. scene.getEngine().hideLoadingUI();
  67592. });
  67593. }
  67594. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67595. };
  67596. /**
  67597. * Append a scene
  67598. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67599. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67600. * @param scene is the instance of BABYLON.Scene to append to
  67601. * @param onProgress a callback with a progress event for each file being loaded
  67602. * @param pluginExtension the extension used to determine the plugin
  67603. * @returns The given scene
  67604. */
  67605. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67606. if (sceneFilename === void 0) { sceneFilename = ""; }
  67607. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67608. if (onProgress === void 0) { onProgress = null; }
  67609. if (pluginExtension === void 0) { pluginExtension = null; }
  67610. return new Promise(function (resolve, reject) {
  67611. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67612. resolve(scene);
  67613. }, onProgress, function (scene, message, exception) {
  67614. reject(exception || new Error(message));
  67615. }, pluginExtension);
  67616. });
  67617. };
  67618. /**
  67619. * Load a scene into an asset container
  67620. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67621. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67622. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67623. * @param onSuccess a callback with the scene when import succeeds
  67624. * @param onProgress a callback with a progress event for each file being loaded
  67625. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67626. * @param pluginExtension the extension used to determine the plugin
  67627. * @returns The loaded plugin
  67628. */
  67629. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67630. if (sceneFilename === void 0) { sceneFilename = ""; }
  67631. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67632. if (onSuccess === void 0) { onSuccess = null; }
  67633. if (onProgress === void 0) { onProgress = null; }
  67634. if (onError === void 0) { onError = null; }
  67635. if (pluginExtension === void 0) { pluginExtension = null; }
  67636. if (!scene) {
  67637. BABYLON.Tools.Error("No scene available to load asset container to");
  67638. return null;
  67639. }
  67640. if (!sceneFilename) {
  67641. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67642. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67643. }
  67644. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67645. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67646. return null;
  67647. }
  67648. var loadingToken = {};
  67649. scene._addPendingData(loadingToken);
  67650. var disposeHandler = function () {
  67651. scene._removePendingData(loadingToken);
  67652. };
  67653. var errorHandler = function (message, exception) {
  67654. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67655. if (onError) {
  67656. onError(scene, errorMessage, exception);
  67657. }
  67658. else {
  67659. BABYLON.Tools.Error(errorMessage);
  67660. // should the exception be thrown?
  67661. }
  67662. disposeHandler();
  67663. };
  67664. var progressHandler = onProgress ? function (event) {
  67665. try {
  67666. onProgress(event);
  67667. }
  67668. catch (e) {
  67669. errorHandler("Error in onProgress callback", e);
  67670. }
  67671. } : undefined;
  67672. var successHandler = function (assets) {
  67673. if (onSuccess) {
  67674. try {
  67675. onSuccess(assets);
  67676. }
  67677. catch (e) {
  67678. errorHandler("Error in onSuccess callback", e);
  67679. }
  67680. }
  67681. scene._removePendingData(loadingToken);
  67682. };
  67683. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67684. if (plugin.loadAssetContainer) {
  67685. var syncedPlugin = plugin;
  67686. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67687. if (!assetContainer) {
  67688. return;
  67689. }
  67690. scene.loadingPluginName = plugin.name;
  67691. successHandler(assetContainer);
  67692. }
  67693. else if (plugin.loadAssetContainerAsync) {
  67694. var asyncedPlugin = plugin;
  67695. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67696. scene.loadingPluginName = plugin.name;
  67697. successHandler(assetContainer);
  67698. }).catch(function (error) {
  67699. errorHandler(error.message, error);
  67700. });
  67701. }
  67702. else {
  67703. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67704. }
  67705. if (SceneLoader.ShowLoadingScreen) {
  67706. scene.executeWhenReady(function () {
  67707. scene.getEngine().hideLoadingUI();
  67708. });
  67709. }
  67710. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67711. };
  67712. /**
  67713. * Load a scene into an asset container
  67714. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67715. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67716. * @param scene is the instance of BABYLON.Scene to append to
  67717. * @param onProgress a callback with a progress event for each file being loaded
  67718. * @param pluginExtension the extension used to determine the plugin
  67719. * @returns The loaded asset container
  67720. */
  67721. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67722. if (sceneFilename === void 0) { sceneFilename = ""; }
  67723. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67724. if (onProgress === void 0) { onProgress = null; }
  67725. if (pluginExtension === void 0) { pluginExtension = null; }
  67726. return new Promise(function (resolve, reject) {
  67727. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67728. resolve(assetContainer);
  67729. }, onProgress, function (scene, message, exception) {
  67730. reject(exception || new Error(message));
  67731. }, pluginExtension);
  67732. });
  67733. };
  67734. // Flags
  67735. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67736. SceneLoader._ShowLoadingScreen = true;
  67737. SceneLoader._CleanBoneMatrixWeights = false;
  67738. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67739. // Members
  67740. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67741. SceneLoader._registeredPlugins = {};
  67742. return SceneLoader;
  67743. }());
  67744. BABYLON.SceneLoader = SceneLoader;
  67745. ;
  67746. })(BABYLON || (BABYLON = {}));
  67747. //# sourceMappingURL=babylon.sceneLoader.js.map
  67748. var BABYLON;
  67749. (function (BABYLON) {
  67750. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67751. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67752. var parsedMaterial = parsedData.materials[index];
  67753. if (parsedMaterial.id === id) {
  67754. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67755. }
  67756. }
  67757. return null;
  67758. };
  67759. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67760. for (var i in names) {
  67761. if (mesh.name === names[i]) {
  67762. hierarchyIds.push(mesh.id);
  67763. return true;
  67764. }
  67765. }
  67766. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67767. hierarchyIds.push(mesh.id);
  67768. return true;
  67769. }
  67770. return false;
  67771. };
  67772. var logOperation = function (operation, producer) {
  67773. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67774. };
  67775. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67776. if (addToScene === void 0) { addToScene = false; }
  67777. var container = new BABYLON.AssetContainer(scene);
  67778. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67779. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67780. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67781. // and avoid problems with multiple concurrent .babylon loads.
  67782. var log = "importScene has failed JSON parse";
  67783. try {
  67784. var parsedData = JSON.parse(data);
  67785. log = "";
  67786. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67787. var index;
  67788. var cache;
  67789. // Lights
  67790. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67791. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67792. var parsedLight = parsedData.lights[index];
  67793. var light = BABYLON.Light.Parse(parsedLight, scene);
  67794. if (light) {
  67795. container.lights.push(light);
  67796. log += (index === 0 ? "\n\tLights:" : "");
  67797. log += "\n\t\t" + light.toString(fullDetails);
  67798. }
  67799. }
  67800. }
  67801. // Animations
  67802. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67803. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67804. var parsedAnimation = parsedData.animations[index];
  67805. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67806. scene.animations.push(animation);
  67807. container.animations.push(animation);
  67808. log += (index === 0 ? "\n\tAnimations:" : "");
  67809. log += "\n\t\t" + animation.toString(fullDetails);
  67810. }
  67811. }
  67812. // Materials
  67813. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67814. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67815. var parsedMaterial = parsedData.materials[index];
  67816. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67817. container.materials.push(mat);
  67818. log += (index === 0 ? "\n\tMaterials:" : "");
  67819. log += "\n\t\t" + mat.toString(fullDetails);
  67820. }
  67821. }
  67822. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67823. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67824. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67825. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67826. container.multiMaterials.push(mmat);
  67827. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67828. log += "\n\t\t" + mmat.toString(fullDetails);
  67829. }
  67830. }
  67831. // Morph targets
  67832. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67833. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67834. var managerData = _a[_i];
  67835. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67836. }
  67837. }
  67838. // Skeletons
  67839. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67840. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67841. var parsedSkeleton = parsedData.skeletons[index];
  67842. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67843. container.skeletons.push(skeleton);
  67844. log += (index === 0 ? "\n\tSkeletons:" : "");
  67845. log += "\n\t\t" + skeleton.toString(fullDetails);
  67846. }
  67847. }
  67848. // Geometries
  67849. var geometries = parsedData.geometries;
  67850. if (geometries !== undefined && geometries !== null) {
  67851. var addedGeometry = new Array();
  67852. // Boxes
  67853. var boxes = geometries.boxes;
  67854. if (boxes !== undefined && boxes !== null) {
  67855. for (index = 0, cache = boxes.length; index < cache; index++) {
  67856. var parsedBox = boxes[index];
  67857. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67858. }
  67859. }
  67860. // Spheres
  67861. var spheres = geometries.spheres;
  67862. if (spheres !== undefined && spheres !== null) {
  67863. for (index = 0, cache = spheres.length; index < cache; index++) {
  67864. var parsedSphere = spheres[index];
  67865. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67866. }
  67867. }
  67868. // Cylinders
  67869. var cylinders = geometries.cylinders;
  67870. if (cylinders !== undefined && cylinders !== null) {
  67871. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67872. var parsedCylinder = cylinders[index];
  67873. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67874. }
  67875. }
  67876. // Toruses
  67877. var toruses = geometries.toruses;
  67878. if (toruses !== undefined && toruses !== null) {
  67879. for (index = 0, cache = toruses.length; index < cache; index++) {
  67880. var parsedTorus = toruses[index];
  67881. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67882. }
  67883. }
  67884. // Grounds
  67885. var grounds = geometries.grounds;
  67886. if (grounds !== undefined && grounds !== null) {
  67887. for (index = 0, cache = grounds.length; index < cache; index++) {
  67888. var parsedGround = grounds[index];
  67889. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67890. }
  67891. }
  67892. // Planes
  67893. var planes = geometries.planes;
  67894. if (planes !== undefined && planes !== null) {
  67895. for (index = 0, cache = planes.length; index < cache; index++) {
  67896. var parsedPlane = planes[index];
  67897. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67898. }
  67899. }
  67900. // TorusKnots
  67901. var torusKnots = geometries.torusKnots;
  67902. if (torusKnots !== undefined && torusKnots !== null) {
  67903. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67904. var parsedTorusKnot = torusKnots[index];
  67905. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67906. }
  67907. }
  67908. // VertexData
  67909. var vertexData = geometries.vertexData;
  67910. if (vertexData !== undefined && vertexData !== null) {
  67911. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67912. var parsedVertexData = vertexData[index];
  67913. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67914. }
  67915. }
  67916. addedGeometry.forEach(function (g) {
  67917. if (g) {
  67918. container.geometries.push(g);
  67919. }
  67920. });
  67921. }
  67922. // Transform nodes
  67923. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67924. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67925. var parsedTransformNode = parsedData.transformNodes[index];
  67926. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67927. container.transformNodes.push(node);
  67928. }
  67929. }
  67930. // Meshes
  67931. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67932. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67933. var parsedMesh = parsedData.meshes[index];
  67934. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67935. container.meshes.push(mesh);
  67936. log += (index === 0 ? "\n\tMeshes:" : "");
  67937. log += "\n\t\t" + mesh.toString(fullDetails);
  67938. }
  67939. }
  67940. // Cameras
  67941. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67942. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67943. var parsedCamera = parsedData.cameras[index];
  67944. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67945. container.cameras.push(camera);
  67946. log += (index === 0 ? "\n\tCameras:" : "");
  67947. log += "\n\t\t" + camera.toString(fullDetails);
  67948. }
  67949. }
  67950. // Browsing all the graph to connect the dots
  67951. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67952. var camera = scene.cameras[index];
  67953. if (camera._waitingParentId) {
  67954. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67955. camera._waitingParentId = null;
  67956. }
  67957. }
  67958. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67959. var light_1 = scene.lights[index];
  67960. if (light_1 && light_1._waitingParentId) {
  67961. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67962. light_1._waitingParentId = null;
  67963. }
  67964. }
  67965. // Sounds
  67966. // TODO: add sound
  67967. var loadedSounds = [];
  67968. var loadedSound;
  67969. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67970. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67971. var parsedSound = parsedData.sounds[index];
  67972. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67973. if (!parsedSound.url)
  67974. parsedSound.url = parsedSound.name;
  67975. if (!loadedSounds[parsedSound.url]) {
  67976. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67977. loadedSounds[parsedSound.url] = loadedSound;
  67978. container.sounds.push(loadedSound);
  67979. }
  67980. else {
  67981. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67982. }
  67983. }
  67984. else {
  67985. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67986. }
  67987. }
  67988. }
  67989. loadedSounds = [];
  67990. // Connect parents & children and parse actions
  67991. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67992. var transformNode = scene.transformNodes[index];
  67993. if (transformNode._waitingParentId) {
  67994. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67995. transformNode._waitingParentId = null;
  67996. }
  67997. }
  67998. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67999. var mesh = scene.meshes[index];
  68000. if (mesh._waitingParentId) {
  68001. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68002. mesh._waitingParentId = null;
  68003. }
  68004. if (mesh._waitingActions) {
  68005. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68006. mesh._waitingActions = null;
  68007. }
  68008. }
  68009. // freeze world matrix application
  68010. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68011. var currentMesh = scene.meshes[index];
  68012. if (currentMesh._waitingFreezeWorldMatrix) {
  68013. currentMesh.freezeWorldMatrix();
  68014. currentMesh._waitingFreezeWorldMatrix = null;
  68015. }
  68016. else {
  68017. currentMesh.computeWorldMatrix(true);
  68018. }
  68019. }
  68020. // Particles Systems
  68021. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68022. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68023. var parsedParticleSystem = parsedData.particleSystems[index];
  68024. if (parsedParticleSystem.activeParticleCount) {
  68025. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68026. container.particleSystems.push(ps);
  68027. }
  68028. else {
  68029. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68030. container.particleSystems.push(ps);
  68031. }
  68032. }
  68033. }
  68034. // Lens flares
  68035. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  68036. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  68037. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  68038. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  68039. container.lensFlareSystems.push(lf);
  68040. }
  68041. }
  68042. // Shadows
  68043. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68044. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68045. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68046. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68047. container.shadowGenerators.push(sg);
  68048. }
  68049. }
  68050. // Lights exclusions / inclusions
  68051. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68052. var light_2 = scene.lights[index];
  68053. // Excluded check
  68054. if (light_2._excludedMeshesIds.length > 0) {
  68055. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68056. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68057. if (excludedMesh) {
  68058. light_2.excludedMeshes.push(excludedMesh);
  68059. }
  68060. }
  68061. light_2._excludedMeshesIds = [];
  68062. }
  68063. // Included check
  68064. if (light_2._includedOnlyMeshesIds.length > 0) {
  68065. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68066. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68067. if (includedOnlyMesh) {
  68068. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68069. }
  68070. }
  68071. light_2._includedOnlyMeshesIds = [];
  68072. }
  68073. }
  68074. // Effect layers
  68075. if (parsedData.effectLayers) {
  68076. for (index = 0; index < parsedData.effectLayers.length; index++) {
  68077. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  68078. container.effectLayers.push(effectLayer);
  68079. }
  68080. }
  68081. // Actions (scene)
  68082. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68083. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68084. }
  68085. if (!addToScene) {
  68086. container.removeAllFromScene();
  68087. }
  68088. }
  68089. catch (err) {
  68090. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68091. if (onError) {
  68092. onError(msg, err);
  68093. }
  68094. else {
  68095. BABYLON.Tools.Log(msg);
  68096. throw err;
  68097. }
  68098. }
  68099. finally {
  68100. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68101. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68102. }
  68103. }
  68104. return container;
  68105. };
  68106. BABYLON.SceneLoader.RegisterPlugin({
  68107. name: "babylon.js",
  68108. extensions: ".babylon",
  68109. canDirectLoad: function (data) {
  68110. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68111. return true;
  68112. }
  68113. return false;
  68114. },
  68115. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68116. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68117. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68118. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68119. // and avoid problems with multiple concurrent .babylon loads.
  68120. var log = "importMesh has failed JSON parse";
  68121. try {
  68122. var parsedData = JSON.parse(data);
  68123. log = "";
  68124. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68125. if (!meshesNames) {
  68126. meshesNames = null;
  68127. }
  68128. else if (!Array.isArray(meshesNames)) {
  68129. meshesNames = [meshesNames];
  68130. }
  68131. var hierarchyIds = new Array();
  68132. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68133. var loadedSkeletonsIds = [];
  68134. var loadedMaterialsIds = [];
  68135. var index;
  68136. var cache;
  68137. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68138. var parsedMesh = parsedData.meshes[index];
  68139. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68140. if (meshesNames !== null) {
  68141. // Remove found mesh name from list.
  68142. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68143. }
  68144. //Geometry?
  68145. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68146. //does the file contain geometries?
  68147. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68148. //find the correct geometry and add it to the scene
  68149. var found = false;
  68150. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68151. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68152. return;
  68153. }
  68154. else {
  68155. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68156. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68157. switch (geometryType) {
  68158. case "boxes":
  68159. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68160. break;
  68161. case "spheres":
  68162. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68163. break;
  68164. case "cylinders":
  68165. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68166. break;
  68167. case "toruses":
  68168. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68169. break;
  68170. case "grounds":
  68171. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68172. break;
  68173. case "planes":
  68174. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68175. break;
  68176. case "torusKnots":
  68177. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68178. break;
  68179. case "vertexData":
  68180. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68181. break;
  68182. }
  68183. found = true;
  68184. }
  68185. });
  68186. }
  68187. });
  68188. if (found === false) {
  68189. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68190. }
  68191. }
  68192. }
  68193. // Material ?
  68194. if (parsedMesh.materialId) {
  68195. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68196. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68197. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68198. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68199. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68200. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68201. var subMatId = parsedMultiMaterial.materials[matIndex];
  68202. loadedMaterialsIds.push(subMatId);
  68203. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68204. if (mat) {
  68205. log += "\n\tMaterial " + mat.toString(fullDetails);
  68206. }
  68207. }
  68208. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68209. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68210. if (mmat) {
  68211. materialFound = true;
  68212. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68213. }
  68214. break;
  68215. }
  68216. }
  68217. }
  68218. if (materialFound === false) {
  68219. loadedMaterialsIds.push(parsedMesh.materialId);
  68220. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68221. if (!mat) {
  68222. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68223. }
  68224. else {
  68225. log += "\n\tMaterial " + mat.toString(fullDetails);
  68226. }
  68227. }
  68228. }
  68229. // Skeleton ?
  68230. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68231. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68232. if (skeletonAlreadyLoaded === false) {
  68233. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68234. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68235. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68236. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68237. skeletons.push(skeleton);
  68238. loadedSkeletonsIds.push(parsedSkeleton.id);
  68239. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68240. }
  68241. }
  68242. }
  68243. }
  68244. // Morph targets ?
  68245. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68246. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68247. var managerData = _a[_i];
  68248. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68249. }
  68250. }
  68251. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68252. meshes.push(mesh);
  68253. log += "\n\tMesh " + mesh.toString(fullDetails);
  68254. }
  68255. }
  68256. // Connecting parents
  68257. var currentMesh;
  68258. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68259. currentMesh = scene.meshes[index];
  68260. if (currentMesh._waitingParentId) {
  68261. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68262. currentMesh._waitingParentId = null;
  68263. }
  68264. }
  68265. // freeze and compute world matrix application
  68266. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68267. currentMesh = scene.meshes[index];
  68268. if (currentMesh._waitingFreezeWorldMatrix) {
  68269. currentMesh.freezeWorldMatrix();
  68270. currentMesh._waitingFreezeWorldMatrix = null;
  68271. }
  68272. else {
  68273. currentMesh.computeWorldMatrix(true);
  68274. }
  68275. }
  68276. }
  68277. // Particles
  68278. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68279. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68280. var parsedParticleSystem = parsedData.particleSystems[index];
  68281. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68282. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68283. }
  68284. }
  68285. }
  68286. return true;
  68287. }
  68288. catch (err) {
  68289. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68290. if (onError) {
  68291. onError(msg, err);
  68292. }
  68293. else {
  68294. BABYLON.Tools.Log(msg);
  68295. throw err;
  68296. }
  68297. }
  68298. finally {
  68299. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68300. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68301. }
  68302. }
  68303. return false;
  68304. },
  68305. load: function (scene, data, rootUrl, onError) {
  68306. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68307. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68308. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68309. // and avoid problems with multiple concurrent .babylon loads.
  68310. var log = "importScene has failed JSON parse";
  68311. try {
  68312. var parsedData = JSON.parse(data);
  68313. log = "";
  68314. // Scene
  68315. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68316. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68317. }
  68318. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68319. scene.autoClear = parsedData.autoClear;
  68320. }
  68321. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68322. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68323. }
  68324. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68325. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68326. }
  68327. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68328. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68329. }
  68330. // Fog
  68331. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68332. scene.fogMode = parsedData.fogMode;
  68333. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68334. scene.fogStart = parsedData.fogStart;
  68335. scene.fogEnd = parsedData.fogEnd;
  68336. scene.fogDensity = parsedData.fogDensity;
  68337. log += "\tFog mode for scene: ";
  68338. switch (scene.fogMode) {
  68339. // getters not compiling, so using hardcoded
  68340. case 1:
  68341. log += "exp\n";
  68342. break;
  68343. case 2:
  68344. log += "exp2\n";
  68345. break;
  68346. case 3:
  68347. log += "linear\n";
  68348. break;
  68349. }
  68350. }
  68351. //Physics
  68352. if (parsedData.physicsEnabled) {
  68353. var physicsPlugin;
  68354. if (parsedData.physicsEngine === "cannon") {
  68355. physicsPlugin = new BABYLON.CannonJSPlugin();
  68356. }
  68357. else if (parsedData.physicsEngine === "oimo") {
  68358. physicsPlugin = new BABYLON.OimoJSPlugin();
  68359. }
  68360. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68361. //else - default engine, which is currently oimo
  68362. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68363. scene.enablePhysics(physicsGravity, physicsPlugin);
  68364. }
  68365. // Metadata
  68366. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68367. scene.metadata = parsedData.metadata;
  68368. }
  68369. //collisions, if defined. otherwise, default is true
  68370. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68371. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68372. }
  68373. scene.workerCollisions = !!parsedData.workerCollisions;
  68374. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68375. if (!container) {
  68376. return false;
  68377. }
  68378. if (parsedData.autoAnimate) {
  68379. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68380. }
  68381. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68382. scene.setActiveCameraByID(parsedData.activeCameraID);
  68383. }
  68384. // Environment texture
  68385. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68386. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68387. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68388. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68389. if (parsedData.environmentTextureRotationY) {
  68390. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68391. }
  68392. scene.environmentTexture = hdrTexture;
  68393. }
  68394. else {
  68395. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68396. if (parsedData.environmentTextureRotationY) {
  68397. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68398. }
  68399. scene.environmentTexture = cubeTexture;
  68400. }
  68401. if (parsedData.createDefaultSkybox === true) {
  68402. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68403. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68404. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68405. }
  68406. }
  68407. // Finish
  68408. return true;
  68409. }
  68410. catch (err) {
  68411. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68412. if (onError) {
  68413. onError(msg, err);
  68414. }
  68415. else {
  68416. BABYLON.Tools.Log(msg);
  68417. throw err;
  68418. }
  68419. }
  68420. finally {
  68421. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68422. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68423. }
  68424. }
  68425. return false;
  68426. },
  68427. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68428. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68429. return container;
  68430. }
  68431. });
  68432. })(BABYLON || (BABYLON = {}));
  68433. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68434. var BABYLON;
  68435. (function (BABYLON) {
  68436. var FilesInput = /** @class */ (function () {
  68437. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68438. this.onProcessFileCallback = function () { return true; };
  68439. this._engine = engine;
  68440. this._currentScene = scene;
  68441. this._sceneLoadedCallback = sceneLoadedCallback;
  68442. this._progressCallback = progressCallback;
  68443. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68444. this._textureLoadingCallback = textureLoadingCallback;
  68445. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68446. this._onReloadCallback = onReloadCallback;
  68447. this._errorCallback = errorCallback;
  68448. }
  68449. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68450. var _this = this;
  68451. if (elementToMonitor) {
  68452. this._elementToMonitor = elementToMonitor;
  68453. this._dragEnterHandler = function (e) { _this.drag(e); };
  68454. this._dragOverHandler = function (e) { _this.drag(e); };
  68455. this._dropHandler = function (e) { _this.drop(e); };
  68456. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68457. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68458. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68459. }
  68460. };
  68461. FilesInput.prototype.dispose = function () {
  68462. if (!this._elementToMonitor) {
  68463. return;
  68464. }
  68465. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68466. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68467. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68468. };
  68469. FilesInput.prototype.renderFunction = function () {
  68470. if (this._additionalRenderLoopLogicCallback) {
  68471. this._additionalRenderLoopLogicCallback();
  68472. }
  68473. if (this._currentScene) {
  68474. if (this._textureLoadingCallback) {
  68475. var remaining = this._currentScene.getWaitingItemsCount();
  68476. if (remaining > 0) {
  68477. this._textureLoadingCallback(remaining);
  68478. }
  68479. }
  68480. this._currentScene.render();
  68481. }
  68482. };
  68483. FilesInput.prototype.drag = function (e) {
  68484. e.stopPropagation();
  68485. e.preventDefault();
  68486. };
  68487. FilesInput.prototype.drop = function (eventDrop) {
  68488. eventDrop.stopPropagation();
  68489. eventDrop.preventDefault();
  68490. this.loadFiles(eventDrop);
  68491. };
  68492. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68493. var _this = this;
  68494. var reader = folder.createReader();
  68495. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68496. reader.readEntries(function (entries) {
  68497. remaining.count += entries.length;
  68498. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68499. var entry = entries_1[_i];
  68500. if (entry.isFile) {
  68501. entry.file(function (file) {
  68502. file.correctName = relativePath + file.name;
  68503. files.push(file);
  68504. if (--remaining.count === 0) {
  68505. callback();
  68506. }
  68507. });
  68508. }
  68509. else if (entry.isDirectory) {
  68510. _this._traverseFolder(entry, files, remaining, callback);
  68511. }
  68512. }
  68513. if (--remaining.count) {
  68514. callback();
  68515. }
  68516. });
  68517. };
  68518. FilesInput.prototype._processFiles = function (files) {
  68519. for (var i = 0; i < files.length; i++) {
  68520. var name = files[i].correctName.toLowerCase();
  68521. var extension = name.split('.').pop();
  68522. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68523. continue;
  68524. }
  68525. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68526. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68527. this._sceneFileToLoad = files[i];
  68528. }
  68529. else {
  68530. FilesInput.FilesToLoad[name] = files[i];
  68531. }
  68532. }
  68533. };
  68534. FilesInput.prototype.loadFiles = function (event) {
  68535. var _this = this;
  68536. if (this._startingProcessingFilesCallback)
  68537. this._startingProcessingFilesCallback();
  68538. // Handling data transfer via drag'n'drop
  68539. if (event && event.dataTransfer && event.dataTransfer.files) {
  68540. this._filesToLoad = event.dataTransfer.files;
  68541. }
  68542. // Handling files from input files
  68543. if (event && event.target && event.target.files) {
  68544. this._filesToLoad = event.target.files;
  68545. }
  68546. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68547. var files_1 = new Array();
  68548. var folders = [];
  68549. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68550. for (var i = 0; i < this._filesToLoad.length; i++) {
  68551. var fileToLoad = this._filesToLoad[i];
  68552. var name_1 = fileToLoad.name.toLowerCase();
  68553. var entry = void 0;
  68554. fileToLoad.correctName = name_1;
  68555. if (items) {
  68556. var item = items[i];
  68557. if (item.getAsEntry) {
  68558. entry = item.getAsEntry();
  68559. }
  68560. else if (item.webkitGetAsEntry) {
  68561. entry = item.webkitGetAsEntry();
  68562. }
  68563. }
  68564. if (!entry) {
  68565. files_1.push(fileToLoad);
  68566. }
  68567. else {
  68568. if (entry.isDirectory) {
  68569. folders.push(entry);
  68570. }
  68571. else {
  68572. files_1.push(fileToLoad);
  68573. }
  68574. }
  68575. }
  68576. if (folders.length === 0) {
  68577. this._processFiles(files_1);
  68578. this._processReload();
  68579. }
  68580. else {
  68581. var remaining = { count: folders.length };
  68582. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68583. var folder = folders_1[_i];
  68584. this._traverseFolder(folder, files_1, remaining, function () {
  68585. _this._processFiles(files_1);
  68586. if (remaining.count === 0) {
  68587. _this._processReload();
  68588. }
  68589. });
  68590. }
  68591. }
  68592. }
  68593. };
  68594. FilesInput.prototype._processReload = function () {
  68595. if (this._onReloadCallback) {
  68596. this._onReloadCallback(this._sceneFileToLoad);
  68597. }
  68598. else {
  68599. this.reload();
  68600. }
  68601. };
  68602. FilesInput.prototype.reload = function () {
  68603. var _this = this;
  68604. // If a scene file has been provided
  68605. if (this._sceneFileToLoad) {
  68606. if (this._currentScene) {
  68607. if (BABYLON.Tools.errorsCount > 0) {
  68608. BABYLON.Tools.ClearLogCache();
  68609. }
  68610. this._engine.stopRenderLoop();
  68611. this._currentScene.dispose();
  68612. }
  68613. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68614. if (_this._progressCallback) {
  68615. _this._progressCallback(progress);
  68616. }
  68617. }).then(function (scene) {
  68618. _this._currentScene = scene;
  68619. if (_this._sceneLoadedCallback) {
  68620. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68621. }
  68622. // Wait for textures and shaders to be ready
  68623. _this._currentScene.executeWhenReady(function () {
  68624. _this._engine.runRenderLoop(function () {
  68625. _this.renderFunction();
  68626. });
  68627. });
  68628. }).catch(function (error) {
  68629. if (_this._errorCallback) {
  68630. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68631. }
  68632. });
  68633. }
  68634. else {
  68635. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68636. }
  68637. };
  68638. FilesInput.FilesToLoad = {};
  68639. return FilesInput;
  68640. }());
  68641. BABYLON.FilesInput = FilesInput;
  68642. })(BABYLON || (BABYLON = {}));
  68643. //# sourceMappingURL=babylon.filesInput.js.map
  68644. var BABYLON;
  68645. (function (BABYLON) {
  68646. /**
  68647. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68648. * The underlying implementation relies on an associative array to ensure the best performances.
  68649. * The value can be anything including 'null' but except 'undefined'
  68650. */
  68651. var StringDictionary = /** @class */ (function () {
  68652. function StringDictionary() {
  68653. this._count = 0;
  68654. this._data = {};
  68655. }
  68656. /**
  68657. * This will clear this dictionary and copy the content from the 'source' one.
  68658. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68659. * @param source the dictionary to take the content from and copy to this dictionary
  68660. */
  68661. StringDictionary.prototype.copyFrom = function (source) {
  68662. var _this = this;
  68663. this.clear();
  68664. source.forEach(function (t, v) { return _this.add(t, v); });
  68665. };
  68666. /**
  68667. * Get a value based from its key
  68668. * @param key the given key to get the matching value from
  68669. * @return the value if found, otherwise undefined is returned
  68670. */
  68671. StringDictionary.prototype.get = function (key) {
  68672. var val = this._data[key];
  68673. if (val !== undefined) {
  68674. return val;
  68675. }
  68676. return undefined;
  68677. };
  68678. /**
  68679. * Get a value from its key or add it if it doesn't exist.
  68680. * This method will ensure you that a given key/data will be present in the dictionary.
  68681. * @param key the given key to get the matching value from
  68682. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68683. * The factory will only be invoked if there's no data for the given key.
  68684. * @return the value corresponding to the key.
  68685. */
  68686. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68687. var val = this.get(key);
  68688. if (val !== undefined) {
  68689. return val;
  68690. }
  68691. val = factory(key);
  68692. if (val) {
  68693. this.add(key, val);
  68694. }
  68695. return val;
  68696. };
  68697. /**
  68698. * Get a value from its key if present in the dictionary otherwise add it
  68699. * @param key the key to get the value from
  68700. * @param val if there's no such key/value pair in the dictionary add it with this value
  68701. * @return the value corresponding to the key
  68702. */
  68703. StringDictionary.prototype.getOrAdd = function (key, val) {
  68704. var curVal = this.get(key);
  68705. if (curVal !== undefined) {
  68706. return curVal;
  68707. }
  68708. this.add(key, val);
  68709. return val;
  68710. };
  68711. /**
  68712. * Check if there's a given key in the dictionary
  68713. * @param key the key to check for
  68714. * @return true if the key is present, false otherwise
  68715. */
  68716. StringDictionary.prototype.contains = function (key) {
  68717. return this._data[key] !== undefined;
  68718. };
  68719. /**
  68720. * Add a new key and its corresponding value
  68721. * @param key the key to add
  68722. * @param value the value corresponding to the key
  68723. * @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
  68724. */
  68725. StringDictionary.prototype.add = function (key, value) {
  68726. if (this._data[key] !== undefined) {
  68727. return false;
  68728. }
  68729. this._data[key] = value;
  68730. ++this._count;
  68731. return true;
  68732. };
  68733. StringDictionary.prototype.set = function (key, value) {
  68734. if (this._data[key] === undefined) {
  68735. return false;
  68736. }
  68737. this._data[key] = value;
  68738. return true;
  68739. };
  68740. /**
  68741. * Get the element of the given key and remove it from the dictionary
  68742. * @param key
  68743. */
  68744. StringDictionary.prototype.getAndRemove = function (key) {
  68745. var val = this.get(key);
  68746. if (val !== undefined) {
  68747. delete this._data[key];
  68748. --this._count;
  68749. return val;
  68750. }
  68751. return null;
  68752. };
  68753. /**
  68754. * Remove a key/value from the dictionary.
  68755. * @param key the key to remove
  68756. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68757. */
  68758. StringDictionary.prototype.remove = function (key) {
  68759. if (this.contains(key)) {
  68760. delete this._data[key];
  68761. --this._count;
  68762. return true;
  68763. }
  68764. return false;
  68765. };
  68766. /**
  68767. * Clear the whole content of the dictionary
  68768. */
  68769. StringDictionary.prototype.clear = function () {
  68770. this._data = {};
  68771. this._count = 0;
  68772. };
  68773. Object.defineProperty(StringDictionary.prototype, "count", {
  68774. get: function () {
  68775. return this._count;
  68776. },
  68777. enumerable: true,
  68778. configurable: true
  68779. });
  68780. /**
  68781. * Execute a callback on each key/val of the dictionary.
  68782. * Note that you can remove any element in this dictionary in the callback implementation
  68783. * @param callback the callback to execute on a given key/value pair
  68784. */
  68785. StringDictionary.prototype.forEach = function (callback) {
  68786. for (var cur in this._data) {
  68787. var val = this._data[cur];
  68788. callback(cur, val);
  68789. }
  68790. };
  68791. /**
  68792. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68793. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68794. * Note that you can remove any element in this dictionary in the callback implementation
  68795. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68796. */
  68797. StringDictionary.prototype.first = function (callback) {
  68798. for (var cur in this._data) {
  68799. var val = this._data[cur];
  68800. var res = callback(cur, val);
  68801. if (res) {
  68802. return res;
  68803. }
  68804. }
  68805. return null;
  68806. };
  68807. return StringDictionary;
  68808. }());
  68809. BABYLON.StringDictionary = StringDictionary;
  68810. })(BABYLON || (BABYLON = {}));
  68811. //# sourceMappingURL=babylon.stringDictionary.js.map
  68812. var BABYLON;
  68813. (function (BABYLON) {
  68814. var Tags = /** @class */ (function () {
  68815. function Tags() {
  68816. }
  68817. Tags.EnableFor = function (obj) {
  68818. obj._tags = obj._tags || {};
  68819. obj.hasTags = function () {
  68820. return Tags.HasTags(obj);
  68821. };
  68822. obj.addTags = function (tagsString) {
  68823. return Tags.AddTagsTo(obj, tagsString);
  68824. };
  68825. obj.removeTags = function (tagsString) {
  68826. return Tags.RemoveTagsFrom(obj, tagsString);
  68827. };
  68828. obj.matchesTagsQuery = function (tagsQuery) {
  68829. return Tags.MatchesQuery(obj, tagsQuery);
  68830. };
  68831. };
  68832. Tags.DisableFor = function (obj) {
  68833. delete obj._tags;
  68834. delete obj.hasTags;
  68835. delete obj.addTags;
  68836. delete obj.removeTags;
  68837. delete obj.matchesTagsQuery;
  68838. };
  68839. Tags.HasTags = function (obj) {
  68840. if (!obj._tags) {
  68841. return false;
  68842. }
  68843. return !BABYLON.Tools.IsEmpty(obj._tags);
  68844. };
  68845. Tags.GetTags = function (obj, asString) {
  68846. if (asString === void 0) { asString = true; }
  68847. if (!obj._tags) {
  68848. return null;
  68849. }
  68850. if (asString) {
  68851. var tagsArray = [];
  68852. for (var tag in obj._tags) {
  68853. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68854. tagsArray.push(tag);
  68855. }
  68856. }
  68857. return tagsArray.join(" ");
  68858. }
  68859. else {
  68860. return obj._tags;
  68861. }
  68862. };
  68863. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68864. // a tag cannot start with '||', '&&', and '!'
  68865. // it cannot contain whitespaces
  68866. Tags.AddTagsTo = function (obj, tagsString) {
  68867. if (!tagsString) {
  68868. return;
  68869. }
  68870. if (typeof tagsString !== "string") {
  68871. return;
  68872. }
  68873. var tags = tagsString.split(" ");
  68874. tags.forEach(function (tag, index, array) {
  68875. Tags._AddTagTo(obj, tag);
  68876. });
  68877. };
  68878. Tags._AddTagTo = function (obj, tag) {
  68879. tag = tag.trim();
  68880. if (tag === "" || tag === "true" || tag === "false") {
  68881. return;
  68882. }
  68883. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68884. return;
  68885. }
  68886. Tags.EnableFor(obj);
  68887. obj._tags[tag] = true;
  68888. };
  68889. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68890. if (!Tags.HasTags(obj)) {
  68891. return;
  68892. }
  68893. var tags = tagsString.split(" ");
  68894. for (var t in tags) {
  68895. Tags._RemoveTagFrom(obj, tags[t]);
  68896. }
  68897. };
  68898. Tags._RemoveTagFrom = function (obj, tag) {
  68899. delete obj._tags[tag];
  68900. };
  68901. Tags.MatchesQuery = function (obj, tagsQuery) {
  68902. if (tagsQuery === undefined) {
  68903. return true;
  68904. }
  68905. if (tagsQuery === "") {
  68906. return Tags.HasTags(obj);
  68907. }
  68908. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68909. };
  68910. return Tags;
  68911. }());
  68912. BABYLON.Tags = Tags;
  68913. })(BABYLON || (BABYLON = {}));
  68914. //# sourceMappingURL=babylon.tags.js.map
  68915. var BABYLON;
  68916. (function (BABYLON) {
  68917. /**
  68918. * Class used to evalaute queries containing `and` and `or` operators
  68919. */
  68920. var AndOrNotEvaluator = /** @class */ (function () {
  68921. function AndOrNotEvaluator() {
  68922. }
  68923. /**
  68924. * Evaluate a query
  68925. * @param query defines the query to evaluate
  68926. * @param evaluateCallback defines the callback used to filter result
  68927. * @returns true if the query matches
  68928. */
  68929. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68930. if (!query.match(/\([^\(\)]*\)/g)) {
  68931. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68932. }
  68933. else {
  68934. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68935. // remove parenthesis
  68936. r = r.slice(1, r.length - 1);
  68937. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68938. });
  68939. }
  68940. if (query === "true") {
  68941. return true;
  68942. }
  68943. if (query === "false") {
  68944. return false;
  68945. }
  68946. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68947. };
  68948. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68949. evaluateCallback = evaluateCallback || (function (r) {
  68950. return r === "true" ? true : false;
  68951. });
  68952. var result;
  68953. var or = parenthesisContent.split("||");
  68954. for (var i in or) {
  68955. if (or.hasOwnProperty(i)) {
  68956. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68957. var and = ori.split("&&");
  68958. if (and.length > 1) {
  68959. for (var j = 0; j < and.length; ++j) {
  68960. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68961. if (andj !== "true" && andj !== "false") {
  68962. if (andj[0] === "!") {
  68963. result = !evaluateCallback(andj.substring(1));
  68964. }
  68965. else {
  68966. result = evaluateCallback(andj);
  68967. }
  68968. }
  68969. else {
  68970. result = andj === "true" ? true : false;
  68971. }
  68972. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68973. ori = "false";
  68974. break;
  68975. }
  68976. }
  68977. }
  68978. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68979. result = true;
  68980. break;
  68981. }
  68982. // result equals false (or undefined)
  68983. if (ori !== "true" && ori !== "false") {
  68984. if (ori[0] === "!") {
  68985. result = !evaluateCallback(ori.substring(1));
  68986. }
  68987. else {
  68988. result = evaluateCallback(ori);
  68989. }
  68990. }
  68991. else {
  68992. result = ori === "true" ? true : false;
  68993. }
  68994. }
  68995. }
  68996. // the whole parenthesis scope is replaced by 'true' or 'false'
  68997. return result ? "true" : "false";
  68998. };
  68999. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69000. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69001. // remove whitespaces
  69002. r = r.replace(/[\s]/g, function () { return ""; });
  69003. return r.length % 2 ? "!" : "";
  69004. });
  69005. booleanString = booleanString.trim();
  69006. if (booleanString === "!true") {
  69007. booleanString = "false";
  69008. }
  69009. else if (booleanString === "!false") {
  69010. booleanString = "true";
  69011. }
  69012. return booleanString;
  69013. };
  69014. return AndOrNotEvaluator;
  69015. }());
  69016. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69017. })(BABYLON || (BABYLON = {}));
  69018. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69019. var BABYLON;
  69020. (function (BABYLON) {
  69021. /**
  69022. * Class used to enable access to IndexedDB
  69023. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69024. */
  69025. var Database = /** @class */ (function () {
  69026. /**
  69027. * Creates a new Database
  69028. * @param urlToScene defines the url to load the scene
  69029. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69030. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69031. */
  69032. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69033. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69034. var _this = this;
  69035. // Handling various flavors of prefixed version of IndexedDB
  69036. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69037. this.callbackManifestChecked = callbackManifestChecked;
  69038. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69039. this.db = null;
  69040. this._enableSceneOffline = false;
  69041. this._enableTexturesOffline = false;
  69042. this.manifestVersionFound = 0;
  69043. this.mustUpdateRessources = false;
  69044. this.hasReachedQuota = false;
  69045. if (!Database.IDBStorageEnabled) {
  69046. this.callbackManifestChecked(true);
  69047. }
  69048. else {
  69049. if (disableManifestCheck) {
  69050. this._enableSceneOffline = true;
  69051. this._enableTexturesOffline = true;
  69052. this.manifestVersionFound = 1;
  69053. BABYLON.Tools.SetImmediate(function () {
  69054. _this.callbackManifestChecked(true);
  69055. });
  69056. }
  69057. else {
  69058. this._checkManifestFile();
  69059. }
  69060. }
  69061. }
  69062. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69063. /**
  69064. * Gets a boolean indicating if scene must be saved in the database
  69065. */
  69066. get: function () {
  69067. return this._enableSceneOffline;
  69068. },
  69069. enumerable: true,
  69070. configurable: true
  69071. });
  69072. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69073. /**
  69074. * Gets a boolean indicating if textures must be saved in the database
  69075. */
  69076. get: function () {
  69077. return this._enableTexturesOffline;
  69078. },
  69079. enumerable: true,
  69080. configurable: true
  69081. });
  69082. Database.prototype._checkManifestFile = function () {
  69083. var _this = this;
  69084. var noManifestFile = function () {
  69085. _this._enableSceneOffline = false;
  69086. _this._enableTexturesOffline = false;
  69087. _this.callbackManifestChecked(false);
  69088. };
  69089. var timeStampUsed = false;
  69090. var manifestURL = this.currentSceneUrl + ".manifest";
  69091. var xhr = new XMLHttpRequest();
  69092. if (navigator.onLine) {
  69093. // Adding a timestamp to by-pass browsers' cache
  69094. timeStampUsed = true;
  69095. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69096. }
  69097. xhr.open("GET", manifestURL, true);
  69098. xhr.addEventListener("load", function () {
  69099. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69100. try {
  69101. var manifestFile = JSON.parse(xhr.response);
  69102. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69103. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69104. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69105. _this.manifestVersionFound = manifestFile.version;
  69106. }
  69107. if (_this.callbackManifestChecked) {
  69108. _this.callbackManifestChecked(true);
  69109. }
  69110. }
  69111. catch (ex) {
  69112. noManifestFile();
  69113. }
  69114. }
  69115. else {
  69116. noManifestFile();
  69117. }
  69118. }, false);
  69119. xhr.addEventListener("error", function (event) {
  69120. if (timeStampUsed) {
  69121. timeStampUsed = false;
  69122. // Let's retry without the timeStamp
  69123. // It could fail when coupled with HTML5 Offline API
  69124. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69125. xhr.open("GET", retryManifestURL, true);
  69126. xhr.send();
  69127. }
  69128. else {
  69129. noManifestFile();
  69130. }
  69131. }, false);
  69132. try {
  69133. xhr.send();
  69134. }
  69135. catch (ex) {
  69136. BABYLON.Tools.Error("Error on XHR send request.");
  69137. this.callbackManifestChecked(false);
  69138. }
  69139. };
  69140. /**
  69141. * Open the database and make it available
  69142. * @param successCallback defines the callback to call on success
  69143. * @param errorCallback defines the callback to call on error
  69144. */
  69145. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69146. var _this = this;
  69147. var handleError = function () {
  69148. _this.isSupported = false;
  69149. if (errorCallback)
  69150. errorCallback();
  69151. };
  69152. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69153. // Your browser doesn't support IndexedDB
  69154. this.isSupported = false;
  69155. if (errorCallback)
  69156. errorCallback();
  69157. }
  69158. else {
  69159. // If the DB hasn't been opened or created yet
  69160. if (!this.db) {
  69161. this.hasReachedQuota = false;
  69162. this.isSupported = true;
  69163. var request = this.idbFactory.open("babylonjs", 1);
  69164. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69165. request.onerror = function (event) {
  69166. handleError();
  69167. };
  69168. // executes when a version change transaction cannot complete due to other active transactions
  69169. request.onblocked = function (event) {
  69170. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69171. handleError();
  69172. };
  69173. // DB has been opened successfully
  69174. request.onsuccess = function (event) {
  69175. _this.db = request.result;
  69176. successCallback();
  69177. };
  69178. // Initialization of the DB. Creating Scenes & Textures stores
  69179. request.onupgradeneeded = function (event) {
  69180. _this.db = (event.target).result;
  69181. if (_this.db) {
  69182. try {
  69183. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69184. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69185. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69186. }
  69187. catch (ex) {
  69188. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69189. handleError();
  69190. }
  69191. }
  69192. };
  69193. }
  69194. // DB has already been created and opened
  69195. else {
  69196. if (successCallback)
  69197. successCallback();
  69198. }
  69199. }
  69200. };
  69201. /**
  69202. * Loads an image from the database
  69203. * @param url defines the url to load from
  69204. * @param image defines the target DOM image
  69205. */
  69206. Database.prototype.loadImageFromDB = function (url, image) {
  69207. var _this = this;
  69208. var completeURL = Database._ReturnFullUrlLocation(url);
  69209. var saveAndLoadImage = function () {
  69210. if (!_this.hasReachedQuota && _this.db !== null) {
  69211. // the texture is not yet in the DB, let's try to save it
  69212. _this._saveImageIntoDBAsync(completeURL, image);
  69213. }
  69214. // If the texture is not in the DB and we've reached the DB quota limit
  69215. // let's load it directly from the web
  69216. else {
  69217. image.src = url;
  69218. }
  69219. };
  69220. if (!this.mustUpdateRessources) {
  69221. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69222. }
  69223. // First time we're download the images or update requested in the manifest file by a version change
  69224. else {
  69225. saveAndLoadImage();
  69226. }
  69227. };
  69228. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69229. if (this.isSupported && this.db !== null) {
  69230. var texture;
  69231. var transaction = this.db.transaction(["textures"]);
  69232. transaction.onabort = function (event) {
  69233. image.src = url;
  69234. };
  69235. transaction.oncomplete = function (event) {
  69236. var blobTextureURL;
  69237. if (texture) {
  69238. var URL = window.URL || window.webkitURL;
  69239. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69240. image.onerror = function () {
  69241. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69242. image.src = url;
  69243. };
  69244. image.src = blobTextureURL;
  69245. }
  69246. else {
  69247. notInDBCallback();
  69248. }
  69249. };
  69250. var getRequest = transaction.objectStore("textures").get(url);
  69251. getRequest.onsuccess = function (event) {
  69252. texture = (event.target).result;
  69253. };
  69254. getRequest.onerror = function (event) {
  69255. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69256. image.src = url;
  69257. };
  69258. }
  69259. else {
  69260. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69261. image.src = url;
  69262. }
  69263. };
  69264. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69265. var _this = this;
  69266. if (this.isSupported) {
  69267. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69268. var generateBlobUrl = function () {
  69269. var blobTextureURL;
  69270. if (blob) {
  69271. var URL = window.URL || window.webkitURL;
  69272. try {
  69273. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69274. }
  69275. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69276. catch (ex) {
  69277. blobTextureURL = URL.createObjectURL(blob);
  69278. }
  69279. }
  69280. if (blobTextureURL) {
  69281. image.src = blobTextureURL;
  69282. }
  69283. };
  69284. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69285. var xhr = new XMLHttpRequest(), blob;
  69286. xhr.open("GET", url, true);
  69287. xhr.responseType = "blob";
  69288. xhr.addEventListener("load", function () {
  69289. if (xhr.status === 200 && _this.db) {
  69290. // Blob as response (XHR2)
  69291. blob = xhr.response;
  69292. var transaction = _this.db.transaction(["textures"], "readwrite");
  69293. // the transaction could abort because of a QuotaExceededError error
  69294. transaction.onabort = function (event) {
  69295. try {
  69296. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69297. var srcElement = (event.srcElement || event.target);
  69298. var error = srcElement.error;
  69299. if (error && error.name === "QuotaExceededError") {
  69300. _this.hasReachedQuota = true;
  69301. }
  69302. }
  69303. catch (ex) { }
  69304. generateBlobUrl();
  69305. };
  69306. transaction.oncomplete = function (event) {
  69307. generateBlobUrl();
  69308. };
  69309. var newTexture = { textureUrl: url, data: blob };
  69310. try {
  69311. // Put the blob into the dabase
  69312. var addRequest = transaction.objectStore("textures").put(newTexture);
  69313. addRequest.onsuccess = function (event) {
  69314. };
  69315. addRequest.onerror = function (event) {
  69316. generateBlobUrl();
  69317. };
  69318. }
  69319. catch (ex) {
  69320. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69321. if (ex.code === 25) {
  69322. Database.IsUASupportingBlobStorage = false;
  69323. }
  69324. image.src = url;
  69325. }
  69326. }
  69327. else {
  69328. image.src = url;
  69329. }
  69330. }, false);
  69331. xhr.addEventListener("error", function (event) {
  69332. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69333. image.src = url;
  69334. }, false);
  69335. xhr.send();
  69336. }
  69337. else {
  69338. image.src = url;
  69339. }
  69340. }
  69341. else {
  69342. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69343. image.src = url;
  69344. }
  69345. };
  69346. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69347. var _this = this;
  69348. var updateVersion = function () {
  69349. // the version is not yet in the DB or we need to update it
  69350. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69351. };
  69352. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69353. };
  69354. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69355. var _this = this;
  69356. if (this.isSupported && this.db) {
  69357. var version;
  69358. try {
  69359. var transaction = this.db.transaction(["versions"]);
  69360. transaction.oncomplete = function (event) {
  69361. if (version) {
  69362. // If the version in the JSON file is different from the version in DB
  69363. if (_this.manifestVersionFound !== version.data) {
  69364. _this.mustUpdateRessources = true;
  69365. updateInDBCallback();
  69366. }
  69367. else {
  69368. callback(version.data);
  69369. }
  69370. }
  69371. // version was not found in DB
  69372. else {
  69373. _this.mustUpdateRessources = true;
  69374. updateInDBCallback();
  69375. }
  69376. };
  69377. transaction.onabort = function (event) {
  69378. callback(-1);
  69379. };
  69380. var getRequest = transaction.objectStore("versions").get(url);
  69381. getRequest.onsuccess = function (event) {
  69382. version = (event.target).result;
  69383. };
  69384. getRequest.onerror = function (event) {
  69385. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69386. callback(-1);
  69387. };
  69388. }
  69389. catch (ex) {
  69390. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69391. callback(-1);
  69392. }
  69393. }
  69394. else {
  69395. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69396. callback(-1);
  69397. }
  69398. };
  69399. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69400. var _this = this;
  69401. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69402. try {
  69403. // Open a transaction to the database
  69404. var transaction = this.db.transaction(["versions"], "readwrite");
  69405. // the transaction could abort because of a QuotaExceededError error
  69406. transaction.onabort = function (event) {
  69407. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69408. var error = event.srcElement['error'];
  69409. if (error && error.name === "QuotaExceededError") {
  69410. _this.hasReachedQuota = true;
  69411. }
  69412. }
  69413. catch (ex) { }
  69414. callback(-1);
  69415. };
  69416. transaction.oncomplete = function (event) {
  69417. callback(_this.manifestVersionFound);
  69418. };
  69419. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69420. // Put the scene into the database
  69421. var addRequest = transaction.objectStore("versions").put(newVersion);
  69422. addRequest.onsuccess = function (event) {
  69423. };
  69424. addRequest.onerror = function (event) {
  69425. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69426. };
  69427. }
  69428. catch (ex) {
  69429. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69430. callback(-1);
  69431. }
  69432. }
  69433. else {
  69434. callback(-1);
  69435. }
  69436. };
  69437. /**
  69438. * Loads a file from database
  69439. * @param url defines the URL to load from
  69440. * @param sceneLoaded defines a callback to call on success
  69441. * @param progressCallBack defines a callback to call when progress changed
  69442. * @param errorCallback defines a callback to call on error
  69443. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69444. */
  69445. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69446. var _this = this;
  69447. var completeUrl = Database._ReturnFullUrlLocation(url);
  69448. var saveAndLoadFile = function () {
  69449. // the scene is not yet in the DB, let's try to save it
  69450. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69451. };
  69452. this._checkVersionFromDB(completeUrl, function (version) {
  69453. if (version !== -1) {
  69454. if (!_this.mustUpdateRessources) {
  69455. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69456. }
  69457. else {
  69458. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69459. }
  69460. }
  69461. else {
  69462. if (errorCallback) {
  69463. errorCallback();
  69464. }
  69465. }
  69466. });
  69467. };
  69468. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69469. if (this.isSupported && this.db) {
  69470. var targetStore;
  69471. if (url.indexOf(".babylon") !== -1) {
  69472. targetStore = "scenes";
  69473. }
  69474. else {
  69475. targetStore = "textures";
  69476. }
  69477. var file;
  69478. var transaction = this.db.transaction([targetStore]);
  69479. transaction.oncomplete = function (event) {
  69480. if (file) {
  69481. callback(file.data);
  69482. }
  69483. // file was not found in DB
  69484. else {
  69485. notInDBCallback();
  69486. }
  69487. };
  69488. transaction.onabort = function (event) {
  69489. notInDBCallback();
  69490. };
  69491. var getRequest = transaction.objectStore(targetStore).get(url);
  69492. getRequest.onsuccess = function (event) {
  69493. file = (event.target).result;
  69494. };
  69495. getRequest.onerror = function (event) {
  69496. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69497. notInDBCallback();
  69498. };
  69499. }
  69500. else {
  69501. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69502. callback();
  69503. }
  69504. };
  69505. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69506. var _this = this;
  69507. if (this.isSupported) {
  69508. var targetStore;
  69509. if (url.indexOf(".babylon") !== -1) {
  69510. targetStore = "scenes";
  69511. }
  69512. else {
  69513. targetStore = "textures";
  69514. }
  69515. // Create XHR
  69516. var xhr = new XMLHttpRequest();
  69517. var fileData;
  69518. xhr.open("GET", url, true);
  69519. if (useArrayBuffer) {
  69520. xhr.responseType = "arraybuffer";
  69521. }
  69522. if (progressCallback) {
  69523. xhr.onprogress = progressCallback;
  69524. }
  69525. xhr.addEventListener("load", function () {
  69526. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69527. // Blob as response (XHR2)
  69528. //fileData = xhr.responseText;
  69529. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69530. if (!_this.hasReachedQuota && _this.db) {
  69531. // Open a transaction to the database
  69532. var transaction = _this.db.transaction([targetStore], "readwrite");
  69533. // the transaction could abort because of a QuotaExceededError error
  69534. transaction.onabort = function (event) {
  69535. try {
  69536. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69537. var error = event.srcElement['error'];
  69538. if (error && error.name === "QuotaExceededError") {
  69539. _this.hasReachedQuota = true;
  69540. }
  69541. }
  69542. catch (ex) { }
  69543. callback(fileData);
  69544. };
  69545. transaction.oncomplete = function (event) {
  69546. callback(fileData);
  69547. };
  69548. var newFile;
  69549. if (targetStore === "scenes") {
  69550. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69551. }
  69552. else {
  69553. newFile = { textureUrl: url, data: fileData };
  69554. }
  69555. try {
  69556. // Put the scene into the database
  69557. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69558. addRequest.onsuccess = function (event) {
  69559. };
  69560. addRequest.onerror = function (event) {
  69561. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69562. };
  69563. }
  69564. catch (ex) {
  69565. callback(fileData);
  69566. }
  69567. }
  69568. else {
  69569. callback(fileData);
  69570. }
  69571. }
  69572. else {
  69573. callback();
  69574. }
  69575. }, false);
  69576. xhr.addEventListener("error", function (event) {
  69577. BABYLON.Tools.Error("error on XHR request.");
  69578. callback();
  69579. }, false);
  69580. xhr.send();
  69581. }
  69582. else {
  69583. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69584. callback();
  69585. }
  69586. };
  69587. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69588. Database.IsUASupportingBlobStorage = true;
  69589. /** Gets a boolean indicating if Database storate is enabled */
  69590. Database.IDBStorageEnabled = true;
  69591. Database._ParseURL = function (url) {
  69592. var a = document.createElement('a');
  69593. a.href = url;
  69594. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69595. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69596. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69597. return absLocation;
  69598. };
  69599. Database._ReturnFullUrlLocation = function (url) {
  69600. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69601. return (Database._ParseURL(window.location.href) + url);
  69602. }
  69603. else {
  69604. return url;
  69605. }
  69606. };
  69607. return Database;
  69608. }());
  69609. BABYLON.Database = Database;
  69610. })(BABYLON || (BABYLON = {}));
  69611. //# sourceMappingURL=babylon.database.js.map
  69612. var BABYLON;
  69613. (function (BABYLON) {
  69614. var FresnelParameters = /** @class */ (function () {
  69615. function FresnelParameters() {
  69616. this._isEnabled = true;
  69617. this.leftColor = BABYLON.Color3.White();
  69618. this.rightColor = BABYLON.Color3.Black();
  69619. this.bias = 0;
  69620. this.power = 1;
  69621. }
  69622. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69623. get: function () {
  69624. return this._isEnabled;
  69625. },
  69626. set: function (value) {
  69627. if (this._isEnabled === value) {
  69628. return;
  69629. }
  69630. this._isEnabled = value;
  69631. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69632. },
  69633. enumerable: true,
  69634. configurable: true
  69635. });
  69636. FresnelParameters.prototype.clone = function () {
  69637. var newFresnelParameters = new FresnelParameters();
  69638. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69639. return newFresnelParameters;
  69640. };
  69641. FresnelParameters.prototype.serialize = function () {
  69642. var serializationObject = {};
  69643. serializationObject.isEnabled = this.isEnabled;
  69644. serializationObject.leftColor = this.leftColor.asArray();
  69645. serializationObject.rightColor = this.rightColor.asArray();
  69646. serializationObject.bias = this.bias;
  69647. serializationObject.power = this.power;
  69648. return serializationObject;
  69649. };
  69650. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69651. var fresnelParameters = new FresnelParameters();
  69652. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69653. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69654. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69655. fresnelParameters.bias = parsedFresnelParameters.bias;
  69656. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69657. return fresnelParameters;
  69658. };
  69659. return FresnelParameters;
  69660. }());
  69661. BABYLON.FresnelParameters = FresnelParameters;
  69662. })(BABYLON || (BABYLON = {}));
  69663. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69664. var BABYLON;
  69665. (function (BABYLON) {
  69666. var MultiMaterial = /** @class */ (function (_super) {
  69667. __extends(MultiMaterial, _super);
  69668. function MultiMaterial(name, scene) {
  69669. var _this = _super.call(this, name, scene, true) || this;
  69670. scene.multiMaterials.push(_this);
  69671. _this.subMaterials = new Array();
  69672. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69673. return _this;
  69674. }
  69675. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69676. get: function () {
  69677. return this._subMaterials;
  69678. },
  69679. set: function (value) {
  69680. this._subMaterials = value;
  69681. this._hookArray(value);
  69682. },
  69683. enumerable: true,
  69684. configurable: true
  69685. });
  69686. MultiMaterial.prototype._hookArray = function (array) {
  69687. var _this = this;
  69688. var oldPush = array.push;
  69689. array.push = function () {
  69690. var items = [];
  69691. for (var _i = 0; _i < arguments.length; _i++) {
  69692. items[_i] = arguments[_i];
  69693. }
  69694. var result = oldPush.apply(array, items);
  69695. _this._markAllSubMeshesAsTexturesDirty();
  69696. return result;
  69697. };
  69698. var oldSplice = array.splice;
  69699. array.splice = function (index, deleteCount) {
  69700. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69701. _this._markAllSubMeshesAsTexturesDirty();
  69702. return deleted;
  69703. };
  69704. };
  69705. // Properties
  69706. MultiMaterial.prototype.getSubMaterial = function (index) {
  69707. if (index < 0 || index >= this.subMaterials.length) {
  69708. return this.getScene().defaultMaterial;
  69709. }
  69710. return this.subMaterials[index];
  69711. };
  69712. MultiMaterial.prototype.getActiveTextures = function () {
  69713. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69714. if (subMaterial) {
  69715. return subMaterial.getActiveTextures();
  69716. }
  69717. else {
  69718. return [];
  69719. }
  69720. }));
  69721. var _a;
  69722. };
  69723. // Methods
  69724. MultiMaterial.prototype.getClassName = function () {
  69725. return "MultiMaterial";
  69726. };
  69727. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69728. for (var index = 0; index < this.subMaterials.length; index++) {
  69729. var subMaterial = this.subMaterials[index];
  69730. if (subMaterial) {
  69731. if (subMaterial.storeEffectOnSubMeshes) {
  69732. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69733. return false;
  69734. }
  69735. continue;
  69736. }
  69737. if (!subMaterial.isReady(mesh)) {
  69738. return false;
  69739. }
  69740. }
  69741. }
  69742. return true;
  69743. };
  69744. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69745. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69746. for (var index = 0; index < this.subMaterials.length; index++) {
  69747. var subMaterial = null;
  69748. var current = this.subMaterials[index];
  69749. if (cloneChildren && current) {
  69750. subMaterial = current.clone(name + "-" + current.name);
  69751. }
  69752. else {
  69753. subMaterial = this.subMaterials[index];
  69754. }
  69755. newMultiMaterial.subMaterials.push(subMaterial);
  69756. }
  69757. return newMultiMaterial;
  69758. };
  69759. MultiMaterial.prototype.serialize = function () {
  69760. var serializationObject = {};
  69761. serializationObject.name = this.name;
  69762. serializationObject.id = this.id;
  69763. if (BABYLON.Tags) {
  69764. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69765. }
  69766. serializationObject.materials = [];
  69767. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69768. var subMat = this.subMaterials[matIndex];
  69769. if (subMat) {
  69770. serializationObject.materials.push(subMat.id);
  69771. }
  69772. else {
  69773. serializationObject.materials.push(null);
  69774. }
  69775. }
  69776. return serializationObject;
  69777. };
  69778. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69779. var scene = this.getScene();
  69780. if (!scene) {
  69781. return;
  69782. }
  69783. var index = scene.multiMaterials.indexOf(this);
  69784. if (index >= 0) {
  69785. scene.multiMaterials.splice(index, 1);
  69786. }
  69787. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69788. };
  69789. return MultiMaterial;
  69790. }(BABYLON.Material));
  69791. BABYLON.MultiMaterial = MultiMaterial;
  69792. })(BABYLON || (BABYLON = {}));
  69793. //# sourceMappingURL=babylon.multiMaterial.js.map
  69794. var BABYLON;
  69795. (function (BABYLON) {
  69796. var FreeCameraTouchInput = /** @class */ (function () {
  69797. function FreeCameraTouchInput() {
  69798. this._offsetX = null;
  69799. this._offsetY = null;
  69800. this._pointerPressed = new Array();
  69801. this.touchAngularSensibility = 200000.0;
  69802. this.touchMoveSensibility = 250.0;
  69803. }
  69804. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69805. var _this = this;
  69806. var previousPosition = null;
  69807. if (this._pointerInput === undefined) {
  69808. this._onLostFocus = function (evt) {
  69809. _this._offsetX = null;
  69810. _this._offsetY = null;
  69811. };
  69812. this._pointerInput = function (p, s) {
  69813. var evt = p.event;
  69814. if (evt.pointerType === "mouse") {
  69815. return;
  69816. }
  69817. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69818. if (!noPreventDefault) {
  69819. evt.preventDefault();
  69820. }
  69821. _this._pointerPressed.push(evt.pointerId);
  69822. if (_this._pointerPressed.length !== 1) {
  69823. return;
  69824. }
  69825. previousPosition = {
  69826. x: evt.clientX,
  69827. y: evt.clientY
  69828. };
  69829. }
  69830. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69831. if (!noPreventDefault) {
  69832. evt.preventDefault();
  69833. }
  69834. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69835. if (index === -1) {
  69836. return;
  69837. }
  69838. _this._pointerPressed.splice(index, 1);
  69839. if (index != 0) {
  69840. return;
  69841. }
  69842. previousPosition = null;
  69843. _this._offsetX = null;
  69844. _this._offsetY = null;
  69845. }
  69846. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69847. if (!noPreventDefault) {
  69848. evt.preventDefault();
  69849. }
  69850. if (!previousPosition) {
  69851. return;
  69852. }
  69853. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69854. if (index != 0) {
  69855. return;
  69856. }
  69857. _this._offsetX = evt.clientX - previousPosition.x;
  69858. _this._offsetY = -(evt.clientY - previousPosition.y);
  69859. }
  69860. };
  69861. }
  69862. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69863. if (this._onLostFocus) {
  69864. element.addEventListener("blur", this._onLostFocus);
  69865. }
  69866. };
  69867. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69868. if (this._pointerInput && element) {
  69869. if (this._observer) {
  69870. this.camera.getScene().onPointerObservable.remove(this._observer);
  69871. this._observer = null;
  69872. }
  69873. if (this._onLostFocus) {
  69874. element.removeEventListener("blur", this._onLostFocus);
  69875. this._onLostFocus = null;
  69876. }
  69877. this._pointerPressed = [];
  69878. this._offsetX = null;
  69879. this._offsetY = null;
  69880. }
  69881. };
  69882. FreeCameraTouchInput.prototype.checkInputs = function () {
  69883. if (this._offsetX && this._offsetY) {
  69884. var camera = this.camera;
  69885. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69886. if (this._pointerPressed.length > 1) {
  69887. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69888. }
  69889. else {
  69890. var speed = camera._computeLocalCameraSpeed();
  69891. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69892. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69893. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69894. }
  69895. }
  69896. };
  69897. FreeCameraTouchInput.prototype.getClassName = function () {
  69898. return "FreeCameraTouchInput";
  69899. };
  69900. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69901. return "touch";
  69902. };
  69903. __decorate([
  69904. BABYLON.serialize()
  69905. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69906. __decorate([
  69907. BABYLON.serialize()
  69908. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69909. return FreeCameraTouchInput;
  69910. }());
  69911. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69912. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69913. })(BABYLON || (BABYLON = {}));
  69914. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69915. var BABYLON;
  69916. (function (BABYLON) {
  69917. // We're mainly based on the logic defined into the FreeCamera code
  69918. var TouchCamera = /** @class */ (function (_super) {
  69919. __extends(TouchCamera, _super);
  69920. //-- end properties for backward compatibility for inputs
  69921. function TouchCamera(name, position, scene) {
  69922. var _this = _super.call(this, name, position, scene) || this;
  69923. _this.inputs.addTouch();
  69924. _this._setupInputs();
  69925. return _this;
  69926. }
  69927. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69928. //-- Begin properties for backward compatibility for inputs
  69929. get: function () {
  69930. var touch = this.inputs.attached["touch"];
  69931. if (touch)
  69932. return touch.touchAngularSensibility;
  69933. return 0;
  69934. },
  69935. set: function (value) {
  69936. var touch = this.inputs.attached["touch"];
  69937. if (touch)
  69938. touch.touchAngularSensibility = value;
  69939. },
  69940. enumerable: true,
  69941. configurable: true
  69942. });
  69943. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69944. get: function () {
  69945. var touch = this.inputs.attached["touch"];
  69946. if (touch)
  69947. return touch.touchMoveSensibility;
  69948. return 0;
  69949. },
  69950. set: function (value) {
  69951. var touch = this.inputs.attached["touch"];
  69952. if (touch)
  69953. touch.touchMoveSensibility = value;
  69954. },
  69955. enumerable: true,
  69956. configurable: true
  69957. });
  69958. TouchCamera.prototype.getClassName = function () {
  69959. return "TouchCamera";
  69960. };
  69961. TouchCamera.prototype._setupInputs = function () {
  69962. var mouse = this.inputs.attached["mouse"];
  69963. if (mouse) {
  69964. mouse.touchEnabled = false;
  69965. }
  69966. };
  69967. return TouchCamera;
  69968. }(BABYLON.FreeCamera));
  69969. BABYLON.TouchCamera = TouchCamera;
  69970. })(BABYLON || (BABYLON = {}));
  69971. //# sourceMappingURL=babylon.touchCamera.js.map
  69972. var BABYLON;
  69973. (function (BABYLON) {
  69974. var ProceduralTexture = /** @class */ (function (_super) {
  69975. __extends(ProceduralTexture, _super);
  69976. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69977. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69978. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69979. if (isCube === void 0) { isCube = false; }
  69980. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69981. _this.isCube = isCube;
  69982. _this.isEnabled = true;
  69983. _this._currentRefreshId = -1;
  69984. _this._refreshRate = 1;
  69985. _this._vertexBuffers = {};
  69986. _this._uniforms = new Array();
  69987. _this._samplers = new Array();
  69988. _this._textures = {};
  69989. _this._floats = {};
  69990. _this._floatsArrays = {};
  69991. _this._colors3 = {};
  69992. _this._colors4 = {};
  69993. _this._vectors2 = {};
  69994. _this._vectors3 = {};
  69995. _this._matrices = {};
  69996. _this._fallbackTextureUsed = false;
  69997. scene.proceduralTextures.push(_this);
  69998. _this._engine = scene.getEngine();
  69999. _this.name = name;
  70000. _this.isRenderTarget = true;
  70001. _this._size = size;
  70002. _this._generateMipMaps = generateMipMaps;
  70003. _this.setFragment(fragment);
  70004. _this._fallbackTexture = fallbackTexture;
  70005. if (isCube) {
  70006. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70007. _this.setFloat("face", 0);
  70008. }
  70009. else {
  70010. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70011. }
  70012. // VBO
  70013. var vertices = [];
  70014. vertices.push(1, 1);
  70015. vertices.push(-1, 1);
  70016. vertices.push(-1, -1);
  70017. vertices.push(1, -1);
  70018. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70019. _this._createIndexBuffer();
  70020. return _this;
  70021. }
  70022. ProceduralTexture.prototype._createIndexBuffer = function () {
  70023. var engine = this._engine;
  70024. // Indices
  70025. var indices = [];
  70026. indices.push(0);
  70027. indices.push(1);
  70028. indices.push(2);
  70029. indices.push(0);
  70030. indices.push(2);
  70031. indices.push(3);
  70032. this._indexBuffer = engine.createIndexBuffer(indices);
  70033. };
  70034. ProceduralTexture.prototype._rebuild = function () {
  70035. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70036. if (vb) {
  70037. vb._rebuild();
  70038. }
  70039. this._createIndexBuffer();
  70040. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70041. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70042. }
  70043. };
  70044. ProceduralTexture.prototype.reset = function () {
  70045. if (this._effect === undefined) {
  70046. return;
  70047. }
  70048. var engine = this._engine;
  70049. engine._releaseEffect(this._effect);
  70050. };
  70051. ProceduralTexture.prototype.isReady = function () {
  70052. var _this = this;
  70053. var engine = this._engine;
  70054. var shaders;
  70055. if (!this._fragment) {
  70056. return false;
  70057. }
  70058. if (this._fallbackTextureUsed) {
  70059. return true;
  70060. }
  70061. if (this._fragment.fragmentElement !== undefined) {
  70062. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70063. }
  70064. else {
  70065. shaders = { vertex: "procedural", fragment: this._fragment };
  70066. }
  70067. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70068. _this.releaseInternalTexture();
  70069. if (_this._fallbackTexture) {
  70070. _this._texture = _this._fallbackTexture._texture;
  70071. if (_this._texture) {
  70072. _this._texture.incrementReferences();
  70073. }
  70074. }
  70075. _this._fallbackTextureUsed = true;
  70076. });
  70077. return this._effect.isReady();
  70078. };
  70079. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70080. this._currentRefreshId = -1;
  70081. };
  70082. ProceduralTexture.prototype.setFragment = function (fragment) {
  70083. this._fragment = fragment;
  70084. };
  70085. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70086. get: function () {
  70087. return this._refreshRate;
  70088. },
  70089. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70090. set: function (value) {
  70091. this._refreshRate = value;
  70092. this.resetRefreshCounter();
  70093. },
  70094. enumerable: true,
  70095. configurable: true
  70096. });
  70097. ProceduralTexture.prototype._shouldRender = function () {
  70098. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70099. return false;
  70100. }
  70101. if (this._fallbackTextureUsed) {
  70102. return false;
  70103. }
  70104. if (this._currentRefreshId === -1) { // At least render once
  70105. this._currentRefreshId = 1;
  70106. return true;
  70107. }
  70108. if (this.refreshRate === this._currentRefreshId) {
  70109. this._currentRefreshId = 1;
  70110. return true;
  70111. }
  70112. this._currentRefreshId++;
  70113. return false;
  70114. };
  70115. ProceduralTexture.prototype.getRenderSize = function () {
  70116. return this._size;
  70117. };
  70118. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70119. if (this._fallbackTextureUsed) {
  70120. return;
  70121. }
  70122. this.releaseInternalTexture();
  70123. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70124. };
  70125. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70126. if (this._uniforms.indexOf(uniformName) === -1) {
  70127. this._uniforms.push(uniformName);
  70128. }
  70129. };
  70130. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70131. if (this._samplers.indexOf(name) === -1) {
  70132. this._samplers.push(name);
  70133. }
  70134. this._textures[name] = texture;
  70135. return this;
  70136. };
  70137. ProceduralTexture.prototype.setFloat = function (name, value) {
  70138. this._checkUniform(name);
  70139. this._floats[name] = value;
  70140. return this;
  70141. };
  70142. ProceduralTexture.prototype.setFloats = function (name, value) {
  70143. this._checkUniform(name);
  70144. this._floatsArrays[name] = value;
  70145. return this;
  70146. };
  70147. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70148. this._checkUniform(name);
  70149. this._colors3[name] = value;
  70150. return this;
  70151. };
  70152. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70153. this._checkUniform(name);
  70154. this._colors4[name] = value;
  70155. return this;
  70156. };
  70157. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70158. this._checkUniform(name);
  70159. this._vectors2[name] = value;
  70160. return this;
  70161. };
  70162. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70163. this._checkUniform(name);
  70164. this._vectors3[name] = value;
  70165. return this;
  70166. };
  70167. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70168. this._checkUniform(name);
  70169. this._matrices[name] = value;
  70170. return this;
  70171. };
  70172. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70173. var scene = this.getScene();
  70174. if (!scene) {
  70175. return;
  70176. }
  70177. var engine = this._engine;
  70178. // Render
  70179. engine.enableEffect(this._effect);
  70180. engine.setState(false);
  70181. // Texture
  70182. for (var name in this._textures) {
  70183. this._effect.setTexture(name, this._textures[name]);
  70184. }
  70185. // Float
  70186. for (name in this._floats) {
  70187. this._effect.setFloat(name, this._floats[name]);
  70188. }
  70189. // Floats
  70190. for (name in this._floatsArrays) {
  70191. this._effect.setArray(name, this._floatsArrays[name]);
  70192. }
  70193. // Color3
  70194. for (name in this._colors3) {
  70195. this._effect.setColor3(name, this._colors3[name]);
  70196. }
  70197. // Color4
  70198. for (name in this._colors4) {
  70199. var color = this._colors4[name];
  70200. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70201. }
  70202. // Vector2
  70203. for (name in this._vectors2) {
  70204. this._effect.setVector2(name, this._vectors2[name]);
  70205. }
  70206. // Vector3
  70207. for (name in this._vectors3) {
  70208. this._effect.setVector3(name, this._vectors3[name]);
  70209. }
  70210. // Matrix
  70211. for (name in this._matrices) {
  70212. this._effect.setMatrix(name, this._matrices[name]);
  70213. }
  70214. if (!this._texture) {
  70215. return;
  70216. }
  70217. if (this.isCube) {
  70218. for (var face = 0; face < 6; face++) {
  70219. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70220. // VBOs
  70221. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70222. this._effect.setFloat("face", face);
  70223. // Clear
  70224. engine.clear(scene.clearColor, true, true, true);
  70225. // Draw order
  70226. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70227. // Mipmaps
  70228. if (face === 5) {
  70229. engine.generateMipMapsForCubemap(this._texture);
  70230. }
  70231. }
  70232. }
  70233. else {
  70234. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70235. // VBOs
  70236. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70237. // Clear
  70238. engine.clear(scene.clearColor, true, true, true);
  70239. // Draw order
  70240. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70241. }
  70242. // Unbind
  70243. engine.unBindFramebuffer(this._texture, this.isCube);
  70244. if (this.onGenerated) {
  70245. this.onGenerated();
  70246. }
  70247. };
  70248. ProceduralTexture.prototype.clone = function () {
  70249. var textureSize = this.getSize();
  70250. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70251. // Base texture
  70252. newTexture.hasAlpha = this.hasAlpha;
  70253. newTexture.level = this.level;
  70254. // RenderTarget Texture
  70255. newTexture.coordinatesMode = this.coordinatesMode;
  70256. return newTexture;
  70257. };
  70258. ProceduralTexture.prototype.dispose = function () {
  70259. var scene = this.getScene();
  70260. if (!scene) {
  70261. return;
  70262. }
  70263. var index = scene.proceduralTextures.indexOf(this);
  70264. if (index >= 0) {
  70265. scene.proceduralTextures.splice(index, 1);
  70266. }
  70267. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70268. if (vertexBuffer) {
  70269. vertexBuffer.dispose();
  70270. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70271. }
  70272. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70273. this._indexBuffer = null;
  70274. }
  70275. _super.prototype.dispose.call(this);
  70276. };
  70277. return ProceduralTexture;
  70278. }(BABYLON.Texture));
  70279. BABYLON.ProceduralTexture = ProceduralTexture;
  70280. })(BABYLON || (BABYLON = {}));
  70281. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70282. var BABYLON;
  70283. (function (BABYLON) {
  70284. var CustomProceduralTexture = /** @class */ (function (_super) {
  70285. __extends(CustomProceduralTexture, _super);
  70286. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70287. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70288. _this._animate = true;
  70289. _this._time = 0;
  70290. _this._texturePath = texturePath;
  70291. //Try to load json
  70292. _this.loadJson(texturePath);
  70293. _this.refreshRate = 1;
  70294. return _this;
  70295. }
  70296. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70297. var _this = this;
  70298. var noConfigFile = function () {
  70299. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70300. try {
  70301. _this.setFragment(_this._texturePath);
  70302. }
  70303. catch (ex) {
  70304. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70305. }
  70306. };
  70307. var configFileUrl = jsonUrl + "/config.json";
  70308. var xhr = new XMLHttpRequest();
  70309. xhr.open("GET", configFileUrl, true);
  70310. xhr.addEventListener("load", function () {
  70311. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70312. try {
  70313. _this._config = JSON.parse(xhr.response);
  70314. _this.updateShaderUniforms();
  70315. _this.updateTextures();
  70316. _this.setFragment(_this._texturePath + "/custom");
  70317. _this._animate = _this._config.animate;
  70318. _this.refreshRate = _this._config.refreshrate;
  70319. }
  70320. catch (ex) {
  70321. noConfigFile();
  70322. }
  70323. }
  70324. else {
  70325. noConfigFile();
  70326. }
  70327. }, false);
  70328. xhr.addEventListener("error", function () {
  70329. noConfigFile();
  70330. }, false);
  70331. try {
  70332. xhr.send();
  70333. }
  70334. catch (ex) {
  70335. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70336. }
  70337. };
  70338. CustomProceduralTexture.prototype.isReady = function () {
  70339. if (!_super.prototype.isReady.call(this)) {
  70340. return false;
  70341. }
  70342. for (var name in this._textures) {
  70343. var texture = this._textures[name];
  70344. if (!texture.isReady()) {
  70345. return false;
  70346. }
  70347. }
  70348. return true;
  70349. };
  70350. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70351. var scene = this.getScene();
  70352. if (this._animate && scene) {
  70353. this._time += scene.getAnimationRatio() * 0.03;
  70354. this.updateShaderUniforms();
  70355. }
  70356. _super.prototype.render.call(this, useCameraPostProcess);
  70357. };
  70358. CustomProceduralTexture.prototype.updateTextures = function () {
  70359. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70360. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70361. }
  70362. };
  70363. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70364. if (this._config) {
  70365. for (var j = 0; j < this._config.uniforms.length; j++) {
  70366. var uniform = this._config.uniforms[j];
  70367. switch (uniform.type) {
  70368. case "float":
  70369. this.setFloat(uniform.name, uniform.value);
  70370. break;
  70371. case "color3":
  70372. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70373. break;
  70374. case "color4":
  70375. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70376. break;
  70377. case "vector2":
  70378. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70379. break;
  70380. case "vector3":
  70381. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70382. break;
  70383. }
  70384. }
  70385. }
  70386. this.setFloat("time", this._time);
  70387. };
  70388. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70389. get: function () {
  70390. return this._animate;
  70391. },
  70392. set: function (value) {
  70393. this._animate = value;
  70394. },
  70395. enumerable: true,
  70396. configurable: true
  70397. });
  70398. return CustomProceduralTexture;
  70399. }(BABYLON.ProceduralTexture));
  70400. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70401. })(BABYLON || (BABYLON = {}));
  70402. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70403. var BABYLON;
  70404. (function (BABYLON) {
  70405. var FreeCameraGamepadInput = /** @class */ (function () {
  70406. function FreeCameraGamepadInput() {
  70407. this.gamepadAngularSensibility = 200;
  70408. this.gamepadMoveSensibility = 40;
  70409. // private members
  70410. this._cameraTransform = BABYLON.Matrix.Identity();
  70411. this._deltaTransform = BABYLON.Vector3.Zero();
  70412. this._vector3 = BABYLON.Vector3.Zero();
  70413. this._vector2 = BABYLON.Vector2.Zero();
  70414. }
  70415. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70416. var _this = this;
  70417. var manager = this.camera.getScene().gamepadManager;
  70418. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70419. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70420. // prioritize XBOX gamepads.
  70421. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70422. _this.gamepad = gamepad;
  70423. }
  70424. }
  70425. });
  70426. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70427. if (_this.gamepad === gamepad) {
  70428. _this.gamepad = null;
  70429. }
  70430. });
  70431. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70432. };
  70433. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70434. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70435. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70436. this.gamepad = null;
  70437. };
  70438. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70439. if (this.gamepad && this.gamepad.leftStick) {
  70440. var camera = this.camera;
  70441. var LSValues = this.gamepad.leftStick;
  70442. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70443. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70444. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70445. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70446. var RSValues = this.gamepad.rightStick;
  70447. if (RSValues) {
  70448. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70449. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70450. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70451. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70452. }
  70453. else {
  70454. RSValues = { x: 0, y: 0 };
  70455. }
  70456. if (!camera.rotationQuaternion) {
  70457. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70458. }
  70459. else {
  70460. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70461. }
  70462. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70463. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70464. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70465. camera.cameraDirection.addInPlace(this._deltaTransform);
  70466. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70467. camera.cameraRotation.addInPlace(this._vector2);
  70468. }
  70469. };
  70470. FreeCameraGamepadInput.prototype.getClassName = function () {
  70471. return "FreeCameraGamepadInput";
  70472. };
  70473. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70474. return "gamepad";
  70475. };
  70476. __decorate([
  70477. BABYLON.serialize()
  70478. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70479. __decorate([
  70480. BABYLON.serialize()
  70481. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70482. return FreeCameraGamepadInput;
  70483. }());
  70484. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70485. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70486. })(BABYLON || (BABYLON = {}));
  70487. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70488. var BABYLON;
  70489. (function (BABYLON) {
  70490. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70491. function ArcRotateCameraGamepadInput() {
  70492. this.gamepadRotationSensibility = 80;
  70493. this.gamepadMoveSensibility = 40;
  70494. }
  70495. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70496. var _this = this;
  70497. var manager = this.camera.getScene().gamepadManager;
  70498. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70499. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70500. // prioritize XBOX gamepads.
  70501. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70502. _this.gamepad = gamepad;
  70503. }
  70504. }
  70505. });
  70506. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70507. if (_this.gamepad === gamepad) {
  70508. _this.gamepad = null;
  70509. }
  70510. });
  70511. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70512. };
  70513. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70514. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70515. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70516. this.gamepad = null;
  70517. };
  70518. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70519. if (this.gamepad) {
  70520. var camera = this.camera;
  70521. var RSValues = this.gamepad.rightStick;
  70522. if (RSValues) {
  70523. if (RSValues.x != 0) {
  70524. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70525. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70526. camera.inertialAlphaOffset += normalizedRX;
  70527. }
  70528. }
  70529. if (RSValues.y != 0) {
  70530. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70531. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70532. camera.inertialBetaOffset += normalizedRY;
  70533. }
  70534. }
  70535. }
  70536. var LSValues = this.gamepad.leftStick;
  70537. if (LSValues && LSValues.y != 0) {
  70538. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70539. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70540. this.camera.inertialRadiusOffset -= normalizedLY;
  70541. }
  70542. }
  70543. }
  70544. };
  70545. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70546. return "ArcRotateCameraGamepadInput";
  70547. };
  70548. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70549. return "gamepad";
  70550. };
  70551. __decorate([
  70552. BABYLON.serialize()
  70553. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70554. __decorate([
  70555. BABYLON.serialize()
  70556. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70557. return ArcRotateCameraGamepadInput;
  70558. }());
  70559. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70560. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70561. })(BABYLON || (BABYLON = {}));
  70562. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70563. var BABYLON;
  70564. (function (BABYLON) {
  70565. var GamepadManager = /** @class */ (function () {
  70566. function GamepadManager(_scene) {
  70567. var _this = this;
  70568. this._scene = _scene;
  70569. this._babylonGamepads = [];
  70570. this._oneGamepadConnected = false;
  70571. this._isMonitoring = false;
  70572. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70573. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70574. this._gamepadEventSupported = false;
  70575. }
  70576. else {
  70577. this._gamepadEventSupported = 'GamepadEvent' in window;
  70578. this._gamepadSupport = (navigator.getGamepads ||
  70579. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70580. }
  70581. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70582. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70583. for (var i in _this._babylonGamepads) {
  70584. var gamepad = _this._babylonGamepads[i];
  70585. if (gamepad && gamepad._isConnected) {
  70586. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70587. }
  70588. }
  70589. });
  70590. this._onGamepadConnectedEvent = function (evt) {
  70591. var gamepad = evt.gamepad;
  70592. if (gamepad.index in _this._babylonGamepads) {
  70593. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70594. return;
  70595. }
  70596. }
  70597. var newGamepad;
  70598. if (_this._babylonGamepads[gamepad.index]) {
  70599. newGamepad = _this._babylonGamepads[gamepad.index];
  70600. newGamepad.browserGamepad = gamepad;
  70601. newGamepad._isConnected = true;
  70602. }
  70603. else {
  70604. newGamepad = _this._addNewGamepad(gamepad);
  70605. }
  70606. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70607. _this._startMonitoringGamepads();
  70608. };
  70609. this._onGamepadDisconnectedEvent = function (evt) {
  70610. var gamepad = evt.gamepad;
  70611. // Remove the gamepad from the list of gamepads to monitor.
  70612. for (var i in _this._babylonGamepads) {
  70613. if (_this._babylonGamepads[i].index === gamepad.index) {
  70614. var disconnectedGamepad = _this._babylonGamepads[i];
  70615. disconnectedGamepad._isConnected = false;
  70616. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70617. break;
  70618. }
  70619. }
  70620. };
  70621. if (this._gamepadSupport) {
  70622. //first add already-connected gamepads
  70623. this._updateGamepadObjects();
  70624. if (this._babylonGamepads.length) {
  70625. this._startMonitoringGamepads();
  70626. }
  70627. // Checking if the gamepad connected event is supported (like in Firefox)
  70628. if (this._gamepadEventSupported) {
  70629. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70630. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70631. }
  70632. else {
  70633. this._startMonitoringGamepads();
  70634. }
  70635. }
  70636. }
  70637. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70638. get: function () {
  70639. return this._babylonGamepads;
  70640. },
  70641. enumerable: true,
  70642. configurable: true
  70643. });
  70644. GamepadManager.prototype.getGamepadByType = function (type) {
  70645. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70646. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70647. var gamepad = _a[_i];
  70648. if (gamepad && gamepad.type === type) {
  70649. return gamepad;
  70650. }
  70651. }
  70652. return null;
  70653. };
  70654. GamepadManager.prototype.dispose = function () {
  70655. if (this._gamepadEventSupported) {
  70656. if (this._onGamepadConnectedEvent) {
  70657. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70658. }
  70659. if (this._onGamepadDisconnectedEvent) {
  70660. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70661. }
  70662. this._onGamepadConnectedEvent = null;
  70663. this._onGamepadDisconnectedEvent = null;
  70664. }
  70665. this._babylonGamepads.forEach(function (gamepad) {
  70666. gamepad.dispose();
  70667. });
  70668. this.onGamepadConnectedObservable.clear();
  70669. this.onGamepadDisconnectedObservable.clear();
  70670. this._oneGamepadConnected = false;
  70671. this._stopMonitoringGamepads();
  70672. this._babylonGamepads = [];
  70673. };
  70674. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70675. if (!this._oneGamepadConnected) {
  70676. this._oneGamepadConnected = true;
  70677. }
  70678. var newGamepad;
  70679. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70680. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70681. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70682. }
  70683. // if pose is supported, use the (WebVR) pose enabled controller
  70684. else if (gamepad.pose) {
  70685. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70686. }
  70687. else {
  70688. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70689. }
  70690. this._babylonGamepads[newGamepad.index] = newGamepad;
  70691. return newGamepad;
  70692. };
  70693. GamepadManager.prototype._startMonitoringGamepads = function () {
  70694. if (!this._isMonitoring) {
  70695. this._isMonitoring = true;
  70696. //back-comp
  70697. if (!this._scene) {
  70698. this._checkGamepadsStatus();
  70699. }
  70700. }
  70701. };
  70702. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70703. this._isMonitoring = false;
  70704. };
  70705. GamepadManager.prototype._checkGamepadsStatus = function () {
  70706. var _this = this;
  70707. // Hack to be compatible Chrome
  70708. this._updateGamepadObjects();
  70709. for (var i in this._babylonGamepads) {
  70710. var gamepad = this._babylonGamepads[i];
  70711. if (!gamepad || !gamepad.isConnected) {
  70712. continue;
  70713. }
  70714. gamepad.update();
  70715. }
  70716. if (this._isMonitoring && !this._scene) {
  70717. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70718. }
  70719. };
  70720. // This function is called only on Chrome, which does not properly support
  70721. // connection/disconnection events and forces you to recopy again the gamepad object
  70722. GamepadManager.prototype._updateGamepadObjects = function () {
  70723. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70724. for (var i = 0; i < gamepads.length; i++) {
  70725. var gamepad = gamepads[i];
  70726. if (gamepad) {
  70727. if (!this._babylonGamepads[gamepad.index]) {
  70728. var newGamepad = this._addNewGamepad(gamepad);
  70729. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70730. }
  70731. else {
  70732. // Forced to copy again this object for Chrome for unknown reason
  70733. this._babylonGamepads[i].browserGamepad = gamepad;
  70734. if (!this._babylonGamepads[i].isConnected) {
  70735. this._babylonGamepads[i]._isConnected = true;
  70736. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70737. }
  70738. }
  70739. }
  70740. }
  70741. };
  70742. return GamepadManager;
  70743. }());
  70744. BABYLON.GamepadManager = GamepadManager;
  70745. })(BABYLON || (BABYLON = {}));
  70746. //# sourceMappingURL=babylon.gamepadManager.js.map
  70747. var BABYLON;
  70748. (function (BABYLON) {
  70749. var StickValues = /** @class */ (function () {
  70750. function StickValues(x, y) {
  70751. this.x = x;
  70752. this.y = y;
  70753. }
  70754. return StickValues;
  70755. }());
  70756. BABYLON.StickValues = StickValues;
  70757. var Gamepad = /** @class */ (function () {
  70758. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70759. if (leftStickX === void 0) { leftStickX = 0; }
  70760. if (leftStickY === void 0) { leftStickY = 1; }
  70761. if (rightStickX === void 0) { rightStickX = 2; }
  70762. if (rightStickY === void 0) { rightStickY = 3; }
  70763. this.id = id;
  70764. this.index = index;
  70765. this.browserGamepad = browserGamepad;
  70766. this._isConnected = true;
  70767. this._invertLeftStickY = false;
  70768. this.type = Gamepad.GAMEPAD;
  70769. this._leftStickAxisX = leftStickX;
  70770. this._leftStickAxisY = leftStickY;
  70771. this._rightStickAxisX = rightStickX;
  70772. this._rightStickAxisY = rightStickY;
  70773. if (this.browserGamepad.axes.length >= 2) {
  70774. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70775. }
  70776. if (this.browserGamepad.axes.length >= 4) {
  70777. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70778. }
  70779. }
  70780. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70781. get: function () {
  70782. return this._isConnected;
  70783. },
  70784. enumerable: true,
  70785. configurable: true
  70786. });
  70787. Gamepad.prototype.onleftstickchanged = function (callback) {
  70788. this._onleftstickchanged = callback;
  70789. };
  70790. Gamepad.prototype.onrightstickchanged = function (callback) {
  70791. this._onrightstickchanged = callback;
  70792. };
  70793. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70794. get: function () {
  70795. return this._leftStick;
  70796. },
  70797. set: function (newValues) {
  70798. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70799. this._onleftstickchanged(newValues);
  70800. }
  70801. this._leftStick = newValues;
  70802. },
  70803. enumerable: true,
  70804. configurable: true
  70805. });
  70806. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70807. get: function () {
  70808. return this._rightStick;
  70809. },
  70810. set: function (newValues) {
  70811. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70812. this._onrightstickchanged(newValues);
  70813. }
  70814. this._rightStick = newValues;
  70815. },
  70816. enumerable: true,
  70817. configurable: true
  70818. });
  70819. Gamepad.prototype.update = function () {
  70820. if (this._leftStick) {
  70821. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70822. if (this._invertLeftStickY) {
  70823. this.leftStick.y *= -1;
  70824. }
  70825. }
  70826. if (this._rightStick) {
  70827. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70828. }
  70829. };
  70830. Gamepad.prototype.dispose = function () {
  70831. };
  70832. Gamepad.GAMEPAD = 0;
  70833. Gamepad.GENERIC = 1;
  70834. Gamepad.XBOX = 2;
  70835. Gamepad.POSE_ENABLED = 3;
  70836. return Gamepad;
  70837. }());
  70838. BABYLON.Gamepad = Gamepad;
  70839. var GenericPad = /** @class */ (function (_super) {
  70840. __extends(GenericPad, _super);
  70841. function GenericPad(id, index, browserGamepad) {
  70842. var _this = _super.call(this, id, index, browserGamepad) || this;
  70843. _this.onButtonDownObservable = new BABYLON.Observable();
  70844. _this.onButtonUpObservable = new BABYLON.Observable();
  70845. _this.type = Gamepad.GENERIC;
  70846. _this._buttons = new Array(browserGamepad.buttons.length);
  70847. return _this;
  70848. }
  70849. GenericPad.prototype.onbuttondown = function (callback) {
  70850. this._onbuttondown = callback;
  70851. };
  70852. GenericPad.prototype.onbuttonup = function (callback) {
  70853. this._onbuttonup = callback;
  70854. };
  70855. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70856. if (newValue !== currentValue) {
  70857. if (newValue === 1) {
  70858. if (this._onbuttondown) {
  70859. this._onbuttondown(buttonIndex);
  70860. }
  70861. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70862. }
  70863. if (newValue === 0) {
  70864. if (this._onbuttonup) {
  70865. this._onbuttonup(buttonIndex);
  70866. }
  70867. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70868. }
  70869. }
  70870. return newValue;
  70871. };
  70872. GenericPad.prototype.update = function () {
  70873. _super.prototype.update.call(this);
  70874. for (var index = 0; index < this._buttons.length; index++) {
  70875. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70876. }
  70877. };
  70878. GenericPad.prototype.dispose = function () {
  70879. _super.prototype.dispose.call(this);
  70880. this.onButtonDownObservable.clear();
  70881. this.onButtonUpObservable.clear();
  70882. };
  70883. return GenericPad;
  70884. }(Gamepad));
  70885. BABYLON.GenericPad = GenericPad;
  70886. })(BABYLON || (BABYLON = {}));
  70887. //# sourceMappingURL=babylon.gamepad.js.map
  70888. var BABYLON;
  70889. (function (BABYLON) {
  70890. /**
  70891. * Defines supported buttons for XBox360 compatible gamepads
  70892. */
  70893. var Xbox360Button;
  70894. (function (Xbox360Button) {
  70895. /** A */
  70896. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70897. /** B */
  70898. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70899. /** X */
  70900. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70901. /** Y */
  70902. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70903. /** Start */
  70904. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70905. /** Back */
  70906. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70907. /** Left button */
  70908. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70909. /** Right button */
  70910. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70911. /** Left stick */
  70912. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70913. /** Right stick */
  70914. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70915. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70916. /** Defines values for XBox360 DPad */
  70917. var Xbox360Dpad;
  70918. (function (Xbox360Dpad) {
  70919. /** Up */
  70920. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70921. /** Down */
  70922. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70923. /** Left */
  70924. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70925. /** Right */
  70926. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70927. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70928. /**
  70929. * Defines a XBox360 gamepad
  70930. */
  70931. var Xbox360Pad = /** @class */ (function (_super) {
  70932. __extends(Xbox360Pad, _super);
  70933. /**
  70934. * Creates a new XBox360 gamepad object
  70935. * @param id defines the id of this gamepad
  70936. * @param index defines its index
  70937. * @param gamepad defines the internal HTML gamepad object
  70938. * @param xboxOne defines if it is a XBox One gamepad
  70939. */
  70940. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70941. if (xboxOne === void 0) { xboxOne = false; }
  70942. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70943. _this._leftTrigger = 0;
  70944. _this._rightTrigger = 0;
  70945. /** Observable raised when a button is pressed */
  70946. _this.onButtonDownObservable = new BABYLON.Observable();
  70947. /** Observable raised when a button is released */
  70948. _this.onButtonUpObservable = new BABYLON.Observable();
  70949. /** Observable raised when a pad is pressed */
  70950. _this.onPadDownObservable = new BABYLON.Observable();
  70951. /** Observable raised when a pad is released */
  70952. _this.onPadUpObservable = new BABYLON.Observable();
  70953. _this._buttonA = 0;
  70954. _this._buttonB = 0;
  70955. _this._buttonX = 0;
  70956. _this._buttonY = 0;
  70957. _this._buttonBack = 0;
  70958. _this._buttonStart = 0;
  70959. _this._buttonLB = 0;
  70960. _this._buttonRB = 0;
  70961. _this._buttonLeftStick = 0;
  70962. _this._buttonRightStick = 0;
  70963. _this._dPadUp = 0;
  70964. _this._dPadDown = 0;
  70965. _this._dPadLeft = 0;
  70966. _this._dPadRight = 0;
  70967. _this._isXboxOnePad = false;
  70968. _this.type = BABYLON.Gamepad.XBOX;
  70969. _this._isXboxOnePad = xboxOne;
  70970. return _this;
  70971. }
  70972. /**
  70973. * Defines the callback to call when left trigger is pressed
  70974. * @param callback defines the callback to use
  70975. */
  70976. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70977. this._onlefttriggerchanged = callback;
  70978. };
  70979. /**
  70980. * Defines the callback to call when right trigger is pressed
  70981. * @param callback defines the callback to use
  70982. */
  70983. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70984. this._onrighttriggerchanged = callback;
  70985. };
  70986. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70987. /**
  70988. * Gets or sets left trigger value
  70989. */
  70990. get: function () {
  70991. return this._leftTrigger;
  70992. },
  70993. set: function (newValue) {
  70994. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70995. this._onlefttriggerchanged(newValue);
  70996. }
  70997. this._leftTrigger = newValue;
  70998. },
  70999. enumerable: true,
  71000. configurable: true
  71001. });
  71002. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71003. /**
  71004. * Gets or sets right trigger value
  71005. */
  71006. get: function () {
  71007. return this._rightTrigger;
  71008. },
  71009. set: function (newValue) {
  71010. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71011. this._onrighttriggerchanged(newValue);
  71012. }
  71013. this._rightTrigger = newValue;
  71014. },
  71015. enumerable: true,
  71016. configurable: true
  71017. });
  71018. /**
  71019. * Defines the callback to call when a button is pressed
  71020. * @param callback defines the callback to use
  71021. */
  71022. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71023. this._onbuttondown = callback;
  71024. };
  71025. /**
  71026. * Defines the callback to call when a button is released
  71027. * @param callback defines the callback to use
  71028. */
  71029. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71030. this._onbuttonup = callback;
  71031. };
  71032. /**
  71033. * Defines the callback to call when a pad is pressed
  71034. * @param callback defines the callback to use
  71035. */
  71036. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71037. this._ondpaddown = callback;
  71038. };
  71039. /**
  71040. * Defines the callback to call when a pad is released
  71041. * @param callback defines the callback to use
  71042. */
  71043. Xbox360Pad.prototype.ondpadup = function (callback) {
  71044. this._ondpadup = callback;
  71045. };
  71046. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71047. if (newValue !== currentValue) {
  71048. if (newValue === 1) {
  71049. if (this._onbuttondown) {
  71050. this._onbuttondown(buttonType);
  71051. }
  71052. this.onButtonDownObservable.notifyObservers(buttonType);
  71053. }
  71054. if (newValue === 0) {
  71055. if (this._onbuttonup) {
  71056. this._onbuttonup(buttonType);
  71057. }
  71058. this.onButtonUpObservable.notifyObservers(buttonType);
  71059. }
  71060. }
  71061. return newValue;
  71062. };
  71063. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71064. if (newValue !== currentValue) {
  71065. if (newValue === 1) {
  71066. if (this._ondpaddown) {
  71067. this._ondpaddown(buttonType);
  71068. }
  71069. this.onPadDownObservable.notifyObservers(buttonType);
  71070. }
  71071. if (newValue === 0) {
  71072. if (this._ondpadup) {
  71073. this._ondpadup(buttonType);
  71074. }
  71075. this.onPadUpObservable.notifyObservers(buttonType);
  71076. }
  71077. }
  71078. return newValue;
  71079. };
  71080. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71081. /** Gets or sets value of A button */
  71082. get: function () {
  71083. return this._buttonA;
  71084. },
  71085. set: function (value) {
  71086. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71087. },
  71088. enumerable: true,
  71089. configurable: true
  71090. });
  71091. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71092. /** Gets or sets value of B button */
  71093. get: function () {
  71094. return this._buttonB;
  71095. },
  71096. set: function (value) {
  71097. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71098. },
  71099. enumerable: true,
  71100. configurable: true
  71101. });
  71102. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71103. /** Gets or sets value of X button */
  71104. get: function () {
  71105. return this._buttonX;
  71106. },
  71107. set: function (value) {
  71108. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71109. },
  71110. enumerable: true,
  71111. configurable: true
  71112. });
  71113. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71114. /** Gets or sets value of Y button */
  71115. get: function () {
  71116. return this._buttonY;
  71117. },
  71118. set: function (value) {
  71119. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71120. },
  71121. enumerable: true,
  71122. configurable: true
  71123. });
  71124. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71125. /** Gets or sets value of Start button */
  71126. get: function () {
  71127. return this._buttonStart;
  71128. },
  71129. set: function (value) {
  71130. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71131. },
  71132. enumerable: true,
  71133. configurable: true
  71134. });
  71135. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71136. /** Gets or sets value of Back button */
  71137. get: function () {
  71138. return this._buttonBack;
  71139. },
  71140. set: function (value) {
  71141. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71142. },
  71143. enumerable: true,
  71144. configurable: true
  71145. });
  71146. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71147. /** Gets or sets value of Left button */
  71148. get: function () {
  71149. return this._buttonLB;
  71150. },
  71151. set: function (value) {
  71152. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71153. },
  71154. enumerable: true,
  71155. configurable: true
  71156. });
  71157. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71158. /** Gets or sets value of Right button */
  71159. get: function () {
  71160. return this._buttonRB;
  71161. },
  71162. set: function (value) {
  71163. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71164. },
  71165. enumerable: true,
  71166. configurable: true
  71167. });
  71168. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71169. /** Gets or sets value of left stick */
  71170. get: function () {
  71171. return this._buttonLeftStick;
  71172. },
  71173. set: function (value) {
  71174. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71175. },
  71176. enumerable: true,
  71177. configurable: true
  71178. });
  71179. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71180. /** Gets or sets value of right stick */
  71181. get: function () {
  71182. return this._buttonRightStick;
  71183. },
  71184. set: function (value) {
  71185. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71186. },
  71187. enumerable: true,
  71188. configurable: true
  71189. });
  71190. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71191. /** Gets or sets value of DPad up */
  71192. get: function () {
  71193. return this._dPadUp;
  71194. },
  71195. set: function (value) {
  71196. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71197. },
  71198. enumerable: true,
  71199. configurable: true
  71200. });
  71201. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71202. /** Gets or sets value of DPad down */
  71203. get: function () {
  71204. return this._dPadDown;
  71205. },
  71206. set: function (value) {
  71207. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71208. },
  71209. enumerable: true,
  71210. configurable: true
  71211. });
  71212. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71213. /** Gets or sets value of DPad left */
  71214. get: function () {
  71215. return this._dPadLeft;
  71216. },
  71217. set: function (value) {
  71218. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71219. },
  71220. enumerable: true,
  71221. configurable: true
  71222. });
  71223. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71224. /** Gets or sets value of DPad right */
  71225. get: function () {
  71226. return this._dPadRight;
  71227. },
  71228. set: function (value) {
  71229. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71230. },
  71231. enumerable: true,
  71232. configurable: true
  71233. });
  71234. /**
  71235. * Force the gamepad to synchronize with device values
  71236. */
  71237. Xbox360Pad.prototype.update = function () {
  71238. _super.prototype.update.call(this);
  71239. if (this._isXboxOnePad) {
  71240. this.buttonA = this.browserGamepad.buttons[0].value;
  71241. this.buttonB = this.browserGamepad.buttons[1].value;
  71242. this.buttonX = this.browserGamepad.buttons[2].value;
  71243. this.buttonY = this.browserGamepad.buttons[3].value;
  71244. this.buttonLB = this.browserGamepad.buttons[4].value;
  71245. this.buttonRB = this.browserGamepad.buttons[5].value;
  71246. this.leftTrigger = this.browserGamepad.axes[2];
  71247. this.rightTrigger = this.browserGamepad.axes[5];
  71248. this.buttonBack = this.browserGamepad.buttons[9].value;
  71249. this.buttonStart = this.browserGamepad.buttons[8].value;
  71250. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71251. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71252. this.dPadUp = this.browserGamepad.buttons[11].value;
  71253. this.dPadDown = this.browserGamepad.buttons[12].value;
  71254. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71255. this.dPadRight = this.browserGamepad.buttons[14].value;
  71256. }
  71257. else {
  71258. this.buttonA = this.browserGamepad.buttons[0].value;
  71259. this.buttonB = this.browserGamepad.buttons[1].value;
  71260. this.buttonX = this.browserGamepad.buttons[2].value;
  71261. this.buttonY = this.browserGamepad.buttons[3].value;
  71262. this.buttonLB = this.browserGamepad.buttons[4].value;
  71263. this.buttonRB = this.browserGamepad.buttons[5].value;
  71264. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71265. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71266. this.buttonBack = this.browserGamepad.buttons[8].value;
  71267. this.buttonStart = this.browserGamepad.buttons[9].value;
  71268. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71269. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71270. this.dPadUp = this.browserGamepad.buttons[12].value;
  71271. this.dPadDown = this.browserGamepad.buttons[13].value;
  71272. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71273. this.dPadRight = this.browserGamepad.buttons[15].value;
  71274. }
  71275. };
  71276. Xbox360Pad.prototype.dispose = function () {
  71277. _super.prototype.dispose.call(this);
  71278. this.onButtonDownObservable.clear();
  71279. this.onButtonUpObservable.clear();
  71280. this.onPadDownObservable.clear();
  71281. this.onPadUpObservable.clear();
  71282. };
  71283. return Xbox360Pad;
  71284. }(BABYLON.Gamepad));
  71285. BABYLON.Xbox360Pad = Xbox360Pad;
  71286. })(BABYLON || (BABYLON = {}));
  71287. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71288. var BABYLON;
  71289. (function (BABYLON) {
  71290. /**
  71291. * Defines the types of pose enabled controllers that are supported
  71292. */
  71293. var PoseEnabledControllerType;
  71294. (function (PoseEnabledControllerType) {
  71295. /**
  71296. * HTC Vive
  71297. */
  71298. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71299. /**
  71300. * Oculus Rift
  71301. */
  71302. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71303. /**
  71304. * Windows mixed reality
  71305. */
  71306. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71307. /**
  71308. * Samsung gear VR
  71309. */
  71310. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71311. /**
  71312. * Google Daydream
  71313. */
  71314. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71315. /**
  71316. * Generic
  71317. */
  71318. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71319. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71320. /**
  71321. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71322. */
  71323. var PoseEnabledControllerHelper = /** @class */ (function () {
  71324. function PoseEnabledControllerHelper() {
  71325. }
  71326. /**
  71327. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71328. * @param vrGamepad the gamepad to initialized
  71329. * @returns a vr controller of the type the gamepad identified as
  71330. */
  71331. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71332. // Oculus Touch
  71333. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71334. return new BABYLON.OculusTouchController(vrGamepad);
  71335. }
  71336. // Windows Mixed Reality controllers
  71337. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71338. return new BABYLON.WindowsMotionController(vrGamepad);
  71339. }
  71340. // HTC Vive
  71341. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71342. return new BABYLON.ViveController(vrGamepad);
  71343. }
  71344. // Samsung/Oculus Gear VR or Oculus Go
  71345. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71346. return new BABYLON.GearVRController(vrGamepad);
  71347. }
  71348. // Google Daydream
  71349. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71350. return new BABYLON.DaydreamController(vrGamepad);
  71351. }
  71352. // Generic
  71353. else {
  71354. return new BABYLON.GenericController(vrGamepad);
  71355. }
  71356. };
  71357. return PoseEnabledControllerHelper;
  71358. }());
  71359. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71360. /**
  71361. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71362. */
  71363. var PoseEnabledController = /** @class */ (function (_super) {
  71364. __extends(PoseEnabledController, _super);
  71365. /**
  71366. * Creates a new PoseEnabledController from a gamepad
  71367. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71368. */
  71369. function PoseEnabledController(browserGamepad) {
  71370. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71371. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71372. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71373. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71374. /**
  71375. * The device position in babylon space
  71376. */
  71377. _this.devicePosition = BABYLON.Vector3.Zero();
  71378. /**
  71379. * The device rotation in babylon space
  71380. */
  71381. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71382. /**
  71383. * The scale factor of the device in babylon space
  71384. */
  71385. _this.deviceScaleFactor = 1;
  71386. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71387. /**
  71388. * Internal, matrix used to convert room space to babylon space
  71389. */
  71390. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71391. /**
  71392. * Node to be used when casting a ray from the controller
  71393. */
  71394. _this._pointingPoseNode = null;
  71395. _this._workingMatrix = BABYLON.Matrix.Identity();
  71396. /**
  71397. * @hidden
  71398. */
  71399. _this._meshAttachedObservable = new BABYLON.Observable();
  71400. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71401. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71402. _this.position = BABYLON.Vector3.Zero();
  71403. _this.rotationQuaternion = new BABYLON.Quaternion();
  71404. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71405. _this._calculatedRotation = new BABYLON.Quaternion();
  71406. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71407. return _this;
  71408. }
  71409. /**
  71410. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71411. */
  71412. PoseEnabledController.prototype.update = function () {
  71413. _super.prototype.update.call(this);
  71414. var pose = this.browserGamepad.pose;
  71415. this.updateFromDevice(pose);
  71416. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71417. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71418. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71419. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71420. if (this._mesh) {
  71421. this._mesh.position.copyFrom(this.devicePosition);
  71422. if (this._mesh.rotationQuaternion) {
  71423. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71424. }
  71425. }
  71426. };
  71427. /**
  71428. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71429. * @param poseData raw pose fromthe device
  71430. */
  71431. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71432. if (poseData) {
  71433. this.rawPose = poseData;
  71434. if (poseData.position) {
  71435. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71436. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71437. this._deviceRoomPosition.z *= -1;
  71438. }
  71439. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71440. this._calculatedPosition.addInPlace(this.position);
  71441. }
  71442. var pose = this.rawPose;
  71443. if (poseData.orientation && pose.orientation) {
  71444. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71445. if (this._mesh) {
  71446. if (this._mesh.getScene().useRightHandedSystem) {
  71447. this._deviceRoomRotationQuaternion.z *= -1;
  71448. this._deviceRoomRotationQuaternion.w *= -1;
  71449. }
  71450. else {
  71451. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71452. }
  71453. }
  71454. // if the camera is set, rotate to the camera's rotation
  71455. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71456. }
  71457. }
  71458. };
  71459. /**
  71460. * Attaches a mesh to the controller
  71461. * @param mesh the mesh to be attached
  71462. */
  71463. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71464. if (this._mesh) {
  71465. this._mesh.parent = null;
  71466. }
  71467. this._mesh = mesh;
  71468. if (this._poseControlledCamera) {
  71469. this._mesh.parent = this._poseControlledCamera;
  71470. }
  71471. if (!this._mesh.rotationQuaternion) {
  71472. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71473. }
  71474. this._meshAttachedObservable.notifyObservers(mesh);
  71475. };
  71476. /**
  71477. * Attaches the controllers mesh to a camera
  71478. * @param camera the camera the mesh should be attached to
  71479. */
  71480. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71481. this._poseControlledCamera = camera;
  71482. if (this._mesh) {
  71483. this._mesh.parent = this._poseControlledCamera;
  71484. }
  71485. };
  71486. /**
  71487. * Disposes of the controller
  71488. */
  71489. PoseEnabledController.prototype.dispose = function () {
  71490. if (this._mesh) {
  71491. this._mesh.dispose();
  71492. }
  71493. this._mesh = null;
  71494. _super.prototype.dispose.call(this);
  71495. };
  71496. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71497. /**
  71498. * The mesh that is attached to the controller
  71499. */
  71500. get: function () {
  71501. return this._mesh;
  71502. },
  71503. enumerable: true,
  71504. configurable: true
  71505. });
  71506. /**
  71507. * Gets the ray of the controller in the direction the controller is pointing
  71508. * @param length the length the resulting ray should be
  71509. * @returns a ray in the direction the controller is pointing
  71510. */
  71511. PoseEnabledController.prototype.getForwardRay = function (length) {
  71512. if (length === void 0) { length = 100; }
  71513. if (!this.mesh) {
  71514. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71515. }
  71516. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71517. var origin = m.getTranslation();
  71518. var forward = new BABYLON.Vector3(0, 0, -1);
  71519. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71520. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71521. return new BABYLON.Ray(origin, direction, length);
  71522. };
  71523. /**
  71524. * Name of the child mesh that can be used to cast a ray from the controller
  71525. */
  71526. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71527. return PoseEnabledController;
  71528. }(BABYLON.Gamepad));
  71529. BABYLON.PoseEnabledController = PoseEnabledController;
  71530. })(BABYLON || (BABYLON = {}));
  71531. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71532. var BABYLON;
  71533. (function (BABYLON) {
  71534. /**
  71535. * Defines the WebVRController object that represents controllers tracked in 3D space
  71536. */
  71537. var WebVRController = /** @class */ (function (_super) {
  71538. __extends(WebVRController, _super);
  71539. /**
  71540. * Creates a new WebVRController from a gamepad
  71541. * @param vrGamepad the gamepad that the WebVRController should be created from
  71542. */
  71543. function WebVRController(vrGamepad) {
  71544. var _this = _super.call(this, vrGamepad) || this;
  71545. // Observables
  71546. /**
  71547. * Fired when the trigger state has changed
  71548. */
  71549. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71550. /**
  71551. * Fired when the main button state has changed
  71552. */
  71553. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71554. /**
  71555. * Fired when the secondary button state has changed
  71556. */
  71557. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71558. /**
  71559. * Fired when the pad state has changed
  71560. */
  71561. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71562. /**
  71563. * Fired when controllers stick values have changed
  71564. */
  71565. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71566. /**
  71567. * X and Y axis corrisponding to the controllers joystick
  71568. */
  71569. _this.pad = { x: 0, y: 0 };
  71570. // avoid GC, store state in a tmp object
  71571. _this._changes = {
  71572. pressChanged: false,
  71573. touchChanged: false,
  71574. valueChanged: false,
  71575. changed: false
  71576. };
  71577. _this._buttons = new Array(vrGamepad.buttons.length);
  71578. _this.hand = vrGamepad.hand;
  71579. return _this;
  71580. }
  71581. /**
  71582. * Fired when a controller button's state has changed
  71583. * @param callback the callback containing the button that was modified
  71584. */
  71585. WebVRController.prototype.onButtonStateChange = function (callback) {
  71586. this._onButtonStateChange = callback;
  71587. };
  71588. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71589. /**
  71590. * The default controller model for the controller
  71591. */
  71592. get: function () {
  71593. return this._defaultModel;
  71594. },
  71595. enumerable: true,
  71596. configurable: true
  71597. });
  71598. /**
  71599. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71600. */
  71601. WebVRController.prototype.update = function () {
  71602. _super.prototype.update.call(this);
  71603. for (var index = 0; index < this._buttons.length; index++) {
  71604. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71605. }
  71606. ;
  71607. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71608. this.pad.x = this.leftStick.x;
  71609. this.pad.y = this.leftStick.y;
  71610. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71611. }
  71612. };
  71613. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71614. if (!newState) {
  71615. newState = {
  71616. pressed: false,
  71617. touched: false,
  71618. value: 0
  71619. };
  71620. }
  71621. if (!currentState) {
  71622. this._buttons[buttonIndex] = {
  71623. pressed: newState.pressed,
  71624. touched: newState.touched,
  71625. value: newState.value
  71626. };
  71627. return;
  71628. }
  71629. this._checkChanges(newState, currentState);
  71630. if (this._changes.changed) {
  71631. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71632. this._handleButtonChange(buttonIndex, newState, this._changes);
  71633. }
  71634. this._buttons[buttonIndex].pressed = newState.pressed;
  71635. this._buttons[buttonIndex].touched = newState.touched;
  71636. // oculus triggers are never 0, thou not touched.
  71637. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71638. };
  71639. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71640. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71641. this._changes.touchChanged = newState.touched !== currentState.touched;
  71642. this._changes.valueChanged = newState.value !== currentState.value;
  71643. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71644. return this._changes;
  71645. };
  71646. /**
  71647. * Disposes of th webVRCOntroller
  71648. */
  71649. WebVRController.prototype.dispose = function () {
  71650. _super.prototype.dispose.call(this);
  71651. this.onTriggerStateChangedObservable.clear();
  71652. this.onMainButtonStateChangedObservable.clear();
  71653. this.onSecondaryButtonStateChangedObservable.clear();
  71654. this.onPadStateChangedObservable.clear();
  71655. this.onPadValuesChangedObservable.clear();
  71656. };
  71657. return WebVRController;
  71658. }(BABYLON.PoseEnabledController));
  71659. BABYLON.WebVRController = WebVRController;
  71660. })(BABYLON || (BABYLON = {}));
  71661. //# sourceMappingURL=babylon.webVRController.js.map
  71662. var BABYLON;
  71663. (function (BABYLON) {
  71664. /**
  71665. * Oculus Touch Controller
  71666. */
  71667. var OculusTouchController = /** @class */ (function (_super) {
  71668. __extends(OculusTouchController, _super);
  71669. /**
  71670. * Creates a new OculusTouchController from a gamepad
  71671. * @param vrGamepad the gamepad that the controller should be created from
  71672. */
  71673. function OculusTouchController(vrGamepad) {
  71674. var _this = _super.call(this, vrGamepad) || this;
  71675. /**
  71676. * Fired when the secondary trigger on this controller is modified
  71677. */
  71678. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71679. /**
  71680. * Fired when the thumb rest on this controller is modified
  71681. */
  71682. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71683. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71684. return _this;
  71685. }
  71686. /**
  71687. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71688. * @param scene scene in which to add meshes
  71689. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71690. */
  71691. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71692. var _this = this;
  71693. var meshName;
  71694. // Hand
  71695. if (this.hand === 'left') {
  71696. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71697. }
  71698. else { // Right is the default if no hand is specified
  71699. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71700. }
  71701. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71702. /*
  71703. Parent Mesh name: oculus_touch_left
  71704. - body
  71705. - trigger
  71706. - thumbstick
  71707. - grip
  71708. - button_y
  71709. - button_x
  71710. - button_enter
  71711. */
  71712. _this._defaultModel = newMeshes[1];
  71713. _this.attachToMesh(_this._defaultModel);
  71714. if (meshLoaded) {
  71715. meshLoaded(_this._defaultModel);
  71716. }
  71717. });
  71718. };
  71719. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71720. /**
  71721. * Fired when the A button on this controller is modified
  71722. */
  71723. get: function () {
  71724. if (this.hand === 'right') {
  71725. return this.onMainButtonStateChangedObservable;
  71726. }
  71727. else {
  71728. throw new Error('No A button on left hand');
  71729. }
  71730. },
  71731. enumerable: true,
  71732. configurable: true
  71733. });
  71734. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71735. /**
  71736. * Fired when the B button on this controller is modified
  71737. */
  71738. get: function () {
  71739. if (this.hand === 'right') {
  71740. return this.onSecondaryButtonStateChangedObservable;
  71741. }
  71742. else {
  71743. throw new Error('No B button on left hand');
  71744. }
  71745. },
  71746. enumerable: true,
  71747. configurable: true
  71748. });
  71749. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71750. /**
  71751. * Fired when the X button on this controller is modified
  71752. */
  71753. get: function () {
  71754. if (this.hand === 'left') {
  71755. return this.onMainButtonStateChangedObservable;
  71756. }
  71757. else {
  71758. throw new Error('No X button on right hand');
  71759. }
  71760. },
  71761. enumerable: true,
  71762. configurable: true
  71763. });
  71764. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71765. /**
  71766. * Fired when the Y button on this controller is modified
  71767. */
  71768. get: function () {
  71769. if (this.hand === 'left') {
  71770. return this.onSecondaryButtonStateChangedObservable;
  71771. }
  71772. else {
  71773. throw new Error('No Y button on right hand');
  71774. }
  71775. },
  71776. enumerable: true,
  71777. configurable: true
  71778. });
  71779. /**
  71780. * Called once for each button that changed state since the last frame
  71781. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71782. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71783. * 2) secondary trigger (same)
  71784. * 3) A (right) X (left), touch, pressed = value
  71785. * 4) B / Y
  71786. * 5) thumb rest
  71787. * @param buttonIdx Which button index changed
  71788. * @param state New state of the button
  71789. * @param changes Which properties on the state changed since last frame
  71790. */
  71791. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71792. var notifyObject = state; //{ state: state, changes: changes };
  71793. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71794. switch (buttonIdx) {
  71795. case 0:
  71796. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71797. return;
  71798. case 1: // index trigger
  71799. if (this._defaultModel) {
  71800. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71801. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71802. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71803. }
  71804. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71805. return;
  71806. case 2: // secondary trigger
  71807. if (this._defaultModel) {
  71808. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71809. }
  71810. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71811. return;
  71812. case 3:
  71813. if (this._defaultModel) {
  71814. if (notifyObject.pressed) {
  71815. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71816. }
  71817. else {
  71818. (this._defaultModel.getChildren()[1]).position.y = 0;
  71819. }
  71820. }
  71821. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71822. return;
  71823. case 4:
  71824. if (this._defaultModel) {
  71825. if (notifyObject.pressed) {
  71826. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71827. }
  71828. else {
  71829. (this._defaultModel.getChildren()[2]).position.y = 0;
  71830. }
  71831. }
  71832. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71833. return;
  71834. case 5:
  71835. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71836. return;
  71837. }
  71838. };
  71839. /**
  71840. * Base Url for the controller model.
  71841. */
  71842. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71843. /**
  71844. * File name for the left controller model.
  71845. */
  71846. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71847. /**
  71848. * File name for the right controller model.
  71849. */
  71850. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71851. return OculusTouchController;
  71852. }(BABYLON.WebVRController));
  71853. BABYLON.OculusTouchController = OculusTouchController;
  71854. })(BABYLON || (BABYLON = {}));
  71855. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71856. var BABYLON;
  71857. (function (BABYLON) {
  71858. /**
  71859. * Vive Controller
  71860. */
  71861. var ViveController = /** @class */ (function (_super) {
  71862. __extends(ViveController, _super);
  71863. /**
  71864. * Creates a new ViveController from a gamepad
  71865. * @param vrGamepad the gamepad that the controller should be created from
  71866. */
  71867. function ViveController(vrGamepad) {
  71868. var _this = _super.call(this, vrGamepad) || this;
  71869. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71870. _this._invertLeftStickY = true;
  71871. return _this;
  71872. }
  71873. /**
  71874. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71875. * @param scene scene in which to add meshes
  71876. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71877. */
  71878. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71879. var _this = this;
  71880. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71881. /*
  71882. Parent Mesh name: ViveWand
  71883. - body
  71884. - r_gripper
  71885. - l_gripper
  71886. - menu_button
  71887. - system_button
  71888. - trackpad
  71889. - trigger
  71890. - LED
  71891. */
  71892. _this._defaultModel = newMeshes[1];
  71893. _this.attachToMesh(_this._defaultModel);
  71894. if (meshLoaded) {
  71895. meshLoaded(_this._defaultModel);
  71896. }
  71897. });
  71898. };
  71899. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71900. /**
  71901. * Fired when the left button on this controller is modified
  71902. */
  71903. get: function () {
  71904. return this.onMainButtonStateChangedObservable;
  71905. },
  71906. enumerable: true,
  71907. configurable: true
  71908. });
  71909. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71910. /**
  71911. * Fired when the right button on this controller is modified
  71912. */
  71913. get: function () {
  71914. return this.onMainButtonStateChangedObservable;
  71915. },
  71916. enumerable: true,
  71917. configurable: true
  71918. });
  71919. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71920. /**
  71921. * Fired when the menu button on this controller is modified
  71922. */
  71923. get: function () {
  71924. return this.onSecondaryButtonStateChangedObservable;
  71925. },
  71926. enumerable: true,
  71927. configurable: true
  71928. });
  71929. /**
  71930. * Called once for each button that changed state since the last frame
  71931. * Vive mapping:
  71932. * 0: touchpad
  71933. * 1: trigger
  71934. * 2: left AND right buttons
  71935. * 3: menu button
  71936. * @param buttonIdx Which button index changed
  71937. * @param state New state of the button
  71938. * @param changes Which properties on the state changed since last frame
  71939. */
  71940. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71941. var notifyObject = state; //{ state: state, changes: changes };
  71942. switch (buttonIdx) {
  71943. case 0:
  71944. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71945. return;
  71946. case 1: // index trigger
  71947. if (this._defaultModel) {
  71948. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71949. }
  71950. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71951. return;
  71952. case 2: // left AND right button
  71953. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71954. return;
  71955. case 3:
  71956. if (this._defaultModel) {
  71957. if (notifyObject.pressed) {
  71958. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71959. }
  71960. else {
  71961. (this._defaultModel.getChildren()[2]).position.y = 0;
  71962. }
  71963. }
  71964. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71965. return;
  71966. }
  71967. };
  71968. /**
  71969. * Base Url for the controller model.
  71970. */
  71971. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71972. /**
  71973. * File name for the controller model.
  71974. */
  71975. ViveController.MODEL_FILENAME = 'wand.babylon';
  71976. return ViveController;
  71977. }(BABYLON.WebVRController));
  71978. BABYLON.ViveController = ViveController;
  71979. })(BABYLON || (BABYLON = {}));
  71980. //# sourceMappingURL=babylon.viveController.js.map
  71981. var BABYLON;
  71982. (function (BABYLON) {
  71983. /**
  71984. * Generic Controller
  71985. */
  71986. var GenericController = /** @class */ (function (_super) {
  71987. __extends(GenericController, _super);
  71988. /**
  71989. * Creates a new GenericController from a gamepad
  71990. * @param vrGamepad the gamepad that the controller should be created from
  71991. */
  71992. function GenericController(vrGamepad) {
  71993. return _super.call(this, vrGamepad) || this;
  71994. }
  71995. /**
  71996. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71997. * @param scene scene in which to add meshes
  71998. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71999. */
  72000. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72001. var _this = this;
  72002. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72003. _this._defaultModel = newMeshes[1];
  72004. _this.attachToMesh(_this._defaultModel);
  72005. if (meshLoaded) {
  72006. meshLoaded(_this._defaultModel);
  72007. }
  72008. });
  72009. };
  72010. /**
  72011. * Called once for each button that changed state since the last frame
  72012. * @param buttonIdx Which button index changed
  72013. * @param state New state of the button
  72014. * @param changes Which properties on the state changed since last frame
  72015. */
  72016. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72017. console.log("Button id: " + buttonIdx + "state: ");
  72018. console.dir(state);
  72019. };
  72020. /**
  72021. * Base Url for the controller model.
  72022. */
  72023. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72024. /**
  72025. * File name for the controller model.
  72026. */
  72027. GenericController.MODEL_FILENAME = 'generic.babylon';
  72028. return GenericController;
  72029. }(BABYLON.WebVRController));
  72030. BABYLON.GenericController = GenericController;
  72031. })(BABYLON || (BABYLON = {}));
  72032. //# sourceMappingURL=babylon.genericController.js.map
  72033. var BABYLON;
  72034. (function (BABYLON) {
  72035. /**
  72036. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72037. */
  72038. var LoadedMeshInfo = /** @class */ (function () {
  72039. function LoadedMeshInfo() {
  72040. /**
  72041. * Map of the button meshes contained in the controller
  72042. */
  72043. this.buttonMeshes = {};
  72044. /**
  72045. * Map of the axis meshes contained in the controller
  72046. */
  72047. this.axisMeshes = {};
  72048. }
  72049. return LoadedMeshInfo;
  72050. }());
  72051. /**
  72052. * Defines the WindowsMotionController object that the state of the windows motion controller
  72053. */
  72054. var WindowsMotionController = /** @class */ (function (_super) {
  72055. __extends(WindowsMotionController, _super);
  72056. /**
  72057. * Creates a new WindowsMotionController from a gamepad
  72058. * @param vrGamepad the gamepad that the controller should be created from
  72059. */
  72060. function WindowsMotionController(vrGamepad) {
  72061. var _this = _super.call(this, vrGamepad) || this;
  72062. _this._mapping = {
  72063. // Semantic button names
  72064. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72065. // A mapping of the button name to glTF model node name
  72066. // that should be transformed by button value.
  72067. buttonMeshNames: {
  72068. 'trigger': 'SELECT',
  72069. 'menu': 'MENU',
  72070. 'grip': 'GRASP',
  72071. 'thumbstick': 'THUMBSTICK_PRESS',
  72072. 'trackpad': 'TOUCHPAD_PRESS'
  72073. },
  72074. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72075. buttonObservableNames: {
  72076. 'trigger': 'onTriggerStateChangedObservable',
  72077. 'menu': 'onSecondaryButtonStateChangedObservable',
  72078. 'grip': 'onMainButtonStateChangedObservable',
  72079. 'thumbstick': 'onPadStateChangedObservable',
  72080. 'trackpad': 'onTrackpadChangedObservable'
  72081. },
  72082. // A mapping of the axis name to glTF model node name
  72083. // that should be transformed by axis value.
  72084. // This array mirrors the browserGamepad.axes array, such that
  72085. // the mesh corresponding to axis 0 is in this array index 0.
  72086. axisMeshNames: [
  72087. 'THUMBSTICK_X',
  72088. 'THUMBSTICK_Y',
  72089. 'TOUCHPAD_TOUCH_X',
  72090. 'TOUCHPAD_TOUCH_Y'
  72091. ],
  72092. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72093. };
  72094. /**
  72095. * Fired when the trackpad on this controller is clicked
  72096. */
  72097. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72098. /**
  72099. * Fired when the trackpad on this controller is modified
  72100. */
  72101. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72102. /**
  72103. * The current x and y values of this controller's trackpad
  72104. */
  72105. _this.trackpad = { x: 0, y: 0 };
  72106. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72107. _this._loadedMeshInfo = null;
  72108. return _this;
  72109. }
  72110. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72111. /**
  72112. * Fired when the trigger on this controller is modified
  72113. */
  72114. get: function () {
  72115. return this.onTriggerStateChangedObservable;
  72116. },
  72117. enumerable: true,
  72118. configurable: true
  72119. });
  72120. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72121. /**
  72122. * Fired when the menu button on this controller is modified
  72123. */
  72124. get: function () {
  72125. return this.onSecondaryButtonStateChangedObservable;
  72126. },
  72127. enumerable: true,
  72128. configurable: true
  72129. });
  72130. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72131. /**
  72132. * Fired when the grip button on this controller is modified
  72133. */
  72134. get: function () {
  72135. return this.onMainButtonStateChangedObservable;
  72136. },
  72137. enumerable: true,
  72138. configurable: true
  72139. });
  72140. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72141. /**
  72142. * Fired when the thumbstick button on this controller is modified
  72143. */
  72144. get: function () {
  72145. return this.onPadStateChangedObservable;
  72146. },
  72147. enumerable: true,
  72148. configurable: true
  72149. });
  72150. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72151. /**
  72152. * Fired when the touchpad button on this controller is modified
  72153. */
  72154. get: function () {
  72155. return this.onTrackpadChangedObservable;
  72156. },
  72157. enumerable: true,
  72158. configurable: true
  72159. });
  72160. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72161. /**
  72162. * Fired when the touchpad values on this controller are modified
  72163. */
  72164. get: function () {
  72165. return this.onTrackpadValuesChangedObservable;
  72166. },
  72167. enumerable: true,
  72168. configurable: true
  72169. });
  72170. /**
  72171. * Called once per frame by the engine.
  72172. */
  72173. WindowsMotionController.prototype.update = function () {
  72174. _super.prototype.update.call(this);
  72175. if (this.browserGamepad.axes) {
  72176. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  72177. this.trackpad.x = this.browserGamepad["axes"][2];
  72178. this.trackpad.y = this.browserGamepad["axes"][3];
  72179. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72180. }
  72181. // Only need to animate axes if there is a loaded mesh
  72182. if (this._loadedMeshInfo) {
  72183. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72184. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72185. }
  72186. }
  72187. }
  72188. };
  72189. /**
  72190. * Called once for each button that changed state since the last frame
  72191. * @param buttonIdx Which button index changed
  72192. * @param state New state of the button
  72193. * @param changes Which properties on the state changed since last frame
  72194. */
  72195. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72196. var buttonName = this._mapping.buttons[buttonIdx];
  72197. if (!buttonName) {
  72198. return;
  72199. }
  72200. // Only emit events for buttons that we know how to map from index to name
  72201. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72202. if (observable) {
  72203. observable.notifyObservers(state);
  72204. }
  72205. this._lerpButtonTransform(buttonName, state.value);
  72206. };
  72207. /**
  72208. * Moves the buttons on the controller mesh based on their current state
  72209. * @param buttonName the name of the button to move
  72210. * @param buttonValue the value of the button which determines the buttons new position
  72211. */
  72212. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72213. // If there is no loaded mesh, there is nothing to transform.
  72214. if (!this._loadedMeshInfo) {
  72215. return;
  72216. }
  72217. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72218. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72219. return;
  72220. }
  72221. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72222. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72223. };
  72224. /**
  72225. * Moves the axis on the controller mesh based on its current state
  72226. * @param axis the index of the axis
  72227. * @param axisValue the value of the axis which determines the meshes new position
  72228. * @hidden
  72229. */
  72230. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72231. if (!this._loadedMeshInfo) {
  72232. return;
  72233. }
  72234. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72235. if (!meshInfo) {
  72236. return;
  72237. }
  72238. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72239. return;
  72240. }
  72241. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72242. var lerpValue = axisValue * 0.5 + 0.5;
  72243. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72244. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72245. };
  72246. /**
  72247. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72248. * @param scene scene in which to add meshes
  72249. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72250. */
  72251. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72252. var _this = this;
  72253. if (forceDefault === void 0) { forceDefault = false; }
  72254. var path;
  72255. var filename;
  72256. // Checking if GLB loader is present
  72257. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72258. // Determine the device specific folder based on the ID suffix
  72259. var device = 'default';
  72260. if (this.id && !forceDefault) {
  72261. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72262. device = ((match && match[0]) || device);
  72263. }
  72264. // Hand
  72265. if (this.hand === 'left') {
  72266. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72267. }
  72268. else { // Right is the default if no hand is specified
  72269. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72270. }
  72271. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72272. }
  72273. else {
  72274. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72275. path = BABYLON.GenericController.MODEL_BASE_URL;
  72276. filename = BABYLON.GenericController.MODEL_FILENAME;
  72277. }
  72278. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72279. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72280. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72281. if (!_this._loadedMeshInfo) {
  72282. return;
  72283. }
  72284. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72285. _this.attachToMesh(_this._defaultModel);
  72286. if (meshLoaded) {
  72287. meshLoaded(_this._defaultModel);
  72288. }
  72289. }, null, function (scene, message) {
  72290. BABYLON.Tools.Log(message);
  72291. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72292. if (!forceDefault) {
  72293. _this.initControllerMesh(scene, meshLoaded, true);
  72294. }
  72295. });
  72296. };
  72297. /**
  72298. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72299. * can be transformed by button presses and axes values, based on this._mapping.
  72300. *
  72301. * @param scene scene in which the meshes exist
  72302. * @param meshes list of meshes that make up the controller model to process
  72303. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72304. */
  72305. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72306. var loadedMeshInfo = null;
  72307. // Create a new mesh to contain the glTF hierarchy
  72308. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72309. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72310. var childMesh = null;
  72311. for (var i = 0; i < meshes.length; i++) {
  72312. var mesh = meshes[i];
  72313. if (!mesh.parent) {
  72314. // Exclude controller meshes from picking results
  72315. mesh.isPickable = false;
  72316. // Handle root node, attach to the new parentMesh
  72317. childMesh = mesh;
  72318. break;
  72319. }
  72320. }
  72321. if (childMesh) {
  72322. childMesh.setParent(parentMesh);
  72323. // Create our mesh info. Note that this method will always return non-null.
  72324. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72325. }
  72326. else {
  72327. BABYLON.Tools.Warn('Could not find root node in model file.');
  72328. }
  72329. return loadedMeshInfo;
  72330. };
  72331. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72332. var loadedMeshInfo = new LoadedMeshInfo();
  72333. var i;
  72334. loadedMeshInfo.rootNode = rootNode;
  72335. // Reset the caches
  72336. loadedMeshInfo.buttonMeshes = {};
  72337. loadedMeshInfo.axisMeshes = {};
  72338. // Button Meshes
  72339. for (i = 0; i < this._mapping.buttons.length; i++) {
  72340. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72341. if (!buttonMeshName) {
  72342. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72343. continue;
  72344. }
  72345. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72346. if (!buttonMesh) {
  72347. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72348. continue;
  72349. }
  72350. var buttonMeshInfo = {
  72351. index: i,
  72352. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72353. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72354. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72355. };
  72356. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72357. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72358. }
  72359. else {
  72360. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72361. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72362. '(VALUE: ' + !!buttonMeshInfo.value +
  72363. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72364. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72365. ')');
  72366. }
  72367. }
  72368. // Axis Meshes
  72369. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72370. var axisMeshName = this._mapping.axisMeshNames[i];
  72371. if (!axisMeshName) {
  72372. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72373. continue;
  72374. }
  72375. var axisMesh = getChildByName(rootNode, axisMeshName);
  72376. if (!axisMesh) {
  72377. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72378. continue;
  72379. }
  72380. var axisMeshInfo = {
  72381. index: i,
  72382. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72383. min: getImmediateChildByName(axisMesh, 'MIN'),
  72384. max: getImmediateChildByName(axisMesh, 'MAX')
  72385. };
  72386. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72387. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72388. }
  72389. else {
  72390. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72391. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72392. '(VALUE: ' + !!axisMeshInfo.value +
  72393. ', MIN: ' + !!axisMeshInfo.min +
  72394. ', MAX:' + !!axisMeshInfo.max +
  72395. ')');
  72396. }
  72397. }
  72398. // Pointing Ray
  72399. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72400. if (!loadedMeshInfo.pointingPoseNode) {
  72401. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72402. }
  72403. return loadedMeshInfo;
  72404. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72405. function getChildByName(node, name) {
  72406. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72407. }
  72408. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72409. function getImmediateChildByName(node, name) {
  72410. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72411. }
  72412. };
  72413. /**
  72414. * Gets the ray of the controller in the direction the controller is pointing
  72415. * @param length the length the resulting ray should be
  72416. * @returns a ray in the direction the controller is pointing
  72417. */
  72418. WindowsMotionController.prototype.getForwardRay = function (length) {
  72419. if (length === void 0) { length = 100; }
  72420. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72421. return _super.prototype.getForwardRay.call(this, length);
  72422. }
  72423. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72424. var origin = m.getTranslation();
  72425. var forward = new BABYLON.Vector3(0, 0, -1);
  72426. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72427. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72428. return new BABYLON.Ray(origin, direction, length);
  72429. };
  72430. /**
  72431. * Disposes of the controller
  72432. */
  72433. WindowsMotionController.prototype.dispose = function () {
  72434. _super.prototype.dispose.call(this);
  72435. this.onTrackpadChangedObservable.clear();
  72436. };
  72437. /**
  72438. * The base url used to load the left and right controller models
  72439. */
  72440. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72441. /**
  72442. * The name of the left controller model file
  72443. */
  72444. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72445. /**
  72446. * The name of the right controller model file
  72447. */
  72448. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72449. /**
  72450. * The controller name prefix for this controller type
  72451. */
  72452. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72453. /**
  72454. * The controller id pattern for this controller type
  72455. */
  72456. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72457. return WindowsMotionController;
  72458. }(BABYLON.WebVRController));
  72459. BABYLON.WindowsMotionController = WindowsMotionController;
  72460. })(BABYLON || (BABYLON = {}));
  72461. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72462. var BABYLON;
  72463. (function (BABYLON) {
  72464. /**
  72465. * Gear VR Controller
  72466. */
  72467. var GearVRController = /** @class */ (function (_super) {
  72468. __extends(GearVRController, _super);
  72469. /**
  72470. * Creates a new GearVRController from a gamepad
  72471. * @param vrGamepad the gamepad that the controller should be created from
  72472. */
  72473. function GearVRController(vrGamepad) {
  72474. var _this = _super.call(this, vrGamepad) || this;
  72475. _this._buttonIndexToObservableNameMap = [
  72476. 'onTrackpadChangedObservable',
  72477. 'onTriggerStateChangedObservable' // Trigger
  72478. ];
  72479. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72480. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72481. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72482. return _this;
  72483. }
  72484. /**
  72485. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72486. * @param scene scene in which to add meshes
  72487. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72488. */
  72489. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72490. var _this = this;
  72491. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72492. _this._defaultModel = newMeshes[1];
  72493. _this.attachToMesh(_this._defaultModel);
  72494. if (meshLoaded) {
  72495. meshLoaded(_this._defaultModel);
  72496. }
  72497. });
  72498. };
  72499. /**
  72500. * Called once for each button that changed state since the last frame
  72501. * @param buttonIdx Which button index changed
  72502. * @param state New state of the button
  72503. * @param changes Which properties on the state changed since last frame
  72504. */
  72505. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72506. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72507. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72508. // Only emit events for buttons that we know how to map from index to observable
  72509. var observable = this[observableName];
  72510. if (observable) {
  72511. observable.notifyObservers(state);
  72512. }
  72513. }
  72514. };
  72515. /**
  72516. * Base Url for the controller model.
  72517. */
  72518. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72519. /**
  72520. * File name for the controller model.
  72521. */
  72522. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72523. /**
  72524. * Gamepad Id prefix used to identify this controller.
  72525. */
  72526. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72527. return GearVRController;
  72528. }(BABYLON.WebVRController));
  72529. BABYLON.GearVRController = GearVRController;
  72530. })(BABYLON || (BABYLON = {}));
  72531. //# sourceMappingURL=babylon.gearVRController.js.map
  72532. var BABYLON;
  72533. (function (BABYLON) {
  72534. /**
  72535. * Google Daydream controller
  72536. */
  72537. var DaydreamController = /** @class */ (function (_super) {
  72538. __extends(DaydreamController, _super);
  72539. /**
  72540. * Creates a new DaydreamController from a gamepad
  72541. * @param vrGamepad the gamepad that the controller should be created from
  72542. */
  72543. function DaydreamController(vrGamepad) {
  72544. var _this = _super.call(this, vrGamepad) || this;
  72545. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72546. return _this;
  72547. }
  72548. /**
  72549. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72550. * @param scene scene in which to add meshes
  72551. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72552. */
  72553. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72554. var _this = this;
  72555. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72556. _this._defaultModel = newMeshes[1];
  72557. _this.attachToMesh(_this._defaultModel);
  72558. if (meshLoaded) {
  72559. meshLoaded(_this._defaultModel);
  72560. }
  72561. });
  72562. };
  72563. /**
  72564. * Called once for each button that changed state since the last frame
  72565. * @param buttonIdx Which button index changed
  72566. * @param state New state of the button
  72567. * @param changes Which properties on the state changed since last frame
  72568. */
  72569. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72570. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72571. if (buttonIdx === 0) {
  72572. var observable = this.onTriggerStateChangedObservable;
  72573. if (observable) {
  72574. observable.notifyObservers(state);
  72575. }
  72576. }
  72577. else {
  72578. // If the app or home buttons are ever made available
  72579. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72580. }
  72581. };
  72582. /**
  72583. * Base Url for the controller model.
  72584. */
  72585. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72586. /**
  72587. * File name for the controller model.
  72588. */
  72589. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72590. /**
  72591. * Gamepad Id prefix used to identify Daydream Controller.
  72592. */
  72593. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72594. return DaydreamController;
  72595. }(BABYLON.WebVRController));
  72596. BABYLON.DaydreamController = DaydreamController;
  72597. })(BABYLON || (BABYLON = {}));
  72598. //# sourceMappingURL=babylon.daydreamController.js.map
  72599. var BABYLON;
  72600. (function (BABYLON) {
  72601. var FollowCamera = /** @class */ (function (_super) {
  72602. __extends(FollowCamera, _super);
  72603. function FollowCamera(name, position, scene, lockedTarget) {
  72604. if (lockedTarget === void 0) { lockedTarget = null; }
  72605. var _this = _super.call(this, name, position, scene) || this;
  72606. _this.radius = 12;
  72607. _this.rotationOffset = 0;
  72608. _this.heightOffset = 4;
  72609. _this.cameraAcceleration = 0.05;
  72610. _this.maxCameraSpeed = 20;
  72611. _this.lockedTarget = lockedTarget;
  72612. return _this;
  72613. }
  72614. FollowCamera.prototype.getRadians = function (degrees) {
  72615. return degrees * Math.PI / 180;
  72616. };
  72617. FollowCamera.prototype.follow = function (cameraTarget) {
  72618. if (!cameraTarget)
  72619. return;
  72620. var yRotation;
  72621. if (cameraTarget.rotationQuaternion) {
  72622. var rotMatrix = new BABYLON.Matrix();
  72623. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72624. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72625. }
  72626. else {
  72627. yRotation = cameraTarget.rotation.y;
  72628. }
  72629. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72630. var targetPosition = cameraTarget.getAbsolutePosition();
  72631. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72632. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72633. var dx = targetX - this.position.x;
  72634. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72635. var dz = (targetZ) - this.position.z;
  72636. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72637. var vy = dy * this.cameraAcceleration;
  72638. var vz = dz * this.cameraAcceleration * 2;
  72639. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72640. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72641. }
  72642. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72643. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72644. }
  72645. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72646. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72647. }
  72648. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72649. this.setTarget(targetPosition);
  72650. };
  72651. FollowCamera.prototype._checkInputs = function () {
  72652. _super.prototype._checkInputs.call(this);
  72653. if (this.lockedTarget) {
  72654. this.follow(this.lockedTarget);
  72655. }
  72656. };
  72657. FollowCamera.prototype.getClassName = function () {
  72658. return "FollowCamera";
  72659. };
  72660. __decorate([
  72661. BABYLON.serialize()
  72662. ], FollowCamera.prototype, "radius", void 0);
  72663. __decorate([
  72664. BABYLON.serialize()
  72665. ], FollowCamera.prototype, "rotationOffset", void 0);
  72666. __decorate([
  72667. BABYLON.serialize()
  72668. ], FollowCamera.prototype, "heightOffset", void 0);
  72669. __decorate([
  72670. BABYLON.serialize()
  72671. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72672. __decorate([
  72673. BABYLON.serialize()
  72674. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72675. __decorate([
  72676. BABYLON.serializeAsMeshReference("lockedTargetId")
  72677. ], FollowCamera.prototype, "lockedTarget", void 0);
  72678. return FollowCamera;
  72679. }(BABYLON.TargetCamera));
  72680. BABYLON.FollowCamera = FollowCamera;
  72681. var ArcFollowCamera = /** @class */ (function (_super) {
  72682. __extends(ArcFollowCamera, _super);
  72683. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72684. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72685. _this.alpha = alpha;
  72686. _this.beta = beta;
  72687. _this.radius = radius;
  72688. _this.target = target;
  72689. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72690. _this.follow();
  72691. return _this;
  72692. }
  72693. ArcFollowCamera.prototype.follow = function () {
  72694. if (!this.target) {
  72695. return;
  72696. }
  72697. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72698. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72699. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72700. var targetPosition = this.target.getAbsolutePosition();
  72701. this.position = targetPosition.add(this._cartesianCoordinates);
  72702. this.setTarget(targetPosition);
  72703. };
  72704. ArcFollowCamera.prototype._checkInputs = function () {
  72705. _super.prototype._checkInputs.call(this);
  72706. this.follow();
  72707. };
  72708. ArcFollowCamera.prototype.getClassName = function () {
  72709. return "ArcFollowCamera";
  72710. };
  72711. return ArcFollowCamera;
  72712. }(BABYLON.TargetCamera));
  72713. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72714. })(BABYLON || (BABYLON = {}));
  72715. //# sourceMappingURL=babylon.followCamera.js.map
  72716. var BABYLON;
  72717. (function (BABYLON) {
  72718. // We're mainly based on the logic defined into the FreeCamera code
  72719. var UniversalCamera = /** @class */ (function (_super) {
  72720. __extends(UniversalCamera, _super);
  72721. //-- end properties for backward compatibility for inputs
  72722. function UniversalCamera(name, position, scene) {
  72723. var _this = _super.call(this, name, position, scene) || this;
  72724. _this.inputs.addGamepad();
  72725. return _this;
  72726. }
  72727. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72728. //-- Begin properties for backward compatibility for inputs
  72729. get: function () {
  72730. var gamepad = this.inputs.attached["gamepad"];
  72731. if (gamepad)
  72732. return gamepad.gamepadAngularSensibility;
  72733. return 0;
  72734. },
  72735. set: function (value) {
  72736. var gamepad = this.inputs.attached["gamepad"];
  72737. if (gamepad)
  72738. gamepad.gamepadAngularSensibility = value;
  72739. },
  72740. enumerable: true,
  72741. configurable: true
  72742. });
  72743. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72744. get: function () {
  72745. var gamepad = this.inputs.attached["gamepad"];
  72746. if (gamepad)
  72747. return gamepad.gamepadMoveSensibility;
  72748. return 0;
  72749. },
  72750. set: function (value) {
  72751. var gamepad = this.inputs.attached["gamepad"];
  72752. if (gamepad)
  72753. gamepad.gamepadMoveSensibility = value;
  72754. },
  72755. enumerable: true,
  72756. configurable: true
  72757. });
  72758. UniversalCamera.prototype.getClassName = function () {
  72759. return "UniversalCamera";
  72760. };
  72761. return UniversalCamera;
  72762. }(BABYLON.TouchCamera));
  72763. BABYLON.UniversalCamera = UniversalCamera;
  72764. })(BABYLON || (BABYLON = {}));
  72765. //# sourceMappingURL=babylon.universalCamera.js.map
  72766. var BABYLON;
  72767. (function (BABYLON) {
  72768. // We're mainly based on the logic defined into the FreeCamera code
  72769. var GamepadCamera = /** @class */ (function (_super) {
  72770. __extends(GamepadCamera, _super);
  72771. //-- end properties for backward compatibility for inputs
  72772. function GamepadCamera(name, position, scene) {
  72773. return _super.call(this, name, position, scene) || this;
  72774. }
  72775. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72776. //-- Begin properties for backward compatibility for inputs
  72777. get: function () {
  72778. var gamepad = this.inputs.attached["gamepad"];
  72779. if (gamepad)
  72780. return gamepad.gamepadAngularSensibility;
  72781. return 0;
  72782. },
  72783. set: function (value) {
  72784. var gamepad = this.inputs.attached["gamepad"];
  72785. if (gamepad)
  72786. gamepad.gamepadAngularSensibility = value;
  72787. },
  72788. enumerable: true,
  72789. configurable: true
  72790. });
  72791. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72792. get: function () {
  72793. var gamepad = this.inputs.attached["gamepad"];
  72794. if (gamepad)
  72795. return gamepad.gamepadMoveSensibility;
  72796. return 0;
  72797. },
  72798. set: function (value) {
  72799. var gamepad = this.inputs.attached["gamepad"];
  72800. if (gamepad)
  72801. gamepad.gamepadMoveSensibility = value;
  72802. },
  72803. enumerable: true,
  72804. configurable: true
  72805. });
  72806. GamepadCamera.prototype.getClassName = function () {
  72807. return "GamepadCamera";
  72808. };
  72809. return GamepadCamera;
  72810. }(BABYLON.UniversalCamera));
  72811. BABYLON.GamepadCamera = GamepadCamera;
  72812. })(BABYLON || (BABYLON = {}));
  72813. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72814. var BABYLON;
  72815. (function (BABYLON) {
  72816. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72817. function PostProcessRenderPipelineManager() {
  72818. this._renderPipelines = {};
  72819. }
  72820. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72821. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72822. };
  72823. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72824. if (unique === void 0) { unique = false; }
  72825. var renderPipeline = this._renderPipelines[renderPipelineName];
  72826. if (!renderPipeline) {
  72827. return;
  72828. }
  72829. renderPipeline._attachCameras(cameras, unique);
  72830. };
  72831. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72832. var renderPipeline = this._renderPipelines[renderPipelineName];
  72833. if (!renderPipeline) {
  72834. return;
  72835. }
  72836. renderPipeline._detachCameras(cameras);
  72837. };
  72838. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72839. var renderPipeline = this._renderPipelines[renderPipelineName];
  72840. if (!renderPipeline) {
  72841. return;
  72842. }
  72843. renderPipeline._enableEffect(renderEffectName, cameras);
  72844. };
  72845. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72846. var renderPipeline = this._renderPipelines[renderPipelineName];
  72847. if (!renderPipeline) {
  72848. return;
  72849. }
  72850. renderPipeline._disableEffect(renderEffectName, cameras);
  72851. };
  72852. PostProcessRenderPipelineManager.prototype.update = function () {
  72853. for (var renderPipelineName in this._renderPipelines) {
  72854. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72855. var pipeline = this._renderPipelines[renderPipelineName];
  72856. if (!pipeline.isSupported) {
  72857. pipeline.dispose();
  72858. delete this._renderPipelines[renderPipelineName];
  72859. }
  72860. else {
  72861. pipeline._update();
  72862. }
  72863. }
  72864. }
  72865. };
  72866. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72867. for (var renderPipelineName in this._renderPipelines) {
  72868. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72869. var pipeline = this._renderPipelines[renderPipelineName];
  72870. pipeline._rebuild();
  72871. }
  72872. }
  72873. };
  72874. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72875. for (var renderPipelineName in this._renderPipelines) {
  72876. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72877. var pipeline = this._renderPipelines[renderPipelineName];
  72878. pipeline.dispose();
  72879. }
  72880. }
  72881. };
  72882. return PostProcessRenderPipelineManager;
  72883. }());
  72884. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72885. })(BABYLON || (BABYLON = {}));
  72886. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72887. var BABYLON;
  72888. (function (BABYLON) {
  72889. /**
  72890. * This represents a set of one or more post processes in Babylon.
  72891. * A post process can be used to apply a shader to a texture after it is rendered.
  72892. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72893. */
  72894. var PostProcessRenderEffect = /** @class */ (function () {
  72895. /**
  72896. * Instantiates a post process render effect.
  72897. * A post process can be used to apply a shader to a texture after it is rendered.
  72898. * @param engine The engine the effect is tied to
  72899. * @param name The name of the effect
  72900. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72901. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72902. */
  72903. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72904. this._name = name;
  72905. this._singleInstance = singleInstance || true;
  72906. this._getPostProcesses = getPostProcesses;
  72907. this._cameras = {};
  72908. this._indicesForCamera = {};
  72909. this._postProcesses = {};
  72910. }
  72911. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72912. /**
  72913. * Checks if all the post processes in the effect are supported.
  72914. */
  72915. get: function () {
  72916. for (var index in this._postProcesses) {
  72917. if (this._postProcesses.hasOwnProperty(index)) {
  72918. var pps = this._postProcesses[index];
  72919. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72920. if (!pps[ppIndex].isSupported) {
  72921. return false;
  72922. }
  72923. }
  72924. }
  72925. }
  72926. return true;
  72927. },
  72928. enumerable: true,
  72929. configurable: true
  72930. });
  72931. /**
  72932. * Updates the current state of the effect
  72933. */
  72934. PostProcessRenderEffect.prototype._update = function () {
  72935. };
  72936. /**
  72937. * Attaches the effect on cameras
  72938. * @param cameras The camera to attach to.
  72939. */
  72940. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72941. var _this = this;
  72942. var cameraKey;
  72943. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72944. if (!cams) {
  72945. return;
  72946. }
  72947. for (var i = 0; i < cams.length; i++) {
  72948. var camera = cams[i];
  72949. var cameraName = camera.name;
  72950. if (this._singleInstance) {
  72951. cameraKey = 0;
  72952. }
  72953. else {
  72954. cameraKey = cameraName;
  72955. }
  72956. if (!this._postProcesses[cameraKey]) {
  72957. var postProcess = this._getPostProcesses();
  72958. if (postProcess) {
  72959. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72960. }
  72961. }
  72962. if (!this._indicesForCamera[cameraName]) {
  72963. this._indicesForCamera[cameraName] = [];
  72964. }
  72965. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72966. var index = camera.attachPostProcess(postProcess);
  72967. _this._indicesForCamera[cameraName].push(index);
  72968. });
  72969. if (!this._cameras[cameraName]) {
  72970. this._cameras[cameraName] = camera;
  72971. }
  72972. }
  72973. };
  72974. /**
  72975. * Detatches the effect on cameras
  72976. * @param cameras The camera to detatch from.
  72977. */
  72978. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72979. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72980. if (!cams) {
  72981. return;
  72982. }
  72983. for (var i = 0; i < cams.length; i++) {
  72984. var camera = cams[i];
  72985. var cameraName = camera.name;
  72986. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72987. camera.detachPostProcess(postProcess);
  72988. });
  72989. if (this._cameras[cameraName]) {
  72990. //this._indicesForCamera.splice(index, 1);
  72991. this._cameras[cameraName] = null;
  72992. }
  72993. }
  72994. };
  72995. /**
  72996. * Enables the effect on given cameras
  72997. * @param cameras The camera to enable.
  72998. */
  72999. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73000. var _this = this;
  73001. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73002. if (!cams) {
  73003. return;
  73004. }
  73005. for (var i = 0; i < cams.length; i++) {
  73006. var camera = cams[i];
  73007. var cameraName = camera.name;
  73008. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73009. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73010. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73011. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73012. });
  73013. }
  73014. }
  73015. }
  73016. };
  73017. /**
  73018. * Disables the effect on the given cameras
  73019. * @param cameras The camera to disable.
  73020. */
  73021. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73022. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73023. if (!cams) {
  73024. return;
  73025. }
  73026. for (var i = 0; i < cams.length; i++) {
  73027. var camera = cams[i];
  73028. var cameraName = camera.name;
  73029. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73030. camera.detachPostProcess(postProcess);
  73031. });
  73032. }
  73033. };
  73034. /**
  73035. * Gets a list of the post processes contained in the effect.
  73036. * @param camera The camera to get the post processes on.
  73037. * @returns The list of the post processes in the effect.
  73038. */
  73039. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73040. if (this._singleInstance) {
  73041. return this._postProcesses[0];
  73042. }
  73043. else {
  73044. if (!camera) {
  73045. return null;
  73046. }
  73047. return this._postProcesses[camera.name];
  73048. }
  73049. };
  73050. return PostProcessRenderEffect;
  73051. }());
  73052. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73053. })(BABYLON || (BABYLON = {}));
  73054. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73055. var BABYLON;
  73056. (function (BABYLON) {
  73057. var PostProcessRenderPipeline = /** @class */ (function () {
  73058. function PostProcessRenderPipeline(engine, name) {
  73059. this.engine = engine;
  73060. this._name = name;
  73061. this._renderEffects = {};
  73062. this._renderEffectsForIsolatedPass = new Array();
  73063. this._cameras = [];
  73064. }
  73065. PostProcessRenderPipeline.prototype.getClassName = function () {
  73066. return "PostProcessRenderPipeline";
  73067. };
  73068. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73069. get: function () {
  73070. for (var renderEffectName in this._renderEffects) {
  73071. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73072. if (!this._renderEffects[renderEffectName].isSupported) {
  73073. return false;
  73074. }
  73075. }
  73076. }
  73077. return true;
  73078. },
  73079. enumerable: true,
  73080. configurable: true
  73081. });
  73082. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73083. this._renderEffects[renderEffect._name] = renderEffect;
  73084. };
  73085. // private
  73086. PostProcessRenderPipeline.prototype._rebuild = function () {
  73087. };
  73088. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73089. var renderEffects = this._renderEffects[renderEffectName];
  73090. if (!renderEffects) {
  73091. return;
  73092. }
  73093. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73094. };
  73095. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73096. var renderEffects = this._renderEffects[renderEffectName];
  73097. if (!renderEffects) {
  73098. return;
  73099. }
  73100. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73101. };
  73102. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73103. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73104. if (!cams) {
  73105. return;
  73106. }
  73107. var indicesToDelete = [];
  73108. var i;
  73109. for (i = 0; i < cams.length; i++) {
  73110. var camera = cams[i];
  73111. var cameraName = camera.name;
  73112. if (this._cameras.indexOf(camera) === -1) {
  73113. this._cameras[cameraName] = camera;
  73114. }
  73115. else if (unique) {
  73116. indicesToDelete.push(i);
  73117. }
  73118. }
  73119. for (i = 0; i < indicesToDelete.length; i++) {
  73120. cameras.splice(indicesToDelete[i], 1);
  73121. }
  73122. for (var renderEffectName in this._renderEffects) {
  73123. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73124. this._renderEffects[renderEffectName]._attachCameras(cams);
  73125. }
  73126. }
  73127. };
  73128. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73129. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73130. if (!cams) {
  73131. return;
  73132. }
  73133. for (var renderEffectName in this._renderEffects) {
  73134. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73135. this._renderEffects[renderEffectName]._detachCameras(cams);
  73136. }
  73137. }
  73138. for (var i = 0; i < cams.length; i++) {
  73139. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73140. }
  73141. };
  73142. PostProcessRenderPipeline.prototype._update = function () {
  73143. for (var renderEffectName in this._renderEffects) {
  73144. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73145. this._renderEffects[renderEffectName]._update();
  73146. }
  73147. }
  73148. for (var i = 0; i < this._cameras.length; i++) {
  73149. var cameraName = this._cameras[i].name;
  73150. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73151. this._renderEffectsForIsolatedPass[cameraName]._update();
  73152. }
  73153. }
  73154. };
  73155. PostProcessRenderPipeline.prototype._reset = function () {
  73156. this._renderEffects = {};
  73157. this._renderEffectsForIsolatedPass = new Array();
  73158. };
  73159. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73160. // 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)
  73161. var effectKeys = Object.keys(this._renderEffects);
  73162. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73163. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73164. if (postProcesses) {
  73165. postProcesses[0].samples = sampleCount;
  73166. return true;
  73167. }
  73168. }
  73169. return false;
  73170. };
  73171. PostProcessRenderPipeline.prototype.dispose = function () {
  73172. // Must be implemented by children
  73173. };
  73174. __decorate([
  73175. BABYLON.serialize()
  73176. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73177. return PostProcessRenderPipeline;
  73178. }());
  73179. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73180. })(BABYLON || (BABYLON = {}));
  73181. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73182. var BABYLON;
  73183. (function (BABYLON) {
  73184. /**
  73185. * This represents a depth renderer in Babylon.
  73186. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73187. */
  73188. var DepthRenderer = /** @class */ (function () {
  73189. /**
  73190. * Instantiates a depth renderer
  73191. * @param scene The scene the renderer belongs to
  73192. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73193. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73194. */
  73195. function DepthRenderer(scene, type, camera) {
  73196. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73197. if (camera === void 0) { camera = null; }
  73198. var _this = this;
  73199. this._scene = scene;
  73200. this._camera = camera;
  73201. var engine = scene.getEngine();
  73202. // Render target
  73203. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73204. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73205. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73206. this._depthMap.refreshRate = 1;
  73207. this._depthMap.renderParticles = false;
  73208. this._depthMap.renderList = null;
  73209. // Camera to get depth map from to support multiple concurrent cameras
  73210. this._depthMap.activeCamera = this._camera;
  73211. this._depthMap.ignoreCameraViewport = true;
  73212. this._depthMap.useCameraPostProcesses = false;
  73213. // set default depth value to 1.0 (far away)
  73214. this._depthMap.onClearObservable.add(function (engine) {
  73215. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73216. });
  73217. // Custom render function
  73218. var renderSubMesh = function (subMesh) {
  73219. var mesh = subMesh.getRenderingMesh();
  73220. var scene = _this._scene;
  73221. var engine = scene.getEngine();
  73222. var material = subMesh.getMaterial();
  73223. if (!material) {
  73224. return;
  73225. }
  73226. // Culling and reverse (right handed system)
  73227. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73228. // Managing instances
  73229. var batch = mesh._getInstancesRenderList(subMesh._id);
  73230. if (batch.mustReturn) {
  73231. return;
  73232. }
  73233. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73234. var camera = _this._camera || scene.activeCamera;
  73235. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73236. engine.enableEffect(_this._effect);
  73237. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73238. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73239. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73240. // Alpha test
  73241. if (material && material.needAlphaTesting()) {
  73242. var alphaTexture = material.getAlphaTestTexture();
  73243. if (alphaTexture) {
  73244. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73245. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73246. }
  73247. }
  73248. // Bones
  73249. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73250. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73251. }
  73252. // Draw
  73253. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73254. }
  73255. };
  73256. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73257. var index;
  73258. if (depthOnlySubMeshes.length) {
  73259. engine.setColorWrite(false);
  73260. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73261. renderSubMesh(depthOnlySubMeshes.data[index]);
  73262. }
  73263. engine.setColorWrite(true);
  73264. }
  73265. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73266. renderSubMesh(opaqueSubMeshes.data[index]);
  73267. }
  73268. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73269. renderSubMesh(alphaTestSubMeshes.data[index]);
  73270. }
  73271. };
  73272. }
  73273. /**
  73274. * Creates the depth rendering effect and checks if the effect is ready.
  73275. * @param subMesh The submesh to be used to render the depth map of
  73276. * @param useInstances If multiple world instances should be used
  73277. * @returns if the depth renderer is ready to render the depth map
  73278. */
  73279. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73280. var material = subMesh.getMaterial();
  73281. if (material.disableDepthWrite) {
  73282. return false;
  73283. }
  73284. var defines = [];
  73285. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73286. var mesh = subMesh.getMesh();
  73287. // Alpha test
  73288. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73289. defines.push("#define ALPHATEST");
  73290. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73291. attribs.push(BABYLON.VertexBuffer.UVKind);
  73292. defines.push("#define UV1");
  73293. }
  73294. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73295. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73296. defines.push("#define UV2");
  73297. }
  73298. }
  73299. // Bones
  73300. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73301. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73302. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73303. if (mesh.numBoneInfluencers > 4) {
  73304. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73305. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73306. }
  73307. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73308. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73309. }
  73310. else {
  73311. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73312. }
  73313. // Instances
  73314. if (useInstances) {
  73315. defines.push("#define INSTANCES");
  73316. attribs.push("world0");
  73317. attribs.push("world1");
  73318. attribs.push("world2");
  73319. attribs.push("world3");
  73320. }
  73321. // Get correct effect
  73322. var join = defines.join("\n");
  73323. if (this._cachedDefines !== join) {
  73324. this._cachedDefines = join;
  73325. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73326. }
  73327. return this._effect.isReady();
  73328. };
  73329. /**
  73330. * Gets the texture which the depth map will be written to.
  73331. * @returns The depth map texture
  73332. */
  73333. DepthRenderer.prototype.getDepthMap = function () {
  73334. return this._depthMap;
  73335. };
  73336. /**
  73337. * Disposes of the depth renderer.
  73338. */
  73339. DepthRenderer.prototype.dispose = function () {
  73340. this._depthMap.dispose();
  73341. };
  73342. return DepthRenderer;
  73343. }());
  73344. BABYLON.DepthRenderer = DepthRenderer;
  73345. })(BABYLON || (BABYLON = {}));
  73346. //# sourceMappingURL=babylon.depthRenderer.js.map
  73347. var BABYLON;
  73348. (function (BABYLON) {
  73349. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73350. __extends(SSAORenderingPipeline, _super);
  73351. /**
  73352. * @constructor
  73353. * @param {string} name - The rendering pipeline name
  73354. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73355. * @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 }
  73356. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73357. */
  73358. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73359. var _this = _super.call(this, scene.getEngine(), name) || this;
  73360. // Members
  73361. /**
  73362. * The PassPostProcess id in the pipeline that contains the original scene color
  73363. */
  73364. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73365. /**
  73366. * The SSAO PostProcess id in the pipeline
  73367. */
  73368. _this.SSAORenderEffect = "SSAORenderEffect";
  73369. /**
  73370. * The horizontal blur PostProcess id in the pipeline
  73371. */
  73372. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73373. /**
  73374. * The vertical blur PostProcess id in the pipeline
  73375. */
  73376. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73377. /**
  73378. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73379. */
  73380. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73381. /**
  73382. * The output strength of the SSAO post-process. Default value is 1.0.
  73383. */
  73384. _this.totalStrength = 1.0;
  73385. /**
  73386. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73387. */
  73388. _this.radius = 0.0001;
  73389. /**
  73390. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73391. * Must not be equal to fallOff and superior to fallOff.
  73392. * Default value is 0.975
  73393. */
  73394. _this.area = 0.0075;
  73395. /**
  73396. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73397. * Must not be equal to area and inferior to area.
  73398. * Default value is 0.0
  73399. */
  73400. _this.fallOff = 0.000001;
  73401. /**
  73402. * The base color of the SSAO post-process
  73403. * The final result is "base + ssao" between [0, 1]
  73404. */
  73405. _this.base = 0.5;
  73406. _this._firstUpdate = true;
  73407. _this._scene = scene;
  73408. // Set up assets
  73409. _this._createRandomTexture();
  73410. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73411. var ssaoRatio = ratio.ssaoRatio || ratio;
  73412. var combineRatio = ratio.combineRatio || ratio;
  73413. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73414. _this._createSSAOPostProcess(ssaoRatio);
  73415. _this._createBlurPostProcess(ssaoRatio);
  73416. _this._createSSAOCombinePostProcess(combineRatio);
  73417. // Set up pipeline
  73418. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73419. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73420. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73421. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73422. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73423. // Finish
  73424. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73425. if (cameras)
  73426. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73427. return _this;
  73428. }
  73429. // Public Methods
  73430. /**
  73431. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73432. */
  73433. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73434. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73435. for (var i = 0; i < this._scene.cameras.length; i++) {
  73436. var camera = this._scene.cameras[i];
  73437. this._originalColorPostProcess.dispose(camera);
  73438. this._ssaoPostProcess.dispose(camera);
  73439. this._blurHPostProcess.dispose(camera);
  73440. this._blurVPostProcess.dispose(camera);
  73441. this._ssaoCombinePostProcess.dispose(camera);
  73442. }
  73443. this._randomTexture.dispose();
  73444. if (disableDepthRender)
  73445. this._scene.disableDepthRenderer();
  73446. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73447. _super.prototype.dispose.call(this);
  73448. };
  73449. // Private Methods
  73450. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73451. var _this = this;
  73452. var size = 16;
  73453. 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);
  73454. 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);
  73455. this._blurHPostProcess.onActivateObservable.add(function () {
  73456. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73457. _this._blurHPostProcess.kernel = size * dw;
  73458. });
  73459. this._blurVPostProcess.onActivateObservable.add(function () {
  73460. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73461. _this._blurVPostProcess.kernel = size * dw;
  73462. });
  73463. };
  73464. SSAORenderingPipeline.prototype._rebuild = function () {
  73465. this._firstUpdate = true;
  73466. _super.prototype._rebuild.call(this);
  73467. };
  73468. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73469. var _this = this;
  73470. var numSamples = 16;
  73471. var sampleSphere = [
  73472. 0.5381, 0.1856, -0.4319,
  73473. 0.1379, 0.2486, 0.4430,
  73474. 0.3371, 0.5679, -0.0057,
  73475. -0.6999, -0.0451, -0.0019,
  73476. 0.0689, -0.1598, -0.8547,
  73477. 0.0560, 0.0069, -0.1843,
  73478. -0.0146, 0.1402, 0.0762,
  73479. 0.0100, -0.1924, -0.0344,
  73480. -0.3577, -0.5301, -0.4358,
  73481. -0.3169, 0.1063, 0.0158,
  73482. 0.0103, -0.5869, 0.0046,
  73483. -0.0897, -0.4940, 0.3287,
  73484. 0.7119, -0.0154, -0.0918,
  73485. -0.0533, 0.0596, -0.5411,
  73486. 0.0352, -0.0631, 0.5460,
  73487. -0.4776, 0.2847, -0.0271
  73488. ];
  73489. var samplesFactor = 1.0 / numSamples;
  73490. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73491. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73492. "area", "fallOff", "base", "range", "viewport"
  73493. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73494. this._ssaoPostProcess.onApply = function (effect) {
  73495. if (_this._firstUpdate) {
  73496. effect.setArray3("sampleSphere", sampleSphere);
  73497. effect.setFloat("samplesFactor", samplesFactor);
  73498. effect.setFloat("randTextureTiles", 4.0);
  73499. }
  73500. effect.setFloat("totalStrength", _this.totalStrength);
  73501. effect.setFloat("radius", _this.radius);
  73502. effect.setFloat("area", _this.area);
  73503. effect.setFloat("fallOff", _this.fallOff);
  73504. effect.setFloat("base", _this.base);
  73505. effect.setTexture("textureSampler", _this._depthTexture);
  73506. effect.setTexture("randomSampler", _this._randomTexture);
  73507. };
  73508. };
  73509. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73510. var _this = this;
  73511. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73512. this._ssaoCombinePostProcess.onApply = function (effect) {
  73513. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73514. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73515. };
  73516. };
  73517. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73518. var size = 512;
  73519. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73520. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73521. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73522. var context = this._randomTexture.getContext();
  73523. var rand = function (min, max) {
  73524. return Math.random() * (max - min) + min;
  73525. };
  73526. var randVector = BABYLON.Vector3.Zero();
  73527. for (var x = 0; x < size; x++) {
  73528. for (var y = 0; y < size; y++) {
  73529. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73530. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73531. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73532. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73533. context.fillRect(x, y, 1, 1);
  73534. }
  73535. }
  73536. this._randomTexture.update(false);
  73537. };
  73538. __decorate([
  73539. BABYLON.serialize()
  73540. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73541. __decorate([
  73542. BABYLON.serialize()
  73543. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73544. __decorate([
  73545. BABYLON.serialize()
  73546. ], SSAORenderingPipeline.prototype, "area", void 0);
  73547. __decorate([
  73548. BABYLON.serialize()
  73549. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73550. __decorate([
  73551. BABYLON.serialize()
  73552. ], SSAORenderingPipeline.prototype, "base", void 0);
  73553. return SSAORenderingPipeline;
  73554. }(BABYLON.PostProcessRenderPipeline));
  73555. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73556. })(BABYLON || (BABYLON = {}));
  73557. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73558. var BABYLON;
  73559. (function (BABYLON) {
  73560. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73561. __extends(SSAO2RenderingPipeline, _super);
  73562. /**
  73563. * @constructor
  73564. * @param {string} name - The rendering pipeline name
  73565. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73566. * @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 }
  73567. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73568. */
  73569. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73570. var _this = _super.call(this, scene.getEngine(), name) || this;
  73571. // Members
  73572. /**
  73573. * The PassPostProcess id in the pipeline that contains the original scene color
  73574. */
  73575. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73576. /**
  73577. * The SSAO PostProcess id in the pipeline
  73578. */
  73579. _this.SSAORenderEffect = "SSAORenderEffect";
  73580. /**
  73581. * The horizontal blur PostProcess id in the pipeline
  73582. */
  73583. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73584. /**
  73585. * The vertical blur PostProcess id in the pipeline
  73586. */
  73587. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73588. /**
  73589. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73590. */
  73591. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73592. /**
  73593. * The output strength of the SSAO post-process. Default value is 1.0.
  73594. */
  73595. _this.totalStrength = 1.0;
  73596. /**
  73597. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73598. */
  73599. _this.maxZ = 100.0;
  73600. /**
  73601. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73602. */
  73603. _this.minZAspect = 0.2;
  73604. /**
  73605. * Number of samples used for the SSAO calculations. Default value is 8
  73606. */
  73607. _this._samples = 8;
  73608. /**
  73609. * Are we using bilateral blur ?
  73610. */
  73611. _this._expensiveBlur = true;
  73612. /**
  73613. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73614. */
  73615. _this.radius = 2.0;
  73616. /**
  73617. * The base color of the SSAO post-process
  73618. * The final result is "base + ssao" between [0, 1]
  73619. */
  73620. _this.base = 0.1;
  73621. _this._firstUpdate = true;
  73622. _this._scene = scene;
  73623. _this._ratio = ratio;
  73624. if (!_this.isSupported) {
  73625. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73626. return _this;
  73627. }
  73628. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73629. var blurRatio = _this._ratio.blurRatio || ratio;
  73630. // Set up assets
  73631. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73632. _this._createRandomTexture();
  73633. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73634. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73635. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73636. _this._createSSAOPostProcess(1.0);
  73637. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73638. _this._createSSAOCombinePostProcess(blurRatio);
  73639. // Set up pipeline
  73640. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73641. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73642. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73643. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73644. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73645. // Finish
  73646. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73647. if (cameras)
  73648. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73649. return _this;
  73650. }
  73651. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73652. get: function () {
  73653. return this._samples;
  73654. },
  73655. set: function (n) {
  73656. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73657. this._samples = n;
  73658. this._sampleSphere = this._generateHemisphere();
  73659. this._firstUpdate = true;
  73660. },
  73661. enumerable: true,
  73662. configurable: true
  73663. });
  73664. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73665. get: function () {
  73666. return this._expensiveBlur;
  73667. },
  73668. set: function (b) {
  73669. 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"]);
  73670. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73671. this._expensiveBlur = b;
  73672. this._firstUpdate = true;
  73673. },
  73674. enumerable: true,
  73675. configurable: true
  73676. });
  73677. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73678. /**
  73679. * Support test.
  73680. */
  73681. get: function () {
  73682. var engine = BABYLON.Engine.LastCreatedEngine;
  73683. if (!engine) {
  73684. return false;
  73685. }
  73686. return engine.getCaps().drawBuffersExtension;
  73687. },
  73688. enumerable: true,
  73689. configurable: true
  73690. });
  73691. // Public Methods
  73692. /**
  73693. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73694. */
  73695. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73696. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73697. for (var i = 0; i < this._scene.cameras.length; i++) {
  73698. var camera = this._scene.cameras[i];
  73699. this._originalColorPostProcess.dispose(camera);
  73700. this._ssaoPostProcess.dispose(camera);
  73701. this._blurHPostProcess.dispose(camera);
  73702. this._blurVPostProcess.dispose(camera);
  73703. this._ssaoCombinePostProcess.dispose(camera);
  73704. }
  73705. this._randomTexture.dispose();
  73706. if (disableGeometryBufferRenderer)
  73707. this._scene.disableGeometryBufferRenderer();
  73708. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73709. _super.prototype.dispose.call(this);
  73710. };
  73711. // Private Methods
  73712. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73713. var _this = this;
  73714. this._samplerOffsets = [];
  73715. var expensive = this.expensiveBlur;
  73716. for (var i = -8; i < 8; i++) {
  73717. this._samplerOffsets.push(i * 2 + 0.5);
  73718. }
  73719. 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");
  73720. this._blurHPostProcess.onApply = function (effect) {
  73721. if (!_this._scene.activeCamera) {
  73722. return;
  73723. }
  73724. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73725. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73726. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73727. effect.setFloat("radius", _this.radius);
  73728. effect.setTexture("depthSampler", _this._depthTexture);
  73729. if (_this._firstUpdate) {
  73730. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73731. }
  73732. };
  73733. 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");
  73734. this._blurVPostProcess.onApply = function (effect) {
  73735. if (!_this._scene.activeCamera) {
  73736. return;
  73737. }
  73738. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73739. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73740. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73741. effect.setFloat("radius", _this.radius);
  73742. effect.setTexture("depthSampler", _this._depthTexture);
  73743. if (_this._firstUpdate) {
  73744. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73745. _this._firstUpdate = false;
  73746. }
  73747. };
  73748. };
  73749. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73750. this._firstUpdate = true;
  73751. _super.prototype._rebuild.call(this);
  73752. };
  73753. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73754. var numSamples = this.samples;
  73755. var result = [];
  73756. var vector, scale;
  73757. var rand = function (min, max) {
  73758. return Math.random() * (max - min) + min;
  73759. };
  73760. var i = 0;
  73761. while (i < numSamples) {
  73762. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73763. vector.normalize();
  73764. scale = i / numSamples;
  73765. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73766. vector.scaleInPlace(scale);
  73767. result.push(vector.x, vector.y, vector.z);
  73768. i++;
  73769. }
  73770. return result;
  73771. };
  73772. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73773. var _this = this;
  73774. var numSamples = this.samples;
  73775. this._sampleSphere = this._generateHemisphere();
  73776. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73777. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73778. "base", "range", "projection", "near", "far", "texelSize",
  73779. "xViewport", "yViewport", "maxZ", "minZAspect"
  73780. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73781. this._ssaoPostProcess.onApply = function (effect) {
  73782. if (_this._firstUpdate) {
  73783. effect.setArray3("sampleSphere", _this._sampleSphere);
  73784. effect.setFloat("randTextureTiles", 4.0);
  73785. }
  73786. if (!_this._scene.activeCamera) {
  73787. return;
  73788. }
  73789. effect.setFloat("samplesFactor", 1 / _this.samples);
  73790. effect.setFloat("totalStrength", _this.totalStrength);
  73791. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73792. effect.setFloat("radius", _this.radius);
  73793. effect.setFloat("maxZ", _this.maxZ);
  73794. effect.setFloat("minZAspect", _this.minZAspect);
  73795. effect.setFloat("base", _this.base);
  73796. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73797. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73798. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73799. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73800. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73801. effect.setTexture("textureSampler", _this._depthTexture);
  73802. effect.setTexture("normalSampler", _this._normalTexture);
  73803. effect.setTexture("randomSampler", _this._randomTexture);
  73804. };
  73805. };
  73806. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73807. var _this = this;
  73808. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73809. this._ssaoCombinePostProcess.onApply = function (effect) {
  73810. var viewport = _this._scene.activeCamera.viewport;
  73811. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  73812. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73813. };
  73814. };
  73815. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73816. var size = 512;
  73817. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73818. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73819. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73820. var context = this._randomTexture.getContext();
  73821. var rand = function (min, max) {
  73822. return Math.random() * (max - min) + min;
  73823. };
  73824. var randVector = BABYLON.Vector3.Zero();
  73825. for (var x = 0; x < size; x++) {
  73826. for (var y = 0; y < size; y++) {
  73827. randVector.x = rand(0.0, 1.0);
  73828. randVector.y = rand(0.0, 1.0);
  73829. randVector.z = 0.0;
  73830. randVector.normalize();
  73831. randVector.scaleInPlace(255);
  73832. randVector.x = Math.floor(randVector.x);
  73833. randVector.y = Math.floor(randVector.y);
  73834. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73835. context.fillRect(x, y, 1, 1);
  73836. }
  73837. }
  73838. this._randomTexture.update(false);
  73839. };
  73840. /**
  73841. * Serialize the rendering pipeline (Used when exporting)
  73842. * @returns the serialized object
  73843. */
  73844. SSAO2RenderingPipeline.prototype.serialize = function () {
  73845. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73846. serializationObject.customType = "SSAO2RenderingPipeline";
  73847. return serializationObject;
  73848. };
  73849. /**
  73850. * Parse the serialized pipeline
  73851. * @param source Source pipeline.
  73852. * @param scene The scene to load the pipeline to.
  73853. * @param rootUrl The URL of the serialized pipeline.
  73854. * @returns An instantiated pipeline from the serialized object.
  73855. */
  73856. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73857. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73858. };
  73859. __decorate([
  73860. BABYLON.serialize()
  73861. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73862. __decorate([
  73863. BABYLON.serialize()
  73864. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73865. __decorate([
  73866. BABYLON.serialize()
  73867. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73868. __decorate([
  73869. BABYLON.serialize("samples")
  73870. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73871. __decorate([
  73872. BABYLON.serialize()
  73873. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73874. __decorate([
  73875. BABYLON.serialize("expensiveBlur")
  73876. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73877. __decorate([
  73878. BABYLON.serialize()
  73879. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73880. __decorate([
  73881. BABYLON.serialize()
  73882. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73883. return SSAO2RenderingPipeline;
  73884. }(BABYLON.PostProcessRenderPipeline));
  73885. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73886. })(BABYLON || (BABYLON = {}));
  73887. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73888. // BABYLON.JS Chromatic Aberration GLSL Shader
  73889. // Author: Olivier Guyot
  73890. // Separates very slightly R, G and B colors on the edges of the screen
  73891. // Inspired by Francois Tarlier & Martins Upitis
  73892. var BABYLON;
  73893. (function (BABYLON) {
  73894. var LensRenderingPipeline = /** @class */ (function (_super) {
  73895. __extends(LensRenderingPipeline, _super);
  73896. /**
  73897. * @constructor
  73898. *
  73899. * Effect parameters are as follow:
  73900. * {
  73901. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73902. * edge_blur: number; // from 0 to x (1 for realism)
  73903. * distortion: number; // from 0 to x (1 for realism)
  73904. * grain_amount: number; // from 0 to 1
  73905. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73906. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73907. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73908. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73909. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73910. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73911. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73912. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73913. * }
  73914. * Note: if an effect parameter is unset, effect is disabled
  73915. *
  73916. * @param {string} name - The rendering pipeline name
  73917. * @param {object} parameters - An object containing all parameters (see above)
  73918. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73919. * @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)
  73920. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73921. */
  73922. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73923. if (ratio === void 0) { ratio = 1.0; }
  73924. var _this = _super.call(this, scene.getEngine(), name) || this;
  73925. // Lens effects can be of the following:
  73926. // - chromatic aberration (slight shift of RGB colors)
  73927. // - blur on the edge of the lens
  73928. // - lens distortion
  73929. // - depth-of-field blur & highlights enhancing
  73930. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73931. // - grain effect (noise or custom texture)
  73932. // Two additional texture samplers are needed:
  73933. // - depth map (for depth-of-field)
  73934. // - grain texture
  73935. /**
  73936. * The chromatic aberration PostProcess id in the pipeline
  73937. */
  73938. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73939. /**
  73940. * The highlights enhancing PostProcess id in the pipeline
  73941. */
  73942. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73943. /**
  73944. * The depth-of-field PostProcess id in the pipeline
  73945. */
  73946. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73947. _this._scene = scene;
  73948. // Fetch texture samplers
  73949. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73950. if (parameters.grain_texture) {
  73951. _this._grainTexture = parameters.grain_texture;
  73952. }
  73953. else {
  73954. _this._createGrainTexture();
  73955. }
  73956. // save parameters
  73957. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73958. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73959. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73960. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73961. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73962. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73963. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73964. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73965. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73966. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73967. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73968. // Create effects
  73969. _this._createChromaticAberrationPostProcess(ratio);
  73970. _this._createHighlightsPostProcess(ratio);
  73971. _this._createDepthOfFieldPostProcess(ratio / 4);
  73972. // Set up pipeline
  73973. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73974. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73975. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73976. if (_this._highlightsGain === -1) {
  73977. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73978. }
  73979. // Finish
  73980. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73981. if (cameras) {
  73982. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73983. }
  73984. return _this;
  73985. }
  73986. // public methods (self explanatory)
  73987. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73988. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73989. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73990. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73991. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73992. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73993. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73994. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73995. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73996. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73997. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73998. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73999. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74000. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74001. };
  74002. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74003. this._highlightsPostProcess.updateEffect();
  74004. };
  74005. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74006. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74007. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74008. this._highlightsGain = amount;
  74009. };
  74010. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74011. if (this._highlightsGain === -1) {
  74012. this._highlightsGain = 1.0;
  74013. }
  74014. this._highlightsThreshold = amount;
  74015. };
  74016. LensRenderingPipeline.prototype.disableHighlights = function () {
  74017. this._highlightsGain = -1;
  74018. };
  74019. /**
  74020. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74021. */
  74022. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74023. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74024. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74025. this._chromaticAberrationPostProcess = null;
  74026. this._highlightsPostProcess = null;
  74027. this._depthOfFieldPostProcess = null;
  74028. this._grainTexture.dispose();
  74029. if (disableDepthRender)
  74030. this._scene.disableDepthRenderer();
  74031. };
  74032. // colors shifting and distortion
  74033. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74034. var _this = this;
  74035. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74036. [], // samplers
  74037. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74038. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74039. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74040. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74041. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74042. effect.setFloat('radialIntensity', 1);
  74043. effect.setFloat2('direction', 17, 17);
  74044. effect.setFloat2('centerPosition', 0.5, 0.5);
  74045. };
  74046. };
  74047. // highlights enhancing
  74048. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74049. var _this = this;
  74050. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74051. [], // samplers
  74052. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74053. this._highlightsPostProcess.onApply = function (effect) {
  74054. effect.setFloat('gain', _this._highlightsGain);
  74055. effect.setFloat('threshold', _this._highlightsThreshold);
  74056. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74057. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74058. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74059. };
  74060. };
  74061. // colors shifting and distortion
  74062. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74063. var _this = this;
  74064. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74065. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74066. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74067. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74068. this._depthOfFieldPostProcess.onApply = function (effect) {
  74069. effect.setTexture("depthSampler", _this._depthTexture);
  74070. effect.setTexture("grainSampler", _this._grainTexture);
  74071. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74072. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74073. effect.setFloat('grain_amount', _this._grainAmount);
  74074. effect.setBool('blur_noise', _this._blurNoise);
  74075. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74076. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74077. effect.setFloat('distortion', _this._distortion);
  74078. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74079. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74080. effect.setFloat('aperture', _this._dofAperture);
  74081. effect.setFloat('darken', _this._dofDarken);
  74082. effect.setFloat('edge_blur', _this._edgeBlur);
  74083. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74084. if (_this._scene.activeCamera) {
  74085. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74086. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74087. }
  74088. };
  74089. };
  74090. // creates a black and white random noise texture, 512x512
  74091. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74092. var size = 512;
  74093. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74094. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74095. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74096. var context = this._grainTexture.getContext();
  74097. var rand = function (min, max) {
  74098. return Math.random() * (max - min) + min;
  74099. };
  74100. var value;
  74101. for (var x = 0; x < size; x++) {
  74102. for (var y = 0; y < size; y++) {
  74103. value = Math.floor(rand(0.42, 0.58) * 255);
  74104. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74105. context.fillRect(x, y, 1, 1);
  74106. }
  74107. }
  74108. this._grainTexture.update(false);
  74109. };
  74110. return LensRenderingPipeline;
  74111. }(BABYLON.PostProcessRenderPipeline));
  74112. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74113. })(BABYLON || (BABYLON = {}));
  74114. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74115. var BABYLON;
  74116. (function (BABYLON) {
  74117. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74118. __extends(StandardRenderingPipeline, _super);
  74119. /**
  74120. * @constructor
  74121. * @param {string} name - The rendering pipeline name
  74122. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74123. * @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)
  74124. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74125. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74126. */
  74127. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74128. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74129. var _this = _super.call(this, scene.getEngine(), name) || this;
  74130. _this.downSampleX4PostProcess = null;
  74131. _this.brightPassPostProcess = null;
  74132. _this.blurHPostProcesses = [];
  74133. _this.blurVPostProcesses = [];
  74134. _this.textureAdderPostProcess = null;
  74135. _this.volumetricLightPostProcess = null;
  74136. _this.volumetricLightSmoothXPostProcess = null;
  74137. _this.volumetricLightSmoothYPostProcess = null;
  74138. _this.volumetricLightMergePostProces = null;
  74139. _this.volumetricLightFinalPostProcess = null;
  74140. _this.luminancePostProcess = null;
  74141. _this.luminanceDownSamplePostProcesses = [];
  74142. _this.hdrPostProcess = null;
  74143. _this.textureAdderFinalPostProcess = null;
  74144. _this.lensFlareFinalPostProcess = null;
  74145. _this.hdrFinalPostProcess = null;
  74146. _this.lensFlarePostProcess = null;
  74147. _this.lensFlareComposePostProcess = null;
  74148. _this.motionBlurPostProcess = null;
  74149. _this.depthOfFieldPostProcess = null;
  74150. // Values
  74151. _this.brightThreshold = 1.0;
  74152. _this.blurWidth = 512.0;
  74153. _this.horizontalBlur = false;
  74154. _this.exposure = 1.0;
  74155. _this.lensTexture = null;
  74156. _this.volumetricLightCoefficient = 0.2;
  74157. _this.volumetricLightPower = 4.0;
  74158. _this.volumetricLightBlurScale = 64.0;
  74159. _this.sourceLight = null;
  74160. _this.hdrMinimumLuminance = 1.0;
  74161. _this.hdrDecreaseRate = 0.5;
  74162. _this.hdrIncreaseRate = 0.5;
  74163. _this.lensColorTexture = null;
  74164. _this.lensFlareStrength = 20.0;
  74165. _this.lensFlareGhostDispersal = 1.4;
  74166. _this.lensFlareHaloWidth = 0.7;
  74167. _this.lensFlareDistortionStrength = 16.0;
  74168. _this.lensStarTexture = null;
  74169. _this.lensFlareDirtTexture = null;
  74170. _this.depthOfFieldDistance = 10.0;
  74171. _this.depthOfFieldBlurWidth = 64.0;
  74172. _this.motionStrength = 1.0;
  74173. // IAnimatable
  74174. _this.animations = [];
  74175. _this._currentDepthOfFieldSource = null;
  74176. _this._hdrCurrentLuminance = 1.0;
  74177. // Getters and setters
  74178. _this._bloomEnabled = true;
  74179. _this._depthOfFieldEnabled = false;
  74180. _this._vlsEnabled = false;
  74181. _this._lensFlareEnabled = false;
  74182. _this._hdrEnabled = false;
  74183. _this._motionBlurEnabled = false;
  74184. _this._motionBlurSamples = 64.0;
  74185. _this._volumetricLightStepsCount = 50.0;
  74186. _this._cameras = cameras || [];
  74187. // Initialize
  74188. _this._scene = scene;
  74189. _this._basePostProcess = originalPostProcess;
  74190. _this._ratio = ratio;
  74191. // Misc
  74192. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74193. // Finish
  74194. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74195. _this._buildPipeline();
  74196. return _this;
  74197. }
  74198. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74199. get: function () {
  74200. return this._bloomEnabled;
  74201. },
  74202. set: function (enabled) {
  74203. if (this._bloomEnabled === enabled) {
  74204. return;
  74205. }
  74206. this._bloomEnabled = enabled;
  74207. this._buildPipeline();
  74208. },
  74209. enumerable: true,
  74210. configurable: true
  74211. });
  74212. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74213. get: function () {
  74214. return this._depthOfFieldEnabled;
  74215. },
  74216. set: function (enabled) {
  74217. if (this._depthOfFieldEnabled === enabled) {
  74218. return;
  74219. }
  74220. this._depthOfFieldEnabled = enabled;
  74221. this._buildPipeline();
  74222. },
  74223. enumerable: true,
  74224. configurable: true
  74225. });
  74226. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74227. get: function () {
  74228. return this._lensFlareEnabled;
  74229. },
  74230. set: function (enabled) {
  74231. if (this._lensFlareEnabled === enabled) {
  74232. return;
  74233. }
  74234. this._lensFlareEnabled = enabled;
  74235. this._buildPipeline();
  74236. },
  74237. enumerable: true,
  74238. configurable: true
  74239. });
  74240. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74241. get: function () {
  74242. return this._hdrEnabled;
  74243. },
  74244. set: function (enabled) {
  74245. if (this._hdrEnabled === enabled) {
  74246. return;
  74247. }
  74248. this._hdrEnabled = enabled;
  74249. this._buildPipeline();
  74250. },
  74251. enumerable: true,
  74252. configurable: true
  74253. });
  74254. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74255. get: function () {
  74256. return this._vlsEnabled;
  74257. },
  74258. set: function (enabled) {
  74259. if (this._vlsEnabled === enabled) {
  74260. return;
  74261. }
  74262. if (enabled) {
  74263. var geometry = this._scene.enableGeometryBufferRenderer();
  74264. if (!geometry) {
  74265. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74266. return;
  74267. }
  74268. }
  74269. this._vlsEnabled = enabled;
  74270. this._buildPipeline();
  74271. },
  74272. enumerable: true,
  74273. configurable: true
  74274. });
  74275. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74276. get: function () {
  74277. return this._motionBlurEnabled;
  74278. },
  74279. set: function (enabled) {
  74280. if (this._motionBlurEnabled === enabled) {
  74281. return;
  74282. }
  74283. this._motionBlurEnabled = enabled;
  74284. this._buildPipeline();
  74285. },
  74286. enumerable: true,
  74287. configurable: true
  74288. });
  74289. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74290. get: function () {
  74291. return this._volumetricLightStepsCount;
  74292. },
  74293. set: function (count) {
  74294. if (this.volumetricLightPostProcess) {
  74295. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74296. }
  74297. this._volumetricLightStepsCount = count;
  74298. },
  74299. enumerable: true,
  74300. configurable: true
  74301. });
  74302. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74303. get: function () {
  74304. return this._motionBlurSamples;
  74305. },
  74306. set: function (samples) {
  74307. if (this.motionBlurPostProcess) {
  74308. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74309. }
  74310. this._motionBlurSamples = samples;
  74311. },
  74312. enumerable: true,
  74313. configurable: true
  74314. });
  74315. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74316. var _this = this;
  74317. var ratio = this._ratio;
  74318. var scene = this._scene;
  74319. this._disposePostProcesses();
  74320. this._reset();
  74321. // Create pass post-process
  74322. if (!this._basePostProcess) {
  74323. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74324. this.originalPostProcess.onApply = function (effect) {
  74325. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74326. };
  74327. }
  74328. else {
  74329. this.originalPostProcess = this._basePostProcess;
  74330. }
  74331. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74332. this._currentDepthOfFieldSource = this.originalPostProcess;
  74333. if (this._bloomEnabled) {
  74334. // Create down sample X4 post-process
  74335. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74336. // Create bright pass post-process
  74337. this._createBrightPassPostProcess(scene, ratio / 2);
  74338. // Create gaussian blur post-processes (down sampling blurs)
  74339. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74340. // Create texture adder post-process
  74341. this._createTextureAdderPostProcess(scene, ratio);
  74342. // Create depth-of-field source post-process
  74343. 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);
  74344. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74345. }
  74346. if (this._vlsEnabled) {
  74347. // Create volumetric light
  74348. this._createVolumetricLightPostProcess(scene, ratio);
  74349. // Create volumetric light final post-process
  74350. 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);
  74351. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74352. }
  74353. if (this._lensFlareEnabled) {
  74354. // Create lens flare post-process
  74355. this._createLensFlarePostProcess(scene, ratio);
  74356. // Create depth-of-field source post-process post lens-flare and disable it now
  74357. 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);
  74358. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74359. }
  74360. if (this._hdrEnabled) {
  74361. // Create luminance
  74362. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74363. // Create HDR
  74364. this._createHdrPostProcess(scene, ratio);
  74365. // Create depth-of-field source post-process post hdr and disable it now
  74366. 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);
  74367. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74368. }
  74369. if (this._depthOfFieldEnabled) {
  74370. // Create gaussian blur used by depth-of-field
  74371. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74372. // Create depth-of-field post-process
  74373. this._createDepthOfFieldPostProcess(scene, ratio);
  74374. }
  74375. if (this._motionBlurEnabled) {
  74376. // Create motion blur post-process
  74377. this._createMotionBlurPostProcess(scene, ratio);
  74378. }
  74379. if (this._cameras !== null) {
  74380. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74381. }
  74382. };
  74383. // Down Sample X4 Post-Processs
  74384. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74385. var _this = this;
  74386. var downSampleX4Offsets = new Array(32);
  74387. 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);
  74388. this.downSampleX4PostProcess.onApply = function (effect) {
  74389. var id = 0;
  74390. var width = _this.downSampleX4PostProcess.width;
  74391. var height = _this.downSampleX4PostProcess.height;
  74392. for (var i = -2; i < 2; i++) {
  74393. for (var j = -2; j < 2; j++) {
  74394. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74395. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74396. id += 2;
  74397. }
  74398. }
  74399. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74400. };
  74401. // Add to pipeline
  74402. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74403. };
  74404. // Brightpass Post-Process
  74405. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74406. var _this = this;
  74407. var brightOffsets = new Array(8);
  74408. 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);
  74409. this.brightPassPostProcess.onApply = function (effect) {
  74410. var sU = (1.0 / _this.brightPassPostProcess.width);
  74411. var sV = (1.0 / _this.brightPassPostProcess.height);
  74412. brightOffsets[0] = -0.5 * sU;
  74413. brightOffsets[1] = 0.5 * sV;
  74414. brightOffsets[2] = 0.5 * sU;
  74415. brightOffsets[3] = 0.5 * sV;
  74416. brightOffsets[4] = -0.5 * sU;
  74417. brightOffsets[5] = -0.5 * sV;
  74418. brightOffsets[6] = 0.5 * sU;
  74419. brightOffsets[7] = -0.5 * sV;
  74420. effect.setArray2("dsOffsets", brightOffsets);
  74421. effect.setFloat("brightThreshold", _this.brightThreshold);
  74422. };
  74423. // Add to pipeline
  74424. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74425. };
  74426. // Create blur H&V post-processes
  74427. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74428. var _this = this;
  74429. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74430. var engine = scene.getEngine();
  74431. 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);
  74432. 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);
  74433. blurX.onActivateObservable.add(function () {
  74434. var dw = blurX.width / engine.getRenderWidth();
  74435. blurX.kernel = _this[blurWidthKey] * dw;
  74436. });
  74437. blurY.onActivateObservable.add(function () {
  74438. var dw = blurY.height / engine.getRenderHeight();
  74439. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74440. });
  74441. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74442. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74443. this.blurHPostProcesses.push(blurX);
  74444. this.blurVPostProcesses.push(blurY);
  74445. };
  74446. // Create texture adder post-process
  74447. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74448. var _this = this;
  74449. 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);
  74450. this.textureAdderPostProcess.onApply = function (effect) {
  74451. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74452. effect.setTexture("lensSampler", _this.lensTexture);
  74453. effect.setFloat("exposure", _this.exposure);
  74454. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74455. };
  74456. // Add to pipeline
  74457. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74458. };
  74459. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74460. var _this = this;
  74461. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74462. geometryRenderer.enablePosition = true;
  74463. var geometry = geometryRenderer.getGBuffer();
  74464. // Base post-process
  74465. 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));
  74466. var depthValues = BABYLON.Vector2.Zero();
  74467. this.volumetricLightPostProcess.onApply = function (effect) {
  74468. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74469. var generator = _this.sourceLight.getShadowGenerator();
  74470. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74471. effect.setTexture("positionSampler", geometry.textures[2]);
  74472. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74473. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74474. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74475. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74476. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74477. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74478. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74479. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74480. effect.setVector2("depthValues", depthValues);
  74481. }
  74482. };
  74483. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74484. // Smooth
  74485. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74486. // Merge
  74487. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74488. this.volumetricLightMergePostProces.onApply = function (effect) {
  74489. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74490. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74491. };
  74492. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74493. };
  74494. // Create luminance
  74495. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74496. var _this = this;
  74497. // Create luminance
  74498. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74499. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74500. var offsets = [];
  74501. this.luminancePostProcess.onApply = function (effect) {
  74502. var sU = (1.0 / _this.luminancePostProcess.width);
  74503. var sV = (1.0 / _this.luminancePostProcess.height);
  74504. offsets[0] = -0.5 * sU;
  74505. offsets[1] = 0.5 * sV;
  74506. offsets[2] = 0.5 * sU;
  74507. offsets[3] = 0.5 * sV;
  74508. offsets[4] = -0.5 * sU;
  74509. offsets[5] = -0.5 * sV;
  74510. offsets[6] = 0.5 * sU;
  74511. offsets[7] = -0.5 * sV;
  74512. effect.setArray2("lumOffsets", offsets);
  74513. };
  74514. // Add to pipeline
  74515. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74516. // Create down sample luminance
  74517. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74518. var size = Math.pow(3, i);
  74519. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74520. if (i === 0) {
  74521. defines += "#define FINAL_DOWN_SAMPLER";
  74522. }
  74523. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74524. this.luminanceDownSamplePostProcesses.push(postProcess);
  74525. }
  74526. // Create callbacks and add effects
  74527. var lastLuminance = this.luminancePostProcess;
  74528. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74529. var downSampleOffsets = new Array(18);
  74530. pp.onApply = function (effect) {
  74531. if (!lastLuminance) {
  74532. return;
  74533. }
  74534. var id = 0;
  74535. for (var x = -1; x < 2; x++) {
  74536. for (var y = -1; y < 2; y++) {
  74537. downSampleOffsets[id] = x / lastLuminance.width;
  74538. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74539. id += 2;
  74540. }
  74541. }
  74542. effect.setArray2("dsOffsets", downSampleOffsets);
  74543. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74544. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74545. lastLuminance = _this.luminancePostProcess;
  74546. }
  74547. else {
  74548. lastLuminance = pp;
  74549. }
  74550. };
  74551. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74552. pp.onAfterRender = function (effect) {
  74553. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74554. 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);
  74555. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74556. };
  74557. }
  74558. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74559. });
  74560. };
  74561. // Create HDR post-process
  74562. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74563. var _this = this;
  74564. 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);
  74565. var outputLiminance = 1;
  74566. var time = 0;
  74567. var lastTime = 0;
  74568. this.hdrPostProcess.onApply = function (effect) {
  74569. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74570. time += scene.getEngine().getDeltaTime();
  74571. if (outputLiminance < 0) {
  74572. outputLiminance = _this._hdrCurrentLuminance;
  74573. }
  74574. else {
  74575. var dt = (lastTime - time) / 1000.0;
  74576. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74577. outputLiminance += _this.hdrDecreaseRate * dt;
  74578. }
  74579. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74580. outputLiminance -= _this.hdrIncreaseRate * dt;
  74581. }
  74582. else {
  74583. outputLiminance = _this._hdrCurrentLuminance;
  74584. }
  74585. }
  74586. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74587. effect.setFloat("averageLuminance", outputLiminance);
  74588. lastTime = time;
  74589. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74590. };
  74591. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74592. };
  74593. // Create lens flare post-process
  74594. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74595. var _this = this;
  74596. 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);
  74597. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74598. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74599. 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);
  74600. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74601. var resolution = new BABYLON.Vector2(0, 0);
  74602. // Lens flare
  74603. this.lensFlarePostProcess.onApply = function (effect) {
  74604. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74605. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74606. effect.setFloat("strength", _this.lensFlareStrength);
  74607. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74608. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74609. // Shift
  74610. resolution.x = _this.lensFlarePostProcess.width;
  74611. resolution.y = _this.lensFlarePostProcess.height;
  74612. effect.setVector2("resolution", resolution);
  74613. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74614. };
  74615. // Compose
  74616. 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);
  74617. 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);
  74618. this.lensFlareComposePostProcess.onApply = function (effect) {
  74619. if (!_this._scene.activeCamera) {
  74620. return;
  74621. }
  74622. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74623. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74624. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74625. // Lens start rotation matrix
  74626. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74627. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74628. 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));
  74629. camRot *= 4.0;
  74630. 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);
  74631. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74632. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74633. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74634. };
  74635. };
  74636. // Create depth-of-field post-process
  74637. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74638. var _this = this;
  74639. 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);
  74640. this.depthOfFieldPostProcess.onApply = function (effect) {
  74641. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74642. effect.setTexture("depthSampler", _this._getDepthTexture());
  74643. effect.setFloat("distance", _this.depthOfFieldDistance);
  74644. };
  74645. // Add to pipeline
  74646. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74647. };
  74648. // Create motion blur post-process
  74649. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74650. var _this = this;
  74651. 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);
  74652. var motionScale = 0;
  74653. var prevViewProjection = BABYLON.Matrix.Identity();
  74654. var invViewProjection = BABYLON.Matrix.Identity();
  74655. var viewProjection = BABYLON.Matrix.Identity();
  74656. var screenSize = BABYLON.Vector2.Zero();
  74657. this.motionBlurPostProcess.onApply = function (effect) {
  74658. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74659. viewProjection.invertToRef(invViewProjection);
  74660. effect.setMatrix("inverseViewProjection", invViewProjection);
  74661. effect.setMatrix("prevViewProjection", prevViewProjection);
  74662. prevViewProjection = viewProjection;
  74663. screenSize.x = _this.motionBlurPostProcess.width;
  74664. screenSize.y = _this.motionBlurPostProcess.height;
  74665. effect.setVector2("screenSize", screenSize);
  74666. motionScale = scene.getEngine().getFps() / 60.0;
  74667. effect.setFloat("motionScale", motionScale);
  74668. effect.setFloat("motionStrength", _this.motionStrength);
  74669. effect.setTexture("depthSampler", _this._getDepthTexture());
  74670. };
  74671. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74672. };
  74673. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74674. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74675. var renderer = this._scene.enableGeometryBufferRenderer();
  74676. return renderer.getGBuffer().textures[0];
  74677. }
  74678. return this._scene.enableDepthRenderer().getDepthMap();
  74679. };
  74680. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74681. for (var i = 0; i < this._cameras.length; i++) {
  74682. var camera = this._cameras[i];
  74683. if (this.originalPostProcess) {
  74684. this.originalPostProcess.dispose(camera);
  74685. }
  74686. if (this.downSampleX4PostProcess) {
  74687. this.downSampleX4PostProcess.dispose(camera);
  74688. }
  74689. if (this.brightPassPostProcess) {
  74690. this.brightPassPostProcess.dispose(camera);
  74691. }
  74692. if (this.textureAdderPostProcess) {
  74693. this.textureAdderPostProcess.dispose(camera);
  74694. }
  74695. if (this.textureAdderFinalPostProcess) {
  74696. this.textureAdderFinalPostProcess.dispose(camera);
  74697. }
  74698. if (this.volumetricLightPostProcess) {
  74699. this.volumetricLightPostProcess.dispose(camera);
  74700. }
  74701. if (this.volumetricLightSmoothXPostProcess) {
  74702. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74703. }
  74704. if (this.volumetricLightSmoothYPostProcess) {
  74705. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74706. }
  74707. if (this.volumetricLightMergePostProces) {
  74708. this.volumetricLightMergePostProces.dispose(camera);
  74709. }
  74710. if (this.volumetricLightFinalPostProcess) {
  74711. this.volumetricLightFinalPostProcess.dispose(camera);
  74712. }
  74713. if (this.lensFlarePostProcess) {
  74714. this.lensFlarePostProcess.dispose(camera);
  74715. }
  74716. if (this.lensFlareComposePostProcess) {
  74717. this.lensFlareComposePostProcess.dispose(camera);
  74718. }
  74719. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74720. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74721. }
  74722. if (this.luminancePostProcess) {
  74723. this.luminancePostProcess.dispose(camera);
  74724. }
  74725. if (this.hdrPostProcess) {
  74726. this.hdrPostProcess.dispose(camera);
  74727. }
  74728. if (this.hdrFinalPostProcess) {
  74729. this.hdrFinalPostProcess.dispose(camera);
  74730. }
  74731. if (this.depthOfFieldPostProcess) {
  74732. this.depthOfFieldPostProcess.dispose(camera);
  74733. }
  74734. if (this.motionBlurPostProcess) {
  74735. this.motionBlurPostProcess.dispose(camera);
  74736. }
  74737. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74738. this.blurHPostProcesses[j].dispose(camera);
  74739. }
  74740. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74741. this.blurVPostProcesses[j].dispose(camera);
  74742. }
  74743. }
  74744. this.originalPostProcess = null;
  74745. this.downSampleX4PostProcess = null;
  74746. this.brightPassPostProcess = null;
  74747. this.textureAdderPostProcess = null;
  74748. this.textureAdderFinalPostProcess = null;
  74749. this.volumetricLightPostProcess = null;
  74750. this.volumetricLightSmoothXPostProcess = null;
  74751. this.volumetricLightSmoothYPostProcess = null;
  74752. this.volumetricLightMergePostProces = null;
  74753. this.volumetricLightFinalPostProcess = null;
  74754. this.lensFlarePostProcess = null;
  74755. this.lensFlareComposePostProcess = null;
  74756. this.luminancePostProcess = null;
  74757. this.hdrPostProcess = null;
  74758. this.hdrFinalPostProcess = null;
  74759. this.depthOfFieldPostProcess = null;
  74760. this.motionBlurPostProcess = null;
  74761. this.luminanceDownSamplePostProcesses = [];
  74762. this.blurHPostProcesses = [];
  74763. this.blurVPostProcesses = [];
  74764. };
  74765. /**
  74766. * Dispose of the pipeline and stop all post processes
  74767. */
  74768. StandardRenderingPipeline.prototype.dispose = function () {
  74769. this._disposePostProcesses();
  74770. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74771. _super.prototype.dispose.call(this);
  74772. };
  74773. /**
  74774. * Serialize the rendering pipeline (Used when exporting)
  74775. * @returns the serialized object
  74776. */
  74777. StandardRenderingPipeline.prototype.serialize = function () {
  74778. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74779. if (this.sourceLight) {
  74780. serializationObject.sourceLightId = this.sourceLight.id;
  74781. }
  74782. serializationObject.customType = "StandardRenderingPipeline";
  74783. return serializationObject;
  74784. };
  74785. /**
  74786. * Parse the serialized pipeline
  74787. * @param source Source pipeline.
  74788. * @param scene The scene to load the pipeline to.
  74789. * @param rootUrl The URL of the serialized pipeline.
  74790. * @returns An instantiated pipeline from the serialized object.
  74791. */
  74792. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74793. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74794. if (source.sourceLightId) {
  74795. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74796. }
  74797. return p;
  74798. };
  74799. // Luminance steps
  74800. StandardRenderingPipeline.LuminanceSteps = 6;
  74801. __decorate([
  74802. BABYLON.serialize()
  74803. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74804. __decorate([
  74805. BABYLON.serialize()
  74806. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74807. __decorate([
  74808. BABYLON.serialize()
  74809. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74810. __decorate([
  74811. BABYLON.serialize()
  74812. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74813. __decorate([
  74814. BABYLON.serializeAsTexture("lensTexture")
  74815. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74816. __decorate([
  74817. BABYLON.serialize()
  74818. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74819. __decorate([
  74820. BABYLON.serialize()
  74821. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74822. __decorate([
  74823. BABYLON.serialize()
  74824. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74825. __decorate([
  74826. BABYLON.serialize()
  74827. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74828. __decorate([
  74829. BABYLON.serialize()
  74830. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74831. __decorate([
  74832. BABYLON.serialize()
  74833. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74834. __decorate([
  74835. BABYLON.serializeAsTexture("lensColorTexture")
  74836. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74837. __decorate([
  74838. BABYLON.serialize()
  74839. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74840. __decorate([
  74841. BABYLON.serialize()
  74842. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74843. __decorate([
  74844. BABYLON.serialize()
  74845. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74846. __decorate([
  74847. BABYLON.serialize()
  74848. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74849. __decorate([
  74850. BABYLON.serializeAsTexture("lensStarTexture")
  74851. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74852. __decorate([
  74853. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74854. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74855. __decorate([
  74856. BABYLON.serialize()
  74857. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74858. __decorate([
  74859. BABYLON.serialize()
  74860. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74861. __decorate([
  74862. BABYLON.serialize()
  74863. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74864. __decorate([
  74865. BABYLON.serialize()
  74866. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74867. __decorate([
  74868. BABYLON.serialize()
  74869. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74870. __decorate([
  74871. BABYLON.serialize()
  74872. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74873. __decorate([
  74874. BABYLON.serialize()
  74875. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74876. __decorate([
  74877. BABYLON.serialize()
  74878. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74879. __decorate([
  74880. BABYLON.serialize()
  74881. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74882. __decorate([
  74883. BABYLON.serialize()
  74884. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74885. __decorate([
  74886. BABYLON.serialize()
  74887. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74888. __decorate([
  74889. BABYLON.serialize()
  74890. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74891. return StandardRenderingPipeline;
  74892. }(BABYLON.PostProcessRenderPipeline));
  74893. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74894. })(BABYLON || (BABYLON = {}));
  74895. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74896. var BABYLON;
  74897. (function (BABYLON) {
  74898. var FxaaPostProcess = /** @class */ (function (_super) {
  74899. __extends(FxaaPostProcess, _super);
  74900. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74901. if (camera === void 0) { camera = null; }
  74902. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74903. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74904. var defines = _this._getDefines();
  74905. _this.updateEffect(defines);
  74906. _this.onApplyObservable.add(function (effect) {
  74907. var texelSize = _this.texelSize;
  74908. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74909. });
  74910. return _this;
  74911. }
  74912. FxaaPostProcess.prototype._getDefines = function () {
  74913. var engine = this.getEngine();
  74914. if (!engine) {
  74915. return null;
  74916. }
  74917. var glInfo = engine.getGlInfo();
  74918. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74919. return "#define MALI 1\n";
  74920. }
  74921. return null;
  74922. };
  74923. return FxaaPostProcess;
  74924. }(BABYLON.PostProcess));
  74925. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74926. })(BABYLON || (BABYLON = {}));
  74927. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74928. var BABYLON;
  74929. (function (BABYLON) {
  74930. /**
  74931. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74932. */
  74933. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74934. __extends(ChromaticAberrationPostProcess, _super);
  74935. /**
  74936. * Creates a new instance ChromaticAberrationPostProcess
  74937. * @param name The name of the effect.
  74938. * @param screenWidth The width of the screen to apply the effect on.
  74939. * @param screenHeight The height of the screen to apply the effect on.
  74940. * @param options The required width/height ratio to downsize to before computing the render pass.
  74941. * @param camera The camera to apply the render pass to.
  74942. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74943. * @param engine The engine which the post process will be applied. (default: current engine)
  74944. * @param reusable If the post process can be reused on the same frame. (default: false)
  74945. * @param textureType Type of textures used when performing the post process. (default: 0)
  74946. * @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)
  74947. */
  74948. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74949. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74950. if (blockCompilation === void 0) { blockCompilation = false; }
  74951. 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;
  74952. /**
  74953. * The amount of seperation of rgb channels (default: 30)
  74954. */
  74955. _this.aberrationAmount = 30;
  74956. /**
  74957. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74958. */
  74959. _this.radialIntensity = 0;
  74960. /**
  74961. * 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))
  74962. */
  74963. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74964. /**
  74965. * 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))
  74966. */
  74967. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74968. _this.onApplyObservable.add(function (effect) {
  74969. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74970. effect.setFloat('screen_width', screenWidth);
  74971. effect.setFloat('screen_height', screenHeight);
  74972. effect.setFloat('radialIntensity', _this.radialIntensity);
  74973. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74974. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74975. });
  74976. return _this;
  74977. }
  74978. return ChromaticAberrationPostProcess;
  74979. }(BABYLON.PostProcess));
  74980. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74981. })(BABYLON || (BABYLON = {}));
  74982. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74983. var BABYLON;
  74984. (function (BABYLON) {
  74985. /**
  74986. * The GrainPostProcess adds noise to the image at mid luminance levels
  74987. */
  74988. var GrainPostProcess = /** @class */ (function (_super) {
  74989. __extends(GrainPostProcess, _super);
  74990. /**
  74991. * Creates a new instance of @see GrainPostProcess
  74992. * @param name The name of the effect.
  74993. * @param options The required width/height ratio to downsize to before computing the render pass.
  74994. * @param camera The camera to apply the render pass to.
  74995. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74996. * @param engine The engine which the post process will be applied. (default: current engine)
  74997. * @param reusable If the post process can be reused on the same frame. (default: false)
  74998. * @param textureType Type of textures used when performing the post process. (default: 0)
  74999. * @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)
  75000. */
  75001. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75002. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75003. if (blockCompilation === void 0) { blockCompilation = false; }
  75004. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75005. /**
  75006. * The intensity of the grain added (default: 30)
  75007. */
  75008. _this.intensity = 30;
  75009. /**
  75010. * If the grain should be randomized on every frame
  75011. */
  75012. _this.animated = false;
  75013. _this.onApplyObservable.add(function (effect) {
  75014. effect.setFloat('intensity', _this.intensity);
  75015. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75016. });
  75017. return _this;
  75018. }
  75019. return GrainPostProcess;
  75020. }(BABYLON.PostProcess));
  75021. BABYLON.GrainPostProcess = GrainPostProcess;
  75022. })(BABYLON || (BABYLON = {}));
  75023. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75024. var BABYLON;
  75025. (function (BABYLON) {
  75026. /**
  75027. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75028. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75029. */
  75030. var SharpenPostProcess = /** @class */ (function (_super) {
  75031. __extends(SharpenPostProcess, _super);
  75032. /**
  75033. * Creates a new instance ConvolutionPostProcess
  75034. * @param name The name of the effect.
  75035. * @param options The required width/height ratio to downsize to before computing the render pass.
  75036. * @param camera The camera to apply the render pass to.
  75037. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75038. * @param engine The engine which the post process will be applied. (default: current engine)
  75039. * @param reusable If the post process can be reused on the same frame. (default: false)
  75040. * @param textureType Type of textures used when performing the post process. (default: 0)
  75041. * @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)
  75042. */
  75043. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75044. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75045. if (blockCompilation === void 0) { blockCompilation = false; }
  75046. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75047. /**
  75048. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75049. */
  75050. _this.colorAmount = 1.0;
  75051. /**
  75052. * How much sharpness should be applied (default: 0.3)
  75053. */
  75054. _this.edgeAmount = 0.3;
  75055. _this.onApply = function (effect) {
  75056. effect.setFloat2("screenSize", _this.width, _this.height);
  75057. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75058. };
  75059. return _this;
  75060. }
  75061. return SharpenPostProcess;
  75062. }(BABYLON.PostProcess));
  75063. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75064. })(BABYLON || (BABYLON = {}));
  75065. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75066. var BABYLON;
  75067. (function (BABYLON) {
  75068. /**
  75069. * The Blur Post Process which blurs an image based on a kernel and direction.
  75070. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75071. */
  75072. var BlurPostProcess = /** @class */ (function (_super) {
  75073. __extends(BlurPostProcess, _super);
  75074. /**
  75075. * Creates a new instance BlurPostProcess
  75076. * @param name The name of the effect.
  75077. * @param direction The direction in which to blur the image.
  75078. * @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.
  75079. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75080. * @param camera The camera to apply the render pass to.
  75081. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75082. * @param engine The engine which the post process will be applied. (default: current engine)
  75083. * @param reusable If the post process can be reused on the same frame. (default: false)
  75084. * @param textureType Type of textures used when performing the post process. (default: 0)
  75085. * @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)
  75086. */
  75087. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75088. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75089. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75090. if (defines === void 0) { defines = ""; }
  75091. if (blockCompilation === void 0) { blockCompilation = false; }
  75092. 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;
  75093. _this.direction = direction;
  75094. _this.blockCompilation = blockCompilation;
  75095. _this._packedFloat = false;
  75096. _this._staticDefines = "";
  75097. _this._staticDefines = defines;
  75098. _this.onApplyObservable.add(function (effect) {
  75099. if (_this._outputTexture) {
  75100. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75101. }
  75102. else {
  75103. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75104. }
  75105. });
  75106. _this.kernel = kernel;
  75107. return _this;
  75108. }
  75109. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75110. /**
  75111. * Gets the length in pixels of the blur sample region
  75112. */
  75113. get: function () {
  75114. return this._idealKernel;
  75115. },
  75116. /**
  75117. * Sets the length in pixels of the blur sample region
  75118. */
  75119. set: function (v) {
  75120. if (this._idealKernel === v) {
  75121. return;
  75122. }
  75123. v = Math.max(v, 1);
  75124. this._idealKernel = v;
  75125. this._kernel = this._nearestBestKernel(v);
  75126. if (!this.blockCompilation) {
  75127. this._updateParameters();
  75128. }
  75129. },
  75130. enumerable: true,
  75131. configurable: true
  75132. });
  75133. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75134. /**
  75135. * Gets wether or not the blur is unpacking/repacking floats
  75136. */
  75137. get: function () {
  75138. return this._packedFloat;
  75139. },
  75140. /**
  75141. * Sets wether or not the blur needs to unpack/repack floats
  75142. */
  75143. set: function (v) {
  75144. if (this._packedFloat === v) {
  75145. return;
  75146. }
  75147. this._packedFloat = v;
  75148. if (!this.blockCompilation) {
  75149. this._updateParameters();
  75150. }
  75151. },
  75152. enumerable: true,
  75153. configurable: true
  75154. });
  75155. /**
  75156. * Updates the effect with the current post process compile time values and recompiles the shader.
  75157. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75158. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75159. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75160. * @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
  75161. * @param onCompiled Called when the shader has been compiled.
  75162. * @param onError Called if there is an error when compiling a shader.
  75163. */
  75164. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75165. if (defines === void 0) { defines = null; }
  75166. if (uniforms === void 0) { uniforms = null; }
  75167. if (samplers === void 0) { samplers = null; }
  75168. this._updateParameters(onCompiled, onError);
  75169. };
  75170. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75171. // Generate sampling offsets and weights
  75172. var N = this._kernel;
  75173. var centerIndex = (N - 1) / 2;
  75174. // Generate Gaussian sampling weights over kernel
  75175. var offsets = [];
  75176. var weights = [];
  75177. var totalWeight = 0;
  75178. for (var i = 0; i < N; i++) {
  75179. var u = i / (N - 1);
  75180. var w = this._gaussianWeight(u * 2.0 - 1);
  75181. offsets[i] = (i - centerIndex);
  75182. weights[i] = w;
  75183. totalWeight += w;
  75184. }
  75185. // Normalize weights
  75186. for (var i = 0; i < weights.length; i++) {
  75187. weights[i] /= totalWeight;
  75188. }
  75189. // Optimize: combine samples to take advantage of hardware linear sampling
  75190. // Walk from left to center, combining pairs (symmetrically)
  75191. var linearSamplingWeights = [];
  75192. var linearSamplingOffsets = [];
  75193. var linearSamplingMap = [];
  75194. for (var i = 0; i <= centerIndex; i += 2) {
  75195. var j = Math.min(i + 1, Math.floor(centerIndex));
  75196. var singleCenterSample = i === j;
  75197. if (singleCenterSample) {
  75198. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75199. }
  75200. else {
  75201. var sharedCell = j === centerIndex;
  75202. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75203. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75204. if (offsetLinear === 0) {
  75205. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75206. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75207. }
  75208. else {
  75209. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75210. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75211. }
  75212. }
  75213. }
  75214. for (var i = 0; i < linearSamplingMap.length; i++) {
  75215. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75216. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75217. }
  75218. // Replace with optimized
  75219. offsets = linearSamplingOffsets;
  75220. weights = linearSamplingWeights;
  75221. // Generate shaders
  75222. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75223. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75224. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75225. var defines = "";
  75226. defines += this._staticDefines;
  75227. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75228. if (this._staticDefines.indexOf("DOF") != -1) {
  75229. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75230. varyingCount--;
  75231. }
  75232. for (var i = 0; i < varyingCount; i++) {
  75233. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75234. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75235. }
  75236. var depCount = 0;
  75237. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75238. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75239. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75240. depCount++;
  75241. }
  75242. if (this.packedFloat) {
  75243. defines += "#define PACKEDFLOAT 1";
  75244. }
  75245. this.blockCompilation = false;
  75246. _super.prototype.updateEffect.call(this, defines, null, null, {
  75247. varyingCount: varyingCount,
  75248. depCount: depCount
  75249. }, onCompiled, onError);
  75250. };
  75251. /**
  75252. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75253. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75254. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75255. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75256. * The gaps between physical kernels are compensated for in the weighting of the samples
  75257. * @param idealKernel Ideal blur kernel.
  75258. * @return Nearest best kernel.
  75259. */
  75260. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75261. var v = Math.round(idealKernel);
  75262. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75263. var k = _a[_i];
  75264. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75265. return Math.max(k, 3);
  75266. }
  75267. }
  75268. return Math.max(v, 3);
  75269. };
  75270. /**
  75271. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75272. * @param x The point on the Gaussian distribution to sample.
  75273. * @return the value of the Gaussian function at x.
  75274. */
  75275. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75276. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75277. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75278. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75279. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75280. // truncated at around 1.3% of peak strength.
  75281. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75282. var sigma = (1 / 3);
  75283. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75284. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75285. var weight = (1.0 / denominator) * Math.exp(exponent);
  75286. return weight;
  75287. };
  75288. /**
  75289. * Generates a string that can be used as a floating point number in GLSL.
  75290. * @param x Value to print.
  75291. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75292. * @return GLSL float string.
  75293. */
  75294. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75295. if (decimalFigures === void 0) { decimalFigures = 8; }
  75296. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75297. };
  75298. return BlurPostProcess;
  75299. }(BABYLON.PostProcess));
  75300. BABYLON.BlurPostProcess = BlurPostProcess;
  75301. })(BABYLON || (BABYLON = {}));
  75302. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75303. var BABYLON;
  75304. (function (BABYLON) {
  75305. /**
  75306. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75307. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75308. * based on samples that have a large difference in distance than the center pixel.
  75309. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75310. */
  75311. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75312. __extends(DepthOfFieldBlurPostProcess, _super);
  75313. /**
  75314. * Creates a new instance CircleOfConfusionPostProcess
  75315. * @param name The name of the effect.
  75316. * @param scene The scene the effect belongs to.
  75317. * @param direction The direction the blur should be applied.
  75318. * @param kernel The size of the kernel used to blur.
  75319. * @param options The required width/height ratio to downsize to before computing the render pass.
  75320. * @param camera The camera to apply the render pass to.
  75321. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75322. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75323. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75324. * @param engine The engine which the post process will be applied. (default: current engine)
  75325. * @param reusable If the post process can be reused on the same frame. (default: false)
  75326. * @param textureType Type of textures used when performing the post process. (default: 0)
  75327. * @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)
  75328. */
  75329. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75330. if (imageToBlur === void 0) { imageToBlur = null; }
  75331. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75332. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75333. if (blockCompilation === void 0) { blockCompilation = false; }
  75334. 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;
  75335. _this.direction = direction;
  75336. _this.onApplyObservable.add(function (effect) {
  75337. if (imageToBlur != null) {
  75338. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75339. }
  75340. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75341. if (scene.activeCamera) {
  75342. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75343. }
  75344. });
  75345. return _this;
  75346. }
  75347. return DepthOfFieldBlurPostProcess;
  75348. }(BABYLON.BlurPostProcess));
  75349. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75350. })(BABYLON || (BABYLON = {}));
  75351. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75352. var BABYLON;
  75353. (function (BABYLON) {
  75354. /**
  75355. * Options to be set when merging outputs from the default pipeline.
  75356. */
  75357. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75358. function DepthOfFieldMergePostProcessOptions() {
  75359. }
  75360. return DepthOfFieldMergePostProcessOptions;
  75361. }());
  75362. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75363. /**
  75364. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75365. */
  75366. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75367. __extends(DepthOfFieldMergePostProcess, _super);
  75368. /**
  75369. * Creates a new instance of DepthOfFieldMergePostProcess
  75370. * @param name The name of the effect.
  75371. * @param originalFromInput Post process which's input will be used for the merge.
  75372. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75373. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75374. * @param options The required width/height ratio to downsize to before computing the render pass.
  75375. * @param camera The camera to apply the render pass to.
  75376. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75377. * @param engine The engine which the post process will be applied. (default: current engine)
  75378. * @param reusable If the post process can be reused on the same frame. (default: false)
  75379. * @param textureType Type of textures used when performing the post process. (default: 0)
  75380. * @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)
  75381. */
  75382. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75383. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75384. if (blockCompilation === void 0) { blockCompilation = false; }
  75385. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75386. _this.blurSteps = blurSteps;
  75387. _this.onApplyObservable.add(function (effect) {
  75388. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75389. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75390. blurSteps.forEach(function (step, index) {
  75391. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75392. });
  75393. });
  75394. if (!blockCompilation) {
  75395. _this.updateEffect();
  75396. }
  75397. return _this;
  75398. }
  75399. /**
  75400. * Updates the effect with the current post process compile time values and recompiles the shader.
  75401. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75402. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75403. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75404. * @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
  75405. * @param onCompiled Called when the shader has been compiled.
  75406. * @param onError Called if there is an error when compiling a shader.
  75407. */
  75408. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75409. if (defines === void 0) { defines = null; }
  75410. if (uniforms === void 0) { uniforms = null; }
  75411. if (samplers === void 0) { samplers = null; }
  75412. if (!defines) {
  75413. defines = "";
  75414. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75415. }
  75416. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75417. };
  75418. return DepthOfFieldMergePostProcess;
  75419. }(BABYLON.PostProcess));
  75420. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75421. })(BABYLON || (BABYLON = {}));
  75422. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75423. var BABYLON;
  75424. (function (BABYLON) {
  75425. /**
  75426. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75427. */
  75428. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75429. __extends(CircleOfConfusionPostProcess, _super);
  75430. /**
  75431. * Creates a new instance CircleOfConfusionPostProcess
  75432. * @param name The name of the effect.
  75433. * @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.
  75434. * @param options The required width/height ratio to downsize to before computing the render pass.
  75435. * @param camera The camera to apply the render pass to.
  75436. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75437. * @param engine The engine which the post process will be applied. (default: current engine)
  75438. * @param reusable If the post process can be reused on the same frame. (default: false)
  75439. * @param textureType Type of textures used when performing the post process. (default: 0)
  75440. * @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)
  75441. */
  75442. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75443. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75444. if (blockCompilation === void 0) { blockCompilation = false; }
  75445. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75446. /**
  75447. * 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.
  75448. */
  75449. _this.lensSize = 50;
  75450. /**
  75451. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75452. */
  75453. _this.fStop = 1.4;
  75454. /**
  75455. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75456. */
  75457. _this.focusDistance = 2000;
  75458. /**
  75459. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75460. */
  75461. _this.focalLength = 50;
  75462. _this._depthTexture = null;
  75463. _this._depthTexture = depthTexture;
  75464. _this.onApplyObservable.add(function (effect) {
  75465. if (!_this._depthTexture) {
  75466. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75467. return;
  75468. }
  75469. effect.setTexture("depthSampler", _this._depthTexture);
  75470. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75471. var aperture = _this.lensSize / _this.fStop;
  75472. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75473. effect.setFloat('focusDistance', _this.focusDistance);
  75474. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75475. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75476. });
  75477. return _this;
  75478. }
  75479. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75480. /**
  75481. * 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.
  75482. */
  75483. set: function (value) {
  75484. this._depthTexture = value;
  75485. },
  75486. enumerable: true,
  75487. configurable: true
  75488. });
  75489. return CircleOfConfusionPostProcess;
  75490. }(BABYLON.PostProcess));
  75491. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75492. })(BABYLON || (BABYLON = {}));
  75493. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75494. var BABYLON;
  75495. (function (BABYLON) {
  75496. /**
  75497. * Specifies the level of max blur that should be applied when using the depth of field effect
  75498. */
  75499. var DepthOfFieldEffectBlurLevel;
  75500. (function (DepthOfFieldEffectBlurLevel) {
  75501. /**
  75502. * Subtle blur
  75503. */
  75504. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75505. /**
  75506. * Medium blur
  75507. */
  75508. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75509. /**
  75510. * Large blur
  75511. */
  75512. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75513. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75514. ;
  75515. /**
  75516. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75517. */
  75518. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75519. __extends(DepthOfFieldEffect, _super);
  75520. /**
  75521. * Creates a new instance DepthOfFieldEffect
  75522. * @param scene The scene the effect belongs to.
  75523. * @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.
  75524. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75525. * @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)
  75526. */
  75527. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75528. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75529. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75530. if (blockCompilation === void 0) { blockCompilation = false; }
  75531. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75532. return _this._effects;
  75533. }, true) || this;
  75534. /**
  75535. * Internal post processes in depth of field effect
  75536. */
  75537. _this._effects = [];
  75538. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75539. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75540. // 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)
  75541. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75542. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75543. _this._depthOfFieldBlurY = [];
  75544. _this._depthOfFieldBlurX = [];
  75545. var blurCount = 1;
  75546. var kernelSize = 15;
  75547. switch (blurLevel) {
  75548. case DepthOfFieldEffectBlurLevel.High: {
  75549. blurCount = 3;
  75550. kernelSize = 51;
  75551. break;
  75552. }
  75553. case DepthOfFieldEffectBlurLevel.Medium: {
  75554. blurCount = 2;
  75555. kernelSize = 31;
  75556. break;
  75557. }
  75558. default: {
  75559. kernelSize = 15;
  75560. blurCount = 1;
  75561. break;
  75562. }
  75563. }
  75564. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75565. var ratio = 1.0;
  75566. for (var i = 0; i < blurCount; i++) {
  75567. 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);
  75568. blurY.autoClear = false;
  75569. ratio = 0.75 / Math.pow(2, i);
  75570. 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);
  75571. blurX.autoClear = false;
  75572. _this._depthOfFieldBlurY.push(blurY);
  75573. _this._depthOfFieldBlurX.push(blurX);
  75574. }
  75575. // Set all post processes on the effect.
  75576. _this._effects = [_this._circleOfConfusion];
  75577. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75578. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75579. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75580. }
  75581. // Merge blurred images with original image based on circleOfConfusion
  75582. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75583. _this._dofMerge.autoClear = false;
  75584. _this._effects.push(_this._dofMerge);
  75585. return _this;
  75586. }
  75587. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75588. get: function () {
  75589. return this._circleOfConfusion.focalLength;
  75590. },
  75591. /**
  75592. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75593. */
  75594. set: function (value) {
  75595. this._circleOfConfusion.focalLength = value;
  75596. },
  75597. enumerable: true,
  75598. configurable: true
  75599. });
  75600. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75601. get: function () {
  75602. return this._circleOfConfusion.fStop;
  75603. },
  75604. /**
  75605. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75606. */
  75607. set: function (value) {
  75608. this._circleOfConfusion.fStop = value;
  75609. },
  75610. enumerable: true,
  75611. configurable: true
  75612. });
  75613. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75614. get: function () {
  75615. return this._circleOfConfusion.focusDistance;
  75616. },
  75617. /**
  75618. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75619. */
  75620. set: function (value) {
  75621. this._circleOfConfusion.focusDistance = value;
  75622. },
  75623. enumerable: true,
  75624. configurable: true
  75625. });
  75626. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75627. get: function () {
  75628. return this._circleOfConfusion.lensSize;
  75629. },
  75630. /**
  75631. * 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.
  75632. */
  75633. set: function (value) {
  75634. this._circleOfConfusion.lensSize = value;
  75635. },
  75636. enumerable: true,
  75637. configurable: true
  75638. });
  75639. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75640. /**
  75641. * 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.
  75642. */
  75643. set: function (value) {
  75644. this._circleOfConfusion.depthTexture = value;
  75645. },
  75646. enumerable: true,
  75647. configurable: true
  75648. });
  75649. /**
  75650. * Disposes each of the internal effects for a given camera.
  75651. * @param camera The camera to dispose the effect on.
  75652. */
  75653. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75654. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75655. this._effects[effectIndex].dispose(camera);
  75656. }
  75657. };
  75658. /**
  75659. * Internal
  75660. */
  75661. DepthOfFieldEffect.prototype._updateEffects = function () {
  75662. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75663. this._effects[effectIndex].updateEffect();
  75664. }
  75665. };
  75666. /**
  75667. * Internal
  75668. * @returns if all the contained post processes are ready.
  75669. */
  75670. DepthOfFieldEffect.prototype._isReady = function () {
  75671. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75672. if (!this._effects[effectIndex].isReady()) {
  75673. return false;
  75674. }
  75675. }
  75676. return true;
  75677. };
  75678. return DepthOfFieldEffect;
  75679. }(BABYLON.PostProcessRenderEffect));
  75680. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75681. })(BABYLON || (BABYLON = {}));
  75682. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75683. var BABYLON;
  75684. (function (BABYLON) {
  75685. /**
  75686. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75687. */
  75688. var BloomMergePostProcess = /** @class */ (function (_super) {
  75689. __extends(BloomMergePostProcess, _super);
  75690. /**
  75691. * Creates a new instance of @see BloomMergePostProcess
  75692. * @param name The name of the effect.
  75693. * @param originalFromInput Post process which's input will be used for the merge.
  75694. * @param blurred Blurred highlights post process which's output will be used.
  75695. * @param weight Weight of the bloom to be added to the original input.
  75696. * @param options The required width/height ratio to downsize to before computing the render pass.
  75697. * @param camera The camera to apply the render pass to.
  75698. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75699. * @param engine The engine which the post process will be applied. (default: current engine)
  75700. * @param reusable If the post process can be reused on the same frame. (default: false)
  75701. * @param textureType Type of textures used when performing the post process. (default: 0)
  75702. * @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)
  75703. */
  75704. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75705. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75706. if (blockCompilation === void 0) { blockCompilation = false; }
  75707. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75708. _this.weight = weight;
  75709. _this.onApplyObservable.add(function (effect) {
  75710. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75711. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75712. effect.setFloat("bloomWeight", _this.weight);
  75713. });
  75714. if (!blockCompilation) {
  75715. _this.updateEffect();
  75716. }
  75717. return _this;
  75718. }
  75719. return BloomMergePostProcess;
  75720. }(BABYLON.PostProcess));
  75721. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75722. })(BABYLON || (BABYLON = {}));
  75723. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75724. var BABYLON;
  75725. (function (BABYLON) {
  75726. /**
  75727. * 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.
  75728. */
  75729. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75730. __extends(ExtractHighlightsPostProcess, _super);
  75731. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75732. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75733. if (blockCompilation === void 0) { blockCompilation = false; }
  75734. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75735. /**
  75736. * The luminance threshold, pixels below this value will be set to black.
  75737. */
  75738. _this.threshold = 0.9;
  75739. /**
  75740. * Internal
  75741. */
  75742. _this._exposure = 1;
  75743. /**
  75744. * Post process which has the input texture to be used when performing highlight extraction
  75745. */
  75746. _this._inputPostProcess = null;
  75747. _this.onApplyObservable.add(function (effect) {
  75748. if (_this._inputPostProcess) {
  75749. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75750. }
  75751. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75752. effect.setFloat('exposure', _this._exposure);
  75753. });
  75754. return _this;
  75755. }
  75756. return ExtractHighlightsPostProcess;
  75757. }(BABYLON.PostProcess));
  75758. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75759. })(BABYLON || (BABYLON = {}));
  75760. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75761. var BABYLON;
  75762. (function (BABYLON) {
  75763. /**
  75764. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75765. */
  75766. var BloomEffect = /** @class */ (function (_super) {
  75767. __extends(BloomEffect, _super);
  75768. /**
  75769. * Creates a new instance of @see BloomEffect
  75770. * @param scene The scene the effect belongs to.
  75771. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75772. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75773. * @param bloomWeight The the strength of bloom.
  75774. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75775. * @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)
  75776. */
  75777. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75778. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75779. if (blockCompilation === void 0) { blockCompilation = false; }
  75780. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75781. return _this._effects;
  75782. }, true) || this;
  75783. _this.bloomScale = bloomScale;
  75784. /**
  75785. * Internal
  75786. */
  75787. _this._effects = [];
  75788. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75789. _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);
  75790. _this._blurX.alwaysForcePOT = true;
  75791. _this._blurX.autoClear = false;
  75792. _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);
  75793. _this._blurY.alwaysForcePOT = true;
  75794. _this._blurY.autoClear = false;
  75795. _this.kernel = bloomKernel;
  75796. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75797. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75798. _this._merge.autoClear = false;
  75799. _this._effects.push(_this._merge);
  75800. return _this;
  75801. }
  75802. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75803. /**
  75804. * The luminance threshold to find bright areas of the image to bloom.
  75805. */
  75806. get: function () {
  75807. return this._downscale.threshold;
  75808. },
  75809. set: function (value) {
  75810. this._downscale.threshold = value;
  75811. },
  75812. enumerable: true,
  75813. configurable: true
  75814. });
  75815. Object.defineProperty(BloomEffect.prototype, "weight", {
  75816. /**
  75817. * The strength of the bloom.
  75818. */
  75819. get: function () {
  75820. return this._merge.weight;
  75821. },
  75822. set: function (value) {
  75823. this._merge.weight = value;
  75824. },
  75825. enumerable: true,
  75826. configurable: true
  75827. });
  75828. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75829. /**
  75830. * Specifies the size of the bloom blur kernel, relative to the final output size
  75831. */
  75832. get: function () {
  75833. return this._blurX.kernel / this.bloomScale;
  75834. },
  75835. set: function (value) {
  75836. this._blurX.kernel = value * this.bloomScale;
  75837. this._blurY.kernel = value * this.bloomScale;
  75838. },
  75839. enumerable: true,
  75840. configurable: true
  75841. });
  75842. /**
  75843. * Disposes each of the internal effects for a given camera.
  75844. * @param camera The camera to dispose the effect on.
  75845. */
  75846. BloomEffect.prototype.disposeEffects = function (camera) {
  75847. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75848. this._effects[effectIndex].dispose(camera);
  75849. }
  75850. };
  75851. /**
  75852. * Internal
  75853. */
  75854. BloomEffect.prototype._updateEffects = function () {
  75855. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75856. this._effects[effectIndex].updateEffect();
  75857. }
  75858. };
  75859. /**
  75860. * Internal
  75861. * @returns if all the contained post processes are ready.
  75862. */
  75863. BloomEffect.prototype._isReady = function () {
  75864. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75865. if (!this._effects[effectIndex].isReady()) {
  75866. return false;
  75867. }
  75868. }
  75869. return true;
  75870. };
  75871. return BloomEffect;
  75872. }(BABYLON.PostProcessRenderEffect));
  75873. BABYLON.BloomEffect = BloomEffect;
  75874. })(BABYLON || (BABYLON = {}));
  75875. //# sourceMappingURL=babylon.bloomEffect.js.map
  75876. var BABYLON;
  75877. (function (BABYLON) {
  75878. /**
  75879. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75880. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75881. */
  75882. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75883. __extends(DefaultRenderingPipeline, _super);
  75884. /**
  75885. * @constructor
  75886. * @param {string} name - The rendering pipeline name (default: "")
  75887. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  75888. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  75889. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  75890. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  75891. */
  75892. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75893. if (name === void 0) { name = ""; }
  75894. if (hdr === void 0) { hdr = true; }
  75895. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75896. if (automaticBuild === void 0) { automaticBuild = true; }
  75897. var _this = _super.call(this, scene.getEngine(), name) || this;
  75898. _this._originalCameras = [];
  75899. /**
  75900. * ID of the sharpen post process,
  75901. */
  75902. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75903. /**
  75904. * ID of the image processing post process;
  75905. */
  75906. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75907. /**
  75908. * ID of the Fast Approximate Anti-Aliasing post process;
  75909. */
  75910. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75911. /**
  75912. * ID of the chromatic aberration post process,
  75913. */
  75914. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75915. /**
  75916. * ID of the grain post process
  75917. */
  75918. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75919. /**
  75920. * Glow post process which adds a glow to emmisive areas of the image
  75921. */
  75922. _this._glowLayer = null;
  75923. /**
  75924. * Animations which can be used to tweak settings over a period of time
  75925. */
  75926. _this.animations = [];
  75927. _this._imageProcessingConfigurationObserver = null;
  75928. // Values
  75929. _this._sharpenEnabled = false;
  75930. _this._bloomEnabled = false;
  75931. _this._depthOfFieldEnabled = false;
  75932. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75933. _this._fxaaEnabled = false;
  75934. _this._imageProcessingEnabled = true;
  75935. _this._bloomScale = 0.5;
  75936. _this._chromaticAberrationEnabled = false;
  75937. _this._grainEnabled = false;
  75938. _this._buildAllowed = true;
  75939. _this._resizeObserver = null;
  75940. _this._hardwareScaleLevel = 1.0;
  75941. _this._bloomKernel = 64;
  75942. /**
  75943. * Specifies the weight of the bloom in the final rendering
  75944. */
  75945. _this._bloomWeight = 0.15;
  75946. /**
  75947. * Specifies the luma threshold for the area that will be blurred by the bloom
  75948. */
  75949. _this._bloomThreshold = 0.9;
  75950. _this._samples = 1;
  75951. _this._hasCleared = false;
  75952. _this._prevPostProcess = null;
  75953. _this._prevPrevPostProcess = null;
  75954. _this._cameras = cameras || scene.cameras;
  75955. _this._originalCameras = _this._cameras.slice();
  75956. _this._buildAllowed = automaticBuild;
  75957. // Initialize
  75958. _this._scene = scene;
  75959. var caps = _this._scene.getEngine().getCaps();
  75960. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75961. // Misc
  75962. if (_this._hdr) {
  75963. if (caps.textureHalfFloatRender) {
  75964. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75965. }
  75966. else if (caps.textureFloatRender) {
  75967. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75968. }
  75969. }
  75970. else {
  75971. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75972. }
  75973. // Attach
  75974. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75975. var engine = _this._scene.getEngine();
  75976. // Create post processes before hand so they can be modified before enabled.
  75977. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75978. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75979. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75980. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75981. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75982. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75983. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75984. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75985. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75986. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75987. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75988. _this.bloomKernel = _this.bloomKernel;
  75989. });
  75990. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75991. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75992. });
  75993. _this._buildPipeline();
  75994. return _this;
  75995. }
  75996. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75997. get: function () {
  75998. return this._sharpenEnabled;
  75999. },
  76000. /**
  76001. * Enable or disable the sharpen process from the pipeline
  76002. */
  76003. set: function (enabled) {
  76004. if (this._sharpenEnabled === enabled) {
  76005. return;
  76006. }
  76007. this._sharpenEnabled = enabled;
  76008. this._buildPipeline();
  76009. },
  76010. enumerable: true,
  76011. configurable: true
  76012. });
  76013. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76014. /**
  76015. * Specifies the size of the bloom blur kernel, relative to the final output size
  76016. */
  76017. get: function () {
  76018. return this._bloomKernel;
  76019. },
  76020. set: function (value) {
  76021. this._bloomKernel = value;
  76022. this.bloom.kernel = value / this._hardwareScaleLevel;
  76023. },
  76024. enumerable: true,
  76025. configurable: true
  76026. });
  76027. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76028. get: function () {
  76029. return this._bloomWeight;
  76030. },
  76031. /**
  76032. * The strength of the bloom.
  76033. */
  76034. set: function (value) {
  76035. if (this._bloomWeight === value) {
  76036. return;
  76037. }
  76038. this.bloom.weight = value;
  76039. this._bloomWeight = value;
  76040. },
  76041. enumerable: true,
  76042. configurable: true
  76043. });
  76044. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76045. get: function () {
  76046. return this._bloomThreshold;
  76047. },
  76048. /**
  76049. * The strength of the bloom.
  76050. */
  76051. set: function (value) {
  76052. if (this._bloomThreshold === value) {
  76053. return;
  76054. }
  76055. this.bloom.threshold = value;
  76056. this._bloomThreshold = value;
  76057. },
  76058. enumerable: true,
  76059. configurable: true
  76060. });
  76061. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76062. get: function () {
  76063. return this._bloomScale;
  76064. },
  76065. /**
  76066. * The scale of the bloom, lower value will provide better performance.
  76067. */
  76068. set: function (value) {
  76069. if (this._bloomScale === value) {
  76070. return;
  76071. }
  76072. this._bloomScale = value;
  76073. // recreate bloom and dispose old as this setting is not dynamic
  76074. this._rebuildBloom();
  76075. this._buildPipeline();
  76076. },
  76077. enumerable: true,
  76078. configurable: true
  76079. });
  76080. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76081. get: function () {
  76082. return this._bloomEnabled;
  76083. },
  76084. /**
  76085. * Enable or disable the bloom from the pipeline
  76086. */
  76087. set: function (enabled) {
  76088. if (this._bloomEnabled === enabled) {
  76089. return;
  76090. }
  76091. this._bloomEnabled = enabled;
  76092. this._buildPipeline();
  76093. },
  76094. enumerable: true,
  76095. configurable: true
  76096. });
  76097. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76098. // recreate bloom and dispose old as this setting is not dynamic
  76099. var oldBloom = this.bloom;
  76100. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76101. this.bloom.threshold = oldBloom.threshold;
  76102. for (var i = 0; i < this._cameras.length; i++) {
  76103. oldBloom.disposeEffects(this._cameras[i]);
  76104. }
  76105. };
  76106. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76107. /**
  76108. * If the depth of field is enabled.
  76109. */
  76110. get: function () {
  76111. return this._depthOfFieldEnabled;
  76112. },
  76113. set: function (enabled) {
  76114. if (this._depthOfFieldEnabled === enabled) {
  76115. return;
  76116. }
  76117. this._depthOfFieldEnabled = enabled;
  76118. this._buildPipeline();
  76119. },
  76120. enumerable: true,
  76121. configurable: true
  76122. });
  76123. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76124. /**
  76125. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76126. */
  76127. get: function () {
  76128. return this._depthOfFieldBlurLevel;
  76129. },
  76130. set: function (value) {
  76131. if (this._depthOfFieldBlurLevel === value) {
  76132. return;
  76133. }
  76134. this._depthOfFieldBlurLevel = value;
  76135. // recreate dof and dispose old as this setting is not dynamic
  76136. var oldDof = this.depthOfField;
  76137. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76138. this.depthOfField.focalLength = oldDof.focalLength;
  76139. this.depthOfField.focusDistance = oldDof.focusDistance;
  76140. this.depthOfField.fStop = oldDof.fStop;
  76141. this.depthOfField.lensSize = oldDof.lensSize;
  76142. for (var i = 0; i < this._cameras.length; i++) {
  76143. oldDof.disposeEffects(this._cameras[i]);
  76144. }
  76145. this._buildPipeline();
  76146. },
  76147. enumerable: true,
  76148. configurable: true
  76149. });
  76150. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76151. get: function () {
  76152. return this._fxaaEnabled;
  76153. },
  76154. /**
  76155. * If the anti aliasing is enabled.
  76156. */
  76157. set: function (enabled) {
  76158. if (this._fxaaEnabled === enabled) {
  76159. return;
  76160. }
  76161. this._fxaaEnabled = enabled;
  76162. this._buildPipeline();
  76163. },
  76164. enumerable: true,
  76165. configurable: true
  76166. });
  76167. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76168. get: function () {
  76169. return this._samples;
  76170. },
  76171. /**
  76172. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76173. */
  76174. set: function (sampleCount) {
  76175. if (this._samples === sampleCount) {
  76176. return;
  76177. }
  76178. this._samples = sampleCount;
  76179. this._buildPipeline();
  76180. },
  76181. enumerable: true,
  76182. configurable: true
  76183. });
  76184. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76185. get: function () {
  76186. return this._imageProcessingEnabled;
  76187. },
  76188. /**
  76189. * If image processing is enabled.
  76190. */
  76191. set: function (enabled) {
  76192. if (this._imageProcessingEnabled === enabled) {
  76193. return;
  76194. }
  76195. this._imageProcessingEnabled = enabled;
  76196. this._buildPipeline();
  76197. },
  76198. enumerable: true,
  76199. configurable: true
  76200. });
  76201. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76202. get: function () {
  76203. return this._glowLayer == null;
  76204. },
  76205. /**
  76206. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76207. */
  76208. set: function (enabled) {
  76209. if (enabled && !this._glowLayer) {
  76210. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76211. }
  76212. else if (!enabled && this._glowLayer) {
  76213. this._glowLayer.dispose();
  76214. this._glowLayer = null;
  76215. }
  76216. },
  76217. enumerable: true,
  76218. configurable: true
  76219. });
  76220. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76221. get: function () {
  76222. return this._chromaticAberrationEnabled;
  76223. },
  76224. /**
  76225. * Enable or disable the chromaticAberration process from the pipeline
  76226. */
  76227. set: function (enabled) {
  76228. if (this._chromaticAberrationEnabled === enabled) {
  76229. return;
  76230. }
  76231. this._chromaticAberrationEnabled = enabled;
  76232. this._buildPipeline();
  76233. },
  76234. enumerable: true,
  76235. configurable: true
  76236. });
  76237. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76238. get: function () {
  76239. return this._grainEnabled;
  76240. },
  76241. /**
  76242. * Enable or disable the grain process from the pipeline
  76243. */
  76244. set: function (enabled) {
  76245. if (this._grainEnabled === enabled) {
  76246. return;
  76247. }
  76248. this._grainEnabled = enabled;
  76249. this._buildPipeline();
  76250. },
  76251. enumerable: true,
  76252. configurable: true
  76253. });
  76254. /**
  76255. * Force the compilation of the entire pipeline.
  76256. */
  76257. DefaultRenderingPipeline.prototype.prepare = function () {
  76258. var previousState = this._buildAllowed;
  76259. this._buildAllowed = true;
  76260. this._buildPipeline();
  76261. this._buildAllowed = previousState;
  76262. };
  76263. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76264. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76265. if (this._hasCleared) {
  76266. postProcess.autoClear = false;
  76267. }
  76268. else {
  76269. postProcess.autoClear = true;
  76270. this._scene.autoClear = false;
  76271. this._hasCleared = true;
  76272. }
  76273. if (!skipTextureSharing) {
  76274. if (this._prevPrevPostProcess) {
  76275. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76276. }
  76277. else {
  76278. postProcess.useOwnOutput();
  76279. }
  76280. if (this._prevPostProcess) {
  76281. this._prevPrevPostProcess = this._prevPostProcess;
  76282. }
  76283. this._prevPostProcess = postProcess;
  76284. }
  76285. };
  76286. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76287. var _this = this;
  76288. if (!this._buildAllowed) {
  76289. return;
  76290. }
  76291. this._scene.autoClear = true;
  76292. var engine = this._scene.getEngine();
  76293. this._disposePostProcesses();
  76294. if (this._cameras !== null) {
  76295. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76296. // get back cameras to be used to reattach pipeline
  76297. this._cameras = this._originalCameras.slice();
  76298. }
  76299. this._reset();
  76300. this._prevPostProcess = null;
  76301. this._prevPrevPostProcess = null;
  76302. this._hasCleared = false;
  76303. if (this.depthOfFieldEnabled) {
  76304. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76305. this.depthOfField.depthTexture = depthTexture;
  76306. if (!this.depthOfField._isReady()) {
  76307. this.depthOfField._updateEffects();
  76308. }
  76309. this.addEffect(this.depthOfField);
  76310. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76311. }
  76312. if (this.bloomEnabled) {
  76313. if (!this.bloom._isReady()) {
  76314. this.bloom._updateEffects();
  76315. }
  76316. this.addEffect(this.bloom);
  76317. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76318. }
  76319. if (this._imageProcessingEnabled) {
  76320. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76321. if (this._hdr) {
  76322. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76323. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76324. }
  76325. else {
  76326. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76327. }
  76328. }
  76329. if (this.sharpenEnabled) {
  76330. if (!this.sharpen.isReady()) {
  76331. this.sharpen.updateEffect();
  76332. }
  76333. this.addEffect(this._sharpenEffect);
  76334. this._setAutoClearAndTextureSharing(this.sharpen);
  76335. }
  76336. if (this.grainEnabled) {
  76337. if (!this.grain.isReady()) {
  76338. this.grain.updateEffect();
  76339. }
  76340. this.addEffect(this._grainEffect);
  76341. this._setAutoClearAndTextureSharing(this.grain);
  76342. }
  76343. if (this.chromaticAberrationEnabled) {
  76344. if (!this.chromaticAberration.isReady()) {
  76345. this.chromaticAberration.updateEffect();
  76346. }
  76347. this.addEffect(this._chromaticAberrationEffect);
  76348. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76349. }
  76350. if (this.fxaaEnabled) {
  76351. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76352. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76353. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76354. }
  76355. if (this._cameras !== null) {
  76356. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76357. }
  76358. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76359. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76360. }
  76361. };
  76362. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76363. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76364. for (var i = 0; i < this._cameras.length; i++) {
  76365. var camera = this._cameras[i];
  76366. if (this.imageProcessing) {
  76367. this.imageProcessing.dispose(camera);
  76368. }
  76369. if (this.fxaa) {
  76370. this.fxaa.dispose(camera);
  76371. }
  76372. // These are created in the constructor and should not be disposed on every pipeline change
  76373. if (disposeNonRecreated) {
  76374. if (this.sharpen) {
  76375. this.sharpen.dispose(camera);
  76376. }
  76377. if (this.depthOfField) {
  76378. this.depthOfField.disposeEffects(camera);
  76379. }
  76380. if (this.bloom) {
  76381. this.bloom.disposeEffects(camera);
  76382. }
  76383. if (this.chromaticAberration) {
  76384. this.chromaticAberration.dispose(camera);
  76385. }
  76386. if (this.grain) {
  76387. this.grain.dispose(camera);
  76388. }
  76389. if (this._glowLayer) {
  76390. this._glowLayer.dispose();
  76391. }
  76392. }
  76393. }
  76394. this.imageProcessing = null;
  76395. this.fxaa = null;
  76396. if (disposeNonRecreated) {
  76397. this.sharpen = null;
  76398. this._sharpenEffect = null;
  76399. this.depthOfField = null;
  76400. this.bloom = null;
  76401. this.chromaticAberration = null;
  76402. this._chromaticAberrationEffect = null;
  76403. this.grain = null;
  76404. this._grainEffect = null;
  76405. this._glowLayer = null;
  76406. }
  76407. };
  76408. /**
  76409. * Dispose of the pipeline and stop all post processes
  76410. */
  76411. DefaultRenderingPipeline.prototype.dispose = function () {
  76412. this._disposePostProcesses(true);
  76413. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76414. this._scene.autoClear = true;
  76415. if (this._resizeObserver) {
  76416. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76417. this._resizeObserver = null;
  76418. }
  76419. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76420. _super.prototype.dispose.call(this);
  76421. };
  76422. /**
  76423. * Serialize the rendering pipeline (Used when exporting)
  76424. * @returns the serialized object
  76425. */
  76426. DefaultRenderingPipeline.prototype.serialize = function () {
  76427. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76428. serializationObject.customType = "DefaultRenderingPipeline";
  76429. return serializationObject;
  76430. };
  76431. /**
  76432. * Parse the serialized pipeline
  76433. * @param source Source pipeline.
  76434. * @param scene The scene to load the pipeline to.
  76435. * @param rootUrl The URL of the serialized pipeline.
  76436. * @returns An instantiated pipeline from the serialized object.
  76437. */
  76438. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76439. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76440. };
  76441. __decorate([
  76442. BABYLON.serialize()
  76443. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76444. __decorate([
  76445. BABYLON.serialize()
  76446. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76447. __decorate([
  76448. BABYLON.serialize()
  76449. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76450. __decorate([
  76451. BABYLON.serialize()
  76452. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76453. __decorate([
  76454. BABYLON.serialize()
  76455. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76456. __decorate([
  76457. BABYLON.serialize()
  76458. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76459. __decorate([
  76460. BABYLON.serialize()
  76461. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76462. __decorate([
  76463. BABYLON.serialize()
  76464. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76465. __decorate([
  76466. BABYLON.serialize()
  76467. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76468. __decorate([
  76469. BABYLON.serialize()
  76470. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76471. __decorate([
  76472. BABYLON.serialize()
  76473. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76474. __decorate([
  76475. BABYLON.serialize()
  76476. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76477. __decorate([
  76478. BABYLON.serialize()
  76479. ], DefaultRenderingPipeline.prototype, "samples", null);
  76480. __decorate([
  76481. BABYLON.serialize()
  76482. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76483. __decorate([
  76484. BABYLON.serialize()
  76485. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76486. __decorate([
  76487. BABYLON.serialize()
  76488. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76489. __decorate([
  76490. BABYLON.serialize()
  76491. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76492. return DefaultRenderingPipeline;
  76493. }(BABYLON.PostProcessRenderPipeline));
  76494. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76495. })(BABYLON || (BABYLON = {}));
  76496. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76497. var BABYLON;
  76498. (function (BABYLON) {
  76499. /**
  76500. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76501. */
  76502. var GeometryBufferRenderer = /** @class */ (function () {
  76503. /**
  76504. * Creates a new G Buffer for the scene
  76505. * @param scene The scene the buffer belongs to
  76506. * @param ratio How big is the buffer related to the main canvas.
  76507. */
  76508. function GeometryBufferRenderer(scene, ratio) {
  76509. if (ratio === void 0) { ratio = 1; }
  76510. this._enablePosition = false;
  76511. this._scene = scene;
  76512. this._ratio = ratio;
  76513. // Render target
  76514. this._createRenderTargets();
  76515. }
  76516. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76517. /**
  76518. * Set the render list (meshes to be rendered) used in the G buffer.
  76519. */
  76520. set: function (meshes) {
  76521. this._multiRenderTarget.renderList = meshes;
  76522. },
  76523. enumerable: true,
  76524. configurable: true
  76525. });
  76526. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76527. /**
  76528. * Gets wether or not G buffer are supported by the running hardware.
  76529. * This requires draw buffer supports
  76530. */
  76531. get: function () {
  76532. return this._multiRenderTarget.isSupported;
  76533. },
  76534. enumerable: true,
  76535. configurable: true
  76536. });
  76537. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76538. /**
  76539. * Gets wether or not position are enabled for the G buffer.
  76540. */
  76541. get: function () {
  76542. return this._enablePosition;
  76543. },
  76544. /**
  76545. * Sets wether or not position are enabled for the G buffer.
  76546. */
  76547. set: function (enable) {
  76548. this._enablePosition = enable;
  76549. this.dispose();
  76550. this._createRenderTargets();
  76551. },
  76552. enumerable: true,
  76553. configurable: true
  76554. });
  76555. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76556. /**
  76557. * Gets the scene associated with the buffer.
  76558. */
  76559. get: function () {
  76560. return this._scene;
  76561. },
  76562. enumerable: true,
  76563. configurable: true
  76564. });
  76565. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76566. /**
  76567. * Gets the ratio used by the buffer during its creation.
  76568. * How big is the buffer related to the main canvas.
  76569. */
  76570. get: function () {
  76571. return this._ratio;
  76572. },
  76573. enumerable: true,
  76574. configurable: true
  76575. });
  76576. /**
  76577. * Checks wether everything is ready to render a submesh to the G buffer.
  76578. * @param subMesh the submesh to check readiness for
  76579. * @param useInstances is the mesh drawn using instance or not
  76580. * @returns true if ready otherwise false
  76581. */
  76582. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76583. var material = subMesh.getMaterial();
  76584. if (material && material.disableDepthWrite) {
  76585. return false;
  76586. }
  76587. var defines = [];
  76588. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76589. var mesh = subMesh.getMesh();
  76590. // Alpha test
  76591. if (material && material.needAlphaTesting()) {
  76592. defines.push("#define ALPHATEST");
  76593. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76594. attribs.push(BABYLON.VertexBuffer.UVKind);
  76595. defines.push("#define UV1");
  76596. }
  76597. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76598. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76599. defines.push("#define UV2");
  76600. }
  76601. }
  76602. // Buffers
  76603. if (this._enablePosition) {
  76604. defines.push("#define POSITION");
  76605. }
  76606. // Bones
  76607. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76608. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76609. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76610. if (mesh.numBoneInfluencers > 4) {
  76611. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76612. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76613. }
  76614. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76615. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76616. }
  76617. else {
  76618. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76619. }
  76620. // Instances
  76621. if (useInstances) {
  76622. defines.push("#define INSTANCES");
  76623. attribs.push("world0");
  76624. attribs.push("world1");
  76625. attribs.push("world2");
  76626. attribs.push("world3");
  76627. }
  76628. // Get correct effect
  76629. var join = defines.join("\n");
  76630. if (this._cachedDefines !== join) {
  76631. this._cachedDefines = join;
  76632. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76633. }
  76634. return this._effect.isReady();
  76635. };
  76636. /**
  76637. * Gets the current underlying G Buffer.
  76638. * @returns the buffer
  76639. */
  76640. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76641. return this._multiRenderTarget;
  76642. };
  76643. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76644. /**
  76645. * Gets the number of samples used to render the buffer (anti aliasing).
  76646. */
  76647. get: function () {
  76648. return this._multiRenderTarget.samples;
  76649. },
  76650. /**
  76651. * Sets the number of samples used to render the buffer (anti aliasing).
  76652. */
  76653. set: function (value) {
  76654. this._multiRenderTarget.samples = value;
  76655. },
  76656. enumerable: true,
  76657. configurable: true
  76658. });
  76659. /**
  76660. * Disposes the renderer and frees up associated resources.
  76661. */
  76662. GeometryBufferRenderer.prototype.dispose = function () {
  76663. this.getGBuffer().dispose();
  76664. };
  76665. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76666. var _this = this;
  76667. var engine = this._scene.getEngine();
  76668. var count = this._enablePosition ? 3 : 2;
  76669. 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 });
  76670. if (!this.isSupported) {
  76671. return;
  76672. }
  76673. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76674. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76675. this._multiRenderTarget.refreshRate = 1;
  76676. this._multiRenderTarget.renderParticles = false;
  76677. this._multiRenderTarget.renderList = null;
  76678. // set default depth value to 1.0 (far away)
  76679. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76680. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76681. });
  76682. // Custom render function
  76683. var renderSubMesh = function (subMesh) {
  76684. var mesh = subMesh.getRenderingMesh();
  76685. var scene = _this._scene;
  76686. var engine = scene.getEngine();
  76687. var material = subMesh.getMaterial();
  76688. if (!material) {
  76689. return;
  76690. }
  76691. // Culling
  76692. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76693. // Managing instances
  76694. var batch = mesh._getInstancesRenderList(subMesh._id);
  76695. if (batch.mustReturn) {
  76696. return;
  76697. }
  76698. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76699. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76700. engine.enableEffect(_this._effect);
  76701. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76702. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76703. _this._effect.setMatrix("view", scene.getViewMatrix());
  76704. // Alpha test
  76705. if (material && material.needAlphaTesting()) {
  76706. var alphaTexture = material.getAlphaTestTexture();
  76707. if (alphaTexture) {
  76708. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76709. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76710. }
  76711. }
  76712. // Bones
  76713. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76714. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76715. }
  76716. // Draw
  76717. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76718. }
  76719. };
  76720. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76721. var index;
  76722. if (depthOnlySubMeshes.length) {
  76723. engine.setColorWrite(false);
  76724. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76725. renderSubMesh(depthOnlySubMeshes.data[index]);
  76726. }
  76727. engine.setColorWrite(true);
  76728. }
  76729. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76730. renderSubMesh(opaqueSubMeshes.data[index]);
  76731. }
  76732. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76733. renderSubMesh(alphaTestSubMeshes.data[index]);
  76734. }
  76735. };
  76736. };
  76737. return GeometryBufferRenderer;
  76738. }());
  76739. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76740. })(BABYLON || (BABYLON = {}));
  76741. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76742. var BABYLON;
  76743. (function (BABYLON) {
  76744. var RefractionPostProcess = /** @class */ (function (_super) {
  76745. __extends(RefractionPostProcess, _super);
  76746. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76747. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76748. _this.color = color;
  76749. _this.depth = depth;
  76750. _this.colorLevel = colorLevel;
  76751. _this._ownRefractionTexture = true;
  76752. _this.onActivateObservable.add(function (cam) {
  76753. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76754. });
  76755. _this.onApplyObservable.add(function (effect) {
  76756. effect.setColor3("baseColor", _this.color);
  76757. effect.setFloat("depth", _this.depth);
  76758. effect.setFloat("colorLevel", _this.colorLevel);
  76759. effect.setTexture("refractionSampler", _this._refTexture);
  76760. });
  76761. return _this;
  76762. }
  76763. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76764. /**
  76765. * Gets or sets the refraction texture
  76766. * Please note that you are responsible for disposing the texture if you set it manually
  76767. */
  76768. get: function () {
  76769. return this._refTexture;
  76770. },
  76771. set: function (value) {
  76772. if (this._refTexture && this._ownRefractionTexture) {
  76773. this._refTexture.dispose();
  76774. }
  76775. this._refTexture = value;
  76776. this._ownRefractionTexture = false;
  76777. },
  76778. enumerable: true,
  76779. configurable: true
  76780. });
  76781. // Methods
  76782. RefractionPostProcess.prototype.dispose = function (camera) {
  76783. if (this._refTexture && this._ownRefractionTexture) {
  76784. this._refTexture.dispose();
  76785. this._refTexture = null;
  76786. }
  76787. _super.prototype.dispose.call(this, camera);
  76788. };
  76789. return RefractionPostProcess;
  76790. }(BABYLON.PostProcess));
  76791. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76792. })(BABYLON || (BABYLON = {}));
  76793. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76794. var BABYLON;
  76795. (function (BABYLON) {
  76796. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76797. __extends(BlackAndWhitePostProcess, _super);
  76798. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76799. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76800. _this.degree = 1;
  76801. _this.onApplyObservable.add(function (effect) {
  76802. effect.setFloat("degree", _this.degree);
  76803. });
  76804. return _this;
  76805. }
  76806. return BlackAndWhitePostProcess;
  76807. }(BABYLON.PostProcess));
  76808. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76809. })(BABYLON || (BABYLON = {}));
  76810. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76811. var BABYLON;
  76812. (function (BABYLON) {
  76813. /**
  76814. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76815. * input texture to perform effects such as edge detection or sharpening
  76816. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76817. */
  76818. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76819. __extends(ConvolutionPostProcess, _super);
  76820. /**
  76821. * Creates a new instance ConvolutionPostProcess
  76822. * @param name The name of the effect.
  76823. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76824. * @param options The required width/height ratio to downsize to before computing the render pass.
  76825. * @param camera The camera to apply the render pass to.
  76826. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76827. * @param engine The engine which the post process will be applied. (default: current engine)
  76828. * @param reusable If the post process can be reused on the same frame. (default: false)
  76829. * @param textureType Type of textures used when performing the post process. (default: 0)
  76830. */
  76831. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76832. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76833. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76834. _this.kernel = kernel;
  76835. _this.onApply = function (effect) {
  76836. effect.setFloat2("screenSize", _this.width, _this.height);
  76837. effect.setArray("kernel", _this.kernel);
  76838. };
  76839. return _this;
  76840. }
  76841. // Statics
  76842. /**
  76843. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76844. */
  76845. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  76846. /**
  76847. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76848. */
  76849. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  76850. /**
  76851. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76852. */
  76853. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  76854. /**
  76855. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76856. */
  76857. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  76858. /**
  76859. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76860. */
  76861. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  76862. /**
  76863. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76864. */
  76865. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  76866. return ConvolutionPostProcess;
  76867. }(BABYLON.PostProcess));
  76868. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  76869. })(BABYLON || (BABYLON = {}));
  76870. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  76871. var BABYLON;
  76872. (function (BABYLON) {
  76873. var FilterPostProcess = /** @class */ (function (_super) {
  76874. __extends(FilterPostProcess, _super);
  76875. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  76876. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  76877. _this.kernelMatrix = kernelMatrix;
  76878. _this.onApply = function (effect) {
  76879. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  76880. };
  76881. return _this;
  76882. }
  76883. return FilterPostProcess;
  76884. }(BABYLON.PostProcess));
  76885. BABYLON.FilterPostProcess = FilterPostProcess;
  76886. })(BABYLON || (BABYLON = {}));
  76887. //# sourceMappingURL=babylon.filterPostProcess.js.map
  76888. var BABYLON;
  76889. (function (BABYLON) {
  76890. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  76891. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  76892. __extends(VolumetricLightScatteringPostProcess, _super);
  76893. /**
  76894. * @constructor
  76895. * @param {string} name - The post-process name
  76896. * @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)
  76897. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  76898. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  76899. * @param {number} samples - The post-process quality, default 100
  76900. * @param {number} samplingMode - The post-process filtering mode
  76901. * @param {BABYLON.Engine} engine - The babylon engine
  76902. * @param {boolean} reusable - If the post-process is reusable
  76903. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  76904. */
  76905. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  76906. if (samples === void 0) { samples = 100; }
  76907. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76908. 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;
  76909. _this._screenCoordinates = BABYLON.Vector2.Zero();
  76910. /**
  76911. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  76912. */
  76913. _this.customMeshPosition = BABYLON.Vector3.Zero();
  76914. /**
  76915. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  76916. */
  76917. _this.useCustomMeshPosition = false;
  76918. /**
  76919. * If the post-process should inverse the light scattering direction
  76920. */
  76921. _this.invert = true;
  76922. /**
  76923. * Array containing the excluded meshes not rendered in the internal pass
  76924. */
  76925. _this.excludedMeshes = new Array();
  76926. /**
  76927. * Controls the overall intensity of the post-process
  76928. */
  76929. _this.exposure = 0.3;
  76930. /**
  76931. * Dissipates each sample's contribution in range [0, 1]
  76932. */
  76933. _this.decay = 0.96815;
  76934. /**
  76935. * Controls the overall intensity of each sample
  76936. */
  76937. _this.weight = 0.58767;
  76938. /**
  76939. * Controls the density of each sample
  76940. */
  76941. _this.density = 0.926;
  76942. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  76943. engine = scene.getEngine();
  76944. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  76945. // Configure mesh
  76946. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  76947. // Configure
  76948. _this._createPass(scene, ratio.passRatio || ratio);
  76949. _this.onActivate = function (camera) {
  76950. if (!_this.isSupported) {
  76951. _this.dispose(camera);
  76952. }
  76953. _this.onActivate = null;
  76954. };
  76955. _this.onApplyObservable.add(function (effect) {
  76956. _this._updateMeshScreenCoordinates(scene);
  76957. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  76958. effect.setFloat("exposure", _this.exposure);
  76959. effect.setFloat("decay", _this.decay);
  76960. effect.setFloat("weight", _this.weight);
  76961. effect.setFloat("density", _this.density);
  76962. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  76963. });
  76964. return _this;
  76965. }
  76966. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  76967. get: function () {
  76968. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76969. return false;
  76970. },
  76971. set: function (useDiffuseColor) {
  76972. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76973. },
  76974. enumerable: true,
  76975. configurable: true
  76976. });
  76977. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  76978. return "VolumetricLightScatteringPostProcess";
  76979. };
  76980. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  76981. var mesh = subMesh.getMesh();
  76982. // Render this.mesh as default
  76983. if (mesh === this.mesh && mesh.material) {
  76984. return mesh.material.isReady(mesh);
  76985. }
  76986. var defines = [];
  76987. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76988. var material = subMesh.getMaterial();
  76989. // Alpha test
  76990. if (material) {
  76991. if (material.needAlphaTesting()) {
  76992. defines.push("#define ALPHATEST");
  76993. }
  76994. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76995. attribs.push(BABYLON.VertexBuffer.UVKind);
  76996. defines.push("#define UV1");
  76997. }
  76998. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76999. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77000. defines.push("#define UV2");
  77001. }
  77002. }
  77003. // Bones
  77004. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77005. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77006. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77007. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77008. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77009. }
  77010. else {
  77011. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77012. }
  77013. // Instances
  77014. if (useInstances) {
  77015. defines.push("#define INSTANCES");
  77016. attribs.push("world0");
  77017. attribs.push("world1");
  77018. attribs.push("world2");
  77019. attribs.push("world3");
  77020. }
  77021. // Get correct effect
  77022. var join = defines.join("\n");
  77023. if (this._cachedDefines !== join) {
  77024. this._cachedDefines = join;
  77025. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  77026. }
  77027. return this._volumetricLightScatteringPass.isReady();
  77028. };
  77029. /**
  77030. * Sets the new light position for light scattering effect
  77031. * @param {BABYLON.Vector3} The new custom light position
  77032. */
  77033. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  77034. this.customMeshPosition = position;
  77035. };
  77036. /**
  77037. * Returns the light position for light scattering effect
  77038. * @return {BABYLON.Vector3} The custom light position
  77039. */
  77040. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  77041. return this.customMeshPosition;
  77042. };
  77043. /**
  77044. * Disposes the internal assets and detaches the post-process from the camera
  77045. */
  77046. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  77047. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  77048. if (rttIndex !== -1) {
  77049. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  77050. }
  77051. this._volumetricLightScatteringRTT.dispose();
  77052. _super.prototype.dispose.call(this, camera);
  77053. };
  77054. /**
  77055. * Returns the render target texture used by the post-process
  77056. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  77057. */
  77058. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  77059. return this._volumetricLightScatteringRTT;
  77060. };
  77061. // Private methods
  77062. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  77063. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  77064. return true;
  77065. }
  77066. return false;
  77067. };
  77068. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  77069. var _this = this;
  77070. var engine = scene.getEngine();
  77071. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77072. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77073. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77074. this._volumetricLightScatteringRTT.renderList = null;
  77075. this._volumetricLightScatteringRTT.renderParticles = false;
  77076. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  77077. var camera = this.getCamera();
  77078. if (camera) {
  77079. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77080. }
  77081. else {
  77082. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77083. }
  77084. // Custom render function for submeshes
  77085. var renderSubMesh = function (subMesh) {
  77086. var mesh = subMesh.getRenderingMesh();
  77087. if (_this._meshExcluded(mesh)) {
  77088. return;
  77089. }
  77090. var material = subMesh.getMaterial();
  77091. if (!material) {
  77092. return;
  77093. }
  77094. var scene = mesh.getScene();
  77095. var engine = scene.getEngine();
  77096. // Culling
  77097. engine.setState(material.backFaceCulling);
  77098. // Managing instances
  77099. var batch = mesh._getInstancesRenderList(subMesh._id);
  77100. if (batch.mustReturn) {
  77101. return;
  77102. }
  77103. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77104. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  77105. var effect = _this._volumetricLightScatteringPass;
  77106. if (mesh === _this.mesh) {
  77107. if (subMesh.effect) {
  77108. effect = subMesh.effect;
  77109. }
  77110. else {
  77111. effect = material.getEffect();
  77112. }
  77113. }
  77114. engine.enableEffect(effect);
  77115. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  77116. if (mesh === _this.mesh) {
  77117. material.bind(mesh.getWorldMatrix(), mesh);
  77118. }
  77119. else {
  77120. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  77121. // Alpha test
  77122. if (material && material.needAlphaTesting()) {
  77123. var alphaTexture = material.getAlphaTestTexture();
  77124. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  77125. if (alphaTexture) {
  77126. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77127. }
  77128. }
  77129. // Bones
  77130. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77131. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77132. }
  77133. }
  77134. // Draw
  77135. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  77136. }
  77137. };
  77138. // Render target texture callbacks
  77139. var savedSceneClearColor;
  77140. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  77141. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  77142. savedSceneClearColor = scene.clearColor;
  77143. scene.clearColor = sceneClearColor;
  77144. });
  77145. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  77146. scene.clearColor = savedSceneClearColor;
  77147. });
  77148. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77149. var engine = scene.getEngine();
  77150. var index;
  77151. if (depthOnlySubMeshes.length) {
  77152. engine.setColorWrite(false);
  77153. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77154. renderSubMesh(depthOnlySubMeshes.data[index]);
  77155. }
  77156. engine.setColorWrite(true);
  77157. }
  77158. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77159. renderSubMesh(opaqueSubMeshes.data[index]);
  77160. }
  77161. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77162. renderSubMesh(alphaTestSubMeshes.data[index]);
  77163. }
  77164. if (transparentSubMeshes.length) {
  77165. // Sort sub meshes
  77166. for (index = 0; index < transparentSubMeshes.length; index++) {
  77167. var submesh = transparentSubMeshes.data[index];
  77168. var boundingInfo = submesh.getBoundingInfo();
  77169. if (boundingInfo && scene.activeCamera) {
  77170. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  77171. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  77172. }
  77173. }
  77174. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  77175. sortedArray.sort(function (a, b) {
  77176. // Alpha index first
  77177. if (a._alphaIndex > b._alphaIndex) {
  77178. return 1;
  77179. }
  77180. if (a._alphaIndex < b._alphaIndex) {
  77181. return -1;
  77182. }
  77183. // Then distance to camera
  77184. if (a._distanceToCamera < b._distanceToCamera) {
  77185. return 1;
  77186. }
  77187. if (a._distanceToCamera > b._distanceToCamera) {
  77188. return -1;
  77189. }
  77190. return 0;
  77191. });
  77192. // Render sub meshes
  77193. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  77194. for (index = 0; index < sortedArray.length; index++) {
  77195. renderSubMesh(sortedArray[index]);
  77196. }
  77197. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77198. }
  77199. };
  77200. };
  77201. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  77202. var transform = scene.getTransformMatrix();
  77203. var meshPosition;
  77204. if (this.useCustomMeshPosition) {
  77205. meshPosition = this.customMeshPosition;
  77206. }
  77207. else if (this.attachedNode) {
  77208. meshPosition = this.attachedNode.position;
  77209. }
  77210. else {
  77211. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  77212. }
  77213. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  77214. this._screenCoordinates.x = pos.x / this._viewPort.width;
  77215. this._screenCoordinates.y = pos.y / this._viewPort.height;
  77216. if (this.invert)
  77217. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  77218. };
  77219. // Static methods
  77220. /**
  77221. * Creates a default mesh for the Volumeric Light Scattering post-process
  77222. * @param {string} The mesh name
  77223. * @param {BABYLON.Scene} The scene where to create the mesh
  77224. * @return {BABYLON.Mesh} the default mesh
  77225. */
  77226. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  77227. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  77228. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  77229. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  77230. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  77231. mesh.material = material;
  77232. return mesh;
  77233. };
  77234. __decorate([
  77235. BABYLON.serializeAsVector3()
  77236. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  77237. __decorate([
  77238. BABYLON.serialize()
  77239. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  77240. __decorate([
  77241. BABYLON.serialize()
  77242. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  77243. __decorate([
  77244. BABYLON.serializeAsMeshReference()
  77245. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  77246. __decorate([
  77247. BABYLON.serialize()
  77248. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  77249. __decorate([
  77250. BABYLON.serialize()
  77251. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  77252. __decorate([
  77253. BABYLON.serialize()
  77254. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  77255. __decorate([
  77256. BABYLON.serialize()
  77257. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  77258. __decorate([
  77259. BABYLON.serialize()
  77260. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  77261. return VolumetricLightScatteringPostProcess;
  77262. }(BABYLON.PostProcess));
  77263. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  77264. })(BABYLON || (BABYLON = {}));
  77265. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  77266. //
  77267. // This post-process allows the modification of rendered colors by using
  77268. // a 'look-up table' (LUT). This effect is also called Color Grading.
  77269. //
  77270. // The object needs to be provided an url to a texture containing the color
  77271. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  77272. // Use an image editing software to tweak the LUT to match your needs.
  77273. //
  77274. // For an example of a color LUT, see here:
  77275. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  77276. // For explanations on color grading, see here:
  77277. // http://udn.epicgames.com/Three/ColorGrading.html
  77278. //
  77279. var BABYLON;
  77280. (function (BABYLON) {
  77281. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  77282. __extends(ColorCorrectionPostProcess, _super);
  77283. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  77284. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  77285. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77286. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  77287. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77288. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77289. _this.onApply = function (effect) {
  77290. effect.setTexture("colorTable", _this._colorTableTexture);
  77291. };
  77292. return _this;
  77293. }
  77294. return ColorCorrectionPostProcess;
  77295. }(BABYLON.PostProcess));
  77296. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77297. })(BABYLON || (BABYLON = {}));
  77298. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77299. var BABYLON;
  77300. (function (BABYLON) {
  77301. /** Defines operator used for tonemapping */
  77302. var TonemappingOperator;
  77303. (function (TonemappingOperator) {
  77304. /** Hable */
  77305. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77306. /** Reinhard */
  77307. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77308. /** HejiDawson */
  77309. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77310. /** Photographic */
  77311. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77312. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77313. ;
  77314. /**
  77315. * Defines a post process to apply tone mapping
  77316. */
  77317. var TonemapPostProcess = /** @class */ (function (_super) {
  77318. __extends(TonemapPostProcess, _super);
  77319. /**
  77320. * Creates a new TonemapPostProcess
  77321. * @param name defines the name of the postprocess
  77322. * @param _operator defines the operator to use
  77323. * @param exposureAdjustment defines the required exposure adjustement
  77324. * @param camera defines the camera to use (can be null)
  77325. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77326. * @param engine defines the hosting engine (can be ignore if camera is set)
  77327. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77328. */
  77329. function TonemapPostProcess(name, _operator,
  77330. /** Defines the required exposure adjustement */
  77331. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77332. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77333. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77334. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77335. _this._operator = _operator;
  77336. _this.exposureAdjustment = exposureAdjustment;
  77337. var defines = "#define ";
  77338. if (_this._operator === TonemappingOperator.Hable)
  77339. defines += "HABLE_TONEMAPPING";
  77340. else if (_this._operator === TonemappingOperator.Reinhard)
  77341. defines += "REINHARD_TONEMAPPING";
  77342. else if (_this._operator === TonemappingOperator.HejiDawson)
  77343. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77344. else if (_this._operator === TonemappingOperator.Photographic)
  77345. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77346. //sadly a second call to create the effect.
  77347. _this.updateEffect(defines);
  77348. _this.onApply = function (effect) {
  77349. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77350. };
  77351. return _this;
  77352. }
  77353. return TonemapPostProcess;
  77354. }(BABYLON.PostProcess));
  77355. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77356. })(BABYLON || (BABYLON = {}));
  77357. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77358. var BABYLON;
  77359. (function (BABYLON) {
  77360. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77361. __extends(DisplayPassPostProcess, _super);
  77362. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77363. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77364. }
  77365. return DisplayPassPostProcess;
  77366. }(BABYLON.PostProcess));
  77367. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77368. })(BABYLON || (BABYLON = {}));
  77369. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77370. var BABYLON;
  77371. (function (BABYLON) {
  77372. var HighlightsPostProcess = /** @class */ (function (_super) {
  77373. __extends(HighlightsPostProcess, _super);
  77374. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77375. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77376. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77377. }
  77378. return HighlightsPostProcess;
  77379. }(BABYLON.PostProcess));
  77380. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77381. })(BABYLON || (BABYLON = {}));
  77382. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77383. var BABYLON;
  77384. (function (BABYLON) {
  77385. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77386. __extends(ImageProcessingPostProcess, _super);
  77387. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77388. if (camera === void 0) { camera = null; }
  77389. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77390. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77391. _this._fromLinearSpace = true;
  77392. /**
  77393. * Defines cache preventing GC.
  77394. */
  77395. _this._defines = {
  77396. IMAGEPROCESSING: false,
  77397. VIGNETTE: false,
  77398. VIGNETTEBLENDMODEMULTIPLY: false,
  77399. VIGNETTEBLENDMODEOPAQUE: false,
  77400. TONEMAPPING: false,
  77401. CONTRAST: false,
  77402. COLORCURVES: false,
  77403. COLORGRADING: false,
  77404. COLORGRADING3D: false,
  77405. FROMLINEARSPACE: false,
  77406. SAMPLER3DGREENDEPTH: false,
  77407. SAMPLER3DBGRMAP: false,
  77408. IMAGEPROCESSINGPOSTPROCESS: false,
  77409. EXPOSURE: false,
  77410. };
  77411. // Setup the configuration as forced by the constructor. This would then not force the
  77412. // scene materials output in linear space and let untouched the default forward pass.
  77413. if (imageProcessingConfiguration) {
  77414. imageProcessingConfiguration.applyByPostProcess = true;
  77415. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77416. // This will cause the shader to be compiled
  77417. _this.fromLinearSpace = false;
  77418. }
  77419. // Setup the default processing configuration to the scene.
  77420. else {
  77421. _this._attachImageProcessingConfiguration(null, true);
  77422. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77423. }
  77424. _this.onApply = function (effect) {
  77425. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77426. };
  77427. return _this;
  77428. }
  77429. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77430. /**
  77431. * Gets the image processing configuration used either in this material.
  77432. */
  77433. get: function () {
  77434. return this._imageProcessingConfiguration;
  77435. },
  77436. /**
  77437. * Sets the Default image processing configuration used either in the this material.
  77438. *
  77439. * If sets to null, the scene one is in use.
  77440. */
  77441. set: function (value) {
  77442. this._attachImageProcessingConfiguration(value);
  77443. },
  77444. enumerable: true,
  77445. configurable: true
  77446. });
  77447. /**
  77448. * Attaches a new image processing configuration to the PBR Material.
  77449. * @param configuration
  77450. */
  77451. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77452. var _this = this;
  77453. if (doNotBuild === void 0) { doNotBuild = false; }
  77454. if (configuration === this._imageProcessingConfiguration) {
  77455. return;
  77456. }
  77457. // Detaches observer.
  77458. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77459. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77460. }
  77461. // Pick the scene configuration if needed.
  77462. if (!configuration) {
  77463. var scene = null;
  77464. var engine = this.getEngine();
  77465. var camera = this.getCamera();
  77466. if (camera) {
  77467. scene = camera.getScene();
  77468. }
  77469. else if (engine && engine.scenes) {
  77470. var scenes = engine.scenes;
  77471. scene = scenes[scenes.length - 1];
  77472. }
  77473. else {
  77474. scene = BABYLON.Engine.LastCreatedScene;
  77475. }
  77476. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77477. }
  77478. else {
  77479. this._imageProcessingConfiguration = configuration;
  77480. }
  77481. // Attaches observer.
  77482. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77483. _this._updateParameters();
  77484. });
  77485. // Ensure the effect will be rebuilt.
  77486. if (!doNotBuild) {
  77487. this._updateParameters();
  77488. }
  77489. };
  77490. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77491. /**
  77492. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77493. */
  77494. get: function () {
  77495. return this.imageProcessingConfiguration.colorCurves;
  77496. },
  77497. /**
  77498. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77499. */
  77500. set: function (value) {
  77501. this.imageProcessingConfiguration.colorCurves = value;
  77502. },
  77503. enumerable: true,
  77504. configurable: true
  77505. });
  77506. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77507. /**
  77508. * Gets wether the color curves effect is enabled.
  77509. */
  77510. get: function () {
  77511. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77512. },
  77513. /**
  77514. * Sets wether the color curves effect is enabled.
  77515. */
  77516. set: function (value) {
  77517. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77518. },
  77519. enumerable: true,
  77520. configurable: true
  77521. });
  77522. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77523. /**
  77524. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77525. */
  77526. get: function () {
  77527. return this.imageProcessingConfiguration.colorGradingTexture;
  77528. },
  77529. /**
  77530. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77531. */
  77532. set: function (value) {
  77533. this.imageProcessingConfiguration.colorGradingTexture = value;
  77534. },
  77535. enumerable: true,
  77536. configurable: true
  77537. });
  77538. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77539. /**
  77540. * Gets wether the color grading effect is enabled.
  77541. */
  77542. get: function () {
  77543. return this.imageProcessingConfiguration.colorGradingEnabled;
  77544. },
  77545. /**
  77546. * Gets wether the color grading effect is enabled.
  77547. */
  77548. set: function (value) {
  77549. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77550. },
  77551. enumerable: true,
  77552. configurable: true
  77553. });
  77554. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77555. /**
  77556. * Gets exposure used in the effect.
  77557. */
  77558. get: function () {
  77559. return this.imageProcessingConfiguration.exposure;
  77560. },
  77561. /**
  77562. * Sets exposure used in the effect.
  77563. */
  77564. set: function (value) {
  77565. this.imageProcessingConfiguration.exposure = value;
  77566. },
  77567. enumerable: true,
  77568. configurable: true
  77569. });
  77570. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77571. /**
  77572. * Gets wether tonemapping is enabled or not.
  77573. */
  77574. get: function () {
  77575. return this._imageProcessingConfiguration.toneMappingEnabled;
  77576. },
  77577. /**
  77578. * Sets wether tonemapping is enabled or not
  77579. */
  77580. set: function (value) {
  77581. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77582. },
  77583. enumerable: true,
  77584. configurable: true
  77585. });
  77586. ;
  77587. ;
  77588. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77589. /**
  77590. * Gets contrast used in the effect.
  77591. */
  77592. get: function () {
  77593. return this.imageProcessingConfiguration.contrast;
  77594. },
  77595. /**
  77596. * Sets contrast used in the effect.
  77597. */
  77598. set: function (value) {
  77599. this.imageProcessingConfiguration.contrast = value;
  77600. },
  77601. enumerable: true,
  77602. configurable: true
  77603. });
  77604. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77605. /**
  77606. * Gets Vignette stretch size.
  77607. */
  77608. get: function () {
  77609. return this.imageProcessingConfiguration.vignetteStretch;
  77610. },
  77611. /**
  77612. * Sets Vignette stretch size.
  77613. */
  77614. set: function (value) {
  77615. this.imageProcessingConfiguration.vignetteStretch = value;
  77616. },
  77617. enumerable: true,
  77618. configurable: true
  77619. });
  77620. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77621. /**
  77622. * Gets Vignette centre X Offset.
  77623. */
  77624. get: function () {
  77625. return this.imageProcessingConfiguration.vignetteCentreX;
  77626. },
  77627. /**
  77628. * Sets Vignette centre X Offset.
  77629. */
  77630. set: function (value) {
  77631. this.imageProcessingConfiguration.vignetteCentreX = value;
  77632. },
  77633. enumerable: true,
  77634. configurable: true
  77635. });
  77636. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77637. /**
  77638. * Gets Vignette centre Y Offset.
  77639. */
  77640. get: function () {
  77641. return this.imageProcessingConfiguration.vignetteCentreY;
  77642. },
  77643. /**
  77644. * Sets Vignette centre Y Offset.
  77645. */
  77646. set: function (value) {
  77647. this.imageProcessingConfiguration.vignetteCentreY = value;
  77648. },
  77649. enumerable: true,
  77650. configurable: true
  77651. });
  77652. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77653. /**
  77654. * Gets Vignette weight or intensity of the vignette effect.
  77655. */
  77656. get: function () {
  77657. return this.imageProcessingConfiguration.vignetteWeight;
  77658. },
  77659. /**
  77660. * Sets Vignette weight or intensity of the vignette effect.
  77661. */
  77662. set: function (value) {
  77663. this.imageProcessingConfiguration.vignetteWeight = value;
  77664. },
  77665. enumerable: true,
  77666. configurable: true
  77667. });
  77668. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77669. /**
  77670. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77671. * if vignetteEnabled is set to true.
  77672. */
  77673. get: function () {
  77674. return this.imageProcessingConfiguration.vignetteColor;
  77675. },
  77676. /**
  77677. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77678. * if vignetteEnabled is set to true.
  77679. */
  77680. set: function (value) {
  77681. this.imageProcessingConfiguration.vignetteColor = value;
  77682. },
  77683. enumerable: true,
  77684. configurable: true
  77685. });
  77686. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77687. /**
  77688. * Gets Camera field of view used by the Vignette effect.
  77689. */
  77690. get: function () {
  77691. return this.imageProcessingConfiguration.vignetteCameraFov;
  77692. },
  77693. /**
  77694. * Sets Camera field of view used by the Vignette effect.
  77695. */
  77696. set: function (value) {
  77697. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77698. },
  77699. enumerable: true,
  77700. configurable: true
  77701. });
  77702. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77703. /**
  77704. * Gets the vignette blend mode allowing different kind of effect.
  77705. */
  77706. get: function () {
  77707. return this.imageProcessingConfiguration.vignetteBlendMode;
  77708. },
  77709. /**
  77710. * Sets the vignette blend mode allowing different kind of effect.
  77711. */
  77712. set: function (value) {
  77713. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77714. },
  77715. enumerable: true,
  77716. configurable: true
  77717. });
  77718. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77719. /**
  77720. * Gets wether the vignette effect is enabled.
  77721. */
  77722. get: function () {
  77723. return this.imageProcessingConfiguration.vignetteEnabled;
  77724. },
  77725. /**
  77726. * Sets wether the vignette effect is enabled.
  77727. */
  77728. set: function (value) {
  77729. this.imageProcessingConfiguration.vignetteEnabled = value;
  77730. },
  77731. enumerable: true,
  77732. configurable: true
  77733. });
  77734. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77735. /**
  77736. * Gets wether the input of the processing is in Gamma or Linear Space.
  77737. */
  77738. get: function () {
  77739. return this._fromLinearSpace;
  77740. },
  77741. /**
  77742. * Sets wether the input of the processing is in Gamma or Linear Space.
  77743. */
  77744. set: function (value) {
  77745. if (this._fromLinearSpace === value) {
  77746. return;
  77747. }
  77748. this._fromLinearSpace = value;
  77749. this._updateParameters();
  77750. },
  77751. enumerable: true,
  77752. configurable: true
  77753. });
  77754. ImageProcessingPostProcess.prototype.getClassName = function () {
  77755. return "ImageProcessingPostProcess";
  77756. };
  77757. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77758. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77759. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77760. var defines = "";
  77761. for (var define in this._defines) {
  77762. if (this._defines[define]) {
  77763. defines += "#define " + define + ";\r\n";
  77764. }
  77765. }
  77766. var samplers = ["textureSampler"];
  77767. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77768. var uniforms = ["scale"];
  77769. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77770. this.updateEffect(defines, uniforms, samplers);
  77771. };
  77772. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77773. _super.prototype.dispose.call(this, camera);
  77774. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77775. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77776. }
  77777. this.imageProcessingConfiguration.applyByPostProcess = false;
  77778. };
  77779. __decorate([
  77780. BABYLON.serialize()
  77781. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77782. return ImageProcessingPostProcess;
  77783. }(BABYLON.PostProcess));
  77784. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77785. })(BABYLON || (BABYLON = {}));
  77786. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77787. var BABYLON;
  77788. (function (BABYLON) {
  77789. /**
  77790. * Class used to store bone information
  77791. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77792. */
  77793. var Bone = /** @class */ (function (_super) {
  77794. __extends(Bone, _super);
  77795. /**
  77796. * Create a new bone
  77797. * @param name defines the bone name
  77798. * @param skeleton defines the parent skeleton
  77799. * @param parentBone defines the parent (can be null if the bone is the root)
  77800. * @param localMatrix defines the local matrix
  77801. * @param restPose defines the rest pose matrix
  77802. * @param baseMatrix defines the base matrix
  77803. * @param index defines index of the bone in the hiearchy
  77804. */
  77805. function Bone(
  77806. /**
  77807. * defines the bone name
  77808. */
  77809. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77810. if (parentBone === void 0) { parentBone = null; }
  77811. if (localMatrix === void 0) { localMatrix = null; }
  77812. if (restPose === void 0) { restPose = null; }
  77813. if (baseMatrix === void 0) { baseMatrix = null; }
  77814. if (index === void 0) { index = null; }
  77815. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77816. _this.name = name;
  77817. /**
  77818. * Gets the list of child bones
  77819. */
  77820. _this.children = new Array();
  77821. /** Gets the animations associated with this bone */
  77822. _this.animations = new Array();
  77823. /**
  77824. * @hidden Internal only
  77825. * Set this value to map this bone to a different index in the transform matrices
  77826. * Set this value to -1 to exclude the bone from the transform matrices
  77827. */
  77828. _this._index = null;
  77829. _this._absoluteTransform = new BABYLON.Matrix();
  77830. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77831. _this._scalingDeterminant = 1;
  77832. _this._worldTransform = new BABYLON.Matrix();
  77833. _this._needToDecompose = true;
  77834. _this._needToCompose = false;
  77835. _this._skeleton = skeleton;
  77836. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77837. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77838. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77839. _this._index = index;
  77840. skeleton.bones.push(_this);
  77841. _this.setParent(parentBone, false);
  77842. if (baseMatrix || localMatrix) {
  77843. _this._updateDifferenceMatrix();
  77844. }
  77845. return _this;
  77846. }
  77847. Object.defineProperty(Bone.prototype, "_matrix", {
  77848. /** @hidden */
  77849. get: function () {
  77850. this._compose();
  77851. return this._localMatrix;
  77852. },
  77853. /** @hidden */
  77854. set: function (value) {
  77855. this._localMatrix.copyFrom(value);
  77856. this._needToDecompose = true;
  77857. },
  77858. enumerable: true,
  77859. configurable: true
  77860. });
  77861. // Members
  77862. /**
  77863. * Gets the parent skeleton
  77864. * @returns a skeleton
  77865. */
  77866. Bone.prototype.getSkeleton = function () {
  77867. return this._skeleton;
  77868. };
  77869. /**
  77870. * Gets parent bone
  77871. * @returns a bone or null if the bone is the root of the bone hierarchy
  77872. */
  77873. Bone.prototype.getParent = function () {
  77874. return this._parent;
  77875. };
  77876. /**
  77877. * Sets the parent bone
  77878. * @param parent defines the parent (can be null if the bone is the root)
  77879. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77880. */
  77881. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  77882. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77883. if (this._parent === parent) {
  77884. return;
  77885. }
  77886. if (this._parent) {
  77887. var index = this._parent.children.indexOf(this);
  77888. if (index !== -1) {
  77889. this._parent.children.splice(index, 1);
  77890. }
  77891. }
  77892. this._parent = parent;
  77893. if (this._parent) {
  77894. this._parent.children.push(this);
  77895. }
  77896. if (updateDifferenceMatrix) {
  77897. this._updateDifferenceMatrix();
  77898. }
  77899. this.markAsDirty();
  77900. };
  77901. /**
  77902. * Gets the local matrix
  77903. * @returns a matrix
  77904. */
  77905. Bone.prototype.getLocalMatrix = function () {
  77906. this._compose();
  77907. return this._localMatrix;
  77908. };
  77909. /**
  77910. * Gets the base matrix (initial matrix which remains unchanged)
  77911. * @returns a matrix
  77912. */
  77913. Bone.prototype.getBaseMatrix = function () {
  77914. return this._baseMatrix;
  77915. };
  77916. /**
  77917. * Gets the rest pose matrix
  77918. * @returns a matrix
  77919. */
  77920. Bone.prototype.getRestPose = function () {
  77921. return this._restPose;
  77922. };
  77923. /**
  77924. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  77925. */
  77926. Bone.prototype.getWorldMatrix = function () {
  77927. return this._worldTransform;
  77928. };
  77929. /**
  77930. * Sets the local matrix to rest pose matrix
  77931. */
  77932. Bone.prototype.returnToRest = function () {
  77933. this.updateMatrix(this._restPose.clone());
  77934. };
  77935. /**
  77936. * Gets the inverse of the absolute transform matrix.
  77937. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  77938. * @returns a matrix
  77939. */
  77940. Bone.prototype.getInvertedAbsoluteTransform = function () {
  77941. return this._invertedAbsoluteTransform;
  77942. };
  77943. /**
  77944. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  77945. * @returns a matrix
  77946. */
  77947. Bone.prototype.getAbsoluteTransform = function () {
  77948. return this._absoluteTransform;
  77949. };
  77950. Object.defineProperty(Bone.prototype, "position", {
  77951. // Properties (matches AbstractMesh properties)
  77952. /** Gets or sets current position (in local space) */
  77953. get: function () {
  77954. this._decompose();
  77955. return this._localPosition;
  77956. },
  77957. set: function (newPosition) {
  77958. this._decompose();
  77959. this._localPosition.copyFrom(newPosition);
  77960. this._markAsDirtyAndCompose();
  77961. },
  77962. enumerable: true,
  77963. configurable: true
  77964. });
  77965. Object.defineProperty(Bone.prototype, "rotation", {
  77966. /** Gets or sets current rotation (in local space) */
  77967. get: function () {
  77968. return this.getRotation();
  77969. },
  77970. set: function (newRotation) {
  77971. this.setRotation(newRotation);
  77972. },
  77973. enumerable: true,
  77974. configurable: true
  77975. });
  77976. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  77977. /** Gets or sets current rotation quaternion (in local space) */
  77978. get: function () {
  77979. this._decompose();
  77980. return this._localRotation;
  77981. },
  77982. set: function (newRotation) {
  77983. this.setRotationQuaternion(newRotation);
  77984. },
  77985. enumerable: true,
  77986. configurable: true
  77987. });
  77988. Object.defineProperty(Bone.prototype, "scaling", {
  77989. /** Gets or sets current scaling (in local space) */
  77990. get: function () {
  77991. return this.getScale();
  77992. },
  77993. set: function (newScaling) {
  77994. this.setScale(newScaling);
  77995. },
  77996. enumerable: true,
  77997. configurable: true
  77998. });
  77999. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  78000. /**
  78001. * Gets the animation properties override
  78002. */
  78003. get: function () {
  78004. return this._skeleton.animationPropertiesOverride;
  78005. },
  78006. enumerable: true,
  78007. configurable: true
  78008. });
  78009. // Methods
  78010. Bone.prototype._decompose = function () {
  78011. if (!this._needToDecompose) {
  78012. return;
  78013. }
  78014. this._needToDecompose = false;
  78015. if (!this._localScaling) {
  78016. this._localScaling = BABYLON.Vector3.Zero();
  78017. this._localRotation = BABYLON.Quaternion.Zero();
  78018. this._localPosition = BABYLON.Vector3.Zero();
  78019. }
  78020. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  78021. };
  78022. Bone.prototype._compose = function () {
  78023. if (!this._needToCompose) {
  78024. return;
  78025. }
  78026. this._needToCompose = false;
  78027. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  78028. };
  78029. /**
  78030. * Update the base and local matrices
  78031. * @param matrix defines the new base or local matrix
  78032. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78033. * @param updateLocalMatrix defines if the local matrix should be updated
  78034. */
  78035. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  78036. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78037. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  78038. this._baseMatrix.copyFrom(matrix);
  78039. if (updateDifferenceMatrix) {
  78040. this._updateDifferenceMatrix();
  78041. }
  78042. if (updateLocalMatrix) {
  78043. this._localMatrix.copyFrom(matrix);
  78044. this._markAsDirtyAndDecompose();
  78045. }
  78046. else {
  78047. this.markAsDirty();
  78048. }
  78049. };
  78050. /** @hidden */
  78051. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  78052. if (updateChildren === void 0) { updateChildren = true; }
  78053. if (!rootMatrix) {
  78054. rootMatrix = this._baseMatrix;
  78055. }
  78056. if (this._parent) {
  78057. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78058. }
  78059. else {
  78060. this._absoluteTransform.copyFrom(rootMatrix);
  78061. }
  78062. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  78063. if (updateChildren) {
  78064. for (var index = 0; index < this.children.length; index++) {
  78065. this.children[index]._updateDifferenceMatrix();
  78066. }
  78067. }
  78068. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  78069. };
  78070. /**
  78071. * Flag the bone as dirty (Forcing it to update everything)
  78072. */
  78073. Bone.prototype.markAsDirty = function () {
  78074. this._currentRenderId++;
  78075. this._childRenderId++;
  78076. this._skeleton._markAsDirty();
  78077. };
  78078. Bone.prototype._markAsDirtyAndCompose = function () {
  78079. this.markAsDirty();
  78080. this._needToCompose = true;
  78081. };
  78082. Bone.prototype._markAsDirtyAndDecompose = function () {
  78083. this.markAsDirty();
  78084. this._needToDecompose = true;
  78085. };
  78086. /**
  78087. * Copy an animation range from another bone
  78088. * @param source defines the source bone
  78089. * @param rangeName defines the range name to copy
  78090. * @param frameOffset defines the frame offset
  78091. * @param rescaleAsRequired defines if rescaling must be applied if required
  78092. * @param skelDimensionsRatio defines the scaling ratio
  78093. * @returns true if operation was successful
  78094. */
  78095. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  78096. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78097. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  78098. // all animation may be coming from a library skeleton, so may need to create animation
  78099. if (this.animations.length === 0) {
  78100. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  78101. this.animations[0].setKeys([]);
  78102. }
  78103. // get animation info / verify there is such a range from the source bone
  78104. var sourceRange = source.animations[0].getRange(rangeName);
  78105. if (!sourceRange) {
  78106. return false;
  78107. }
  78108. var from = sourceRange.from;
  78109. var to = sourceRange.to;
  78110. var sourceKeys = source.animations[0].getKeys();
  78111. // rescaling prep
  78112. var sourceBoneLength = source.length;
  78113. var sourceParent = source.getParent();
  78114. var parent = this.getParent();
  78115. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  78116. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  78117. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  78118. var destKeys = this.animations[0].getKeys();
  78119. // loop vars declaration
  78120. var orig;
  78121. var origTranslation;
  78122. var mat;
  78123. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  78124. orig = sourceKeys[key];
  78125. if (orig.frame >= from && orig.frame <= to) {
  78126. if (rescaleAsRequired) {
  78127. mat = orig.value.clone();
  78128. // scale based on parent ratio, when bone has parent
  78129. if (parentScalingReqd) {
  78130. origTranslation = mat.getTranslation();
  78131. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  78132. // scale based on skeleton dimension ratio when root bone, and value is passed
  78133. }
  78134. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  78135. origTranslation = mat.getTranslation();
  78136. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  78137. // use original when root bone, and no data for skelDimensionsRatio
  78138. }
  78139. else {
  78140. mat = orig.value;
  78141. }
  78142. }
  78143. else {
  78144. mat = orig.value;
  78145. }
  78146. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  78147. }
  78148. }
  78149. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  78150. return true;
  78151. };
  78152. /**
  78153. * Translate the bone in local or world space
  78154. * @param vec The amount to translate the bone
  78155. * @param space The space that the translation is in
  78156. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78157. */
  78158. Bone.prototype.translate = function (vec, space, mesh) {
  78159. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78160. var lm = this.getLocalMatrix();
  78161. if (space == BABYLON.Space.LOCAL) {
  78162. lm.m[12] += vec.x;
  78163. lm.m[13] += vec.y;
  78164. lm.m[14] += vec.z;
  78165. }
  78166. else {
  78167. var wm = null;
  78168. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78169. if (mesh) {
  78170. wm = mesh.getWorldMatrix();
  78171. }
  78172. this._skeleton.computeAbsoluteTransforms();
  78173. var tmat = Bone._tmpMats[0];
  78174. var tvec = Bone._tmpVecs[0];
  78175. if (this._parent) {
  78176. if (mesh && wm) {
  78177. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78178. tmat.multiplyToRef(wm, tmat);
  78179. }
  78180. else {
  78181. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78182. }
  78183. }
  78184. tmat.m[12] = 0;
  78185. tmat.m[13] = 0;
  78186. tmat.m[14] = 0;
  78187. tmat.invert();
  78188. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  78189. lm.m[12] += tvec.x;
  78190. lm.m[13] += tvec.y;
  78191. lm.m[14] += tvec.z;
  78192. }
  78193. this._markAsDirtyAndDecompose();
  78194. };
  78195. /**
  78196. * Set the postion of the bone in local or world space
  78197. * @param position The position to set the bone
  78198. * @param space The space that the position is in
  78199. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78200. */
  78201. Bone.prototype.setPosition = function (position, space, mesh) {
  78202. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78203. var lm = this.getLocalMatrix();
  78204. if (space == BABYLON.Space.LOCAL) {
  78205. lm.m[12] = position.x;
  78206. lm.m[13] = position.y;
  78207. lm.m[14] = position.z;
  78208. }
  78209. else {
  78210. var wm = null;
  78211. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78212. if (mesh) {
  78213. wm = mesh.getWorldMatrix();
  78214. }
  78215. this._skeleton.computeAbsoluteTransforms();
  78216. var tmat = Bone._tmpMats[0];
  78217. var vec = Bone._tmpVecs[0];
  78218. if (this._parent) {
  78219. if (mesh && wm) {
  78220. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78221. tmat.multiplyToRef(wm, tmat);
  78222. }
  78223. else {
  78224. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78225. }
  78226. }
  78227. tmat.invert();
  78228. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  78229. lm.m[12] = vec.x;
  78230. lm.m[13] = vec.y;
  78231. lm.m[14] = vec.z;
  78232. }
  78233. this._markAsDirtyAndDecompose();
  78234. };
  78235. /**
  78236. * Set the absolute position of the bone (world space)
  78237. * @param position The position to set the bone
  78238. * @param mesh The mesh that this bone is attached to
  78239. */
  78240. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  78241. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  78242. };
  78243. /**
  78244. * Scale the bone on the x, y and z axes (in local space)
  78245. * @param x The amount to scale the bone on the x axis
  78246. * @param y The amount to scale the bone on the y axis
  78247. * @param z The amount to scale the bone on the z axis
  78248. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  78249. */
  78250. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  78251. if (scaleChildren === void 0) { scaleChildren = false; }
  78252. var locMat = this.getLocalMatrix();
  78253. // Apply new scaling on top of current local matrix
  78254. var scaleMat = Bone._tmpMats[0];
  78255. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  78256. scaleMat.multiplyToRef(locMat, locMat);
  78257. // Invert scaling matrix and apply the inverse to all children
  78258. scaleMat.invert();
  78259. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  78260. var child = _a[_i];
  78261. var cm = child.getLocalMatrix();
  78262. cm.multiplyToRef(scaleMat, cm);
  78263. cm.m[12] *= x;
  78264. cm.m[13] *= y;
  78265. cm.m[14] *= z;
  78266. child._markAsDirtyAndDecompose();
  78267. }
  78268. this._markAsDirtyAndDecompose();
  78269. if (scaleChildren) {
  78270. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  78271. var child = _c[_b];
  78272. child.scale(x, y, z, scaleChildren);
  78273. }
  78274. }
  78275. };
  78276. /**
  78277. * Set the bone scaling in local space
  78278. * @param scale defines the scaling vector
  78279. */
  78280. Bone.prototype.setScale = function (scale) {
  78281. this._decompose();
  78282. this._localScaling.copyFrom(scale);
  78283. this._markAsDirtyAndCompose();
  78284. };
  78285. /**
  78286. * Gets the current scaling in local space
  78287. * @returns the current scaling vector
  78288. */
  78289. Bone.prototype.getScale = function () {
  78290. this._decompose();
  78291. return this._localScaling;
  78292. };
  78293. /**
  78294. * Gets the current scaling in local space and stores it in a target vector
  78295. * @param result defines the target vector
  78296. */
  78297. Bone.prototype.getScaleToRef = function (result) {
  78298. this._decompose();
  78299. result.copyFrom(this._localScaling);
  78300. };
  78301. /**
  78302. * Set the yaw, pitch, and roll of the bone in local or world space
  78303. * @param yaw The rotation of the bone on the y axis
  78304. * @param pitch The rotation of the bone on the x axis
  78305. * @param roll The rotation of the bone on the z axis
  78306. * @param space The space that the axes of rotation are in
  78307. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78308. */
  78309. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78310. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78311. if (space === BABYLON.Space.LOCAL) {
  78312. var quat = Bone._tmpQuat;
  78313. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78314. this.setRotationQuaternion(quat, space, mesh);
  78315. return;
  78316. }
  78317. var rotMatInv = Bone._tmpMats[0];
  78318. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78319. return;
  78320. }
  78321. var rotMat = Bone._tmpMats[1];
  78322. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78323. rotMatInv.multiplyToRef(rotMat, rotMat);
  78324. this._rotateWithMatrix(rotMat, space, mesh);
  78325. };
  78326. /**
  78327. * Add a rotation to the bone on an axis in local or world space
  78328. * @param axis The axis to rotate the bone on
  78329. * @param amount The amount to rotate the bone
  78330. * @param space The space that the axis is in
  78331. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78332. */
  78333. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78334. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78335. var rmat = Bone._tmpMats[0];
  78336. rmat.m[12] = 0;
  78337. rmat.m[13] = 0;
  78338. rmat.m[14] = 0;
  78339. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78340. this._rotateWithMatrix(rmat, space, mesh);
  78341. };
  78342. /**
  78343. * Set the rotation of the bone to a particular axis angle in local or world space
  78344. * @param axis The axis to rotate the bone on
  78345. * @param angle The angle that the bone should be rotated to
  78346. * @param space The space that the axis is in
  78347. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78348. */
  78349. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78350. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78351. if (space === BABYLON.Space.LOCAL) {
  78352. var quat = Bone._tmpQuat;
  78353. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78354. this.setRotationQuaternion(quat, space, mesh);
  78355. return;
  78356. }
  78357. var rotMatInv = Bone._tmpMats[0];
  78358. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78359. return;
  78360. }
  78361. var rotMat = Bone._tmpMats[1];
  78362. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78363. rotMatInv.multiplyToRef(rotMat, rotMat);
  78364. this._rotateWithMatrix(rotMat, space, mesh);
  78365. };
  78366. /**
  78367. * Set the euler rotation of the bone in local of world space
  78368. * @param rotation The euler rotation that the bone should be set to
  78369. * @param space The space that the rotation is in
  78370. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78371. */
  78372. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78373. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78374. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78375. };
  78376. /**
  78377. * Set the quaternion rotation of the bone in local of world space
  78378. * @param quat The quaternion rotation that the bone should be set to
  78379. * @param space The space that the rotation is in
  78380. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78381. */
  78382. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78383. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78384. if (space === BABYLON.Space.LOCAL) {
  78385. this._decompose();
  78386. this._localRotation.copyFrom(quat);
  78387. this._markAsDirtyAndCompose();
  78388. return;
  78389. }
  78390. var rotMatInv = Bone._tmpMats[0];
  78391. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78392. return;
  78393. }
  78394. var rotMat = Bone._tmpMats[1];
  78395. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78396. rotMatInv.multiplyToRef(rotMat, rotMat);
  78397. this._rotateWithMatrix(rotMat, space, mesh);
  78398. };
  78399. /**
  78400. * Set the rotation matrix of the bone in local of world space
  78401. * @param rotMat The rotation matrix that the bone should be set to
  78402. * @param space The space that the rotation is in
  78403. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78404. */
  78405. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78406. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78407. if (space === BABYLON.Space.LOCAL) {
  78408. var quat = Bone._tmpQuat;
  78409. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78410. this.setRotationQuaternion(quat, space, mesh);
  78411. return;
  78412. }
  78413. var rotMatInv = Bone._tmpMats[0];
  78414. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78415. return;
  78416. }
  78417. var rotMat2 = Bone._tmpMats[1];
  78418. rotMat2.copyFrom(rotMat);
  78419. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78420. this._rotateWithMatrix(rotMat2, space, mesh);
  78421. };
  78422. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78423. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78424. var lmat = this.getLocalMatrix();
  78425. var lx = lmat.m[12];
  78426. var ly = lmat.m[13];
  78427. var lz = lmat.m[14];
  78428. var parent = this.getParent();
  78429. var parentScale = Bone._tmpMats[3];
  78430. var parentScaleInv = Bone._tmpMats[4];
  78431. if (parent && space == BABYLON.Space.WORLD) {
  78432. if (mesh) {
  78433. parentScale.copyFrom(mesh.getWorldMatrix());
  78434. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78435. }
  78436. else {
  78437. parentScale.copyFrom(parent.getAbsoluteTransform());
  78438. }
  78439. parentScaleInv.copyFrom(parentScale);
  78440. parentScaleInv.invert();
  78441. lmat.multiplyToRef(parentScale, lmat);
  78442. lmat.multiplyToRef(rmat, lmat);
  78443. lmat.multiplyToRef(parentScaleInv, lmat);
  78444. }
  78445. else {
  78446. if (space == BABYLON.Space.WORLD && mesh) {
  78447. parentScale.copyFrom(mesh.getWorldMatrix());
  78448. parentScaleInv.copyFrom(parentScale);
  78449. parentScaleInv.invert();
  78450. lmat.multiplyToRef(parentScale, lmat);
  78451. lmat.multiplyToRef(rmat, lmat);
  78452. lmat.multiplyToRef(parentScaleInv, lmat);
  78453. }
  78454. else {
  78455. lmat.multiplyToRef(rmat, lmat);
  78456. }
  78457. }
  78458. lmat.m[12] = lx;
  78459. lmat.m[13] = ly;
  78460. lmat.m[14] = lz;
  78461. this.computeAbsoluteTransforms();
  78462. this._markAsDirtyAndDecompose();
  78463. };
  78464. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78465. var scaleMatrix = Bone._tmpMats[2];
  78466. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78467. if (mesh) {
  78468. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78469. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78470. }
  78471. rotMatInv.invert();
  78472. if (isNaN(rotMatInv.m[0])) {
  78473. // Matrix failed to invert.
  78474. // This can happen if scale is zero for example.
  78475. return false;
  78476. }
  78477. scaleMatrix.m[0] *= this._scalingDeterminant;
  78478. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78479. return true;
  78480. };
  78481. /**
  78482. * Get the position of the bone in local or world space
  78483. * @param space The space that the returned position is in
  78484. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78485. * @returns The position of the bone
  78486. */
  78487. Bone.prototype.getPosition = function (space, mesh) {
  78488. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78489. if (mesh === void 0) { mesh = null; }
  78490. var pos = BABYLON.Vector3.Zero();
  78491. this.getPositionToRef(space, mesh, pos);
  78492. return pos;
  78493. };
  78494. /**
  78495. * Copy the position of the bone to a vector3 in local or world space
  78496. * @param space The space that the returned position is in
  78497. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78498. * @param result The vector3 to copy the position to
  78499. */
  78500. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78501. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78502. if (space == BABYLON.Space.LOCAL) {
  78503. var lm = this.getLocalMatrix();
  78504. result.x = lm.m[12];
  78505. result.y = lm.m[13];
  78506. result.z = lm.m[14];
  78507. }
  78508. else {
  78509. var wm = null;
  78510. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78511. if (mesh) {
  78512. wm = mesh.getWorldMatrix();
  78513. }
  78514. this._skeleton.computeAbsoluteTransforms();
  78515. var tmat = Bone._tmpMats[0];
  78516. if (mesh && wm) {
  78517. tmat.copyFrom(this.getAbsoluteTransform());
  78518. tmat.multiplyToRef(wm, tmat);
  78519. }
  78520. else {
  78521. tmat = this.getAbsoluteTransform();
  78522. }
  78523. result.x = tmat.m[12];
  78524. result.y = tmat.m[13];
  78525. result.z = tmat.m[14];
  78526. }
  78527. };
  78528. /**
  78529. * Get the absolute position of the bone (world space)
  78530. * @param mesh The mesh that this bone is attached to
  78531. * @returns The absolute position of the bone
  78532. */
  78533. Bone.prototype.getAbsolutePosition = function (mesh) {
  78534. if (mesh === void 0) { mesh = null; }
  78535. var pos = BABYLON.Vector3.Zero();
  78536. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78537. return pos;
  78538. };
  78539. /**
  78540. * Copy the absolute position of the bone (world space) to the result param
  78541. * @param mesh The mesh that this bone is attached to
  78542. * @param result The vector3 to copy the absolute position to
  78543. */
  78544. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78545. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78546. };
  78547. /**
  78548. * Compute the absolute transforms of this bone and its children
  78549. */
  78550. Bone.prototype.computeAbsoluteTransforms = function () {
  78551. this._compose();
  78552. if (this._parent) {
  78553. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78554. }
  78555. else {
  78556. this._absoluteTransform.copyFrom(this._localMatrix);
  78557. var poseMatrix = this._skeleton.getPoseMatrix();
  78558. if (poseMatrix) {
  78559. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78560. }
  78561. }
  78562. var children = this.children;
  78563. var len = children.length;
  78564. for (var i = 0; i < len; i++) {
  78565. children[i].computeAbsoluteTransforms();
  78566. }
  78567. };
  78568. /**
  78569. * Get the world direction from an axis that is in the local space of the bone
  78570. * @param localAxis The local direction that is used to compute the world direction
  78571. * @param mesh The mesh that this bone is attached to
  78572. * @returns The world direction
  78573. */
  78574. Bone.prototype.getDirection = function (localAxis, mesh) {
  78575. if (mesh === void 0) { mesh = null; }
  78576. var result = BABYLON.Vector3.Zero();
  78577. this.getDirectionToRef(localAxis, mesh, result);
  78578. return result;
  78579. };
  78580. /**
  78581. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78582. * @param localAxis The local direction that is used to compute the world direction
  78583. * @param mesh The mesh that this bone is attached to
  78584. * @param result The vector3 that the world direction will be copied to
  78585. */
  78586. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78587. if (mesh === void 0) { mesh = null; }
  78588. var wm = null;
  78589. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78590. if (mesh) {
  78591. wm = mesh.getWorldMatrix();
  78592. }
  78593. this._skeleton.computeAbsoluteTransforms();
  78594. var mat = Bone._tmpMats[0];
  78595. mat.copyFrom(this.getAbsoluteTransform());
  78596. if (mesh && wm) {
  78597. mat.multiplyToRef(wm, mat);
  78598. }
  78599. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78600. result.normalize();
  78601. };
  78602. /**
  78603. * Get the euler rotation of the bone in local or world space
  78604. * @param space The space that the rotation should be in
  78605. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78606. * @returns The euler rotation
  78607. */
  78608. Bone.prototype.getRotation = function (space, mesh) {
  78609. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78610. if (mesh === void 0) { mesh = null; }
  78611. var result = BABYLON.Vector3.Zero();
  78612. this.getRotationToRef(space, mesh, result);
  78613. return result;
  78614. };
  78615. /**
  78616. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78617. * @param space The space that the rotation should be in
  78618. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78619. * @param result The vector3 that the rotation should be copied to
  78620. */
  78621. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78622. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78623. if (mesh === void 0) { mesh = null; }
  78624. var quat = Bone._tmpQuat;
  78625. this.getRotationQuaternionToRef(space, mesh, quat);
  78626. quat.toEulerAnglesToRef(result);
  78627. };
  78628. /**
  78629. * Get the quaternion rotation of the bone in either local or world space
  78630. * @param space The space that the rotation should be in
  78631. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78632. * @returns The quaternion rotation
  78633. */
  78634. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78635. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78636. if (mesh === void 0) { mesh = null; }
  78637. var result = BABYLON.Quaternion.Identity();
  78638. this.getRotationQuaternionToRef(space, mesh, result);
  78639. return result;
  78640. };
  78641. /**
  78642. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78643. * @param space The space that the rotation should be in
  78644. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78645. * @param result The quaternion that the rotation should be copied to
  78646. */
  78647. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78648. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78649. if (mesh === void 0) { mesh = null; }
  78650. if (space == BABYLON.Space.LOCAL) {
  78651. this._decompose();
  78652. result.copyFrom(this._localRotation);
  78653. }
  78654. else {
  78655. var mat = Bone._tmpMats[0];
  78656. var amat = this.getAbsoluteTransform();
  78657. if (mesh) {
  78658. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78659. }
  78660. else {
  78661. mat.copyFrom(amat);
  78662. }
  78663. mat.m[0] *= this._scalingDeterminant;
  78664. mat.m[1] *= this._scalingDeterminant;
  78665. mat.m[2] *= this._scalingDeterminant;
  78666. mat.decompose(undefined, result, undefined);
  78667. }
  78668. };
  78669. /**
  78670. * Get the rotation matrix of the bone in local or world space
  78671. * @param space The space that the rotation should be in
  78672. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78673. * @returns The rotation matrix
  78674. */
  78675. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78676. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78677. var result = BABYLON.Matrix.Identity();
  78678. this.getRotationMatrixToRef(space, mesh, result);
  78679. return result;
  78680. };
  78681. /**
  78682. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78683. * @param space The space that the rotation should be in
  78684. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78685. * @param result The quaternion that the rotation should be copied to
  78686. */
  78687. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78688. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78689. if (space == BABYLON.Space.LOCAL) {
  78690. this.getLocalMatrix().getRotationMatrixToRef(result);
  78691. }
  78692. else {
  78693. var mat = Bone._tmpMats[0];
  78694. var amat = this.getAbsoluteTransform();
  78695. if (mesh) {
  78696. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78697. }
  78698. else {
  78699. mat.copyFrom(amat);
  78700. }
  78701. mat.m[0] *= this._scalingDeterminant;
  78702. mat.m[1] *= this._scalingDeterminant;
  78703. mat.m[2] *= this._scalingDeterminant;
  78704. mat.getRotationMatrixToRef(result);
  78705. }
  78706. };
  78707. /**
  78708. * Get the world position of a point that is in the local space of the bone
  78709. * @param position The local position
  78710. * @param mesh The mesh that this bone is attached to
  78711. * @returns The world position
  78712. */
  78713. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78714. if (mesh === void 0) { mesh = null; }
  78715. var result = BABYLON.Vector3.Zero();
  78716. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78717. return result;
  78718. };
  78719. /**
  78720. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78721. * @param position The local position
  78722. * @param mesh The mesh that this bone is attached to
  78723. * @param result The vector3 that the world position should be copied to
  78724. */
  78725. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78726. if (mesh === void 0) { mesh = null; }
  78727. var wm = null;
  78728. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78729. if (mesh) {
  78730. wm = mesh.getWorldMatrix();
  78731. }
  78732. this._skeleton.computeAbsoluteTransforms();
  78733. var tmat = Bone._tmpMats[0];
  78734. if (mesh && wm) {
  78735. tmat.copyFrom(this.getAbsoluteTransform());
  78736. tmat.multiplyToRef(wm, tmat);
  78737. }
  78738. else {
  78739. tmat = this.getAbsoluteTransform();
  78740. }
  78741. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78742. };
  78743. /**
  78744. * Get the local position of a point that is in world space
  78745. * @param position The world position
  78746. * @param mesh The mesh that this bone is attached to
  78747. * @returns The local position
  78748. */
  78749. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78750. if (mesh === void 0) { mesh = null; }
  78751. var result = BABYLON.Vector3.Zero();
  78752. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78753. return result;
  78754. };
  78755. /**
  78756. * Get the local position of a point that is in world space and copy it to the result param
  78757. * @param position The world position
  78758. * @param mesh The mesh that this bone is attached to
  78759. * @param result The vector3 that the local position should be copied to
  78760. */
  78761. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78762. if (mesh === void 0) { mesh = null; }
  78763. var wm = null;
  78764. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78765. if (mesh) {
  78766. wm = mesh.getWorldMatrix();
  78767. }
  78768. this._skeleton.computeAbsoluteTransforms();
  78769. var tmat = Bone._tmpMats[0];
  78770. tmat.copyFrom(this.getAbsoluteTransform());
  78771. if (mesh && wm) {
  78772. tmat.multiplyToRef(wm, tmat);
  78773. }
  78774. tmat.invert();
  78775. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78776. };
  78777. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78778. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78779. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78780. return Bone;
  78781. }(BABYLON.Node));
  78782. BABYLON.Bone = Bone;
  78783. })(BABYLON || (BABYLON = {}));
  78784. //# sourceMappingURL=babylon.bone.js.map
  78785. var BABYLON;
  78786. (function (BABYLON) {
  78787. /**
  78788. * Class used to apply inverse kinematics to bones
  78789. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78790. */
  78791. var BoneIKController = /** @class */ (function () {
  78792. /**
  78793. * Creates a new BoneIKController
  78794. * @param mesh defines the mesh to control
  78795. * @param bone defines the bone to control
  78796. * @param options defines options to set up the controller
  78797. */
  78798. function BoneIKController(mesh, bone, options) {
  78799. /**
  78800. * Gets or sets the target position
  78801. */
  78802. this.targetPosition = BABYLON.Vector3.Zero();
  78803. /**
  78804. * Gets or sets the pole target position
  78805. */
  78806. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78807. /**
  78808. * Gets or sets the pole target local offset
  78809. */
  78810. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78811. /**
  78812. * Gets or sets the pole angle
  78813. */
  78814. this.poleAngle = 0;
  78815. /**
  78816. * 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)
  78817. */
  78818. this.slerpAmount = 1;
  78819. this._bone1Quat = BABYLON.Quaternion.Identity();
  78820. this._bone1Mat = BABYLON.Matrix.Identity();
  78821. this._bone2Ang = Math.PI;
  78822. this._maxAngle = Math.PI;
  78823. this._rightHandedSystem = false;
  78824. this._bendAxis = BABYLON.Vector3.Right();
  78825. this._slerping = false;
  78826. this._adjustRoll = 0;
  78827. this._bone2 = bone;
  78828. this._bone1 = bone.getParent();
  78829. if (!this._bone1) {
  78830. return;
  78831. }
  78832. this.mesh = mesh;
  78833. var bonePos = bone.getPosition();
  78834. if (bone.getAbsoluteTransform().determinant() > 0) {
  78835. this._rightHandedSystem = true;
  78836. this._bendAxis.x = 0;
  78837. this._bendAxis.y = 0;
  78838. this._bendAxis.z = -1;
  78839. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78840. this._adjustRoll = Math.PI * .5;
  78841. this._bendAxis.z = 1;
  78842. }
  78843. }
  78844. if (this._bone1.length) {
  78845. var boneScale1 = this._bone1.getScale();
  78846. var boneScale2 = this._bone2.getScale();
  78847. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  78848. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  78849. }
  78850. else if (this._bone1.children[0]) {
  78851. mesh.computeWorldMatrix(true);
  78852. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  78853. var pos2 = this._bone2.getAbsolutePosition(mesh);
  78854. var pos3 = this._bone1.getAbsolutePosition(mesh);
  78855. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  78856. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  78857. }
  78858. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  78859. this.maxAngle = Math.PI;
  78860. if (options) {
  78861. if (options.targetMesh) {
  78862. this.targetMesh = options.targetMesh;
  78863. this.targetMesh.computeWorldMatrix(true);
  78864. }
  78865. if (options.poleTargetMesh) {
  78866. this.poleTargetMesh = options.poleTargetMesh;
  78867. this.poleTargetMesh.computeWorldMatrix(true);
  78868. }
  78869. else if (options.poleTargetBone) {
  78870. this.poleTargetBone = options.poleTargetBone;
  78871. }
  78872. else if (this._bone1.getParent()) {
  78873. this.poleTargetBone = this._bone1.getParent();
  78874. }
  78875. if (options.poleTargetLocalOffset) {
  78876. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  78877. }
  78878. if (options.poleAngle) {
  78879. this.poleAngle = options.poleAngle;
  78880. }
  78881. if (options.bendAxis) {
  78882. this._bendAxis.copyFrom(options.bendAxis);
  78883. }
  78884. if (options.maxAngle) {
  78885. this.maxAngle = options.maxAngle;
  78886. }
  78887. if (options.slerpAmount) {
  78888. this.slerpAmount = options.slerpAmount;
  78889. }
  78890. }
  78891. }
  78892. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  78893. /**
  78894. * Gets or sets maximum allowed angle
  78895. */
  78896. get: function () {
  78897. return this._maxAngle;
  78898. },
  78899. set: function (value) {
  78900. this._setMaxAngle(value);
  78901. },
  78902. enumerable: true,
  78903. configurable: true
  78904. });
  78905. BoneIKController.prototype._setMaxAngle = function (ang) {
  78906. if (ang < 0) {
  78907. ang = 0;
  78908. }
  78909. if (ang > Math.PI || ang == undefined) {
  78910. ang = Math.PI;
  78911. }
  78912. this._maxAngle = ang;
  78913. var a = this._bone1Length;
  78914. var b = this._bone2Length;
  78915. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  78916. };
  78917. /**
  78918. * Force the controller to update the bones
  78919. */
  78920. BoneIKController.prototype.update = function () {
  78921. var bone1 = this._bone1;
  78922. if (!bone1) {
  78923. return;
  78924. }
  78925. var target = this.targetPosition;
  78926. var poleTarget = this.poleTargetPosition;
  78927. var mat1 = BoneIKController._tmpMats[0];
  78928. var mat2 = BoneIKController._tmpMats[1];
  78929. if (this.targetMesh) {
  78930. target.copyFrom(this.targetMesh.getAbsolutePosition());
  78931. }
  78932. if (this.poleTargetBone) {
  78933. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  78934. }
  78935. else if (this.poleTargetMesh) {
  78936. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  78937. }
  78938. var bonePos = BoneIKController._tmpVecs[0];
  78939. var zaxis = BoneIKController._tmpVecs[1];
  78940. var xaxis = BoneIKController._tmpVecs[2];
  78941. var yaxis = BoneIKController._tmpVecs[3];
  78942. var upAxis = BoneIKController._tmpVecs[4];
  78943. var _tmpQuat = BoneIKController._tmpQuat;
  78944. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  78945. poleTarget.subtractToRef(bonePos, upAxis);
  78946. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  78947. upAxis.y = 1;
  78948. }
  78949. else {
  78950. upAxis.normalize();
  78951. }
  78952. target.subtractToRef(bonePos, yaxis);
  78953. yaxis.normalize();
  78954. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  78955. zaxis.normalize();
  78956. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  78957. xaxis.normalize();
  78958. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  78959. var a = this._bone1Length;
  78960. var b = this._bone2Length;
  78961. var c = BABYLON.Vector3.Distance(bonePos, target);
  78962. if (this._maxReach > 0) {
  78963. c = Math.min(this._maxReach, c);
  78964. }
  78965. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  78966. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  78967. if (acosa > 1) {
  78968. acosa = 1;
  78969. }
  78970. if (acosb > 1) {
  78971. acosb = 1;
  78972. }
  78973. if (acosa < -1) {
  78974. acosa = -1;
  78975. }
  78976. if (acosb < -1) {
  78977. acosb = -1;
  78978. }
  78979. var angA = Math.acos(acosa);
  78980. var angB = Math.acos(acosb);
  78981. var angC = -angA - angB;
  78982. if (this._rightHandedSystem) {
  78983. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  78984. mat2.multiplyToRef(mat1, mat1);
  78985. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  78986. mat2.multiplyToRef(mat1, mat1);
  78987. }
  78988. else {
  78989. var _tmpVec = BoneIKController._tmpVecs[5];
  78990. _tmpVec.copyFrom(this._bendAxis);
  78991. _tmpVec.x *= -1;
  78992. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  78993. mat2.multiplyToRef(mat1, mat1);
  78994. }
  78995. if (this.poleAngle) {
  78996. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  78997. mat1.multiplyToRef(mat2, mat1);
  78998. }
  78999. if (this._bone1) {
  79000. if (this.slerpAmount < 1) {
  79001. if (!this._slerping) {
  79002. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  79003. }
  79004. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  79005. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  79006. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  79007. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  79008. this._slerping = true;
  79009. }
  79010. else {
  79011. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  79012. this._bone1Mat.copyFrom(mat1);
  79013. this._slerping = false;
  79014. }
  79015. }
  79016. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  79017. this._bone2Ang = angC;
  79018. };
  79019. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79020. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  79021. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79022. return BoneIKController;
  79023. }());
  79024. BABYLON.BoneIKController = BoneIKController;
  79025. })(BABYLON || (BABYLON = {}));
  79026. //# sourceMappingURL=babylon.boneIKController.js.map
  79027. var BABYLON;
  79028. (function (BABYLON) {
  79029. /**
  79030. * Class used to make a bone look toward a point in space
  79031. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  79032. */
  79033. var BoneLookController = /** @class */ (function () {
  79034. /**
  79035. * Create a BoneLookController
  79036. * @param mesh the mesh that the bone belongs to
  79037. * @param bone the bone that will be looking to the target
  79038. * @param target the target Vector3 to look at
  79039. * @param settings optional settings:
  79040. * * maxYaw: the maximum angle the bone will yaw to
  79041. * * minYaw: the minimum angle the bone will yaw to
  79042. * * maxPitch: the maximum angle the bone will pitch to
  79043. * * minPitch: the minimum angle the bone will yaw to
  79044. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  79045. * * upAxis: the up axis of the coordinate system
  79046. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  79047. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  79048. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  79049. * * adjustYaw: used to make an adjustment to the yaw of the bone
  79050. * * adjustPitch: used to make an adjustment to the pitch of the bone
  79051. * * adjustRoll: used to make an adjustment to the roll of the bone
  79052. **/
  79053. function BoneLookController(mesh, bone, target, options) {
  79054. /**
  79055. * The up axis of the coordinate system that is used when the bone is rotated
  79056. */
  79057. this.upAxis = BABYLON.Vector3.Up();
  79058. /**
  79059. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  79060. */
  79061. this.upAxisSpace = BABYLON.Space.LOCAL;
  79062. /**
  79063. * Used to make an adjustment to the yaw of the bone
  79064. */
  79065. this.adjustYaw = 0;
  79066. /**
  79067. * Used to make an adjustment to the pitch of the bone
  79068. */
  79069. this.adjustPitch = 0;
  79070. /**
  79071. * Used to make an adjustment to the roll of the bone
  79072. */
  79073. this.adjustRoll = 0;
  79074. /**
  79075. * 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)
  79076. */
  79077. this.slerpAmount = 1;
  79078. this._boneQuat = BABYLON.Quaternion.Identity();
  79079. this._slerping = false;
  79080. this._firstFrameSkipped = false;
  79081. this._fowardAxis = BABYLON.Vector3.Forward();
  79082. this.mesh = mesh;
  79083. this.bone = bone;
  79084. this.target = target;
  79085. if (options) {
  79086. if (options.adjustYaw) {
  79087. this.adjustYaw = options.adjustYaw;
  79088. }
  79089. if (options.adjustPitch) {
  79090. this.adjustPitch = options.adjustPitch;
  79091. }
  79092. if (options.adjustRoll) {
  79093. this.adjustRoll = options.adjustRoll;
  79094. }
  79095. if (options.maxYaw != null) {
  79096. this.maxYaw = options.maxYaw;
  79097. }
  79098. else {
  79099. this.maxYaw = Math.PI;
  79100. }
  79101. if (options.minYaw != null) {
  79102. this.minYaw = options.minYaw;
  79103. }
  79104. else {
  79105. this.minYaw = -Math.PI;
  79106. }
  79107. if (options.maxPitch != null) {
  79108. this.maxPitch = options.maxPitch;
  79109. }
  79110. else {
  79111. this.maxPitch = Math.PI;
  79112. }
  79113. if (options.minPitch != null) {
  79114. this.minPitch = options.minPitch;
  79115. }
  79116. else {
  79117. this.minPitch = -Math.PI;
  79118. }
  79119. if (options.slerpAmount != null) {
  79120. this.slerpAmount = options.slerpAmount;
  79121. }
  79122. if (options.upAxis != null) {
  79123. this.upAxis = options.upAxis;
  79124. }
  79125. if (options.upAxisSpace != null) {
  79126. this.upAxisSpace = options.upAxisSpace;
  79127. }
  79128. if (options.yawAxis != null || options.pitchAxis != null) {
  79129. var newYawAxis = BABYLON.Axis.Y;
  79130. var newPitchAxis = BABYLON.Axis.X;
  79131. if (options.yawAxis != null) {
  79132. newYawAxis = options.yawAxis.clone();
  79133. newYawAxis.normalize();
  79134. }
  79135. if (options.pitchAxis != null) {
  79136. newPitchAxis = options.pitchAxis.clone();
  79137. newPitchAxis.normalize();
  79138. }
  79139. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  79140. this._transformYawPitch = BABYLON.Matrix.Identity();
  79141. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  79142. this._transformYawPitchInv = this._transformYawPitch.clone();
  79143. this._transformYawPitch.invert();
  79144. }
  79145. }
  79146. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  79147. this.upAxisSpace = BABYLON.Space.LOCAL;
  79148. }
  79149. }
  79150. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  79151. /**
  79152. * Gets or sets the minimum yaw angle that the bone can look to
  79153. */
  79154. get: function () {
  79155. return this._minYaw;
  79156. },
  79157. set: function (value) {
  79158. this._minYaw = value;
  79159. this._minYawSin = Math.sin(value);
  79160. this._minYawCos = Math.cos(value);
  79161. if (this._maxYaw != null) {
  79162. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79163. this._yawRange = this._maxYaw - this._minYaw;
  79164. }
  79165. },
  79166. enumerable: true,
  79167. configurable: true
  79168. });
  79169. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  79170. /**
  79171. * Gets or sets the maximum yaw angle that the bone can look to
  79172. */
  79173. get: function () {
  79174. return this._maxYaw;
  79175. },
  79176. set: function (value) {
  79177. this._maxYaw = value;
  79178. this._maxYawSin = Math.sin(value);
  79179. this._maxYawCos = Math.cos(value);
  79180. if (this._minYaw != null) {
  79181. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79182. this._yawRange = this._maxYaw - this._minYaw;
  79183. }
  79184. },
  79185. enumerable: true,
  79186. configurable: true
  79187. });
  79188. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  79189. /**
  79190. * Gets or sets the minimum pitch angle that the bone can look to
  79191. */
  79192. get: function () {
  79193. return this._minPitch;
  79194. },
  79195. set: function (value) {
  79196. this._minPitch = value;
  79197. this._minPitchTan = Math.tan(value);
  79198. },
  79199. enumerable: true,
  79200. configurable: true
  79201. });
  79202. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  79203. /**
  79204. * Gets or sets the maximum pitch angle that the bone can look to
  79205. */
  79206. get: function () {
  79207. return this._maxPitch;
  79208. },
  79209. set: function (value) {
  79210. this._maxPitch = value;
  79211. this._maxPitchTan = Math.tan(value);
  79212. },
  79213. enumerable: true,
  79214. configurable: true
  79215. });
  79216. /**
  79217. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  79218. */
  79219. BoneLookController.prototype.update = function () {
  79220. //skip the first frame when slerping so that the mesh rotation is correct
  79221. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  79222. this._firstFrameSkipped = true;
  79223. return;
  79224. }
  79225. var bone = this.bone;
  79226. var bonePos = BoneLookController._tmpVecs[0];
  79227. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  79228. var target = this.target;
  79229. var _tmpMat1 = BoneLookController._tmpMats[0];
  79230. var _tmpMat2 = BoneLookController._tmpMats[1];
  79231. var mesh = this.mesh;
  79232. var parentBone = bone.getParent();
  79233. var upAxis = BoneLookController._tmpVecs[1];
  79234. upAxis.copyFrom(this.upAxis);
  79235. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  79236. if (this._transformYawPitch) {
  79237. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  79238. }
  79239. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  79240. }
  79241. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  79242. mesh.getDirectionToRef(upAxis, upAxis);
  79243. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  79244. upAxis.normalize();
  79245. }
  79246. }
  79247. var checkYaw = false;
  79248. var checkPitch = false;
  79249. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  79250. checkYaw = true;
  79251. }
  79252. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  79253. checkPitch = true;
  79254. }
  79255. if (checkYaw || checkPitch) {
  79256. var spaceMat = BoneLookController._tmpMats[2];
  79257. var spaceMatInv = BoneLookController._tmpMats[3];
  79258. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  79259. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  79260. }
  79261. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  79262. spaceMat.copyFrom(mesh.getWorldMatrix());
  79263. }
  79264. else {
  79265. var forwardAxis = BoneLookController._tmpVecs[2];
  79266. forwardAxis.copyFrom(this._fowardAxis);
  79267. if (this._transformYawPitch) {
  79268. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  79269. }
  79270. if (parentBone) {
  79271. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  79272. }
  79273. else {
  79274. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  79275. }
  79276. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  79277. rightAxis.normalize();
  79278. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  79279. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  79280. }
  79281. spaceMat.invertToRef(spaceMatInv);
  79282. var xzlen = null;
  79283. if (checkPitch) {
  79284. var localTarget = BoneLookController._tmpVecs[3];
  79285. target.subtractToRef(bonePos, localTarget);
  79286. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79287. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79288. var pitch = Math.atan2(localTarget.y, xzlen);
  79289. var newPitch = pitch;
  79290. if (pitch > this._maxPitch) {
  79291. localTarget.y = this._maxPitchTan * xzlen;
  79292. newPitch = this._maxPitch;
  79293. }
  79294. else if (pitch < this._minPitch) {
  79295. localTarget.y = this._minPitchTan * xzlen;
  79296. newPitch = this._minPitch;
  79297. }
  79298. if (pitch != newPitch) {
  79299. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79300. localTarget.addInPlace(bonePos);
  79301. target = localTarget;
  79302. }
  79303. }
  79304. if (checkYaw) {
  79305. var localTarget = BoneLookController._tmpVecs[4];
  79306. target.subtractToRef(bonePos, localTarget);
  79307. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79308. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79309. var newYaw = yaw;
  79310. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79311. if (xzlen == null) {
  79312. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79313. }
  79314. if (this._yawRange > Math.PI) {
  79315. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79316. localTarget.z = this._maxYawCos * xzlen;
  79317. localTarget.x = this._maxYawSin * xzlen;
  79318. newYaw = this._maxYaw;
  79319. }
  79320. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79321. localTarget.z = this._minYawCos * xzlen;
  79322. localTarget.x = this._minYawSin * xzlen;
  79323. newYaw = this._minYaw;
  79324. }
  79325. }
  79326. else {
  79327. if (yaw > this._maxYaw) {
  79328. localTarget.z = this._maxYawCos * xzlen;
  79329. localTarget.x = this._maxYawSin * xzlen;
  79330. newYaw = this._maxYaw;
  79331. }
  79332. else if (yaw < this._minYaw) {
  79333. localTarget.z = this._minYawCos * xzlen;
  79334. localTarget.x = this._minYawSin * xzlen;
  79335. newYaw = this._minYaw;
  79336. }
  79337. }
  79338. }
  79339. if (this._slerping && this._yawRange > Math.PI) {
  79340. //are we going to be crossing into the min/max region?
  79341. var boneFwd = BoneLookController._tmpVecs[8];
  79342. boneFwd.copyFrom(BABYLON.Axis.Z);
  79343. if (this._transformYawPitch) {
  79344. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79345. }
  79346. var boneRotMat = BoneLookController._tmpMats[4];
  79347. this._boneQuat.toRotationMatrix(boneRotMat);
  79348. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79349. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79350. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79351. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79352. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79353. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79354. if (angBtwTar > angBtwMidYaw) {
  79355. if (xzlen == null) {
  79356. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79357. }
  79358. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79359. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79360. if (angBtwMin < angBtwMax) {
  79361. newYaw = boneYaw + Math.PI * .75;
  79362. localTarget.z = Math.cos(newYaw) * xzlen;
  79363. localTarget.x = Math.sin(newYaw) * xzlen;
  79364. }
  79365. else {
  79366. newYaw = boneYaw - Math.PI * .75;
  79367. localTarget.z = Math.cos(newYaw) * xzlen;
  79368. localTarget.x = Math.sin(newYaw) * xzlen;
  79369. }
  79370. }
  79371. }
  79372. if (yaw != newYaw) {
  79373. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79374. localTarget.addInPlace(bonePos);
  79375. target = localTarget;
  79376. }
  79377. }
  79378. }
  79379. var zaxis = BoneLookController._tmpVecs[5];
  79380. var xaxis = BoneLookController._tmpVecs[6];
  79381. var yaxis = BoneLookController._tmpVecs[7];
  79382. var _tmpQuat = BoneLookController._tmpQuat;
  79383. target.subtractToRef(bonePos, zaxis);
  79384. zaxis.normalize();
  79385. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79386. xaxis.normalize();
  79387. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79388. yaxis.normalize();
  79389. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79390. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79391. return;
  79392. }
  79393. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79394. return;
  79395. }
  79396. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79397. return;
  79398. }
  79399. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79400. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79401. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79402. }
  79403. if (this.slerpAmount < 1) {
  79404. if (!this._slerping) {
  79405. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79406. }
  79407. if (this._transformYawPitch) {
  79408. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79409. }
  79410. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79411. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79412. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79413. this._slerping = true;
  79414. }
  79415. else {
  79416. if (this._transformYawPitch) {
  79417. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79418. }
  79419. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79420. this._slerping = false;
  79421. }
  79422. };
  79423. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79424. var angDiff = ang2 - ang1;
  79425. angDiff %= Math.PI * 2;
  79426. if (angDiff > Math.PI) {
  79427. angDiff -= Math.PI * 2;
  79428. }
  79429. else if (angDiff < -Math.PI) {
  79430. angDiff += Math.PI * 2;
  79431. }
  79432. return angDiff;
  79433. };
  79434. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79435. ang1 %= (2 * Math.PI);
  79436. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79437. ang2 %= (2 * Math.PI);
  79438. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79439. var ab = 0;
  79440. if (ang1 < ang2) {
  79441. ab = ang2 - ang1;
  79442. }
  79443. else {
  79444. ab = ang1 - ang2;
  79445. }
  79446. if (ab > Math.PI) {
  79447. ab = Math.PI * 2 - ab;
  79448. }
  79449. return ab;
  79450. };
  79451. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79452. ang %= (2 * Math.PI);
  79453. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79454. ang1 %= (2 * Math.PI);
  79455. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79456. ang2 %= (2 * Math.PI);
  79457. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79458. if (ang1 < ang2) {
  79459. if (ang > ang1 && ang < ang2) {
  79460. return true;
  79461. }
  79462. }
  79463. else {
  79464. if (ang > ang2 && ang < ang1) {
  79465. return true;
  79466. }
  79467. }
  79468. return false;
  79469. };
  79470. 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()];
  79471. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79472. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79473. return BoneLookController;
  79474. }());
  79475. BABYLON.BoneLookController = BoneLookController;
  79476. })(BABYLON || (BABYLON = {}));
  79477. //# sourceMappingURL=babylon.boneLookController.js.map
  79478. var BABYLON;
  79479. (function (BABYLON) {
  79480. /**
  79481. * Class used to handle skinning animations
  79482. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79483. */
  79484. var Skeleton = /** @class */ (function () {
  79485. /**
  79486. * Creates a new skeleton
  79487. * @param name defines the skeleton name
  79488. * @param id defines the skeleton Id
  79489. * @param scene defines the hosting scene
  79490. */
  79491. function Skeleton(
  79492. /** defines the skeleton name */
  79493. name,
  79494. /** defines the skeleton Id */
  79495. id, scene) {
  79496. this.name = name;
  79497. this.id = id;
  79498. /**
  79499. * Gets the list of child bones
  79500. */
  79501. this.bones = new Array();
  79502. /**
  79503. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79504. */
  79505. this.needInitialSkinMatrix = false;
  79506. this._isDirty = true;
  79507. this._meshesWithPoseMatrix = new Array();
  79508. this._identity = BABYLON.Matrix.Identity();
  79509. this._ranges = {};
  79510. this._lastAbsoluteTransformsUpdateId = -1;
  79511. /**
  79512. * Specifies if the skeleton should be serialized
  79513. */
  79514. this.doNotSerialize = false;
  79515. this._animationPropertiesOverride = null;
  79516. // Events
  79517. /**
  79518. * An observable triggered before computing the skeleton's matrices
  79519. */
  79520. this.onBeforeComputeObservable = new BABYLON.Observable();
  79521. this.bones = [];
  79522. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79523. scene.skeletons.push(this);
  79524. //make sure it will recalculate the matrix next time prepare is called.
  79525. this._isDirty = true;
  79526. }
  79527. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79528. /**
  79529. * Gets or sets the animation properties override
  79530. */
  79531. get: function () {
  79532. if (!this._animationPropertiesOverride) {
  79533. return this._scene.animationPropertiesOverride;
  79534. }
  79535. return this._animationPropertiesOverride;
  79536. },
  79537. set: function (value) {
  79538. this._animationPropertiesOverride = value;
  79539. },
  79540. enumerable: true,
  79541. configurable: true
  79542. });
  79543. // Members
  79544. /**
  79545. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79546. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79547. * @returns a Float32Array containing matrices data
  79548. */
  79549. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79550. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79551. return mesh._bonesTransformMatrices;
  79552. }
  79553. if (!this._transformMatrices) {
  79554. this.prepare();
  79555. }
  79556. return this._transformMatrices;
  79557. };
  79558. /**
  79559. * Gets the current hosting scene
  79560. * @returns a scene object
  79561. */
  79562. Skeleton.prototype.getScene = function () {
  79563. return this._scene;
  79564. };
  79565. // Methods
  79566. /**
  79567. * Gets a string representing the current skeleton data
  79568. * @param fullDetails defines a boolean indicating if we want a verbose version
  79569. * @returns a string representing the current skeleton data
  79570. */
  79571. Skeleton.prototype.toString = function (fullDetails) {
  79572. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79573. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79574. if (fullDetails) {
  79575. ret += ", Ranges: {";
  79576. var first = true;
  79577. for (var name_1 in this._ranges) {
  79578. if (first) {
  79579. ret += ", ";
  79580. first = false;
  79581. }
  79582. ret += name_1;
  79583. }
  79584. ret += "}";
  79585. }
  79586. return ret;
  79587. };
  79588. /**
  79589. * Get bone's index searching by name
  79590. * @param name defines bone's name to search for
  79591. * @return the indice of the bone. Returns -1 if not found
  79592. */
  79593. Skeleton.prototype.getBoneIndexByName = function (name) {
  79594. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79595. if (this.bones[boneIndex].name === name) {
  79596. return boneIndex;
  79597. }
  79598. }
  79599. return -1;
  79600. };
  79601. /**
  79602. * Creater a new animation range
  79603. * @param name defines the name of the range
  79604. * @param from defines the start key
  79605. * @param to defines the end key
  79606. */
  79607. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79608. // check name not already in use
  79609. if (!this._ranges[name]) {
  79610. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79611. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79612. if (this.bones[i].animations[0]) {
  79613. this.bones[i].animations[0].createRange(name, from, to);
  79614. }
  79615. }
  79616. }
  79617. };
  79618. /**
  79619. * Delete a specific animation range
  79620. * @param name defines the name of the range
  79621. * @param deleteFrames defines if frames must be removed as well
  79622. */
  79623. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79624. if (deleteFrames === void 0) { deleteFrames = true; }
  79625. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79626. if (this.bones[i].animations[0]) {
  79627. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79628. }
  79629. }
  79630. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79631. };
  79632. /**
  79633. * Gets a specific animation range
  79634. * @param name defines the name of the range to look for
  79635. * @returns the requested animation range or null if not found
  79636. */
  79637. Skeleton.prototype.getAnimationRange = function (name) {
  79638. return this._ranges[name];
  79639. };
  79640. /**
  79641. * Gets the list of all animation ranges defined on this skeleton
  79642. * @returns an array
  79643. */
  79644. Skeleton.prototype.getAnimationRanges = function () {
  79645. var animationRanges = [];
  79646. var name;
  79647. var i = 0;
  79648. for (name in this._ranges) {
  79649. animationRanges[i] = this._ranges[name];
  79650. i++;
  79651. }
  79652. return animationRanges;
  79653. };
  79654. /**
  79655. * Copy animation range from a source skeleton.
  79656. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79657. * @param source defines the source skeleton
  79658. * @param name defines the name of the range to copy
  79659. * @param rescaleAsRequired defines if rescaling must be applied if required
  79660. * @returns true if operation was successful
  79661. */
  79662. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79663. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79664. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79665. return false;
  79666. }
  79667. var ret = true;
  79668. var frameOffset = this._getHighestAnimationFrame() + 1;
  79669. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79670. var boneDict = {};
  79671. var sourceBones = source.bones;
  79672. var nBones;
  79673. var i;
  79674. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79675. boneDict[sourceBones[i].name] = sourceBones[i];
  79676. }
  79677. if (this.bones.length !== sourceBones.length) {
  79678. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79679. ret = false;
  79680. }
  79681. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79682. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79683. var boneName = this.bones[i].name;
  79684. var sourceBone = boneDict[boneName];
  79685. if (sourceBone) {
  79686. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79687. }
  79688. else {
  79689. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79690. ret = false;
  79691. }
  79692. }
  79693. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79694. var range = source.getAnimationRange(name);
  79695. if (range) {
  79696. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79697. }
  79698. return ret;
  79699. };
  79700. /**
  79701. * Forces the skeleton to go to rest pose
  79702. */
  79703. Skeleton.prototype.returnToRest = function () {
  79704. for (var index = 0; index < this.bones.length; index++) {
  79705. this.bones[index].returnToRest();
  79706. }
  79707. };
  79708. Skeleton.prototype._getHighestAnimationFrame = function () {
  79709. var ret = 0;
  79710. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79711. if (this.bones[i].animations[0]) {
  79712. var highest = this.bones[i].animations[0].getHighestFrame();
  79713. if (ret < highest) {
  79714. ret = highest;
  79715. }
  79716. }
  79717. }
  79718. return ret;
  79719. };
  79720. /**
  79721. * Begin a specific animation range
  79722. * @param name defines the name of the range to start
  79723. * @param loop defines if looping must be turned on (false by default)
  79724. * @param speedRatio defines the speed ratio to apply (1 by default)
  79725. * @param onAnimationEnd defines a callback which will be called when animation will end
  79726. * @returns a new animatable
  79727. */
  79728. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79729. var range = this.getAnimationRange(name);
  79730. if (!range) {
  79731. return null;
  79732. }
  79733. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79734. };
  79735. /** @hidden */
  79736. Skeleton.prototype._markAsDirty = function () {
  79737. this._isDirty = true;
  79738. };
  79739. /** @hidden */
  79740. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79741. this._meshesWithPoseMatrix.push(mesh);
  79742. };
  79743. /** @hidden */
  79744. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79745. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79746. if (index > -1) {
  79747. this._meshesWithPoseMatrix.splice(index, 1);
  79748. }
  79749. };
  79750. /** @hidden */
  79751. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79752. this.onBeforeComputeObservable.notifyObservers(this);
  79753. for (var index = 0; index < this.bones.length; index++) {
  79754. var bone = this.bones[index];
  79755. var parentBone = bone.getParent();
  79756. if (parentBone) {
  79757. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79758. }
  79759. else {
  79760. if (initialSkinMatrix) {
  79761. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79762. }
  79763. else {
  79764. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79765. }
  79766. }
  79767. if (bone._index !== -1) {
  79768. var mappedIndex = bone._index === null ? index : bone._index;
  79769. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79770. }
  79771. }
  79772. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79773. };
  79774. /**
  79775. * Build all resources required to render a skeleton
  79776. */
  79777. Skeleton.prototype.prepare = function () {
  79778. if (!this._isDirty) {
  79779. return;
  79780. }
  79781. if (this.needInitialSkinMatrix) {
  79782. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79783. var mesh = this._meshesWithPoseMatrix[index];
  79784. var poseMatrix = mesh.getPoseMatrix();
  79785. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79786. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79787. }
  79788. if (this._synchronizedWithMesh !== mesh) {
  79789. this._synchronizedWithMesh = mesh;
  79790. // Prepare bones
  79791. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79792. var bone = this.bones[boneIndex];
  79793. if (!bone.getParent()) {
  79794. var matrix = bone.getBaseMatrix();
  79795. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79796. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79797. }
  79798. }
  79799. }
  79800. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79801. }
  79802. }
  79803. else {
  79804. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79805. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79806. }
  79807. this._computeTransformMatrices(this._transformMatrices, null);
  79808. }
  79809. this._isDirty = false;
  79810. this._scene._activeBones.addCount(this.bones.length, false);
  79811. };
  79812. /**
  79813. * Gets the list of animatables currently running for this skeleton
  79814. * @returns an array of animatables
  79815. */
  79816. Skeleton.prototype.getAnimatables = function () {
  79817. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79818. this._animatables = [];
  79819. for (var index = 0; index < this.bones.length; index++) {
  79820. this._animatables.push(this.bones[index]);
  79821. }
  79822. }
  79823. return this._animatables;
  79824. };
  79825. /**
  79826. * Clone the current skeleton
  79827. * @param name defines the name of the new skeleton
  79828. * @param id defines the id of the enw skeleton
  79829. * @returns the new skeleton
  79830. */
  79831. Skeleton.prototype.clone = function (name, id) {
  79832. var result = new Skeleton(name, id || name, this._scene);
  79833. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79834. for (var index = 0; index < this.bones.length; index++) {
  79835. var source = this.bones[index];
  79836. var parentBone = null;
  79837. var parent_1 = source.getParent();
  79838. if (parent_1) {
  79839. var parentIndex = this.bones.indexOf(parent_1);
  79840. parentBone = result.bones[parentIndex];
  79841. }
  79842. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  79843. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  79844. }
  79845. if (this._ranges) {
  79846. result._ranges = {};
  79847. for (var rangeName in this._ranges) {
  79848. var range = this._ranges[rangeName];
  79849. if (range) {
  79850. result._ranges[rangeName] = range.clone();
  79851. }
  79852. }
  79853. }
  79854. this._isDirty = true;
  79855. return result;
  79856. };
  79857. /**
  79858. * Enable animation blending for this skeleton
  79859. * @param blendingSpeed defines the blending speed to apply
  79860. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  79861. */
  79862. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  79863. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  79864. this.bones.forEach(function (bone) {
  79865. bone.animations.forEach(function (animation) {
  79866. animation.enableBlending = true;
  79867. animation.blendingSpeed = blendingSpeed;
  79868. });
  79869. });
  79870. };
  79871. /**
  79872. * Releases all resources associated with the current skeleton
  79873. */
  79874. Skeleton.prototype.dispose = function () {
  79875. this._meshesWithPoseMatrix = [];
  79876. // Animations
  79877. this.getScene().stopAnimation(this);
  79878. // Remove from scene
  79879. this.getScene().removeSkeleton(this);
  79880. };
  79881. /**
  79882. * Serialize the skeleton in a JSON object
  79883. * @returns a JSON object
  79884. */
  79885. Skeleton.prototype.serialize = function () {
  79886. var serializationObject = {};
  79887. serializationObject.name = this.name;
  79888. serializationObject.id = this.id;
  79889. if (this.dimensionsAtRest) {
  79890. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  79891. }
  79892. serializationObject.bones = [];
  79893. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79894. for (var index = 0; index < this.bones.length; index++) {
  79895. var bone = this.bones[index];
  79896. var parent_2 = bone.getParent();
  79897. var serializedBone = {
  79898. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  79899. name: bone.name,
  79900. matrix: bone.getBaseMatrix().toArray(),
  79901. rest: bone.getRestPose().toArray()
  79902. };
  79903. serializationObject.bones.push(serializedBone);
  79904. if (bone.length) {
  79905. serializedBone.length = bone.length;
  79906. }
  79907. if (bone.metadata) {
  79908. serializedBone.metadata = bone.metadata;
  79909. }
  79910. if (bone.animations && bone.animations.length > 0) {
  79911. serializedBone.animation = bone.animations[0].serialize();
  79912. }
  79913. serializationObject.ranges = [];
  79914. for (var name in this._ranges) {
  79915. var source = this._ranges[name];
  79916. if (!source) {
  79917. continue;
  79918. }
  79919. var range = {};
  79920. range.name = name;
  79921. range.from = source.from;
  79922. range.to = source.to;
  79923. serializationObject.ranges.push(range);
  79924. }
  79925. }
  79926. return serializationObject;
  79927. };
  79928. /**
  79929. * Creates a new skeleton from serialized data
  79930. * @param parsedSkeleton defines the serialized data
  79931. * @param scene defines the hosting scene
  79932. * @returns a new skeleton
  79933. */
  79934. Skeleton.Parse = function (parsedSkeleton, scene) {
  79935. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  79936. if (parsedSkeleton.dimensionsAtRest) {
  79937. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  79938. }
  79939. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  79940. var index;
  79941. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  79942. var parsedBone = parsedSkeleton.bones[index];
  79943. var parentBone = null;
  79944. if (parsedBone.parentBoneIndex > -1) {
  79945. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  79946. }
  79947. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  79948. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  79949. if (parsedBone.length) {
  79950. bone.length = parsedBone.length;
  79951. }
  79952. if (parsedBone.metadata) {
  79953. bone.metadata = parsedBone.metadata;
  79954. }
  79955. if (parsedBone.animation) {
  79956. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  79957. }
  79958. }
  79959. // placed after bones, so createAnimationRange can cascade down
  79960. if (parsedSkeleton.ranges) {
  79961. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  79962. var data = parsedSkeleton.ranges[index];
  79963. skeleton.createAnimationRange(data.name, data.from, data.to);
  79964. }
  79965. }
  79966. return skeleton;
  79967. };
  79968. /**
  79969. * Compute all node absolute transforms
  79970. * @param forceUpdate defines if computation must be done even if cache is up to date
  79971. */
  79972. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  79973. if (forceUpdate === void 0) { forceUpdate = false; }
  79974. var renderId = this._scene.getRenderId();
  79975. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  79976. this.bones[0].computeAbsoluteTransforms();
  79977. this._lastAbsoluteTransformsUpdateId = renderId;
  79978. }
  79979. };
  79980. /**
  79981. * Gets the root pose matrix
  79982. * @returns a matrix
  79983. */
  79984. Skeleton.prototype.getPoseMatrix = function () {
  79985. var poseMatrix = null;
  79986. if (this._meshesWithPoseMatrix.length > 0) {
  79987. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  79988. }
  79989. return poseMatrix;
  79990. };
  79991. /**
  79992. * Sorts bones per internal index
  79993. */
  79994. Skeleton.prototype.sortBones = function () {
  79995. var bones = new Array();
  79996. var visited = new Array(this.bones.length);
  79997. for (var index = 0; index < this.bones.length; index++) {
  79998. this._sortBones(index, bones, visited);
  79999. }
  80000. this.bones = bones;
  80001. };
  80002. Skeleton.prototype._sortBones = function (index, bones, visited) {
  80003. if (visited[index]) {
  80004. return;
  80005. }
  80006. visited[index] = true;
  80007. var bone = this.bones[index];
  80008. if (bone._index === undefined) {
  80009. bone._index = index;
  80010. }
  80011. var parentBone = bone.getParent();
  80012. if (parentBone) {
  80013. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  80014. }
  80015. bones.push(bone);
  80016. };
  80017. return Skeleton;
  80018. }());
  80019. BABYLON.Skeleton = Skeleton;
  80020. })(BABYLON || (BABYLON = {}));
  80021. //# sourceMappingURL=babylon.skeleton.js.map
  80022. var BABYLON;
  80023. (function (BABYLON) {
  80024. var SphericalPolynomial = /** @class */ (function () {
  80025. function SphericalPolynomial() {
  80026. this.x = BABYLON.Vector3.Zero();
  80027. this.y = BABYLON.Vector3.Zero();
  80028. this.z = BABYLON.Vector3.Zero();
  80029. this.xx = BABYLON.Vector3.Zero();
  80030. this.yy = BABYLON.Vector3.Zero();
  80031. this.zz = BABYLON.Vector3.Zero();
  80032. this.xy = BABYLON.Vector3.Zero();
  80033. this.yz = BABYLON.Vector3.Zero();
  80034. this.zx = BABYLON.Vector3.Zero();
  80035. }
  80036. SphericalPolynomial.prototype.addAmbient = function (color) {
  80037. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80038. this.xx = this.xx.add(colorVector);
  80039. this.yy = this.yy.add(colorVector);
  80040. this.zz = this.zz.add(colorVector);
  80041. };
  80042. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  80043. var result = new SphericalPolynomial();
  80044. result.x = harmonics.L11.scale(1.02333);
  80045. result.y = harmonics.L1_1.scale(1.02333);
  80046. result.z = harmonics.L10.scale(1.02333);
  80047. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  80048. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  80049. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  80050. result.yz = harmonics.L2_1.scale(0.858086);
  80051. result.zx = harmonics.L21.scale(0.858086);
  80052. result.xy = harmonics.L2_2.scale(0.858086);
  80053. result.scale(1.0 / Math.PI);
  80054. return result;
  80055. };
  80056. SphericalPolynomial.prototype.scale = function (scale) {
  80057. this.x = this.x.scale(scale);
  80058. this.y = this.y.scale(scale);
  80059. this.z = this.z.scale(scale);
  80060. this.xx = this.xx.scale(scale);
  80061. this.yy = this.yy.scale(scale);
  80062. this.zz = this.zz.scale(scale);
  80063. this.yz = this.yz.scale(scale);
  80064. this.zx = this.zx.scale(scale);
  80065. this.xy = this.xy.scale(scale);
  80066. };
  80067. return SphericalPolynomial;
  80068. }());
  80069. BABYLON.SphericalPolynomial = SphericalPolynomial;
  80070. var SphericalHarmonics = /** @class */ (function () {
  80071. function SphericalHarmonics() {
  80072. this.L00 = BABYLON.Vector3.Zero();
  80073. this.L1_1 = BABYLON.Vector3.Zero();
  80074. this.L10 = BABYLON.Vector3.Zero();
  80075. this.L11 = BABYLON.Vector3.Zero();
  80076. this.L2_2 = BABYLON.Vector3.Zero();
  80077. this.L2_1 = BABYLON.Vector3.Zero();
  80078. this.L20 = BABYLON.Vector3.Zero();
  80079. this.L21 = BABYLON.Vector3.Zero();
  80080. this.L22 = BABYLON.Vector3.Zero();
  80081. }
  80082. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  80083. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80084. var c = colorVector.scale(deltaSolidAngle);
  80085. this.L00 = this.L00.add(c.scale(0.282095));
  80086. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  80087. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  80088. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  80089. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  80090. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  80091. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  80092. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  80093. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  80094. };
  80095. SphericalHarmonics.prototype.scale = function (scale) {
  80096. this.L00 = this.L00.scale(scale);
  80097. this.L1_1 = this.L1_1.scale(scale);
  80098. this.L10 = this.L10.scale(scale);
  80099. this.L11 = this.L11.scale(scale);
  80100. this.L2_2 = this.L2_2.scale(scale);
  80101. this.L2_1 = this.L2_1.scale(scale);
  80102. this.L20 = this.L20.scale(scale);
  80103. this.L21 = this.L21.scale(scale);
  80104. this.L22 = this.L22.scale(scale);
  80105. };
  80106. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  80107. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  80108. //
  80109. // E_lm = A_l * L_lm
  80110. //
  80111. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  80112. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  80113. // the scaling factors are given in equation 9.
  80114. // Constant (Band 0)
  80115. this.L00 = this.L00.scale(3.141593);
  80116. // Linear (Band 1)
  80117. this.L1_1 = this.L1_1.scale(2.094395);
  80118. this.L10 = this.L10.scale(2.094395);
  80119. this.L11 = this.L11.scale(2.094395);
  80120. // Quadratic (Band 2)
  80121. this.L2_2 = this.L2_2.scale(0.785398);
  80122. this.L2_1 = this.L2_1.scale(0.785398);
  80123. this.L20 = this.L20.scale(0.785398);
  80124. this.L21 = this.L21.scale(0.785398);
  80125. this.L22 = this.L22.scale(0.785398);
  80126. };
  80127. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  80128. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  80129. // L = (1/pi) * E * rho
  80130. //
  80131. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  80132. this.scale(1.0 / Math.PI);
  80133. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  80134. // (The pixel shader must apply albedo after texture fetches, etc).
  80135. };
  80136. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  80137. var result = new SphericalHarmonics();
  80138. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  80139. result.L1_1 = polynomial.y.scale(0.977204);
  80140. result.L10 = polynomial.z.scale(0.977204);
  80141. result.L11 = polynomial.x.scale(0.977204);
  80142. result.L2_2 = polynomial.xy.scale(1.16538);
  80143. result.L2_1 = polynomial.yz.scale(1.16538);
  80144. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  80145. result.L21 = polynomial.zx.scale(1.16538);
  80146. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  80147. result.scale(Math.PI);
  80148. return result;
  80149. };
  80150. return SphericalHarmonics;
  80151. }());
  80152. BABYLON.SphericalHarmonics = SphericalHarmonics;
  80153. })(BABYLON || (BABYLON = {}));
  80154. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  80155. var BABYLON;
  80156. (function (BABYLON) {
  80157. var FileFaceOrientation = /** @class */ (function () {
  80158. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  80159. this.name = name;
  80160. this.worldAxisForNormal = worldAxisForNormal;
  80161. this.worldAxisForFileX = worldAxisForFileX;
  80162. this.worldAxisForFileY = worldAxisForFileY;
  80163. }
  80164. return FileFaceOrientation;
  80165. }());
  80166. ;
  80167. /**
  80168. * Helper class dealing with the extraction of spherical polynomial dataArray
  80169. * from a cube map.
  80170. */
  80171. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  80172. function CubeMapToSphericalPolynomialTools() {
  80173. }
  80174. /**
  80175. * Converts a texture to the according Spherical Polynomial data.
  80176. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80177. *
  80178. * @param texture The texture to extract the information from.
  80179. * @return The Spherical Polynomial data.
  80180. */
  80181. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  80182. if (!texture.isCube) {
  80183. // Only supports cube Textures currently.
  80184. return null;
  80185. }
  80186. var size = texture.getSize().width;
  80187. var right = texture.readPixels(0);
  80188. var left = texture.readPixels(1);
  80189. var up;
  80190. var down;
  80191. if (texture.isRenderTarget) {
  80192. up = texture.readPixels(3);
  80193. down = texture.readPixels(2);
  80194. }
  80195. else {
  80196. up = texture.readPixels(2);
  80197. down = texture.readPixels(3);
  80198. }
  80199. var front = texture.readPixels(4);
  80200. var back = texture.readPixels(5);
  80201. var gammaSpace = texture.gammaSpace;
  80202. // Always read as RGBA.
  80203. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  80204. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80205. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80206. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80207. }
  80208. var cubeInfo = {
  80209. size: size,
  80210. right: right,
  80211. left: left,
  80212. up: up,
  80213. down: down,
  80214. front: front,
  80215. back: back,
  80216. format: format,
  80217. type: type,
  80218. gammaSpace: gammaSpace,
  80219. };
  80220. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  80221. };
  80222. /**
  80223. * Converts a cubemap to the according Spherical Polynomial data.
  80224. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80225. *
  80226. * @param cubeInfo The Cube map to extract the information from.
  80227. * @return The Spherical Polynomial data.
  80228. */
  80229. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  80230. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  80231. var totalSolidAngle = 0.0;
  80232. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  80233. var du = 2.0 / cubeInfo.size;
  80234. var dv = du;
  80235. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  80236. var minUV = du * 0.5 - 1.0;
  80237. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80238. var fileFace = this.FileFaces[faceIndex];
  80239. var dataArray = cubeInfo[fileFace.name];
  80240. var v = minUV;
  80241. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  80242. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  80243. // Because SP is still linear, so summation is fine in that basis.
  80244. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  80245. for (var y = 0; y < cubeInfo.size; y++) {
  80246. var u = minUV;
  80247. for (var x = 0; x < cubeInfo.size; x++) {
  80248. // World direction (not normalised)
  80249. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  80250. worldDirection.normalize();
  80251. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  80252. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  80253. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  80254. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  80255. // Handle Integer types.
  80256. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80257. r /= 255;
  80258. g /= 255;
  80259. b /= 255;
  80260. }
  80261. // Handle Gamma space textures.
  80262. if (cubeInfo.gammaSpace) {
  80263. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  80264. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  80265. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  80266. }
  80267. var color = new BABYLON.Color3(r, g, b);
  80268. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  80269. totalSolidAngle += deltaSolidAngle;
  80270. u += du;
  80271. }
  80272. v += dv;
  80273. }
  80274. }
  80275. // Solid angle for entire sphere is 4*pi
  80276. var sphereSolidAngle = 4.0 * Math.PI;
  80277. // Adjust the solid angle to allow for how many faces we processed.
  80278. var facesProcessed = 6.0;
  80279. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  80280. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  80281. // This is needed because the numerical integration over the cube uses a
  80282. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  80283. // and also to compensate for accumulative error due to float precision in the summation.
  80284. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  80285. sphericalHarmonics.scale(correctionFactor);
  80286. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  80287. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  80288. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  80289. };
  80290. CubeMapToSphericalPolynomialTools.FileFaces = [
  80291. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  80292. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80293. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80294. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80295. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80296. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80297. ];
  80298. return CubeMapToSphericalPolynomialTools;
  80299. }());
  80300. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80301. })(BABYLON || (BABYLON = {}));
  80302. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80303. var BABYLON;
  80304. (function (BABYLON) {
  80305. /**
  80306. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80307. */
  80308. var PanoramaToCubeMapTools = /** @class */ (function () {
  80309. function PanoramaToCubeMapTools() {
  80310. }
  80311. /**
  80312. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80313. *
  80314. * @param float32Array The source data.
  80315. * @param inputWidth The width of the input panorama.
  80316. * @param inputhHeight The height of the input panorama.
  80317. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80318. * @return The cubemap data
  80319. */
  80320. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80321. if (!float32Array) {
  80322. throw "ConvertPanoramaToCubemap: input cannot be null";
  80323. }
  80324. if (float32Array.length != inputWidth * inputHeight * 3) {
  80325. throw "ConvertPanoramaToCubemap: input size is wrong";
  80326. }
  80327. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80328. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80329. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80330. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80331. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80332. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80333. return {
  80334. front: textureFront,
  80335. back: textureBack,
  80336. left: textureLeft,
  80337. right: textureRight,
  80338. up: textureUp,
  80339. down: textureDown,
  80340. size: size,
  80341. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80342. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80343. gammaSpace: false,
  80344. };
  80345. };
  80346. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80347. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80348. var textureArray = new Float32Array(buffer);
  80349. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80350. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80351. var dy = 1 / texSize;
  80352. var fy = 0;
  80353. for (var y = 0; y < texSize; y++) {
  80354. var xv1 = faceData[0];
  80355. var xv2 = faceData[2];
  80356. for (var x = 0; x < texSize; x++) {
  80357. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80358. v.normalize();
  80359. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80360. // 3 channels per pixels
  80361. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80362. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80363. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80364. xv1 = xv1.add(rotDX1);
  80365. xv2 = xv2.add(rotDX2);
  80366. }
  80367. fy += dy;
  80368. }
  80369. return textureArray;
  80370. };
  80371. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80372. var theta = Math.atan2(vDir.z, vDir.x);
  80373. var phi = Math.acos(vDir.y);
  80374. while (theta < -Math.PI)
  80375. theta += 2 * Math.PI;
  80376. while (theta > Math.PI)
  80377. theta -= 2 * Math.PI;
  80378. var dx = theta / Math.PI;
  80379. var dy = phi / Math.PI;
  80380. // recenter.
  80381. dx = dx * 0.5 + 0.5;
  80382. var px = Math.round(dx * inputWidth);
  80383. if (px < 0)
  80384. px = 0;
  80385. else if (px >= inputWidth)
  80386. px = inputWidth - 1;
  80387. var py = Math.round(dy * inputHeight);
  80388. if (py < 0)
  80389. py = 0;
  80390. else if (py >= inputHeight)
  80391. py = inputHeight - 1;
  80392. var inputY = (inputHeight - py - 1);
  80393. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80394. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80395. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80396. return {
  80397. r: r,
  80398. g: g,
  80399. b: b
  80400. };
  80401. };
  80402. PanoramaToCubeMapTools.FACE_FRONT = [
  80403. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80404. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80405. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80406. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80407. ];
  80408. PanoramaToCubeMapTools.FACE_BACK = [
  80409. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80410. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80411. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80412. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80413. ];
  80414. PanoramaToCubeMapTools.FACE_RIGHT = [
  80415. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80416. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80417. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80418. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80419. ];
  80420. PanoramaToCubeMapTools.FACE_LEFT = [
  80421. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80422. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80423. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80424. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80425. ];
  80426. PanoramaToCubeMapTools.FACE_DOWN = [
  80427. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80428. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80429. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80430. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80431. ];
  80432. PanoramaToCubeMapTools.FACE_UP = [
  80433. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80434. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80435. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80436. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80437. ];
  80438. return PanoramaToCubeMapTools;
  80439. }());
  80440. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80441. })(BABYLON || (BABYLON = {}));
  80442. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80443. var BABYLON;
  80444. (function (BABYLON) {
  80445. ;
  80446. /**
  80447. * This groups tools to convert HDR texture to native colors array.
  80448. */
  80449. var HDRTools = /** @class */ (function () {
  80450. function HDRTools() {
  80451. }
  80452. HDRTools.Ldexp = function (mantissa, exponent) {
  80453. if (exponent > 1023) {
  80454. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80455. }
  80456. if (exponent < -1074) {
  80457. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80458. }
  80459. return mantissa * Math.pow(2, exponent);
  80460. };
  80461. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80462. if (exponent > 0) { /*nonzero pixel*/
  80463. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80464. float32array[index + 0] = red * exponent;
  80465. float32array[index + 1] = green * exponent;
  80466. float32array[index + 2] = blue * exponent;
  80467. }
  80468. else {
  80469. float32array[index + 0] = 0;
  80470. float32array[index + 1] = 0;
  80471. float32array[index + 2] = 0;
  80472. }
  80473. };
  80474. HDRTools.readStringLine = function (uint8array, startIndex) {
  80475. var line = "";
  80476. var character = "";
  80477. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80478. character = String.fromCharCode(uint8array[i]);
  80479. if (character == "\n") {
  80480. break;
  80481. }
  80482. line += character;
  80483. }
  80484. return line;
  80485. };
  80486. /**
  80487. * Reads header information from an RGBE texture stored in a native array.
  80488. * More information on this format are available here:
  80489. * https://en.wikipedia.org/wiki/RGBE_image_format
  80490. *
  80491. * @param uint8array The binary file stored in native array.
  80492. * @return The header information.
  80493. */
  80494. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80495. var height = 0;
  80496. var width = 0;
  80497. var line = this.readStringLine(uint8array, 0);
  80498. if (line[0] != '#' || line[1] != '?') {
  80499. throw "Bad HDR Format.";
  80500. }
  80501. var endOfHeader = false;
  80502. var findFormat = false;
  80503. var lineIndex = 0;
  80504. do {
  80505. lineIndex += (line.length + 1);
  80506. line = this.readStringLine(uint8array, lineIndex);
  80507. if (line == "FORMAT=32-bit_rle_rgbe") {
  80508. findFormat = true;
  80509. }
  80510. else if (line.length == 0) {
  80511. endOfHeader = true;
  80512. }
  80513. } while (!endOfHeader);
  80514. if (!findFormat) {
  80515. throw "HDR Bad header format, unsupported FORMAT";
  80516. }
  80517. lineIndex += (line.length + 1);
  80518. line = this.readStringLine(uint8array, lineIndex);
  80519. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80520. var match = sizeRegexp.exec(line);
  80521. // TODO. Support +Y and -X if needed.
  80522. if (!match || match.length < 3) {
  80523. throw "HDR Bad header format, no size";
  80524. }
  80525. width = parseInt(match[2]);
  80526. height = parseInt(match[1]);
  80527. if (width < 8 || width > 0x7fff) {
  80528. throw "HDR Bad header format, unsupported size";
  80529. }
  80530. lineIndex += (line.length + 1);
  80531. return {
  80532. height: height,
  80533. width: width,
  80534. dataPosition: lineIndex
  80535. };
  80536. };
  80537. /**
  80538. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80539. * This RGBE texture needs to store the information as a panorama.
  80540. *
  80541. * More information on this format are available here:
  80542. * https://en.wikipedia.org/wiki/RGBE_image_format
  80543. *
  80544. * @param buffer The binary file stored in an array buffer.
  80545. * @param size The expected size of the extracted cubemap.
  80546. * @return The Cube Map information.
  80547. */
  80548. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80549. var uint8array = new Uint8Array(buffer);
  80550. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80551. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80552. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80553. return cubeMapData;
  80554. };
  80555. /**
  80556. * Returns the pixels data extracted from an RGBE texture.
  80557. * This pixels will be stored left to right up to down in the R G B order in one array.
  80558. *
  80559. * More information on this format are available here:
  80560. * https://en.wikipedia.org/wiki/RGBE_image_format
  80561. *
  80562. * @param uint8array The binary file stored in an array buffer.
  80563. * @param hdrInfo The header information of the file.
  80564. * @return The pixels data in RGB right to left up to down order.
  80565. */
  80566. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80567. // Keep for multi format supports.
  80568. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80569. };
  80570. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80571. var num_scanlines = hdrInfo.height;
  80572. var scanline_width = hdrInfo.width;
  80573. var a, b, c, d, count;
  80574. var dataIndex = hdrInfo.dataPosition;
  80575. var index = 0, endIndex = 0, i = 0;
  80576. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80577. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80578. // 3 channels of 4 bytes per pixel in float.
  80579. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80580. var resultArray = new Float32Array(resultBuffer);
  80581. // read in each successive scanline
  80582. while (num_scanlines > 0) {
  80583. a = uint8array[dataIndex++];
  80584. b = uint8array[dataIndex++];
  80585. c = uint8array[dataIndex++];
  80586. d = uint8array[dataIndex++];
  80587. if (a != 2 || b != 2 || (c & 0x80)) {
  80588. // this file is not run length encoded
  80589. throw "HDR Bad header format, not RLE";
  80590. }
  80591. if (((c << 8) | d) != scanline_width) {
  80592. throw "HDR Bad header format, wrong scan line width";
  80593. }
  80594. index = 0;
  80595. // read each of the four channels for the scanline into the buffer
  80596. for (i = 0; i < 4; i++) {
  80597. endIndex = (i + 1) * scanline_width;
  80598. while (index < endIndex) {
  80599. a = uint8array[dataIndex++];
  80600. b = uint8array[dataIndex++];
  80601. if (a > 128) {
  80602. // a run of the same value
  80603. count = a - 128;
  80604. if ((count == 0) || (count > endIndex - index)) {
  80605. throw "HDR Bad Format, bad scanline data (run)";
  80606. }
  80607. while (count-- > 0) {
  80608. scanLineArray[index++] = b;
  80609. }
  80610. }
  80611. else {
  80612. // a non-run
  80613. count = a;
  80614. if ((count == 0) || (count > endIndex - index)) {
  80615. throw "HDR Bad Format, bad scanline data (non-run)";
  80616. }
  80617. scanLineArray[index++] = b;
  80618. if (--count > 0) {
  80619. for (var j = 0; j < count; j++) {
  80620. scanLineArray[index++] = uint8array[dataIndex++];
  80621. }
  80622. }
  80623. }
  80624. }
  80625. }
  80626. // now convert data from buffer into floats
  80627. for (i = 0; i < scanline_width; i++) {
  80628. a = scanLineArray[i];
  80629. b = scanLineArray[i + scanline_width];
  80630. c = scanLineArray[i + 2 * scanline_width];
  80631. d = scanLineArray[i + 3 * scanline_width];
  80632. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80633. }
  80634. num_scanlines--;
  80635. }
  80636. return resultArray;
  80637. };
  80638. return HDRTools;
  80639. }());
  80640. BABYLON.HDRTools = HDRTools;
  80641. })(BABYLON || (BABYLON = {}));
  80642. //# sourceMappingURL=babylon.hdr.js.map
  80643. var BABYLON;
  80644. (function (BABYLON) {
  80645. /**
  80646. * This represents a texture coming from an HDR input.
  80647. *
  80648. * The only supported format is currently panorama picture stored in RGBE format.
  80649. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80650. */
  80651. var HDRCubeTexture = /** @class */ (function (_super) {
  80652. __extends(HDRCubeTexture, _super);
  80653. /**
  80654. * Instantiates an HDRTexture from the following parameters.
  80655. *
  80656. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80657. * @param scene The scene the texture will be used in
  80658. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80659. * @param noMipmap Forces to not generate the mipmap if true
  80660. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80661. * @param gammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  80662. * @param reserved Reserved flag for internal use.
  80663. */
  80664. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80665. if (noMipmap === void 0) { noMipmap = false; }
  80666. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80667. if (gammaSpace === void 0) { gammaSpace = false; }
  80668. if (reserved === void 0) { reserved = false; }
  80669. if (onLoad === void 0) { onLoad = null; }
  80670. if (onError === void 0) { onError = null; }
  80671. var _this = _super.call(this, scene) || this;
  80672. _this._generateHarmonics = true;
  80673. _this._onLoad = null;
  80674. _this._onError = null;
  80675. /**
  80676. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80677. */
  80678. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80679. _this._isBlocking = true;
  80680. _this._rotationY = 0;
  80681. /**
  80682. * Gets or sets the center of the bounding box associated with the cube texture
  80683. * It must define where the camera used to render the texture was set
  80684. */
  80685. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80686. if (!url) {
  80687. return _this;
  80688. }
  80689. _this.name = url;
  80690. _this.url = url;
  80691. _this.hasAlpha = false;
  80692. _this.isCube = true;
  80693. _this._textureMatrix = BABYLON.Matrix.Identity();
  80694. _this._onLoad = onLoad;
  80695. _this._onError = onError;
  80696. _this.gammaSpace = gammaSpace;
  80697. _this._noMipmap = noMipmap;
  80698. _this._size = size;
  80699. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80700. if (!_this._texture) {
  80701. if (!scene.useDelayedTextureLoading) {
  80702. _this.loadTexture();
  80703. }
  80704. else {
  80705. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80706. }
  80707. }
  80708. return _this;
  80709. }
  80710. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80711. /**
  80712. * Gets wether or not the texture is blocking during loading.
  80713. */
  80714. get: function () {
  80715. return this._isBlocking;
  80716. },
  80717. /**
  80718. * Sets wether or not the texture is blocking during loading.
  80719. */
  80720. set: function (value) {
  80721. this._isBlocking = value;
  80722. },
  80723. enumerable: true,
  80724. configurable: true
  80725. });
  80726. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80727. /**
  80728. * Gets texture matrix rotation angle around Y axis radians.
  80729. */
  80730. get: function () {
  80731. return this._rotationY;
  80732. },
  80733. /**
  80734. * Sets texture matrix rotation angle around Y axis in radians.
  80735. */
  80736. set: function (value) {
  80737. this._rotationY = value;
  80738. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80739. },
  80740. enumerable: true,
  80741. configurable: true
  80742. });
  80743. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80744. get: function () {
  80745. return this._boundingBoxSize;
  80746. },
  80747. /**
  80748. * Gets or sets the size of the bounding box associated with the cube texture
  80749. * When defined, the cubemap will switch to local mode
  80750. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80751. * @example https://www.babylonjs-playground.com/#RNASML
  80752. */
  80753. set: function (value) {
  80754. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80755. return;
  80756. }
  80757. this._boundingBoxSize = value;
  80758. var scene = this.getScene();
  80759. if (scene) {
  80760. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80761. }
  80762. },
  80763. enumerable: true,
  80764. configurable: true
  80765. });
  80766. /**
  80767. * Occurs when the file is raw .hdr file.
  80768. */
  80769. HDRCubeTexture.prototype.loadTexture = function () {
  80770. var _this = this;
  80771. var callback = function (buffer) {
  80772. var scene = _this.getScene();
  80773. if (!scene) {
  80774. return null;
  80775. }
  80776. // Extract the raw linear data.
  80777. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80778. // Generate harmonics if needed.
  80779. if (_this._generateHarmonics) {
  80780. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80781. _this.sphericalPolynomial = sphericalPolynomial;
  80782. }
  80783. var results = [];
  80784. var byteArray = null;
  80785. // Push each faces.
  80786. for (var j = 0; j < 6; j++) {
  80787. // Create uintarray fallback.
  80788. if (!scene.getEngine().getCaps().textureFloat) {
  80789. // 3 channels of 1 bytes per pixel in bytes.
  80790. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80791. byteArray = new Uint8Array(byteBuffer);
  80792. }
  80793. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80794. // If special cases.
  80795. if (_this.gammaSpace || byteArray) {
  80796. for (var i = 0; i < _this._size * _this._size; i++) {
  80797. // Put in gamma space if requested.
  80798. if (_this.gammaSpace) {
  80799. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80800. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80801. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80802. }
  80803. // Convert to int texture for fallback.
  80804. if (byteArray) {
  80805. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80806. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80807. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80808. // May use luminance instead if the result is not accurate.
  80809. var max = Math.max(Math.max(r, g), b);
  80810. if (max > 255) {
  80811. var scale = 255 / max;
  80812. r *= scale;
  80813. g *= scale;
  80814. b *= scale;
  80815. }
  80816. byteArray[(i * 3) + 0] = r;
  80817. byteArray[(i * 3) + 1] = g;
  80818. byteArray[(i * 3) + 2] = b;
  80819. }
  80820. }
  80821. }
  80822. if (byteArray) {
  80823. results.push(byteArray);
  80824. }
  80825. else {
  80826. results.push(dataFace);
  80827. }
  80828. }
  80829. return results;
  80830. };
  80831. var scene = this.getScene();
  80832. if (scene) {
  80833. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, null, this._onLoad, this._onError);
  80834. }
  80835. };
  80836. HDRCubeTexture.prototype.clone = function () {
  80837. var scene = this.getScene();
  80838. if (!scene) {
  80839. return this;
  80840. }
  80841. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  80842. // Base texture
  80843. newTexture.level = this.level;
  80844. newTexture.wrapU = this.wrapU;
  80845. newTexture.wrapV = this.wrapV;
  80846. newTexture.coordinatesIndex = this.coordinatesIndex;
  80847. newTexture.coordinatesMode = this.coordinatesMode;
  80848. return newTexture;
  80849. };
  80850. // Methods
  80851. HDRCubeTexture.prototype.delayLoad = function () {
  80852. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80853. return;
  80854. }
  80855. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80856. this._texture = this._getFromCache(this.url, this._noMipmap);
  80857. if (!this._texture) {
  80858. this.loadTexture();
  80859. }
  80860. };
  80861. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  80862. return this._textureMatrix;
  80863. };
  80864. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  80865. this._textureMatrix = value;
  80866. };
  80867. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80868. var texture = null;
  80869. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80870. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  80871. texture.name = parsedTexture.name;
  80872. texture.hasAlpha = parsedTexture.hasAlpha;
  80873. texture.level = parsedTexture.level;
  80874. texture.coordinatesMode = parsedTexture.coordinatesMode;
  80875. texture.isBlocking = parsedTexture.isBlocking;
  80876. }
  80877. if (texture) {
  80878. if (parsedTexture.boundingBoxPosition) {
  80879. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  80880. }
  80881. if (parsedTexture.boundingBoxSize) {
  80882. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  80883. }
  80884. if (parsedTexture.rotationY) {
  80885. texture.rotationY = parsedTexture.rotationY;
  80886. }
  80887. }
  80888. return texture;
  80889. };
  80890. HDRCubeTexture.prototype.serialize = function () {
  80891. if (!this.name) {
  80892. return null;
  80893. }
  80894. var serializationObject = {};
  80895. serializationObject.name = this.name;
  80896. serializationObject.hasAlpha = this.hasAlpha;
  80897. serializationObject.isCube = true;
  80898. serializationObject.level = this.level;
  80899. serializationObject.size = this._size;
  80900. serializationObject.coordinatesMode = this.coordinatesMode;
  80901. serializationObject.useInGammaSpace = this.gammaSpace;
  80902. serializationObject.generateHarmonics = this._generateHarmonics;
  80903. serializationObject.customType = "BABYLON.HDRCubeTexture";
  80904. serializationObject.noMipmap = this._noMipmap;
  80905. serializationObject.isBlocking = this._isBlocking;
  80906. serializationObject.rotationY = this._rotationY;
  80907. return serializationObject;
  80908. };
  80909. HDRCubeTexture._facesMapping = [
  80910. "right",
  80911. "left",
  80912. "up",
  80913. "down",
  80914. "front",
  80915. "back"
  80916. ];
  80917. return HDRCubeTexture;
  80918. }(BABYLON.BaseTexture));
  80919. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80920. })(BABYLON || (BABYLON = {}));
  80921. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80922. var BABYLON;
  80923. (function (BABYLON) {
  80924. var IndexedVector2 = /** @class */ (function (_super) {
  80925. __extends(IndexedVector2, _super);
  80926. function IndexedVector2(original, index) {
  80927. var _this = _super.call(this, original.x, original.y) || this;
  80928. _this.index = index;
  80929. return _this;
  80930. }
  80931. return IndexedVector2;
  80932. }(BABYLON.Vector2));
  80933. var PolygonPoints = /** @class */ (function () {
  80934. function PolygonPoints() {
  80935. this.elements = new Array();
  80936. }
  80937. PolygonPoints.prototype.add = function (originalPoints) {
  80938. var _this = this;
  80939. var result = new Array();
  80940. originalPoints.forEach(function (point) {
  80941. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80942. var newPoint = new IndexedVector2(point, _this.elements.length);
  80943. result.push(newPoint);
  80944. _this.elements.push(newPoint);
  80945. }
  80946. });
  80947. return result;
  80948. };
  80949. PolygonPoints.prototype.computeBounds = function () {
  80950. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80951. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80952. this.elements.forEach(function (point) {
  80953. // x
  80954. if (point.x < lmin.x) {
  80955. lmin.x = point.x;
  80956. }
  80957. else if (point.x > lmax.x) {
  80958. lmax.x = point.x;
  80959. }
  80960. // y
  80961. if (point.y < lmin.y) {
  80962. lmin.y = point.y;
  80963. }
  80964. else if (point.y > lmax.y) {
  80965. lmax.y = point.y;
  80966. }
  80967. });
  80968. return {
  80969. min: lmin,
  80970. max: lmax,
  80971. width: lmax.x - lmin.x,
  80972. height: lmax.y - lmin.y
  80973. };
  80974. };
  80975. return PolygonPoints;
  80976. }());
  80977. var Polygon = /** @class */ (function () {
  80978. function Polygon() {
  80979. }
  80980. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  80981. return [
  80982. new BABYLON.Vector2(xmin, ymin),
  80983. new BABYLON.Vector2(xmax, ymin),
  80984. new BABYLON.Vector2(xmax, ymax),
  80985. new BABYLON.Vector2(xmin, ymax)
  80986. ];
  80987. };
  80988. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  80989. if (cx === void 0) { cx = 0; }
  80990. if (cy === void 0) { cy = 0; }
  80991. if (numberOfSides === void 0) { numberOfSides = 32; }
  80992. var result = new Array();
  80993. var angle = 0;
  80994. var increment = (Math.PI * 2) / numberOfSides;
  80995. for (var i = 0; i < numberOfSides; i++) {
  80996. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  80997. angle -= increment;
  80998. }
  80999. return result;
  81000. };
  81001. Polygon.Parse = function (input) {
  81002. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  81003. var i, result = [];
  81004. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  81005. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  81006. }
  81007. return result;
  81008. };
  81009. Polygon.StartingAt = function (x, y) {
  81010. return BABYLON.Path2.StartingAt(x, y);
  81011. };
  81012. return Polygon;
  81013. }());
  81014. BABYLON.Polygon = Polygon;
  81015. var PolygonMeshBuilder = /** @class */ (function () {
  81016. function PolygonMeshBuilder(name, contours, scene) {
  81017. this._points = new PolygonPoints();
  81018. this._outlinepoints = new PolygonPoints();
  81019. this._holes = new Array();
  81020. this._epoints = new Array();
  81021. this._eholes = new Array();
  81022. this._name = name;
  81023. this._scene = scene;
  81024. var points;
  81025. if (contours instanceof BABYLON.Path2) {
  81026. points = contours.getPoints();
  81027. }
  81028. else {
  81029. points = contours;
  81030. }
  81031. this._addToepoint(points);
  81032. this._points.add(points);
  81033. this._outlinepoints.add(points);
  81034. if (typeof earcut === 'undefined') {
  81035. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  81036. }
  81037. }
  81038. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  81039. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  81040. var p = points_1[_i];
  81041. this._epoints.push(p.x, p.y);
  81042. }
  81043. };
  81044. PolygonMeshBuilder.prototype.addHole = function (hole) {
  81045. this._points.add(hole);
  81046. var holepoints = new PolygonPoints();
  81047. holepoints.add(hole);
  81048. this._holes.push(holepoints);
  81049. this._eholes.push(this._epoints.length / 2);
  81050. this._addToepoint(hole);
  81051. return this;
  81052. };
  81053. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  81054. var _this = this;
  81055. if (updatable === void 0) { updatable = false; }
  81056. if (depth === void 0) { depth = 0; }
  81057. var result = new BABYLON.Mesh(this._name, this._scene);
  81058. var normals = new Array();
  81059. var positions = new Array();
  81060. var uvs = new Array();
  81061. var bounds = this._points.computeBounds();
  81062. this._points.elements.forEach(function (p) {
  81063. normals.push(0, 1.0, 0);
  81064. positions.push(p.x, 0, p.y);
  81065. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  81066. });
  81067. var indices = new Array();
  81068. var res = earcut(this._epoints, this._eholes, 2);
  81069. for (var i = 0; i < res.length; i++) {
  81070. indices.push(res[i]);
  81071. }
  81072. if (depth > 0) {
  81073. var positionscount = (positions.length / 3); //get the current pointcount
  81074. this._points.elements.forEach(function (p) {
  81075. normals.push(0, -1.0, 0);
  81076. positions.push(p.x, -depth, p.y);
  81077. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  81078. });
  81079. var totalCount = indices.length;
  81080. for (var i = 0; i < totalCount; i += 3) {
  81081. var i0 = indices[i + 0];
  81082. var i1 = indices[i + 1];
  81083. var i2 = indices[i + 2];
  81084. indices.push(i2 + positionscount);
  81085. indices.push(i1 + positionscount);
  81086. indices.push(i0 + positionscount);
  81087. }
  81088. //Add the sides
  81089. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  81090. this._holes.forEach(function (hole) {
  81091. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  81092. });
  81093. }
  81094. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  81095. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  81096. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  81097. result.setIndices(indices);
  81098. return result;
  81099. };
  81100. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  81101. var StartIndex = positions.length / 3;
  81102. var ulength = 0;
  81103. for (var i = 0; i < points.elements.length; i++) {
  81104. var p = points.elements[i];
  81105. var p1;
  81106. if ((i + 1) > points.elements.length - 1) {
  81107. p1 = points.elements[0];
  81108. }
  81109. else {
  81110. p1 = points.elements[i + 1];
  81111. }
  81112. positions.push(p.x, 0, p.y);
  81113. positions.push(p.x, -depth, p.y);
  81114. positions.push(p1.x, 0, p1.y);
  81115. positions.push(p1.x, -depth, p1.y);
  81116. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  81117. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  81118. var v3 = v2.subtract(v1);
  81119. var v4 = new BABYLON.Vector3(0, 1, 0);
  81120. var vn = BABYLON.Vector3.Cross(v3, v4);
  81121. vn = vn.normalize();
  81122. uvs.push(ulength / bounds.width, 0);
  81123. uvs.push(ulength / bounds.width, 1);
  81124. ulength += v3.length();
  81125. uvs.push((ulength / bounds.width), 0);
  81126. uvs.push((ulength / bounds.width), 1);
  81127. if (!flip) {
  81128. normals.push(-vn.x, -vn.y, -vn.z);
  81129. normals.push(-vn.x, -vn.y, -vn.z);
  81130. normals.push(-vn.x, -vn.y, -vn.z);
  81131. normals.push(-vn.x, -vn.y, -vn.z);
  81132. indices.push(StartIndex);
  81133. indices.push(StartIndex + 1);
  81134. indices.push(StartIndex + 2);
  81135. indices.push(StartIndex + 1);
  81136. indices.push(StartIndex + 3);
  81137. indices.push(StartIndex + 2);
  81138. }
  81139. else {
  81140. normals.push(vn.x, vn.y, vn.z);
  81141. normals.push(vn.x, vn.y, vn.z);
  81142. normals.push(vn.x, vn.y, vn.z);
  81143. normals.push(vn.x, vn.y, vn.z);
  81144. indices.push(StartIndex);
  81145. indices.push(StartIndex + 2);
  81146. indices.push(StartIndex + 1);
  81147. indices.push(StartIndex + 1);
  81148. indices.push(StartIndex + 2);
  81149. indices.push(StartIndex + 3);
  81150. }
  81151. StartIndex += 4;
  81152. }
  81153. ;
  81154. };
  81155. return PolygonMeshBuilder;
  81156. }());
  81157. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  81158. })(BABYLON || (BABYLON = {}));
  81159. //# sourceMappingURL=babylon.polygonMesh.js.map
  81160. var BABYLON;
  81161. (function (BABYLON) {
  81162. // Unique ID when we import meshes from Babylon to CSG
  81163. var currentCSGMeshId = 0;
  81164. // # class Vertex
  81165. // Represents a vertex of a polygon. Use your own vertex class instead of this
  81166. // one to provide additional features like texture coordinates and vertex
  81167. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  81168. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  81169. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  81170. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  81171. // is not used anywhere else.
  81172. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  81173. var Vertex = /** @class */ (function () {
  81174. function Vertex(pos, normal, uv) {
  81175. this.pos = pos;
  81176. this.normal = normal;
  81177. this.uv = uv;
  81178. }
  81179. Vertex.prototype.clone = function () {
  81180. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  81181. };
  81182. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  81183. // orientation of a polygon is flipped.
  81184. Vertex.prototype.flip = function () {
  81185. this.normal = this.normal.scale(-1);
  81186. };
  81187. // Create a new vertex between this vertex and `other` by linearly
  81188. // interpolating all properties using a parameter of `t`. Subclasses should
  81189. // override this to interpolate additional properties.
  81190. Vertex.prototype.interpolate = function (other, t) {
  81191. 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));
  81192. };
  81193. return Vertex;
  81194. }());
  81195. // # class Plane
  81196. // Represents a plane in 3D space.
  81197. var Plane = /** @class */ (function () {
  81198. function Plane(normal, w) {
  81199. this.normal = normal;
  81200. this.w = w;
  81201. }
  81202. Plane.FromPoints = function (a, b, c) {
  81203. var v0 = c.subtract(a);
  81204. var v1 = b.subtract(a);
  81205. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  81206. return null;
  81207. }
  81208. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  81209. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  81210. };
  81211. Plane.prototype.clone = function () {
  81212. return new Plane(this.normal.clone(), this.w);
  81213. };
  81214. Plane.prototype.flip = function () {
  81215. this.normal.scaleInPlace(-1);
  81216. this.w = -this.w;
  81217. };
  81218. // Split `polygon` by this plane if needed, then put the polygon or polygon
  81219. // fragments in the appropriate lists. Coplanar polygons go into either
  81220. // `coplanarFront` or `coplanarBack` depending on their orientation with
  81221. // respect to this plane. Polygons in front or in back of this plane go into
  81222. // either `front` or `back`.
  81223. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  81224. var COPLANAR = 0;
  81225. var FRONT = 1;
  81226. var BACK = 2;
  81227. var SPANNING = 3;
  81228. // Classify each point as well as the entire polygon into one of the above
  81229. // four classes.
  81230. var polygonType = 0;
  81231. var types = [];
  81232. var i;
  81233. var t;
  81234. for (i = 0; i < polygon.vertices.length; i++) {
  81235. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  81236. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  81237. polygonType |= type;
  81238. types.push(type);
  81239. }
  81240. // Put the polygon in the correct list, splitting it when necessary.
  81241. switch (polygonType) {
  81242. case COPLANAR:
  81243. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  81244. break;
  81245. case FRONT:
  81246. front.push(polygon);
  81247. break;
  81248. case BACK:
  81249. back.push(polygon);
  81250. break;
  81251. case SPANNING:
  81252. var f = [], b = [];
  81253. for (i = 0; i < polygon.vertices.length; i++) {
  81254. var j = (i + 1) % polygon.vertices.length;
  81255. var ti = types[i], tj = types[j];
  81256. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  81257. if (ti !== BACK)
  81258. f.push(vi);
  81259. if (ti !== FRONT)
  81260. b.push(ti !== BACK ? vi.clone() : vi);
  81261. if ((ti | tj) === SPANNING) {
  81262. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  81263. var v = vi.interpolate(vj, t);
  81264. f.push(v);
  81265. b.push(v.clone());
  81266. }
  81267. }
  81268. var poly;
  81269. if (f.length >= 3) {
  81270. poly = new Polygon(f, polygon.shared);
  81271. if (poly.plane)
  81272. front.push(poly);
  81273. }
  81274. if (b.length >= 3) {
  81275. poly = new Polygon(b, polygon.shared);
  81276. if (poly.plane)
  81277. back.push(poly);
  81278. }
  81279. break;
  81280. }
  81281. };
  81282. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  81283. // point is on the plane.
  81284. Plane.EPSILON = 1e-5;
  81285. return Plane;
  81286. }());
  81287. // # class Polygon
  81288. // Represents a convex polygon. The vertices used to initialize a polygon must
  81289. // be coplanar and form a convex loop.
  81290. //
  81291. // Each convex polygon has a `shared` property, which is shared between all
  81292. // polygons that are clones of each other or were split from the same polygon.
  81293. // This can be used to define per-polygon properties (such as surface color).
  81294. var Polygon = /** @class */ (function () {
  81295. function Polygon(vertices, shared) {
  81296. this.vertices = vertices;
  81297. this.shared = shared;
  81298. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  81299. }
  81300. Polygon.prototype.clone = function () {
  81301. var vertices = this.vertices.map(function (v) { return v.clone(); });
  81302. return new Polygon(vertices, this.shared);
  81303. };
  81304. Polygon.prototype.flip = function () {
  81305. this.vertices.reverse().map(function (v) { v.flip(); });
  81306. this.plane.flip();
  81307. };
  81308. return Polygon;
  81309. }());
  81310. // # class Node
  81311. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  81312. // by picking a polygon to split along. That polygon (and all other coplanar
  81313. // polygons) are added directly to that node and the other polygons are added to
  81314. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  81315. // no distinction between internal and leaf nodes.
  81316. var Node = /** @class */ (function () {
  81317. function Node(polygons) {
  81318. this.plane = null;
  81319. this.front = null;
  81320. this.back = null;
  81321. this.polygons = new Array();
  81322. if (polygons) {
  81323. this.build(polygons);
  81324. }
  81325. }
  81326. Node.prototype.clone = function () {
  81327. var node = new Node();
  81328. node.plane = this.plane && this.plane.clone();
  81329. node.front = this.front && this.front.clone();
  81330. node.back = this.back && this.back.clone();
  81331. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  81332. return node;
  81333. };
  81334. // Convert solid space to empty space and empty space to solid space.
  81335. Node.prototype.invert = function () {
  81336. for (var i = 0; i < this.polygons.length; i++) {
  81337. this.polygons[i].flip();
  81338. }
  81339. if (this.plane) {
  81340. this.plane.flip();
  81341. }
  81342. if (this.front) {
  81343. this.front.invert();
  81344. }
  81345. if (this.back) {
  81346. this.back.invert();
  81347. }
  81348. var temp = this.front;
  81349. this.front = this.back;
  81350. this.back = temp;
  81351. };
  81352. // Recursively remove all polygons in `polygons` that are inside this BSP
  81353. // tree.
  81354. Node.prototype.clipPolygons = function (polygons) {
  81355. if (!this.plane)
  81356. return polygons.slice();
  81357. var front = new Array(), back = new Array();
  81358. for (var i = 0; i < polygons.length; i++) {
  81359. this.plane.splitPolygon(polygons[i], front, back, front, back);
  81360. }
  81361. if (this.front) {
  81362. front = this.front.clipPolygons(front);
  81363. }
  81364. if (this.back) {
  81365. back = this.back.clipPolygons(back);
  81366. }
  81367. else {
  81368. back = [];
  81369. }
  81370. return front.concat(back);
  81371. };
  81372. // Remove all polygons in this BSP tree that are inside the other BSP tree
  81373. // `bsp`.
  81374. Node.prototype.clipTo = function (bsp) {
  81375. this.polygons = bsp.clipPolygons(this.polygons);
  81376. if (this.front)
  81377. this.front.clipTo(bsp);
  81378. if (this.back)
  81379. this.back.clipTo(bsp);
  81380. };
  81381. // Return a list of all polygons in this BSP tree.
  81382. Node.prototype.allPolygons = function () {
  81383. var polygons = this.polygons.slice();
  81384. if (this.front)
  81385. polygons = polygons.concat(this.front.allPolygons());
  81386. if (this.back)
  81387. polygons = polygons.concat(this.back.allPolygons());
  81388. return polygons;
  81389. };
  81390. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  81391. // new polygons are filtered down to the bottom of the tree and become new
  81392. // nodes there. Each set of polygons is partitioned using the first polygon
  81393. // (no heuristic is used to pick a good split).
  81394. Node.prototype.build = function (polygons) {
  81395. if (!polygons.length)
  81396. return;
  81397. if (!this.plane)
  81398. this.plane = polygons[0].plane.clone();
  81399. var front = new Array(), back = new Array();
  81400. for (var i = 0; i < polygons.length; i++) {
  81401. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  81402. }
  81403. if (front.length) {
  81404. if (!this.front)
  81405. this.front = new Node();
  81406. this.front.build(front);
  81407. }
  81408. if (back.length) {
  81409. if (!this.back)
  81410. this.back = new Node();
  81411. this.back.build(back);
  81412. }
  81413. };
  81414. return Node;
  81415. }());
  81416. var CSG = /** @class */ (function () {
  81417. function CSG() {
  81418. this.polygons = new Array();
  81419. }
  81420. // Convert BABYLON.Mesh to BABYLON.CSG
  81421. CSG.FromMesh = function (mesh) {
  81422. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  81423. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  81424. if (mesh instanceof BABYLON.Mesh) {
  81425. mesh.computeWorldMatrix(true);
  81426. matrix = mesh.getWorldMatrix();
  81427. meshPosition = mesh.position.clone();
  81428. meshRotation = mesh.rotation.clone();
  81429. if (mesh.rotationQuaternion) {
  81430. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  81431. }
  81432. meshScaling = mesh.scaling.clone();
  81433. }
  81434. else {
  81435. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  81436. }
  81437. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81438. var subMeshes = mesh.subMeshes;
  81439. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  81440. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  81441. vertices = [];
  81442. for (var j = 0; j < 3; j++) {
  81443. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  81444. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  81445. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  81446. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  81447. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  81448. vertex = new Vertex(position, normal, uv);
  81449. vertices.push(vertex);
  81450. }
  81451. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  81452. // To handle the case of degenerated triangle
  81453. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  81454. if (polygon.plane)
  81455. polygons.push(polygon);
  81456. }
  81457. }
  81458. var csg = CSG.FromPolygons(polygons);
  81459. csg.matrix = matrix;
  81460. csg.position = meshPosition;
  81461. csg.rotation = meshRotation;
  81462. csg.scaling = meshScaling;
  81463. csg.rotationQuaternion = meshRotationQuaternion;
  81464. currentCSGMeshId++;
  81465. return csg;
  81466. };
  81467. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  81468. CSG.FromPolygons = function (polygons) {
  81469. var csg = new CSG();
  81470. csg.polygons = polygons;
  81471. return csg;
  81472. };
  81473. CSG.prototype.clone = function () {
  81474. var csg = new CSG();
  81475. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  81476. csg.copyTransformAttributes(this);
  81477. return csg;
  81478. };
  81479. CSG.prototype.union = function (csg) {
  81480. var a = new Node(this.clone().polygons);
  81481. var b = new Node(csg.clone().polygons);
  81482. a.clipTo(b);
  81483. b.clipTo(a);
  81484. b.invert();
  81485. b.clipTo(a);
  81486. b.invert();
  81487. a.build(b.allPolygons());
  81488. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81489. };
  81490. CSG.prototype.unionInPlace = function (csg) {
  81491. var a = new Node(this.polygons);
  81492. var b = new Node(csg.polygons);
  81493. a.clipTo(b);
  81494. b.clipTo(a);
  81495. b.invert();
  81496. b.clipTo(a);
  81497. b.invert();
  81498. a.build(b.allPolygons());
  81499. this.polygons = a.allPolygons();
  81500. };
  81501. CSG.prototype.subtract = function (csg) {
  81502. var a = new Node(this.clone().polygons);
  81503. var b = new Node(csg.clone().polygons);
  81504. a.invert();
  81505. a.clipTo(b);
  81506. b.clipTo(a);
  81507. b.invert();
  81508. b.clipTo(a);
  81509. b.invert();
  81510. a.build(b.allPolygons());
  81511. a.invert();
  81512. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81513. };
  81514. CSG.prototype.subtractInPlace = function (csg) {
  81515. var a = new Node(this.polygons);
  81516. var b = new Node(csg.polygons);
  81517. a.invert();
  81518. a.clipTo(b);
  81519. b.clipTo(a);
  81520. b.invert();
  81521. b.clipTo(a);
  81522. b.invert();
  81523. a.build(b.allPolygons());
  81524. a.invert();
  81525. this.polygons = a.allPolygons();
  81526. };
  81527. CSG.prototype.intersect = function (csg) {
  81528. var a = new Node(this.clone().polygons);
  81529. var b = new Node(csg.clone().polygons);
  81530. a.invert();
  81531. b.clipTo(a);
  81532. b.invert();
  81533. a.clipTo(b);
  81534. b.clipTo(a);
  81535. a.build(b.allPolygons());
  81536. a.invert();
  81537. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81538. };
  81539. CSG.prototype.intersectInPlace = function (csg) {
  81540. var a = new Node(this.polygons);
  81541. var b = new Node(csg.polygons);
  81542. a.invert();
  81543. b.clipTo(a);
  81544. b.invert();
  81545. a.clipTo(b);
  81546. b.clipTo(a);
  81547. a.build(b.allPolygons());
  81548. a.invert();
  81549. this.polygons = a.allPolygons();
  81550. };
  81551. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81552. // not modified.
  81553. CSG.prototype.inverse = function () {
  81554. var csg = this.clone();
  81555. csg.inverseInPlace();
  81556. return csg;
  81557. };
  81558. CSG.prototype.inverseInPlace = function () {
  81559. this.polygons.map(function (p) { p.flip(); });
  81560. };
  81561. // This is used to keep meshes transformations so they can be restored
  81562. // when we build back a Babylon Mesh
  81563. // NB : All CSG operations are performed in world coordinates
  81564. CSG.prototype.copyTransformAttributes = function (csg) {
  81565. this.matrix = csg.matrix;
  81566. this.position = csg.position;
  81567. this.rotation = csg.rotation;
  81568. this.scaling = csg.scaling;
  81569. this.rotationQuaternion = csg.rotationQuaternion;
  81570. return this;
  81571. };
  81572. // Build Raw mesh from CSG
  81573. // Coordinates here are in world space
  81574. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81575. var matrix = this.matrix.clone();
  81576. matrix.invert();
  81577. 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;
  81578. if (keepSubMeshes) {
  81579. // Sort Polygons, since subMeshes are indices range
  81580. polygons.sort(function (a, b) {
  81581. if (a.shared.meshId === b.shared.meshId) {
  81582. return a.shared.subMeshId - b.shared.subMeshId;
  81583. }
  81584. else {
  81585. return a.shared.meshId - b.shared.meshId;
  81586. }
  81587. });
  81588. }
  81589. for (var i = 0, il = polygons.length; i < il; i++) {
  81590. polygon = polygons[i];
  81591. // Building SubMeshes
  81592. if (!subMesh_dict[polygon.shared.meshId]) {
  81593. subMesh_dict[polygon.shared.meshId] = {};
  81594. }
  81595. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81596. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81597. indexStart: +Infinity,
  81598. indexEnd: -Infinity,
  81599. materialIndex: polygon.shared.materialIndex
  81600. };
  81601. }
  81602. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81603. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81604. polygonIndices[0] = 0;
  81605. polygonIndices[1] = j - 1;
  81606. polygonIndices[2] = j;
  81607. for (var k = 0; k < 3; k++) {
  81608. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81609. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81610. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81611. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81612. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81613. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81614. // Check if 2 points can be merged
  81615. if (!(typeof vertex_idx !== 'undefined' &&
  81616. normals[vertex_idx * 3] === localNormal.x &&
  81617. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81618. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81619. uvs[vertex_idx * 2] === uv.x &&
  81620. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81621. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81622. uvs.push(uv.x, uv.y);
  81623. normals.push(normal.x, normal.y, normal.z);
  81624. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81625. }
  81626. indices.push(vertex_idx);
  81627. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81628. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81629. currentIndex++;
  81630. }
  81631. }
  81632. }
  81633. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81634. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81635. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81636. mesh.setIndices(indices, null);
  81637. if (keepSubMeshes) {
  81638. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81639. var materialIndexOffset = 0, materialMaxIndex;
  81640. mesh.subMeshes = new Array();
  81641. for (var m in subMesh_dict) {
  81642. materialMaxIndex = -1;
  81643. for (var sm in subMesh_dict[m]) {
  81644. subMesh_obj = subMesh_dict[m][sm];
  81645. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81646. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81647. }
  81648. materialIndexOffset += ++materialMaxIndex;
  81649. }
  81650. }
  81651. return mesh;
  81652. };
  81653. // Build Mesh from CSG taking material and transforms into account
  81654. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81655. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81656. mesh.material = material;
  81657. mesh.position.copyFrom(this.position);
  81658. mesh.rotation.copyFrom(this.rotation);
  81659. if (this.rotationQuaternion) {
  81660. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81661. }
  81662. mesh.scaling.copyFrom(this.scaling);
  81663. mesh.computeWorldMatrix(true);
  81664. return mesh;
  81665. };
  81666. return CSG;
  81667. }());
  81668. BABYLON.CSG = CSG;
  81669. })(BABYLON || (BABYLON = {}));
  81670. //# sourceMappingURL=babylon.csg.js.map
  81671. var BABYLON;
  81672. (function (BABYLON) {
  81673. var LensFlare = /** @class */ (function () {
  81674. function LensFlare(size, position, color, imgUrl, system) {
  81675. this.size = size;
  81676. this.position = position;
  81677. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81678. this.color = color || new BABYLON.Color3(1, 1, 1);
  81679. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81680. this._system = system;
  81681. system.lensFlares.push(this);
  81682. }
  81683. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81684. return new LensFlare(size, position, color, imgUrl, system);
  81685. };
  81686. LensFlare.prototype.dispose = function () {
  81687. if (this.texture) {
  81688. this.texture.dispose();
  81689. }
  81690. // Remove from scene
  81691. var index = this._system.lensFlares.indexOf(this);
  81692. this._system.lensFlares.splice(index, 1);
  81693. };
  81694. ;
  81695. return LensFlare;
  81696. }());
  81697. BABYLON.LensFlare = LensFlare;
  81698. })(BABYLON || (BABYLON = {}));
  81699. //# sourceMappingURL=babylon.lensFlare.js.map
  81700. var BABYLON;
  81701. (function (BABYLON) {
  81702. var LensFlareSystem = /** @class */ (function () {
  81703. function LensFlareSystem(name, emitter, scene) {
  81704. this.name = name;
  81705. this.lensFlares = new Array();
  81706. this.borderLimit = 300;
  81707. this.viewportBorder = 0;
  81708. this.layerMask = 0x0FFFFFFF;
  81709. this._vertexBuffers = {};
  81710. this._isEnabled = true;
  81711. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81712. this._emitter = emitter;
  81713. this.id = name;
  81714. scene.lensFlareSystems.push(this);
  81715. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81716. var engine = scene.getEngine();
  81717. // VBO
  81718. var vertices = [];
  81719. vertices.push(1, 1);
  81720. vertices.push(-1, 1);
  81721. vertices.push(-1, -1);
  81722. vertices.push(1, -1);
  81723. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81724. // Indices
  81725. var indices = [];
  81726. indices.push(0);
  81727. indices.push(1);
  81728. indices.push(2);
  81729. indices.push(0);
  81730. indices.push(2);
  81731. indices.push(3);
  81732. this._indexBuffer = engine.createIndexBuffer(indices);
  81733. // Effects
  81734. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81735. }
  81736. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81737. get: function () {
  81738. return this._isEnabled;
  81739. },
  81740. set: function (value) {
  81741. this._isEnabled = value;
  81742. },
  81743. enumerable: true,
  81744. configurable: true
  81745. });
  81746. LensFlareSystem.prototype.getScene = function () {
  81747. return this._scene;
  81748. };
  81749. LensFlareSystem.prototype.getEmitter = function () {
  81750. return this._emitter;
  81751. };
  81752. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81753. this._emitter = newEmitter;
  81754. };
  81755. LensFlareSystem.prototype.getEmitterPosition = function () {
  81756. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81757. };
  81758. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81759. var position = this.getEmitterPosition();
  81760. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81761. this._positionX = position.x;
  81762. this._positionY = position.y;
  81763. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81764. if (this.viewportBorder > 0) {
  81765. globalViewport.x -= this.viewportBorder;
  81766. globalViewport.y -= this.viewportBorder;
  81767. globalViewport.width += this.viewportBorder * 2;
  81768. globalViewport.height += this.viewportBorder * 2;
  81769. position.x += this.viewportBorder;
  81770. position.y += this.viewportBorder;
  81771. this._positionX += this.viewportBorder;
  81772. this._positionY += this.viewportBorder;
  81773. }
  81774. if (position.z > 0) {
  81775. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81776. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81777. return true;
  81778. }
  81779. return true;
  81780. }
  81781. return false;
  81782. };
  81783. LensFlareSystem.prototype._isVisible = function () {
  81784. if (!this._isEnabled || !this._scene.activeCamera) {
  81785. return false;
  81786. }
  81787. var emitterPosition = this.getEmitterPosition();
  81788. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81789. var distance = direction.length();
  81790. direction.normalize();
  81791. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81792. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81793. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81794. };
  81795. LensFlareSystem.prototype.render = function () {
  81796. if (!this._effect.isReady() || !this._scene.activeCamera)
  81797. return false;
  81798. var engine = this._scene.getEngine();
  81799. var viewport = this._scene.activeCamera.viewport;
  81800. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81801. // Position
  81802. if (!this.computeEffectivePosition(globalViewport)) {
  81803. return false;
  81804. }
  81805. // Visibility
  81806. if (!this._isVisible()) {
  81807. return false;
  81808. }
  81809. // Intensity
  81810. var awayX;
  81811. var awayY;
  81812. if (this._positionX < this.borderLimit + globalViewport.x) {
  81813. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81814. }
  81815. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81816. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81817. }
  81818. else {
  81819. awayX = 0;
  81820. }
  81821. if (this._positionY < this.borderLimit + globalViewport.y) {
  81822. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81823. }
  81824. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81825. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81826. }
  81827. else {
  81828. awayY = 0;
  81829. }
  81830. var away = (awayX > awayY) ? awayX : awayY;
  81831. away -= this.viewportBorder;
  81832. if (away > this.borderLimit) {
  81833. away = this.borderLimit;
  81834. }
  81835. var intensity = 1.0 - (away / this.borderLimit);
  81836. if (intensity < 0) {
  81837. return false;
  81838. }
  81839. if (intensity > 1.0) {
  81840. intensity = 1.0;
  81841. }
  81842. if (this.viewportBorder > 0) {
  81843. globalViewport.x += this.viewportBorder;
  81844. globalViewport.y += this.viewportBorder;
  81845. globalViewport.width -= this.viewportBorder * 2;
  81846. globalViewport.height -= this.viewportBorder * 2;
  81847. this._positionX -= this.viewportBorder;
  81848. this._positionY -= this.viewportBorder;
  81849. }
  81850. // Position
  81851. var centerX = globalViewport.x + globalViewport.width / 2;
  81852. var centerY = globalViewport.y + globalViewport.height / 2;
  81853. var distX = centerX - this._positionX;
  81854. var distY = centerY - this._positionY;
  81855. // Effects
  81856. engine.enableEffect(this._effect);
  81857. engine.setState(false);
  81858. engine.setDepthBuffer(false);
  81859. // VBOs
  81860. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81861. // Flares
  81862. for (var index = 0; index < this.lensFlares.length; index++) {
  81863. var flare = this.lensFlares[index];
  81864. engine.setAlphaMode(flare.alphaMode);
  81865. var x = centerX - (distX * flare.position);
  81866. var y = centerY - (distY * flare.position);
  81867. var cw = flare.size;
  81868. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  81869. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  81870. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  81871. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  81872. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  81873. // Texture
  81874. this._effect.setTexture("textureSampler", flare.texture);
  81875. // Color
  81876. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  81877. // Draw order
  81878. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81879. }
  81880. engine.setDepthBuffer(true);
  81881. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81882. return true;
  81883. };
  81884. LensFlareSystem.prototype.dispose = function () {
  81885. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81886. if (vertexBuffer) {
  81887. vertexBuffer.dispose();
  81888. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81889. }
  81890. if (this._indexBuffer) {
  81891. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81892. this._indexBuffer = null;
  81893. }
  81894. while (this.lensFlares.length) {
  81895. this.lensFlares[0].dispose();
  81896. }
  81897. // Remove from scene
  81898. var index = this._scene.lensFlareSystems.indexOf(this);
  81899. this._scene.lensFlareSystems.splice(index, 1);
  81900. };
  81901. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  81902. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  81903. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  81904. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  81905. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  81906. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  81907. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  81908. var parsedFlare = parsedLensFlareSystem.flares[index];
  81909. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  81910. }
  81911. return lensFlareSystem;
  81912. };
  81913. LensFlareSystem.prototype.serialize = function () {
  81914. var serializationObject = {};
  81915. serializationObject.id = this.id;
  81916. serializationObject.name = this.name;
  81917. serializationObject.emitterId = this.getEmitter().id;
  81918. serializationObject.borderLimit = this.borderLimit;
  81919. serializationObject.flares = [];
  81920. for (var index = 0; index < this.lensFlares.length; index++) {
  81921. var flare = this.lensFlares[index];
  81922. serializationObject.flares.push({
  81923. size: flare.size,
  81924. position: flare.position,
  81925. color: flare.color.asArray(),
  81926. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81927. });
  81928. }
  81929. return serializationObject;
  81930. };
  81931. return LensFlareSystem;
  81932. }());
  81933. BABYLON.LensFlareSystem = LensFlareSystem;
  81934. })(BABYLON || (BABYLON = {}));
  81935. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81936. var BABYLON;
  81937. (function (BABYLON) {
  81938. /**
  81939. * This is a holder class for the physics joint created by the physics plugin.
  81940. * It holds a set of functions to control the underlying joint.
  81941. */
  81942. var PhysicsJoint = /** @class */ (function () {
  81943. function PhysicsJoint(type, jointData) {
  81944. this.type = type;
  81945. this.jointData = jointData;
  81946. jointData.nativeParams = jointData.nativeParams || {};
  81947. }
  81948. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81949. get: function () {
  81950. return this._physicsJoint;
  81951. },
  81952. set: function (newJoint) {
  81953. if (this._physicsJoint) {
  81954. //remove from the wolrd
  81955. }
  81956. this._physicsJoint = newJoint;
  81957. },
  81958. enumerable: true,
  81959. configurable: true
  81960. });
  81961. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  81962. set: function (physicsPlugin) {
  81963. this._physicsPlugin = physicsPlugin;
  81964. },
  81965. enumerable: true,
  81966. configurable: true
  81967. });
  81968. /**
  81969. * Execute a function that is physics-plugin specific.
  81970. * @param {Function} func the function that will be executed.
  81971. * It accepts two parameters: the physics world and the physics joint.
  81972. */
  81973. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  81974. func(this._physicsPlugin.world, this._physicsJoint);
  81975. };
  81976. //TODO check if the native joints are the same
  81977. //Joint Types
  81978. PhysicsJoint.DistanceJoint = 0;
  81979. PhysicsJoint.HingeJoint = 1;
  81980. PhysicsJoint.BallAndSocketJoint = 2;
  81981. PhysicsJoint.WheelJoint = 3;
  81982. PhysicsJoint.SliderJoint = 4;
  81983. //OIMO
  81984. PhysicsJoint.PrismaticJoint = 5;
  81985. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  81986. PhysicsJoint.UniversalJoint = 6;
  81987. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  81988. //Cannon
  81989. //Similar to a Ball-Joint. Different in params
  81990. PhysicsJoint.PointToPointJoint = 8;
  81991. //Cannon only at the moment
  81992. PhysicsJoint.SpringJoint = 9;
  81993. PhysicsJoint.LockJoint = 10;
  81994. return PhysicsJoint;
  81995. }());
  81996. BABYLON.PhysicsJoint = PhysicsJoint;
  81997. /**
  81998. * A class representing a physics distance joint.
  81999. */
  82000. var DistanceJoint = /** @class */ (function (_super) {
  82001. __extends(DistanceJoint, _super);
  82002. function DistanceJoint(jointData) {
  82003. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  82004. }
  82005. /**
  82006. * Update the predefined distance.
  82007. */
  82008. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  82009. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  82010. };
  82011. return DistanceJoint;
  82012. }(PhysicsJoint));
  82013. BABYLON.DistanceJoint = DistanceJoint;
  82014. var MotorEnabledJoint = /** @class */ (function (_super) {
  82015. __extends(MotorEnabledJoint, _super);
  82016. function MotorEnabledJoint(type, jointData) {
  82017. return _super.call(this, type, jointData) || this;
  82018. }
  82019. /**
  82020. * Set the motor values.
  82021. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82022. * @param {number} force the force to apply
  82023. * @param {number} maxForce max force for this motor.
  82024. */
  82025. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  82026. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82027. };
  82028. /**
  82029. * Set the motor's limits.
  82030. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82031. */
  82032. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82033. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82034. };
  82035. return MotorEnabledJoint;
  82036. }(PhysicsJoint));
  82037. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  82038. /**
  82039. * This class represents a single hinge physics joint
  82040. */
  82041. var HingeJoint = /** @class */ (function (_super) {
  82042. __extends(HingeJoint, _super);
  82043. function HingeJoint(jointData) {
  82044. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  82045. }
  82046. /**
  82047. * Set the motor values.
  82048. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82049. * @param {number} force the force to apply
  82050. * @param {number} maxForce max force for this motor.
  82051. */
  82052. HingeJoint.prototype.setMotor = function (force, maxForce) {
  82053. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82054. };
  82055. /**
  82056. * Set the motor's limits.
  82057. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82058. */
  82059. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82060. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82061. };
  82062. return HingeJoint;
  82063. }(MotorEnabledJoint));
  82064. BABYLON.HingeJoint = HingeJoint;
  82065. /**
  82066. * This class represents a dual hinge physics joint (same as wheel joint)
  82067. */
  82068. var Hinge2Joint = /** @class */ (function (_super) {
  82069. __extends(Hinge2Joint, _super);
  82070. function Hinge2Joint(jointData) {
  82071. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  82072. }
  82073. /**
  82074. * Set the motor values.
  82075. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82076. * @param {number} force the force to apply
  82077. * @param {number} maxForce max force for this motor.
  82078. * @param {motorIndex} the motor's index, 0 or 1.
  82079. */
  82080. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  82081. if (motorIndex === void 0) { motorIndex = 0; }
  82082. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  82083. };
  82084. /**
  82085. * Set the motor limits.
  82086. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82087. * @param {number} upperLimit the upper limit
  82088. * @param {number} lowerLimit lower limit
  82089. * @param {motorIndex} the motor's index, 0 or 1.
  82090. */
  82091. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  82092. if (motorIndex === void 0) { motorIndex = 0; }
  82093. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  82094. };
  82095. return Hinge2Joint;
  82096. }(MotorEnabledJoint));
  82097. BABYLON.Hinge2Joint = Hinge2Joint;
  82098. })(BABYLON || (BABYLON = {}));
  82099. //# sourceMappingURL=babylon.physicsJoint.js.map
  82100. var BABYLON;
  82101. (function (BABYLON) {
  82102. var PhysicsImpostor = /** @class */ (function () {
  82103. function PhysicsImpostor(object, type, _options, _scene) {
  82104. if (_options === void 0) { _options = { mass: 0 }; }
  82105. var _this = this;
  82106. this.object = object;
  82107. this.type = type;
  82108. this._options = _options;
  82109. this._scene = _scene;
  82110. this._bodyUpdateRequired = false;
  82111. this._onBeforePhysicsStepCallbacks = new Array();
  82112. this._onAfterPhysicsStepCallbacks = new Array();
  82113. this._onPhysicsCollideCallbacks = [];
  82114. this._deltaPosition = BABYLON.Vector3.Zero();
  82115. this._isDisposed = false;
  82116. //temp variables for parent rotation calculations
  82117. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  82118. this._tmpQuat = new BABYLON.Quaternion();
  82119. this._tmpQuat2 = new BABYLON.Quaternion();
  82120. /**
  82121. * this function is executed by the physics engine.
  82122. */
  82123. this.beforeStep = function () {
  82124. if (!_this._physicsEngine) {
  82125. return;
  82126. }
  82127. _this.object.translate(_this._deltaPosition, -1);
  82128. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  82129. _this.object.computeWorldMatrix(false);
  82130. if (_this.object.parent && _this.object.rotationQuaternion) {
  82131. _this.getParentsRotation();
  82132. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  82133. }
  82134. else {
  82135. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  82136. }
  82137. if (!_this._options.disableBidirectionalTransformation) {
  82138. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  82139. }
  82140. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  82141. func(_this);
  82142. });
  82143. };
  82144. /**
  82145. * this function is executed by the physics engine.
  82146. */
  82147. this.afterStep = function () {
  82148. if (!_this._physicsEngine) {
  82149. return;
  82150. }
  82151. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  82152. func(_this);
  82153. });
  82154. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  82155. // object has now its world rotation. needs to be converted to local.
  82156. if (_this.object.parent && _this.object.rotationQuaternion) {
  82157. _this.getParentsRotation();
  82158. _this._tmpQuat.conjugateInPlace();
  82159. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  82160. }
  82161. // take the position set and make it the absolute position of this object.
  82162. _this.object.setAbsolutePosition(_this.object.position);
  82163. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  82164. _this.object.translate(_this._deltaPosition, 1);
  82165. };
  82166. /**
  82167. * Legacy collision detection event support
  82168. */
  82169. this.onCollideEvent = null;
  82170. //event and body object due to cannon's event-based architecture.
  82171. this.onCollide = function (e) {
  82172. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  82173. return;
  82174. }
  82175. if (!_this._physicsEngine) {
  82176. return;
  82177. }
  82178. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  82179. if (otherImpostor) {
  82180. // Legacy collision detection event support
  82181. if (_this.onCollideEvent) {
  82182. _this.onCollideEvent(_this, otherImpostor);
  82183. }
  82184. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  82185. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  82186. }).forEach(function (obj) {
  82187. obj.callback(_this, otherImpostor);
  82188. });
  82189. }
  82190. };
  82191. //sanity check!
  82192. if (!this.object) {
  82193. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  82194. return;
  82195. }
  82196. //legacy support for old syntax.
  82197. if (!this._scene && object.getScene) {
  82198. this._scene = object.getScene();
  82199. }
  82200. if (!this._scene) {
  82201. return;
  82202. }
  82203. this._physicsEngine = this._scene.getPhysicsEngine();
  82204. if (!this._physicsEngine) {
  82205. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  82206. }
  82207. else {
  82208. //set the object's quaternion, if not set
  82209. if (!this.object.rotationQuaternion) {
  82210. if (this.object.rotation) {
  82211. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  82212. }
  82213. else {
  82214. this.object.rotationQuaternion = new BABYLON.Quaternion();
  82215. }
  82216. }
  82217. //default options params
  82218. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  82219. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  82220. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  82221. this._joints = [];
  82222. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  82223. if (!this.object.parent || this._options.ignoreParent) {
  82224. this._init();
  82225. }
  82226. else if (this.object.parent.physicsImpostor) {
  82227. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  82228. }
  82229. }
  82230. }
  82231. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  82232. get: function () {
  82233. return this._isDisposed;
  82234. },
  82235. enumerable: true,
  82236. configurable: true
  82237. });
  82238. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  82239. get: function () {
  82240. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  82241. },
  82242. set: function (value) {
  82243. this.setMass(value);
  82244. },
  82245. enumerable: true,
  82246. configurable: true
  82247. });
  82248. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  82249. get: function () {
  82250. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  82251. },
  82252. set: function (value) {
  82253. if (!this._physicsEngine) {
  82254. return;
  82255. }
  82256. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  82257. },
  82258. enumerable: true,
  82259. configurable: true
  82260. });
  82261. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  82262. get: function () {
  82263. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  82264. },
  82265. set: function (value) {
  82266. if (!this._physicsEngine) {
  82267. return;
  82268. }
  82269. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  82270. },
  82271. enumerable: true,
  82272. configurable: true
  82273. });
  82274. /**
  82275. * This function will completly initialize this impostor.
  82276. * It will create a new body - but only if this mesh has no parent.
  82277. * If it has, this impostor will not be used other than to define the impostor
  82278. * of the child mesh.
  82279. */
  82280. PhysicsImpostor.prototype._init = function () {
  82281. if (!this._physicsEngine) {
  82282. return;
  82283. }
  82284. this._physicsEngine.removeImpostor(this);
  82285. this.physicsBody = null;
  82286. this._parent = this._parent || this._getPhysicsParent();
  82287. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  82288. this._physicsEngine.addImpostor(this);
  82289. }
  82290. };
  82291. PhysicsImpostor.prototype._getPhysicsParent = function () {
  82292. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  82293. var parentMesh = this.object.parent;
  82294. return parentMesh.physicsImpostor;
  82295. }
  82296. return null;
  82297. };
  82298. /**
  82299. * Should a new body be generated.
  82300. */
  82301. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  82302. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  82303. };
  82304. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  82305. this.forceUpdate();
  82306. };
  82307. /**
  82308. * Force a regeneration of this or the parent's impostor's body.
  82309. * Use under cautious - This will remove all joints already implemented.
  82310. */
  82311. PhysicsImpostor.prototype.forceUpdate = function () {
  82312. this._init();
  82313. if (this.parent && !this._options.ignoreParent) {
  82314. this.parent.forceUpdate();
  82315. }
  82316. };
  82317. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  82318. /*public get mesh(): AbstractMesh {
  82319. return this._mesh;
  82320. }*/
  82321. /**
  82322. * Gets the body that holds this impostor. Either its own, or its parent.
  82323. */
  82324. get: function () {
  82325. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  82326. },
  82327. /**
  82328. * Set the physics body. Used mainly by the physics engine/plugin
  82329. */
  82330. set: function (physicsBody) {
  82331. if (this._physicsBody && this._physicsEngine) {
  82332. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  82333. }
  82334. this._physicsBody = physicsBody;
  82335. this.resetUpdateFlags();
  82336. },
  82337. enumerable: true,
  82338. configurable: true
  82339. });
  82340. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  82341. get: function () {
  82342. return !this._options.ignoreParent && this._parent ? this._parent : null;
  82343. },
  82344. set: function (value) {
  82345. this._parent = value;
  82346. },
  82347. enumerable: true,
  82348. configurable: true
  82349. });
  82350. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  82351. this._bodyUpdateRequired = false;
  82352. };
  82353. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  82354. if (this.object.getBoundingInfo) {
  82355. var q = this.object.rotationQuaternion;
  82356. //reset rotation
  82357. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  82358. //calculate the world matrix with no rotation
  82359. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82360. var boundingInfo = this.object.getBoundingInfo();
  82361. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  82362. //bring back the rotation
  82363. this.object.rotationQuaternion = q;
  82364. //calculate the world matrix with the new rotation
  82365. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82366. return size;
  82367. }
  82368. else {
  82369. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  82370. }
  82371. };
  82372. PhysicsImpostor.prototype.getObjectCenter = function () {
  82373. if (this.object.getBoundingInfo) {
  82374. var boundingInfo = this.object.getBoundingInfo();
  82375. return boundingInfo.boundingBox.centerWorld;
  82376. }
  82377. else {
  82378. return this.object.position;
  82379. }
  82380. };
  82381. /**
  82382. * Get a specific parametes from the options parameter.
  82383. */
  82384. PhysicsImpostor.prototype.getParam = function (paramName) {
  82385. return this._options[paramName];
  82386. };
  82387. /**
  82388. * Sets a specific parameter in the options given to the physics plugin
  82389. */
  82390. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  82391. this._options[paramName] = value;
  82392. this._bodyUpdateRequired = true;
  82393. };
  82394. /**
  82395. * Specifically change the body's mass option. Won't recreate the physics body object
  82396. */
  82397. PhysicsImpostor.prototype.setMass = function (mass) {
  82398. if (this.getParam("mass") !== mass) {
  82399. this.setParam("mass", mass);
  82400. }
  82401. if (this._physicsEngine) {
  82402. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  82403. }
  82404. };
  82405. PhysicsImpostor.prototype.getLinearVelocity = function () {
  82406. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  82407. };
  82408. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  82409. if (this._physicsEngine) {
  82410. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  82411. }
  82412. };
  82413. PhysicsImpostor.prototype.getAngularVelocity = function () {
  82414. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  82415. };
  82416. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  82417. if (this._physicsEngine) {
  82418. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  82419. }
  82420. };
  82421. /**
  82422. * Execute a function with the physics plugin native code.
  82423. * Provide a function the will have two variables - the world object and the physics body object.
  82424. */
  82425. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  82426. if (this._physicsEngine) {
  82427. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  82428. }
  82429. };
  82430. /**
  82431. * Register a function that will be executed before the physics world is stepping forward.
  82432. */
  82433. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  82434. this._onBeforePhysicsStepCallbacks.push(func);
  82435. };
  82436. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  82437. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  82438. if (index > -1) {
  82439. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  82440. }
  82441. else {
  82442. BABYLON.Tools.Warn("Function to remove was not found");
  82443. }
  82444. };
  82445. /**
  82446. * Register a function that will be executed after the physics step
  82447. */
  82448. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  82449. this._onAfterPhysicsStepCallbacks.push(func);
  82450. };
  82451. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  82452. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  82453. if (index > -1) {
  82454. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  82455. }
  82456. else {
  82457. BABYLON.Tools.Warn("Function to remove was not found");
  82458. }
  82459. };
  82460. /**
  82461. * register a function that will be executed when this impostor collides against a different body.
  82462. */
  82463. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  82464. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82465. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  82466. };
  82467. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  82468. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82469. var index = -1;
  82470. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  82471. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  82472. // chcek the arrays match
  82473. var sameList = cbDef.otherImpostors.every(function (impostor) {
  82474. return collidedAgainstList.indexOf(impostor) > -1;
  82475. });
  82476. if (sameList) {
  82477. index = idx;
  82478. }
  82479. return sameList;
  82480. }
  82481. return false;
  82482. });
  82483. if (found) {
  82484. this._onPhysicsCollideCallbacks.splice(index, 1);
  82485. }
  82486. else {
  82487. BABYLON.Tools.Warn("Function to remove was not found");
  82488. }
  82489. };
  82490. PhysicsImpostor.prototype.getParentsRotation = function () {
  82491. var parent = this.object.parent;
  82492. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82493. while (parent) {
  82494. if (parent.rotationQuaternion) {
  82495. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82496. }
  82497. else {
  82498. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82499. }
  82500. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82501. parent = parent.parent;
  82502. }
  82503. return this._tmpQuat;
  82504. };
  82505. /**
  82506. * Apply a force
  82507. */
  82508. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82509. if (this._physicsEngine) {
  82510. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82511. }
  82512. return this;
  82513. };
  82514. /**
  82515. * Apply an impulse
  82516. */
  82517. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82518. if (this._physicsEngine) {
  82519. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82520. }
  82521. return this;
  82522. };
  82523. /**
  82524. * A help function to create a joint.
  82525. */
  82526. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82527. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82528. this.addJoint(otherImpostor, joint);
  82529. return this;
  82530. };
  82531. /**
  82532. * Add a joint to this impostor with a different impostor.
  82533. */
  82534. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82535. this._joints.push({
  82536. otherImpostor: otherImpostor,
  82537. joint: joint
  82538. });
  82539. if (this._physicsEngine) {
  82540. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82541. }
  82542. return this;
  82543. };
  82544. /**
  82545. * Will keep this body still, in a sleep mode.
  82546. */
  82547. PhysicsImpostor.prototype.sleep = function () {
  82548. if (this._physicsEngine) {
  82549. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82550. }
  82551. return this;
  82552. };
  82553. /**
  82554. * Wake the body up.
  82555. */
  82556. PhysicsImpostor.prototype.wakeUp = function () {
  82557. if (this._physicsEngine) {
  82558. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82559. }
  82560. return this;
  82561. };
  82562. PhysicsImpostor.prototype.clone = function (newObject) {
  82563. if (!newObject)
  82564. return null;
  82565. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82566. };
  82567. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82568. var _this = this;
  82569. //no dispose if no physics engine is available.
  82570. if (!this._physicsEngine) {
  82571. return;
  82572. }
  82573. this._joints.forEach(function (j) {
  82574. if (_this._physicsEngine) {
  82575. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82576. }
  82577. });
  82578. //dispose the physics body
  82579. this._physicsEngine.removeImpostor(this);
  82580. if (this.parent) {
  82581. this.parent.forceUpdate();
  82582. }
  82583. else {
  82584. /*this._object.getChildMeshes().forEach(function(mesh) {
  82585. if (mesh.physicsImpostor) {
  82586. if (disposeChildren) {
  82587. mesh.physicsImpostor.dispose();
  82588. mesh.physicsImpostor = null;
  82589. }
  82590. }
  82591. })*/
  82592. }
  82593. this._isDisposed = true;
  82594. };
  82595. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82596. this._deltaPosition.copyFrom(position);
  82597. };
  82598. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82599. if (!this._deltaRotation) {
  82600. this._deltaRotation = new BABYLON.Quaternion();
  82601. }
  82602. this._deltaRotation.copyFrom(rotation);
  82603. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82604. };
  82605. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82606. if (this._physicsEngine) {
  82607. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82608. }
  82609. return this;
  82610. };
  82611. PhysicsImpostor.prototype.getRadius = function () {
  82612. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82613. };
  82614. /**
  82615. * Sync a bone with this impostor
  82616. * @param bone The bone to sync to the impostor.
  82617. * @param boneMesh The mesh that the bone is influencing.
  82618. * @param jointPivot The pivot of the joint / bone in local space.
  82619. * @param distToJoint Optional distance from the impostor to the joint.
  82620. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82621. */
  82622. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82623. var tempVec = PhysicsImpostor._tmpVecs[0];
  82624. var mesh = this.object;
  82625. if (mesh.rotationQuaternion) {
  82626. if (adjustRotation) {
  82627. var tempQuat = PhysicsImpostor._tmpQuat;
  82628. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82629. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82630. }
  82631. else {
  82632. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82633. }
  82634. }
  82635. tempVec.x = 0;
  82636. tempVec.y = 0;
  82637. tempVec.z = 0;
  82638. if (jointPivot) {
  82639. tempVec.x = jointPivot.x;
  82640. tempVec.y = jointPivot.y;
  82641. tempVec.z = jointPivot.z;
  82642. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82643. if (distToJoint === undefined || distToJoint === null) {
  82644. distToJoint = jointPivot.length();
  82645. }
  82646. tempVec.x *= distToJoint;
  82647. tempVec.y *= distToJoint;
  82648. tempVec.z *= distToJoint;
  82649. }
  82650. if (bone.getParent()) {
  82651. tempVec.addInPlace(mesh.getAbsolutePosition());
  82652. bone.setAbsolutePosition(tempVec, boneMesh);
  82653. }
  82654. else {
  82655. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82656. boneMesh.position.x -= tempVec.x;
  82657. boneMesh.position.y -= tempVec.y;
  82658. boneMesh.position.z -= tempVec.z;
  82659. }
  82660. };
  82661. /**
  82662. * Sync impostor to a bone
  82663. * @param bone The bone that the impostor will be synced to.
  82664. * @param boneMesh The mesh that the bone is influencing.
  82665. * @param jointPivot The pivot of the joint / bone in local space.
  82666. * @param distToJoint Optional distance from the impostor to the joint.
  82667. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82668. * @param boneAxis Optional vector3 axis the bone is aligned with
  82669. */
  82670. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82671. var mesh = this.object;
  82672. if (mesh.rotationQuaternion) {
  82673. if (adjustRotation) {
  82674. var tempQuat = PhysicsImpostor._tmpQuat;
  82675. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82676. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82677. }
  82678. else {
  82679. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82680. }
  82681. }
  82682. var pos = PhysicsImpostor._tmpVecs[0];
  82683. var boneDir = PhysicsImpostor._tmpVecs[1];
  82684. if (!boneAxis) {
  82685. boneAxis = PhysicsImpostor._tmpVecs[2];
  82686. boneAxis.x = 0;
  82687. boneAxis.y = 1;
  82688. boneAxis.z = 0;
  82689. }
  82690. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82691. bone.getAbsolutePositionToRef(boneMesh, pos);
  82692. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82693. distToJoint = jointPivot.length();
  82694. }
  82695. if (distToJoint !== undefined && distToJoint !== null) {
  82696. pos.x += boneDir.x * distToJoint;
  82697. pos.y += boneDir.y * distToJoint;
  82698. pos.z += boneDir.z * distToJoint;
  82699. }
  82700. mesh.setAbsolutePosition(pos);
  82701. };
  82702. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82703. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82704. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82705. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82706. //Impostor types
  82707. PhysicsImpostor.NoImpostor = 0;
  82708. PhysicsImpostor.SphereImpostor = 1;
  82709. PhysicsImpostor.BoxImpostor = 2;
  82710. PhysicsImpostor.PlaneImpostor = 3;
  82711. PhysicsImpostor.MeshImpostor = 4;
  82712. PhysicsImpostor.CylinderImpostor = 7;
  82713. PhysicsImpostor.ParticleImpostor = 8;
  82714. PhysicsImpostor.HeightmapImpostor = 9;
  82715. return PhysicsImpostor;
  82716. }());
  82717. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82718. })(BABYLON || (BABYLON = {}));
  82719. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82720. var BABYLON;
  82721. (function (BABYLON) {
  82722. var PhysicsEngine = /** @class */ (function () {
  82723. function PhysicsEngine(gravity, _physicsPlugin) {
  82724. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82725. this._physicsPlugin = _physicsPlugin;
  82726. //new methods and parameters
  82727. this._impostors = [];
  82728. this._joints = [];
  82729. if (!this._physicsPlugin.isSupported()) {
  82730. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82731. + "Please make sure it is included.");
  82732. }
  82733. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82734. this.setGravity(gravity);
  82735. this.setTimeStep();
  82736. }
  82737. PhysicsEngine.prototype.setGravity = function (gravity) {
  82738. this.gravity = gravity;
  82739. this._physicsPlugin.setGravity(this.gravity);
  82740. };
  82741. /**
  82742. * Set the time step of the physics engine.
  82743. * default is 1/60.
  82744. * To slow it down, enter 1/600 for example.
  82745. * To speed it up, 1/30
  82746. * @param {number} newTimeStep the new timestep to apply to this world.
  82747. */
  82748. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82749. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82750. this._physicsPlugin.setTimeStep(newTimeStep);
  82751. };
  82752. /**
  82753. * Get the time step of the physics engine.
  82754. */
  82755. PhysicsEngine.prototype.getTimeStep = function () {
  82756. return this._physicsPlugin.getTimeStep();
  82757. };
  82758. PhysicsEngine.prototype.dispose = function () {
  82759. this._impostors.forEach(function (impostor) {
  82760. impostor.dispose();
  82761. });
  82762. this._physicsPlugin.dispose();
  82763. };
  82764. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82765. return this._physicsPlugin.name;
  82766. };
  82767. /**
  82768. * Adding a new impostor for the impostor tracking.
  82769. * This will be done by the impostor itself.
  82770. * @param {PhysicsImpostor} impostor the impostor to add
  82771. */
  82772. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82773. impostor.uniqueId = this._impostors.push(impostor);
  82774. //if no parent, generate the body
  82775. if (!impostor.parent) {
  82776. this._physicsPlugin.generatePhysicsBody(impostor);
  82777. }
  82778. };
  82779. /**
  82780. * Remove an impostor from the engine.
  82781. * This impostor and its mesh will not longer be updated by the physics engine.
  82782. * @param {PhysicsImpostor} impostor the impostor to remove
  82783. */
  82784. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82785. var index = this._impostors.indexOf(impostor);
  82786. if (index > -1) {
  82787. var removed = this._impostors.splice(index, 1);
  82788. //Is it needed?
  82789. if (removed.length) {
  82790. //this will also remove it from the world.
  82791. removed[0].physicsBody = null;
  82792. }
  82793. }
  82794. };
  82795. /**
  82796. * Add a joint to the physics engine
  82797. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82798. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82799. * @param {PhysicsJoint} the joint that will connect both impostors.
  82800. */
  82801. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82802. var impostorJoint = {
  82803. mainImpostor: mainImpostor,
  82804. connectedImpostor: connectedImpostor,
  82805. joint: joint
  82806. };
  82807. joint.physicsPlugin = this._physicsPlugin;
  82808. this._joints.push(impostorJoint);
  82809. this._physicsPlugin.generateJoint(impostorJoint);
  82810. };
  82811. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82812. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82813. return (impostorJoint.connectedImpostor === connectedImpostor
  82814. && impostorJoint.joint === joint
  82815. && impostorJoint.mainImpostor === mainImpostor);
  82816. });
  82817. if (matchingJoints.length) {
  82818. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82819. //TODO remove it from the list as well
  82820. }
  82821. };
  82822. /**
  82823. * Called by the scene. no need to call it.
  82824. */
  82825. PhysicsEngine.prototype._step = function (delta) {
  82826. var _this = this;
  82827. //check if any mesh has no body / requires an update
  82828. this._impostors.forEach(function (impostor) {
  82829. if (impostor.isBodyInitRequired()) {
  82830. _this._physicsPlugin.generatePhysicsBody(impostor);
  82831. }
  82832. });
  82833. if (delta > 0.1) {
  82834. delta = 0.1;
  82835. }
  82836. else if (delta <= 0) {
  82837. delta = 1.0 / 60.0;
  82838. }
  82839. this._physicsPlugin.executeStep(delta, this._impostors);
  82840. };
  82841. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  82842. return this._physicsPlugin;
  82843. };
  82844. PhysicsEngine.prototype.getImpostors = function () {
  82845. return this._impostors;
  82846. };
  82847. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  82848. for (var i = 0; i < this._impostors.length; ++i) {
  82849. if (this._impostors[i].object === object) {
  82850. return this._impostors[i];
  82851. }
  82852. }
  82853. return null;
  82854. };
  82855. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  82856. for (var i = 0; i < this._impostors.length; ++i) {
  82857. if (this._impostors[i].physicsBody === body) {
  82858. return this._impostors[i];
  82859. }
  82860. }
  82861. return null;
  82862. };
  82863. // Statics
  82864. PhysicsEngine.Epsilon = 0.001;
  82865. return PhysicsEngine;
  82866. }());
  82867. BABYLON.PhysicsEngine = PhysicsEngine;
  82868. })(BABYLON || (BABYLON = {}));
  82869. //# sourceMappingURL=babylon.physicsEngine.js.map
  82870. var BABYLON;
  82871. (function (BABYLON) {
  82872. var PhysicsHelper = /** @class */ (function () {
  82873. function PhysicsHelper(scene) {
  82874. this._scene = scene;
  82875. this._physicsEngine = this._scene.getPhysicsEngine();
  82876. if (!this._physicsEngine) {
  82877. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  82878. }
  82879. }
  82880. /**
  82881. * @param {Vector3} origin the origin of the explosion
  82882. * @param {number} radius the explosion radius
  82883. * @param {number} strength the explosion strength
  82884. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82885. */
  82886. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  82887. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82888. if (!this._physicsEngine) {
  82889. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  82890. return null;
  82891. }
  82892. var impostors = this._physicsEngine.getImpostors();
  82893. if (impostors.length === 0) {
  82894. return null;
  82895. }
  82896. var event = new PhysicsRadialExplosionEvent(this._scene);
  82897. impostors.forEach(function (impostor) {
  82898. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82899. if (!impostorForceAndContactPoint) {
  82900. return;
  82901. }
  82902. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82903. });
  82904. event.dispose(false);
  82905. return event;
  82906. };
  82907. /**
  82908. * @param {Vector3} origin the origin of the explosion
  82909. * @param {number} radius the explosion radius
  82910. * @param {number} strength the explosion strength
  82911. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82912. */
  82913. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  82914. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82915. if (!this._physicsEngine) {
  82916. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82917. return null;
  82918. }
  82919. var impostors = this._physicsEngine.getImpostors();
  82920. if (impostors.length === 0) {
  82921. return null;
  82922. }
  82923. var event = new PhysicsRadialExplosionEvent(this._scene);
  82924. impostors.forEach(function (impostor) {
  82925. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82926. if (!impostorForceAndContactPoint) {
  82927. return;
  82928. }
  82929. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82930. });
  82931. event.dispose(false);
  82932. return event;
  82933. };
  82934. /**
  82935. * @param {Vector3} origin the origin of the explosion
  82936. * @param {number} radius the explosion radius
  82937. * @param {number} strength the explosion strength
  82938. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82939. */
  82940. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82941. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82942. if (!this._physicsEngine) {
  82943. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82944. return null;
  82945. }
  82946. var impostors = this._physicsEngine.getImpostors();
  82947. if (impostors.length === 0) {
  82948. return null;
  82949. }
  82950. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82951. event.dispose(false);
  82952. return event;
  82953. };
  82954. /**
  82955. * @param {Vector3} origin the origin of the updraft
  82956. * @param {number} radius the radius of the updraft
  82957. * @param {number} strength the strength of the updraft
  82958. * @param {number} height the height of the updraft
  82959. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  82960. */
  82961. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  82962. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  82963. if (!this._physicsEngine) {
  82964. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82965. return null;
  82966. }
  82967. if (this._physicsEngine.getImpostors().length === 0) {
  82968. return null;
  82969. }
  82970. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  82971. event.dispose(false);
  82972. return event;
  82973. };
  82974. /**
  82975. * @param {Vector3} origin the of the vortex
  82976. * @param {number} radius the radius of the vortex
  82977. * @param {number} strength the strength of the vortex
  82978. * @param {number} height the height of the vortex
  82979. */
  82980. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  82981. if (!this._physicsEngine) {
  82982. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82983. return null;
  82984. }
  82985. if (this._physicsEngine.getImpostors().length === 0) {
  82986. return null;
  82987. }
  82988. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  82989. event.dispose(false);
  82990. return event;
  82991. };
  82992. return PhysicsHelper;
  82993. }());
  82994. BABYLON.PhysicsHelper = PhysicsHelper;
  82995. /***** Radial explosion *****/
  82996. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  82997. function PhysicsRadialExplosionEvent(scene) {
  82998. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  82999. this._rays = [];
  83000. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  83001. this._scene = scene;
  83002. }
  83003. /**
  83004. * Returns the data related to the radial explosion event (sphere & rays).
  83005. * @returns {PhysicsRadialExplosionEventData}
  83006. */
  83007. PhysicsRadialExplosionEvent.prototype.getData = function () {
  83008. this._dataFetched = true;
  83009. return {
  83010. sphere: this._sphere,
  83011. rays: this._rays,
  83012. };
  83013. };
  83014. /**
  83015. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  83016. * @param impostor
  83017. * @param {Vector3} origin the origin of the explosion
  83018. * @param {number} radius the explosion radius
  83019. * @param {number} strength the explosion strength
  83020. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  83021. * @returns {Nullable<PhysicsForceAndContactPoint>}
  83022. */
  83023. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  83024. if (impostor.mass === 0) {
  83025. return null;
  83026. }
  83027. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  83028. return null;
  83029. }
  83030. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83031. return null;
  83032. }
  83033. var impostorObjectCenter = impostor.getObjectCenter();
  83034. var direction = impostorObjectCenter.subtract(origin);
  83035. var ray = new BABYLON.Ray(origin, direction, radius);
  83036. this._rays.push(ray);
  83037. var hit = ray.intersectsMesh(impostor.object);
  83038. var contactPoint = hit.pickedPoint;
  83039. if (!contactPoint) {
  83040. return null;
  83041. }
  83042. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  83043. if (distanceFromOrigin > radius) {
  83044. return null;
  83045. }
  83046. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  83047. ? strength
  83048. : strength * (1 - (distanceFromOrigin / radius));
  83049. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83050. return { force: force, contactPoint: contactPoint };
  83051. };
  83052. /**
  83053. * Disposes the sphere.
  83054. * @param {bolean} force
  83055. */
  83056. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  83057. var _this = this;
  83058. if (force === void 0) { force = true; }
  83059. if (force) {
  83060. this._sphere.dispose();
  83061. }
  83062. else {
  83063. setTimeout(function () {
  83064. if (!_this._dataFetched) {
  83065. _this._sphere.dispose();
  83066. }
  83067. }, 0);
  83068. }
  83069. };
  83070. /*** Helpers ***/
  83071. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  83072. if (!this._sphere) {
  83073. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  83074. this._sphere.isVisible = false;
  83075. }
  83076. };
  83077. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  83078. var impostorObject = impostor.object;
  83079. this._prepareSphere();
  83080. this._sphere.position = origin;
  83081. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  83082. this._sphere._updateBoundingInfo();
  83083. this._sphere.computeWorldMatrix(true);
  83084. return this._sphere.intersectsMesh(impostorObject, true);
  83085. };
  83086. return PhysicsRadialExplosionEvent;
  83087. }());
  83088. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  83089. /***** Gravitational Field *****/
  83090. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  83091. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  83092. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83093. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83094. this._physicsHelper = physicsHelper;
  83095. this._scene = scene;
  83096. this._origin = origin;
  83097. this._radius = radius;
  83098. this._strength = strength;
  83099. this._falloff = falloff;
  83100. this._tickCallback = this._tick.bind(this);
  83101. }
  83102. /**
  83103. * Returns the data related to the gravitational field event (sphere).
  83104. * @returns {PhysicsGravitationalFieldEventData}
  83105. */
  83106. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  83107. this._dataFetched = true;
  83108. return {
  83109. sphere: this._sphere,
  83110. };
  83111. };
  83112. /**
  83113. * Enables the gravitational field.
  83114. */
  83115. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  83116. this._tickCallback.call(this);
  83117. this._scene.registerBeforeRender(this._tickCallback);
  83118. };
  83119. /**
  83120. * Disables the gravitational field.
  83121. */
  83122. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  83123. this._scene.unregisterBeforeRender(this._tickCallback);
  83124. };
  83125. /**
  83126. * Disposes the sphere.
  83127. * @param {bolean} force
  83128. */
  83129. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  83130. var _this = this;
  83131. if (force === void 0) { force = true; }
  83132. if (force) {
  83133. this._sphere.dispose();
  83134. }
  83135. else {
  83136. setTimeout(function () {
  83137. if (!_this._dataFetched) {
  83138. _this._sphere.dispose();
  83139. }
  83140. }, 0);
  83141. }
  83142. };
  83143. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  83144. // Since the params won't change, we fetch the event only once
  83145. if (this._sphere) {
  83146. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  83147. }
  83148. else {
  83149. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  83150. if (radialExplosionEvent) {
  83151. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  83152. }
  83153. }
  83154. };
  83155. return PhysicsGravitationalFieldEvent;
  83156. }());
  83157. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  83158. /***** Updraft *****/
  83159. var PhysicsUpdraftEvent = /** @class */ (function () {
  83160. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  83161. this._scene = _scene;
  83162. this._origin = _origin;
  83163. this._radius = _radius;
  83164. this._strength = _strength;
  83165. this._height = _height;
  83166. this._updraftMode = _updraftMode;
  83167. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  83168. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  83169. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  83170. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83171. this._physicsEngine = this._scene.getPhysicsEngine();
  83172. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  83173. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  83174. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  83175. this._originDirection = this._origin.subtract(this._originTop).normalize();
  83176. }
  83177. this._tickCallback = this._tick.bind(this);
  83178. }
  83179. /**
  83180. * Returns the data related to the updraft event (cylinder).
  83181. * @returns {PhysicsUpdraftEventData}
  83182. */
  83183. PhysicsUpdraftEvent.prototype.getData = function () {
  83184. this._dataFetched = true;
  83185. return {
  83186. cylinder: this._cylinder,
  83187. };
  83188. };
  83189. /**
  83190. * Enables the updraft.
  83191. */
  83192. PhysicsUpdraftEvent.prototype.enable = function () {
  83193. this._tickCallback.call(this);
  83194. this._scene.registerBeforeRender(this._tickCallback);
  83195. };
  83196. /**
  83197. * Disables the cortex.
  83198. */
  83199. PhysicsUpdraftEvent.prototype.disable = function () {
  83200. this._scene.unregisterBeforeRender(this._tickCallback);
  83201. };
  83202. /**
  83203. * Disposes the sphere.
  83204. * @param {bolean} force
  83205. */
  83206. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  83207. var _this = this;
  83208. if (force === void 0) { force = true; }
  83209. if (force) {
  83210. this._cylinder.dispose();
  83211. }
  83212. else {
  83213. setTimeout(function () {
  83214. if (!_this._dataFetched) {
  83215. _this._cylinder.dispose();
  83216. }
  83217. }, 0);
  83218. }
  83219. };
  83220. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83221. if (impostor.mass === 0) {
  83222. return null;
  83223. }
  83224. if (!this._intersectsWithCylinder(impostor)) {
  83225. return null;
  83226. }
  83227. var impostorObjectCenter = impostor.getObjectCenter();
  83228. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  83229. var direction = this._originDirection;
  83230. }
  83231. else {
  83232. var direction = impostorObjectCenter.subtract(this._originTop);
  83233. }
  83234. var multiplier = this._strength * -1;
  83235. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83236. return { force: force, contactPoint: impostorObjectCenter };
  83237. };
  83238. PhysicsUpdraftEvent.prototype._tick = function () {
  83239. var _this = this;
  83240. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83241. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83242. if (!impostorForceAndContactPoint) {
  83243. return;
  83244. }
  83245. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83246. });
  83247. };
  83248. /*** Helpers ***/
  83249. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  83250. if (!this._cylinder) {
  83251. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  83252. height: this._height,
  83253. diameter: this._radius * 2,
  83254. }, this._scene);
  83255. this._cylinder.isVisible = false;
  83256. }
  83257. };
  83258. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  83259. var impostorObject = impostor.object;
  83260. this._prepareCylinder();
  83261. this._cylinder.position = this._cylinderPosition;
  83262. return this._cylinder.intersectsMesh(impostorObject, true);
  83263. };
  83264. return PhysicsUpdraftEvent;
  83265. }());
  83266. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  83267. /***** Vortex *****/
  83268. var PhysicsVortexEvent = /** @class */ (function () {
  83269. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  83270. this._scene = _scene;
  83271. this._origin = _origin;
  83272. this._radius = _radius;
  83273. this._strength = _strength;
  83274. this._height = _height;
  83275. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  83276. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  83277. this._updraftMultiplier = 0.02;
  83278. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  83279. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83280. this._physicsEngine = this._scene.getPhysicsEngine();
  83281. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  83282. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  83283. this._tickCallback = this._tick.bind(this);
  83284. }
  83285. /**
  83286. * Returns the data related to the vortex event (cylinder).
  83287. * @returns {PhysicsVortexEventData}
  83288. */
  83289. PhysicsVortexEvent.prototype.getData = function () {
  83290. this._dataFetched = true;
  83291. return {
  83292. cylinder: this._cylinder,
  83293. };
  83294. };
  83295. /**
  83296. * Enables the vortex.
  83297. */
  83298. PhysicsVortexEvent.prototype.enable = function () {
  83299. this._tickCallback.call(this);
  83300. this._scene.registerBeforeRender(this._tickCallback);
  83301. };
  83302. /**
  83303. * Disables the cortex.
  83304. */
  83305. PhysicsVortexEvent.prototype.disable = function () {
  83306. this._scene.unregisterBeforeRender(this._tickCallback);
  83307. };
  83308. /**
  83309. * Disposes the sphere.
  83310. * @param {bolean} force
  83311. */
  83312. PhysicsVortexEvent.prototype.dispose = function (force) {
  83313. var _this = this;
  83314. if (force === void 0) { force = true; }
  83315. if (force) {
  83316. this._cylinder.dispose();
  83317. }
  83318. else {
  83319. setTimeout(function () {
  83320. if (!_this._dataFetched) {
  83321. _this._cylinder.dispose();
  83322. }
  83323. }, 0);
  83324. }
  83325. };
  83326. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83327. if (impostor.mass === 0) {
  83328. return null;
  83329. }
  83330. if (!this._intersectsWithCylinder(impostor)) {
  83331. return null;
  83332. }
  83333. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83334. return null;
  83335. }
  83336. var impostorObjectCenter = impostor.getObjectCenter();
  83337. 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)
  83338. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  83339. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  83340. var hit = ray.intersectsMesh(impostor.object);
  83341. var contactPoint = hit.pickedPoint;
  83342. if (!contactPoint) {
  83343. return null;
  83344. }
  83345. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  83346. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  83347. var directionToOrigin = contactPoint.normalize();
  83348. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83349. directionToOrigin = directionToOrigin.negate();
  83350. }
  83351. // TODO: find a more physically based solution
  83352. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83353. var forceX = directionToOrigin.x * this._strength / 8;
  83354. var forceY = directionToOrigin.y * this._updraftMultiplier;
  83355. var forceZ = directionToOrigin.z * this._strength / 8;
  83356. }
  83357. else {
  83358. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  83359. var forceY = this._originTop.y * this._updraftMultiplier;
  83360. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  83361. }
  83362. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  83363. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  83364. return { force: force, contactPoint: impostorObjectCenter };
  83365. };
  83366. PhysicsVortexEvent.prototype._tick = function () {
  83367. var _this = this;
  83368. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83369. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83370. if (!impostorForceAndContactPoint) {
  83371. return;
  83372. }
  83373. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83374. });
  83375. };
  83376. /*** Helpers ***/
  83377. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  83378. if (!this._cylinder) {
  83379. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  83380. height: this._height,
  83381. diameter: this._radius * 2,
  83382. }, this._scene);
  83383. this._cylinder.isVisible = false;
  83384. }
  83385. };
  83386. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  83387. var impostorObject = impostor.object;
  83388. this._prepareCylinder();
  83389. this._cylinder.position = this._cylinderPosition;
  83390. return this._cylinder.intersectsMesh(impostorObject, true);
  83391. };
  83392. return PhysicsVortexEvent;
  83393. }());
  83394. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  83395. /***** Enums *****/
  83396. /**
  83397. * The strenght of the force in correspondence to the distance of the affected object
  83398. */
  83399. var PhysicsRadialImpulseFalloff;
  83400. (function (PhysicsRadialImpulseFalloff) {
  83401. /** Defines that impulse is constant in strength across it's whole radius */
  83402. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  83403. /** DEfines that impulse gets weaker if it's further from the origin */
  83404. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  83405. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  83406. /**
  83407. * The strenght of the force in correspondence to the distance of the affected object
  83408. */
  83409. var PhysicsUpdraftMode;
  83410. (function (PhysicsUpdraftMode) {
  83411. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  83412. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  83413. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  83414. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  83415. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  83416. })(BABYLON || (BABYLON = {}));
  83417. //# sourceMappingURL=babylon.physicsHelper.js.map
  83418. var BABYLON;
  83419. (function (BABYLON) {
  83420. var CannonJSPlugin = /** @class */ (function () {
  83421. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  83422. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  83423. if (iterations === void 0) { iterations = 10; }
  83424. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  83425. this.name = "CannonJSPlugin";
  83426. this._physicsMaterials = new Array();
  83427. this._fixedTimeStep = 1 / 60;
  83428. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  83429. this.BJSCANNON = CANNON;
  83430. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  83431. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  83432. this._tmpPosition = BABYLON.Vector3.Zero();
  83433. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  83434. this._tmpUnityRotation = new BABYLON.Quaternion();
  83435. if (!this.isSupported()) {
  83436. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  83437. return;
  83438. }
  83439. this._extendNamespace();
  83440. this.world = new this.BJSCANNON.World();
  83441. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  83442. this.world.solver.iterations = iterations;
  83443. }
  83444. CannonJSPlugin.prototype.setGravity = function (gravity) {
  83445. this.world.gravity.copy(gravity);
  83446. };
  83447. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  83448. this._fixedTimeStep = timeStep;
  83449. };
  83450. CannonJSPlugin.prototype.getTimeStep = function () {
  83451. return this._fixedTimeStep;
  83452. };
  83453. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  83454. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  83455. };
  83456. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83457. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83458. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83459. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  83460. };
  83461. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83462. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83463. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83464. impostor.physicsBody.applyForce(impulse, worldPoint);
  83465. };
  83466. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83467. //parent-child relationship. Does this impostor has a parent impostor?
  83468. if (impostor.parent) {
  83469. if (impostor.physicsBody) {
  83470. this.removePhysicsBody(impostor);
  83471. //TODO is that needed?
  83472. impostor.forceUpdate();
  83473. }
  83474. return;
  83475. }
  83476. //should a new body be created for this impostor?
  83477. if (impostor.isBodyInitRequired()) {
  83478. var shape = this._createShape(impostor);
  83479. //unregister events, if body is being changed
  83480. var oldBody = impostor.physicsBody;
  83481. if (oldBody) {
  83482. this.removePhysicsBody(impostor);
  83483. }
  83484. //create the body and material
  83485. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  83486. var bodyCreationObject = {
  83487. mass: impostor.getParam("mass"),
  83488. material: material
  83489. };
  83490. // A simple extend, in case native options were used.
  83491. var nativeOptions = impostor.getParam("nativeOptions");
  83492. for (var key in nativeOptions) {
  83493. if (nativeOptions.hasOwnProperty(key)) {
  83494. bodyCreationObject[key] = nativeOptions[key];
  83495. }
  83496. }
  83497. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83498. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83499. this.world.addEventListener("preStep", impostor.beforeStep);
  83500. this.world.addEventListener("postStep", impostor.afterStep);
  83501. impostor.physicsBody.addShape(shape);
  83502. this.world.add(impostor.physicsBody);
  83503. //try to keep the body moving in the right direction by taking old properties.
  83504. //Should be tested!
  83505. if (oldBody) {
  83506. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83507. impostor.physicsBody[param].copy(oldBody[param]);
  83508. });
  83509. }
  83510. this._processChildMeshes(impostor);
  83511. }
  83512. //now update the body's transformation
  83513. this._updatePhysicsBodyTransformation(impostor);
  83514. };
  83515. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83516. var _this = this;
  83517. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83518. var currentRotation = mainImpostor.object.rotationQuaternion;
  83519. if (meshChildren.length) {
  83520. var processMesh = function (localPosition, mesh) {
  83521. if (!currentRotation || !mesh.rotationQuaternion) {
  83522. return;
  83523. }
  83524. var childImpostor = mesh.getPhysicsImpostor();
  83525. if (childImpostor) {
  83526. var parent = childImpostor.parent;
  83527. if (parent !== mainImpostor) {
  83528. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83529. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83530. if (childImpostor.physicsBody) {
  83531. _this.removePhysicsBody(childImpostor);
  83532. childImpostor.physicsBody = null;
  83533. }
  83534. childImpostor.parent = mainImpostor;
  83535. childImpostor.resetUpdateFlags();
  83536. 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));
  83537. //Add the mass of the children.
  83538. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83539. }
  83540. }
  83541. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83542. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83543. };
  83544. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83545. }
  83546. };
  83547. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83548. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83549. this.world.removeEventListener("preStep", impostor.beforeStep);
  83550. this.world.removeEventListener("postStep", impostor.afterStep);
  83551. this.world.remove(impostor.physicsBody);
  83552. };
  83553. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83554. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83555. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83556. if (!mainBody || !connectedBody) {
  83557. return;
  83558. }
  83559. var constraint;
  83560. var jointData = impostorJoint.joint.jointData;
  83561. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83562. var constraintData = {
  83563. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83564. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83565. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83566. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83567. maxForce: jointData.nativeParams.maxForce,
  83568. collideConnected: !!jointData.collision
  83569. };
  83570. switch (impostorJoint.joint.type) {
  83571. case BABYLON.PhysicsJoint.HingeJoint:
  83572. case BABYLON.PhysicsJoint.Hinge2Joint:
  83573. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83574. break;
  83575. case BABYLON.PhysicsJoint.DistanceJoint:
  83576. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83577. break;
  83578. case BABYLON.PhysicsJoint.SpringJoint:
  83579. var springData = jointData;
  83580. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83581. restLength: springData.length,
  83582. stiffness: springData.stiffness,
  83583. damping: springData.damping,
  83584. localAnchorA: constraintData.pivotA,
  83585. localAnchorB: constraintData.pivotB
  83586. });
  83587. break;
  83588. case BABYLON.PhysicsJoint.LockJoint:
  83589. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83590. break;
  83591. case BABYLON.PhysicsJoint.PointToPointJoint:
  83592. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83593. default:
  83594. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83595. break;
  83596. }
  83597. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83598. constraint.collideConnected = !!jointData.collision;
  83599. impostorJoint.joint.physicsJoint = constraint;
  83600. //don't add spring as constraint, as it is not one.
  83601. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83602. this.world.addConstraint(constraint);
  83603. }
  83604. else {
  83605. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83606. constraint.applyForce();
  83607. });
  83608. }
  83609. };
  83610. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83611. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83612. };
  83613. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83614. var index;
  83615. var mat;
  83616. for (index = 0; index < this._physicsMaterials.length; index++) {
  83617. mat = this._physicsMaterials[index];
  83618. if (mat.friction === friction && mat.restitution === restitution) {
  83619. return mat;
  83620. }
  83621. }
  83622. var currentMat = new this.BJSCANNON.Material(name);
  83623. currentMat.friction = friction;
  83624. currentMat.restitution = restitution;
  83625. this._physicsMaterials.push(currentMat);
  83626. return currentMat;
  83627. };
  83628. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83629. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83630. };
  83631. CannonJSPlugin.prototype._createShape = function (impostor) {
  83632. var object = impostor.object;
  83633. var returnValue;
  83634. var extendSize = impostor.getObjectExtendSize();
  83635. switch (impostor.type) {
  83636. case BABYLON.PhysicsImpostor.SphereImpostor:
  83637. var radiusX = extendSize.x;
  83638. var radiusY = extendSize.y;
  83639. var radiusZ = extendSize.z;
  83640. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83641. break;
  83642. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83643. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83644. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83645. break;
  83646. case BABYLON.PhysicsImpostor.BoxImpostor:
  83647. var box = extendSize.scale(0.5);
  83648. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83649. break;
  83650. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83651. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83652. returnValue = new this.BJSCANNON.Plane();
  83653. break;
  83654. case BABYLON.PhysicsImpostor.MeshImpostor:
  83655. // should transform the vertex data to world coordinates!!
  83656. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83657. var rawFaces = object.getIndices ? object.getIndices() : [];
  83658. if (!rawVerts)
  83659. return;
  83660. // get only scale! so the object could transform correctly.
  83661. var oldPosition = object.position.clone();
  83662. var oldRotation = object.rotation && object.rotation.clone();
  83663. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83664. object.position.copyFromFloats(0, 0, 0);
  83665. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83666. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83667. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83668. var transform = object.computeWorldMatrix(true);
  83669. // convert rawVerts to object space
  83670. var temp = new Array();
  83671. var index;
  83672. for (index = 0; index < rawVerts.length; index += 3) {
  83673. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83674. }
  83675. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83676. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83677. //now set back the transformation!
  83678. object.position.copyFrom(oldPosition);
  83679. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83680. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83681. break;
  83682. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83683. var oldPosition2 = object.position.clone();
  83684. var oldRotation2 = object.rotation && object.rotation.clone();
  83685. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83686. object.position.copyFromFloats(0, 0, 0);
  83687. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83688. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83689. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83690. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83691. returnValue = this._createHeightmap(object);
  83692. object.position.copyFrom(oldPosition2);
  83693. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83694. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83695. object.computeWorldMatrix(true);
  83696. break;
  83697. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83698. returnValue = new this.BJSCANNON.Particle();
  83699. break;
  83700. }
  83701. return returnValue;
  83702. };
  83703. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83704. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83705. var transform = object.computeWorldMatrix(true);
  83706. // convert rawVerts to object space
  83707. var temp = new Array();
  83708. var index;
  83709. for (index = 0; index < pos.length; index += 3) {
  83710. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83711. }
  83712. pos = temp;
  83713. var matrix = new Array();
  83714. //For now pointDepth will not be used and will be automatically calculated.
  83715. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83716. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83717. var boundingInfo = object.getBoundingInfo();
  83718. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83719. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83720. var elementSize = dim * 2 / arraySize;
  83721. for (var i = 0; i < pos.length; i = i + 3) {
  83722. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83723. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83724. var y = -pos[i + 2] + minY;
  83725. if (!matrix[x]) {
  83726. matrix[x] = [];
  83727. }
  83728. if (!matrix[x][z]) {
  83729. matrix[x][z] = y;
  83730. }
  83731. matrix[x][z] = Math.max(y, matrix[x][z]);
  83732. }
  83733. for (var x = 0; x <= arraySize; ++x) {
  83734. if (!matrix[x]) {
  83735. var loc = 1;
  83736. while (!matrix[(x + loc) % arraySize]) {
  83737. loc++;
  83738. }
  83739. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83740. //console.log("missing x", x);
  83741. }
  83742. for (var z = 0; z <= arraySize; ++z) {
  83743. if (!matrix[x][z]) {
  83744. var loc = 1;
  83745. var newValue;
  83746. while (newValue === undefined) {
  83747. newValue = matrix[x][(z + loc++) % arraySize];
  83748. }
  83749. matrix[x][z] = newValue;
  83750. }
  83751. }
  83752. }
  83753. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83754. elementSize: elementSize
  83755. });
  83756. //For future reference, needed for body transformation
  83757. shape.minY = minY;
  83758. return shape;
  83759. };
  83760. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83761. var object = impostor.object;
  83762. //make sure it is updated...
  83763. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83764. // The delta between the mesh position and the mesh bounding box center
  83765. var bInfo = object.getBoundingInfo();
  83766. if (!bInfo)
  83767. return;
  83768. var center = impostor.getObjectCenter();
  83769. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83770. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83771. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83772. this._tmpPosition.copyFrom(center);
  83773. var quaternion = object.rotationQuaternion;
  83774. if (!quaternion) {
  83775. return;
  83776. }
  83777. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83778. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83779. //-90 DEG in X, precalculated
  83780. quaternion = quaternion.multiply(this._minus90X);
  83781. //Invert! (Precalculated, 90 deg in X)
  83782. //No need to clone. this will never change.
  83783. impostor.setDeltaRotation(this._plus90X);
  83784. }
  83785. //If it is a heightfield, if should be centered.
  83786. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83787. var mesh = object;
  83788. var boundingInfo = mesh.getBoundingInfo();
  83789. //calculate the correct body position:
  83790. var rotationQuaternion = mesh.rotationQuaternion;
  83791. mesh.rotationQuaternion = this._tmpUnityRotation;
  83792. mesh.computeWorldMatrix(true);
  83793. //get original center with no rotation
  83794. var c = center.clone();
  83795. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83796. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83797. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83798. mesh.setPreTransformMatrix(p);
  83799. mesh.computeWorldMatrix(true);
  83800. //calculate the translation
  83801. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83802. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83803. //add it inverted to the delta
  83804. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83805. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83806. //rotation is back
  83807. mesh.rotationQuaternion = rotationQuaternion;
  83808. mesh.setPreTransformMatrix(oldPivot);
  83809. mesh.computeWorldMatrix(true);
  83810. }
  83811. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83812. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83813. //this._tmpPosition.copyFrom(object.position);
  83814. }
  83815. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83816. //Now update the impostor object
  83817. impostor.physicsBody.position.copy(this._tmpPosition);
  83818. impostor.physicsBody.quaternion.copy(quaternion);
  83819. };
  83820. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83821. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83822. if (impostor.object.rotationQuaternion) {
  83823. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83824. }
  83825. };
  83826. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83827. impostor.physicsBody.position.copy(newPosition);
  83828. impostor.physicsBody.quaternion.copy(newRotation);
  83829. };
  83830. CannonJSPlugin.prototype.isSupported = function () {
  83831. return this.BJSCANNON !== undefined;
  83832. };
  83833. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83834. impostor.physicsBody.velocity.copy(velocity);
  83835. };
  83836. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83837. impostor.physicsBody.angularVelocity.copy(velocity);
  83838. };
  83839. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83840. var v = impostor.physicsBody.velocity;
  83841. if (!v) {
  83842. return null;
  83843. }
  83844. return new BABYLON.Vector3(v.x, v.y, v.z);
  83845. };
  83846. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83847. var v = impostor.physicsBody.angularVelocity;
  83848. if (!v) {
  83849. return null;
  83850. }
  83851. return new BABYLON.Vector3(v.x, v.y, v.z);
  83852. };
  83853. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83854. impostor.physicsBody.mass = mass;
  83855. impostor.physicsBody.updateMassProperties();
  83856. };
  83857. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  83858. return impostor.physicsBody.mass;
  83859. };
  83860. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  83861. return impostor.physicsBody.material.friction;
  83862. };
  83863. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83864. impostor.physicsBody.material.friction = friction;
  83865. };
  83866. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83867. return impostor.physicsBody.material.restitution;
  83868. };
  83869. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83870. impostor.physicsBody.material.restitution = restitution;
  83871. };
  83872. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  83873. impostor.physicsBody.sleep();
  83874. };
  83875. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  83876. impostor.physicsBody.wakeUp();
  83877. };
  83878. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83879. joint.physicsJoint.distance = maxDistance;
  83880. };
  83881. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83882. // if (!motorIndex) {
  83883. // joint.physicsJoint.enableMotor();
  83884. // }
  83885. // }
  83886. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83887. // if (!motorIndex) {
  83888. // joint.physicsJoint.disableMotor();
  83889. // }
  83890. // }
  83891. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83892. if (!motorIndex) {
  83893. joint.physicsJoint.enableMotor();
  83894. joint.physicsJoint.setMotorSpeed(speed);
  83895. if (maxForce) {
  83896. this.setLimit(joint, maxForce);
  83897. }
  83898. }
  83899. };
  83900. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  83901. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  83902. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  83903. };
  83904. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83905. var body = impostor.physicsBody;
  83906. mesh.position.x = body.position.x;
  83907. mesh.position.y = body.position.y;
  83908. mesh.position.z = body.position.z;
  83909. if (mesh.rotationQuaternion) {
  83910. mesh.rotationQuaternion.x = body.quaternion.x;
  83911. mesh.rotationQuaternion.y = body.quaternion.y;
  83912. mesh.rotationQuaternion.z = body.quaternion.z;
  83913. mesh.rotationQuaternion.w = body.quaternion.w;
  83914. }
  83915. };
  83916. CannonJSPlugin.prototype.getRadius = function (impostor) {
  83917. var shape = impostor.physicsBody.shapes[0];
  83918. return shape.boundingSphereRadius;
  83919. };
  83920. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83921. var shape = impostor.physicsBody.shapes[0];
  83922. result.x = shape.halfExtents.x * 2;
  83923. result.y = shape.halfExtents.y * 2;
  83924. result.z = shape.halfExtents.z * 2;
  83925. };
  83926. CannonJSPlugin.prototype.dispose = function () {
  83927. };
  83928. CannonJSPlugin.prototype._extendNamespace = function () {
  83929. //this will force cannon to execute at least one step when using interpolation
  83930. var step_tmp1 = new this.BJSCANNON.Vec3();
  83931. var Engine = this.BJSCANNON;
  83932. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83933. maxSubSteps = maxSubSteps || 10;
  83934. timeSinceLastCalled = timeSinceLastCalled || 0;
  83935. if (timeSinceLastCalled === 0) {
  83936. this.internalStep(dt);
  83937. this.time += dt;
  83938. }
  83939. else {
  83940. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83941. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83942. var t0 = performance.now();
  83943. for (var i = 0; i !== internalSteps; i++) {
  83944. this.internalStep(dt);
  83945. if (performance.now() - t0 > dt * 1000) {
  83946. break;
  83947. }
  83948. }
  83949. this.time += timeSinceLastCalled;
  83950. var h = this.time % dt;
  83951. var h_div_dt = h / dt;
  83952. var interpvelo = step_tmp1;
  83953. var bodies = this.bodies;
  83954. for (var j = 0; j !== bodies.length; j++) {
  83955. var b = bodies[j];
  83956. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  83957. b.position.vsub(b.previousPosition, interpvelo);
  83958. interpvelo.scale(h_div_dt, interpvelo);
  83959. b.position.vadd(interpvelo, b.interpolatedPosition);
  83960. }
  83961. else {
  83962. b.interpolatedPosition.copy(b.position);
  83963. b.interpolatedQuaternion.copy(b.quaternion);
  83964. }
  83965. }
  83966. }
  83967. };
  83968. };
  83969. return CannonJSPlugin;
  83970. }());
  83971. BABYLON.CannonJSPlugin = CannonJSPlugin;
  83972. })(BABYLON || (BABYLON = {}));
  83973. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  83974. var BABYLON;
  83975. (function (BABYLON) {
  83976. var OimoJSPlugin = /** @class */ (function () {
  83977. function OimoJSPlugin(iterations) {
  83978. this.name = "OimoJSPlugin";
  83979. this._tmpImpostorsArray = [];
  83980. this._tmpPositionVector = BABYLON.Vector3.Zero();
  83981. this.BJSOIMO = OIMO;
  83982. this.world = new this.BJSOIMO.World({
  83983. iterations: iterations
  83984. });
  83985. this.world.clear();
  83986. }
  83987. OimoJSPlugin.prototype.setGravity = function (gravity) {
  83988. this.world.gravity.copy(gravity);
  83989. };
  83990. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  83991. this.world.timeStep = timeStep;
  83992. };
  83993. OimoJSPlugin.prototype.getTimeStep = function () {
  83994. return this.world.timeStep;
  83995. };
  83996. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  83997. var _this = this;
  83998. impostors.forEach(function (impostor) {
  83999. impostor.beforeStep();
  84000. });
  84001. this.world.step();
  84002. impostors.forEach(function (impostor) {
  84003. impostor.afterStep();
  84004. //update the ordered impostors array
  84005. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  84006. });
  84007. //check for collisions
  84008. var contact = this.world.contacts;
  84009. while (contact !== null) {
  84010. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  84011. contact = contact.next;
  84012. continue;
  84013. }
  84014. //is this body colliding with any other? get the impostor
  84015. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  84016. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  84017. if (!mainImpostor || !collidingImpostor) {
  84018. contact = contact.next;
  84019. continue;
  84020. }
  84021. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  84022. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  84023. contact = contact.next;
  84024. }
  84025. };
  84026. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84027. var mass = impostor.physicsBody.mass;
  84028. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  84029. };
  84030. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84031. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  84032. this.applyImpulse(impostor, force, contactPoint);
  84033. };
  84034. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84035. var _this = this;
  84036. //parent-child relationship. Does this impostor has a parent impostor?
  84037. if (impostor.parent) {
  84038. if (impostor.physicsBody) {
  84039. this.removePhysicsBody(impostor);
  84040. //TODO is that needed?
  84041. impostor.forceUpdate();
  84042. }
  84043. return;
  84044. }
  84045. if (impostor.isBodyInitRequired()) {
  84046. var bodyConfig = {
  84047. name: impostor.uniqueId,
  84048. //Oimo must have mass, also for static objects.
  84049. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  84050. size: [],
  84051. type: [],
  84052. pos: [],
  84053. posShape: [],
  84054. rot: [],
  84055. rotShape: [],
  84056. move: impostor.getParam("mass") !== 0,
  84057. density: impostor.getParam("mass"),
  84058. friction: impostor.getParam("friction"),
  84059. restitution: impostor.getParam("restitution"),
  84060. //Supporting older versions of Oimo
  84061. world: this.world
  84062. };
  84063. var impostors = [impostor];
  84064. var addToArray = function (parent) {
  84065. if (!parent.getChildMeshes)
  84066. return;
  84067. parent.getChildMeshes().forEach(function (m) {
  84068. if (m.physicsImpostor) {
  84069. impostors.push(m.physicsImpostor);
  84070. //m.physicsImpostor._init();
  84071. }
  84072. });
  84073. };
  84074. addToArray(impostor.object);
  84075. var checkWithEpsilon_1 = function (value) {
  84076. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  84077. };
  84078. impostors.forEach(function (i) {
  84079. if (!i.object.rotationQuaternion) {
  84080. return;
  84081. }
  84082. //get the correct bounding box
  84083. var oldQuaternion = i.object.rotationQuaternion;
  84084. var rot = oldQuaternion.toEulerAngles();
  84085. var extendSize = i.getObjectExtendSize();
  84086. var radToDeg = 57.295779513082320876;
  84087. if (i === impostor) {
  84088. var center = impostor.getObjectCenter();
  84089. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  84090. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  84091. //Can also use Array.prototype.push.apply
  84092. bodyConfig.pos.push(center.x);
  84093. bodyConfig.pos.push(center.y);
  84094. bodyConfig.pos.push(center.z);
  84095. bodyConfig.posShape.push(0, 0, 0);
  84096. //tmp solution
  84097. bodyConfig.rot.push(rot.x * radToDeg);
  84098. bodyConfig.rot.push(rot.y * radToDeg);
  84099. bodyConfig.rot.push(rot.z * radToDeg);
  84100. bodyConfig.rotShape.push(0, 0, 0);
  84101. }
  84102. else {
  84103. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  84104. bodyConfig.posShape.push(localPosition.x);
  84105. bodyConfig.posShape.push(localPosition.y);
  84106. bodyConfig.posShape.push(localPosition.z);
  84107. bodyConfig.pos.push(0, 0, 0);
  84108. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  84109. bodyConfig.rot.push(0);
  84110. bodyConfig.rot.push(0);
  84111. bodyConfig.rot.push(0);
  84112. bodyConfig.rotShape.push(rot.x * radToDeg);
  84113. bodyConfig.rotShape.push(rot.y * radToDeg);
  84114. bodyConfig.rotShape.push(rot.z * radToDeg);
  84115. }
  84116. // register mesh
  84117. switch (i.type) {
  84118. case BABYLON.PhysicsImpostor.ParticleImpostor:
  84119. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  84120. case BABYLON.PhysicsImpostor.SphereImpostor:
  84121. var radiusX = extendSize.x;
  84122. var radiusY = extendSize.y;
  84123. var radiusZ = extendSize.z;
  84124. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  84125. bodyConfig.type.push('sphere');
  84126. //due to the way oimo works with compounds, add 3 times
  84127. bodyConfig.size.push(size);
  84128. bodyConfig.size.push(size);
  84129. bodyConfig.size.push(size);
  84130. break;
  84131. case BABYLON.PhysicsImpostor.CylinderImpostor:
  84132. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  84133. var sizeY = checkWithEpsilon_1(extendSize.y);
  84134. bodyConfig.type.push('cylinder');
  84135. bodyConfig.size.push(sizeX);
  84136. bodyConfig.size.push(sizeY);
  84137. //due to the way oimo works with compounds, add one more value.
  84138. bodyConfig.size.push(sizeY);
  84139. break;
  84140. case BABYLON.PhysicsImpostor.PlaneImpostor:
  84141. case BABYLON.PhysicsImpostor.BoxImpostor:
  84142. default:
  84143. var sizeX = checkWithEpsilon_1(extendSize.x);
  84144. var sizeY = checkWithEpsilon_1(extendSize.y);
  84145. var sizeZ = checkWithEpsilon_1(extendSize.z);
  84146. bodyConfig.type.push('box');
  84147. //if (i === impostor) {
  84148. bodyConfig.size.push(sizeX);
  84149. bodyConfig.size.push(sizeY);
  84150. bodyConfig.size.push(sizeZ);
  84151. //} else {
  84152. // bodyConfig.size.push(0,0,0);
  84153. //}
  84154. break;
  84155. }
  84156. //actually not needed, but hey...
  84157. i.object.rotationQuaternion = oldQuaternion;
  84158. });
  84159. impostor.physicsBody = this.world.add(bodyConfig);
  84160. }
  84161. else {
  84162. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  84163. }
  84164. impostor.setDeltaPosition(this._tmpPositionVector);
  84165. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  84166. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  84167. };
  84168. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  84169. //impostor.physicsBody.dispose();
  84170. //Same as : (older oimo versions)
  84171. this.world.removeRigidBody(impostor.physicsBody);
  84172. };
  84173. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  84174. var mainBody = impostorJoint.mainImpostor.physicsBody;
  84175. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  84176. if (!mainBody || !connectedBody) {
  84177. return;
  84178. }
  84179. var jointData = impostorJoint.joint.jointData;
  84180. var options = jointData.nativeParams || {};
  84181. var type;
  84182. var nativeJointData = {
  84183. body1: mainBody,
  84184. body2: connectedBody,
  84185. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  84186. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  84187. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  84188. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  84189. min: options.min,
  84190. max: options.max,
  84191. collision: options.collision || jointData.collision,
  84192. spring: options.spring,
  84193. //supporting older version of Oimo
  84194. world: this.world
  84195. };
  84196. switch (impostorJoint.joint.type) {
  84197. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  84198. type = "jointBall";
  84199. break;
  84200. case BABYLON.PhysicsJoint.SpringJoint:
  84201. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  84202. var springData = jointData;
  84203. nativeJointData.min = springData.length || nativeJointData.min;
  84204. //Max should also be set, just make sure it is at least min
  84205. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  84206. case BABYLON.PhysicsJoint.DistanceJoint:
  84207. type = "jointDistance";
  84208. nativeJointData.max = jointData.maxDistance;
  84209. break;
  84210. case BABYLON.PhysicsJoint.PrismaticJoint:
  84211. type = "jointPrisme";
  84212. break;
  84213. case BABYLON.PhysicsJoint.SliderJoint:
  84214. type = "jointSlide";
  84215. break;
  84216. case BABYLON.PhysicsJoint.WheelJoint:
  84217. type = "jointWheel";
  84218. break;
  84219. case BABYLON.PhysicsJoint.HingeJoint:
  84220. default:
  84221. type = "jointHinge";
  84222. break;
  84223. }
  84224. nativeJointData.type = type;
  84225. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  84226. };
  84227. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  84228. //Bug in Oimo prevents us from disposing a joint in the playground
  84229. //joint.joint.physicsJoint.dispose();
  84230. //So we will bruteforce it!
  84231. try {
  84232. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  84233. }
  84234. catch (e) {
  84235. BABYLON.Tools.Warn(e);
  84236. }
  84237. };
  84238. OimoJSPlugin.prototype.isSupported = function () {
  84239. return this.BJSOIMO !== undefined;
  84240. };
  84241. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84242. if (!impostor.physicsBody.sleeping) {
  84243. //TODO check that
  84244. /*if (impostor.physicsBody.shapes.next) {
  84245. var parentShape = this._getLastShape(impostor.physicsBody);
  84246. impostor.object.position.copyFrom(parentShape.position);
  84247. console.log(parentShape.position);
  84248. } else {*/
  84249. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  84250. //}
  84251. if (impostor.object.rotationQuaternion) {
  84252. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  84253. }
  84254. }
  84255. };
  84256. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84257. var body = impostor.physicsBody;
  84258. body.position.copy(newPosition);
  84259. body.orientation.copy(newRotation);
  84260. body.syncShapes();
  84261. body.awake();
  84262. };
  84263. /*private _getLastShape(body: any): any {
  84264. var lastShape = body.shapes;
  84265. while (lastShape.next) {
  84266. lastShape = lastShape.next;
  84267. }
  84268. return lastShape;
  84269. }*/
  84270. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84271. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  84272. };
  84273. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84274. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  84275. };
  84276. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84277. var v = impostor.physicsBody.linearVelocity;
  84278. if (!v) {
  84279. return null;
  84280. }
  84281. return new BABYLON.Vector3(v.x, v.y, v.z);
  84282. };
  84283. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84284. var v = impostor.physicsBody.angularVelocity;
  84285. if (!v) {
  84286. return null;
  84287. }
  84288. return new BABYLON.Vector3(v.x, v.y, v.z);
  84289. };
  84290. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84291. var staticBody = mass === 0;
  84292. //this will actually set the body's density and not its mass.
  84293. //But this is how oimo treats the mass variable.
  84294. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  84295. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  84296. };
  84297. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  84298. return impostor.physicsBody.shapes.density;
  84299. };
  84300. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  84301. return impostor.physicsBody.shapes.friction;
  84302. };
  84303. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84304. impostor.physicsBody.shapes.friction = friction;
  84305. };
  84306. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84307. return impostor.physicsBody.shapes.restitution;
  84308. };
  84309. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84310. impostor.physicsBody.shapes.restitution = restitution;
  84311. };
  84312. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  84313. impostor.physicsBody.sleep();
  84314. };
  84315. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  84316. impostor.physicsBody.awake();
  84317. };
  84318. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84319. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  84320. if (minDistance !== void 0) {
  84321. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  84322. }
  84323. };
  84324. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84325. //TODO separate rotational and transational motors.
  84326. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84327. if (motor) {
  84328. motor.setMotor(speed, maxForce);
  84329. }
  84330. };
  84331. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  84332. //TODO separate rotational and transational motors.
  84333. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84334. if (motor) {
  84335. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  84336. }
  84337. };
  84338. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84339. var body = impostor.physicsBody;
  84340. mesh.position.x = body.position.x;
  84341. mesh.position.y = body.position.y;
  84342. mesh.position.z = body.position.z;
  84343. if (mesh.rotationQuaternion) {
  84344. mesh.rotationQuaternion.x = body.orientation.x;
  84345. mesh.rotationQuaternion.y = body.orientation.y;
  84346. mesh.rotationQuaternion.z = body.orientation.z;
  84347. mesh.rotationQuaternion.w = body.orientation.s;
  84348. }
  84349. };
  84350. OimoJSPlugin.prototype.getRadius = function (impostor) {
  84351. return impostor.physicsBody.shapes.radius;
  84352. };
  84353. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84354. var shape = impostor.physicsBody.shapes;
  84355. result.x = shape.halfWidth * 2;
  84356. result.y = shape.halfHeight * 2;
  84357. result.z = shape.halfDepth * 2;
  84358. };
  84359. OimoJSPlugin.prototype.dispose = function () {
  84360. this.world.clear();
  84361. };
  84362. return OimoJSPlugin;
  84363. }());
  84364. BABYLON.OimoJSPlugin = OimoJSPlugin;
  84365. })(BABYLON || (BABYLON = {}));
  84366. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  84367. var BABYLON;
  84368. (function (BABYLON) {
  84369. /*
  84370. * Based on jsTGALoader - Javascript loader for TGA file
  84371. * By Vincent Thibault
  84372. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  84373. */
  84374. var TGATools = /** @class */ (function () {
  84375. function TGATools() {
  84376. }
  84377. TGATools.GetTGAHeader = function (data) {
  84378. var offset = 0;
  84379. var header = {
  84380. id_length: data[offset++],
  84381. colormap_type: data[offset++],
  84382. image_type: data[offset++],
  84383. colormap_index: data[offset++] | data[offset++] << 8,
  84384. colormap_length: data[offset++] | data[offset++] << 8,
  84385. colormap_size: data[offset++],
  84386. origin: [
  84387. data[offset++] | data[offset++] << 8,
  84388. data[offset++] | data[offset++] << 8
  84389. ],
  84390. width: data[offset++] | data[offset++] << 8,
  84391. height: data[offset++] | data[offset++] << 8,
  84392. pixel_size: data[offset++],
  84393. flags: data[offset++]
  84394. };
  84395. return header;
  84396. };
  84397. TGATools.UploadContent = function (gl, data) {
  84398. // Not enough data to contain header ?
  84399. if (data.length < 19) {
  84400. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  84401. return;
  84402. }
  84403. // Read Header
  84404. var offset = 18;
  84405. var header = TGATools.GetTGAHeader(data);
  84406. // Assume it's a valid Targa file.
  84407. if (header.id_length + offset > data.length) {
  84408. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  84409. return;
  84410. }
  84411. // Skip not needed data
  84412. offset += header.id_length;
  84413. var use_rle = false;
  84414. var use_pal = false;
  84415. var use_grey = false;
  84416. // Get some informations.
  84417. switch (header.image_type) {
  84418. case TGATools._TYPE_RLE_INDEXED:
  84419. use_rle = true;
  84420. case TGATools._TYPE_INDEXED:
  84421. use_pal = true;
  84422. break;
  84423. case TGATools._TYPE_RLE_RGB:
  84424. use_rle = true;
  84425. case TGATools._TYPE_RGB:
  84426. // use_rgb = true;
  84427. break;
  84428. case TGATools._TYPE_RLE_GREY:
  84429. use_rle = true;
  84430. case TGATools._TYPE_GREY:
  84431. use_grey = true;
  84432. break;
  84433. }
  84434. var pixel_data;
  84435. // var numAlphaBits = header.flags & 0xf;
  84436. var pixel_size = header.pixel_size >> 3;
  84437. var pixel_total = header.width * header.height * pixel_size;
  84438. // Read palettes
  84439. var palettes;
  84440. if (use_pal) {
  84441. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  84442. }
  84443. // Read LRE
  84444. if (use_rle) {
  84445. pixel_data = new Uint8Array(pixel_total);
  84446. var c, count, i;
  84447. var localOffset = 0;
  84448. var pixels = new Uint8Array(pixel_size);
  84449. while (offset < pixel_total && localOffset < pixel_total) {
  84450. c = data[offset++];
  84451. count = (c & 0x7f) + 1;
  84452. // RLE pixels
  84453. if (c & 0x80) {
  84454. // Bind pixel tmp array
  84455. for (i = 0; i < pixel_size; ++i) {
  84456. pixels[i] = data[offset++];
  84457. }
  84458. // Copy pixel array
  84459. for (i = 0; i < count; ++i) {
  84460. pixel_data.set(pixels, localOffset + i * pixel_size);
  84461. }
  84462. localOffset += pixel_size * count;
  84463. }
  84464. // Raw pixels
  84465. else {
  84466. count *= pixel_size;
  84467. for (i = 0; i < count; ++i) {
  84468. pixel_data[localOffset + i] = data[offset++];
  84469. }
  84470. localOffset += count;
  84471. }
  84472. }
  84473. }
  84474. // RAW Pixels
  84475. else {
  84476. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  84477. }
  84478. // Load to texture
  84479. var x_start, y_start, x_step, y_step, y_end, x_end;
  84480. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  84481. default:
  84482. case TGATools._ORIGIN_UL:
  84483. x_start = 0;
  84484. x_step = 1;
  84485. x_end = header.width;
  84486. y_start = 0;
  84487. y_step = 1;
  84488. y_end = header.height;
  84489. break;
  84490. case TGATools._ORIGIN_BL:
  84491. x_start = 0;
  84492. x_step = 1;
  84493. x_end = header.width;
  84494. y_start = header.height - 1;
  84495. y_step = -1;
  84496. y_end = -1;
  84497. break;
  84498. case TGATools._ORIGIN_UR:
  84499. x_start = header.width - 1;
  84500. x_step = -1;
  84501. x_end = -1;
  84502. y_start = 0;
  84503. y_step = 1;
  84504. y_end = header.height;
  84505. break;
  84506. case TGATools._ORIGIN_BR:
  84507. x_start = header.width - 1;
  84508. x_step = -1;
  84509. x_end = -1;
  84510. y_start = header.height - 1;
  84511. y_step = -1;
  84512. y_end = -1;
  84513. break;
  84514. }
  84515. // Load the specify method
  84516. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84517. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84518. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84519. };
  84520. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84521. var image = pixel_data, colormap = palettes;
  84522. var width = header.width, height = header.height;
  84523. var color, i = 0, x, y;
  84524. var imageData = new Uint8Array(width * height * 4);
  84525. for (y = y_start; y !== y_end; y += y_step) {
  84526. for (x = x_start; x !== x_end; x += x_step, i++) {
  84527. color = image[i];
  84528. imageData[(x + width * y) * 4 + 3] = 255;
  84529. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84530. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84531. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84532. }
  84533. }
  84534. return imageData;
  84535. };
  84536. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84537. var image = pixel_data;
  84538. var width = header.width, height = header.height;
  84539. var color, i = 0, x, y;
  84540. var imageData = new Uint8Array(width * height * 4);
  84541. for (y = y_start; y !== y_end; y += y_step) {
  84542. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84543. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84544. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84545. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84546. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84547. imageData[(x + width * y) * 4 + 0] = r;
  84548. imageData[(x + width * y) * 4 + 1] = g;
  84549. imageData[(x + width * y) * 4 + 2] = b;
  84550. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84551. }
  84552. }
  84553. return imageData;
  84554. };
  84555. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84556. var image = pixel_data;
  84557. var width = header.width, height = header.height;
  84558. var i = 0, x, y;
  84559. var imageData = new Uint8Array(width * height * 4);
  84560. for (y = y_start; y !== y_end; y += y_step) {
  84561. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84562. imageData[(x + width * y) * 4 + 3] = 255;
  84563. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84564. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84565. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84566. }
  84567. }
  84568. return imageData;
  84569. };
  84570. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84571. var image = pixel_data;
  84572. var width = header.width, height = header.height;
  84573. var i = 0, x, y;
  84574. var imageData = new Uint8Array(width * height * 4);
  84575. for (y = y_start; y !== y_end; y += y_step) {
  84576. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84577. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84578. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84579. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84580. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84581. }
  84582. }
  84583. return imageData;
  84584. };
  84585. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84586. var image = pixel_data;
  84587. var width = header.width, height = header.height;
  84588. var color, i = 0, x, y;
  84589. var imageData = new Uint8Array(width * height * 4);
  84590. for (y = y_start; y !== y_end; y += y_step) {
  84591. for (x = x_start; x !== x_end; x += x_step, i++) {
  84592. color = image[i];
  84593. imageData[(x + width * y) * 4 + 0] = color;
  84594. imageData[(x + width * y) * 4 + 1] = color;
  84595. imageData[(x + width * y) * 4 + 2] = color;
  84596. imageData[(x + width * y) * 4 + 3] = 255;
  84597. }
  84598. }
  84599. return imageData;
  84600. };
  84601. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84602. var image = pixel_data;
  84603. var width = header.width, height = header.height;
  84604. var i = 0, x, y;
  84605. var imageData = new Uint8Array(width * height * 4);
  84606. for (y = y_start; y !== y_end; y += y_step) {
  84607. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84608. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84609. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84610. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84611. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84612. }
  84613. }
  84614. return imageData;
  84615. };
  84616. //private static _TYPE_NO_DATA = 0;
  84617. TGATools._TYPE_INDEXED = 1;
  84618. TGATools._TYPE_RGB = 2;
  84619. TGATools._TYPE_GREY = 3;
  84620. TGATools._TYPE_RLE_INDEXED = 9;
  84621. TGATools._TYPE_RLE_RGB = 10;
  84622. TGATools._TYPE_RLE_GREY = 11;
  84623. TGATools._ORIGIN_MASK = 0x30;
  84624. TGATools._ORIGIN_SHIFT = 0x04;
  84625. TGATools._ORIGIN_BL = 0x00;
  84626. TGATools._ORIGIN_BR = 0x01;
  84627. TGATools._ORIGIN_UL = 0x02;
  84628. TGATools._ORIGIN_UR = 0x03;
  84629. return TGATools;
  84630. }());
  84631. BABYLON.TGATools = TGATools;
  84632. })(BABYLON || (BABYLON = {}));
  84633. //# sourceMappingURL=babylon.tga.js.map
  84634. var BABYLON;
  84635. (function (BABYLON) {
  84636. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84637. // All values and structures referenced from:
  84638. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84639. var DDS_MAGIC = 0x20534444;
  84640. var
  84641. //DDSD_CAPS = 0x1,
  84642. //DDSD_HEIGHT = 0x2,
  84643. //DDSD_WIDTH = 0x4,
  84644. //DDSD_PITCH = 0x8,
  84645. //DDSD_PIXELFORMAT = 0x1000,
  84646. DDSD_MIPMAPCOUNT = 0x20000;
  84647. //DDSD_LINEARSIZE = 0x80000,
  84648. //DDSD_DEPTH = 0x800000;
  84649. // var DDSCAPS_COMPLEX = 0x8,
  84650. // DDSCAPS_MIPMAP = 0x400000,
  84651. // DDSCAPS_TEXTURE = 0x1000;
  84652. var DDSCAPS2_CUBEMAP = 0x200;
  84653. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84654. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84655. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84656. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84657. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84658. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84659. // DDSCAPS2_VOLUME = 0x200000;
  84660. var
  84661. //DDPF_ALPHAPIXELS = 0x1,
  84662. //DDPF_ALPHA = 0x2,
  84663. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84664. //DDPF_YUV = 0x200,
  84665. DDPF_LUMINANCE = 0x20000;
  84666. function FourCCToInt32(value) {
  84667. return value.charCodeAt(0) +
  84668. (value.charCodeAt(1) << 8) +
  84669. (value.charCodeAt(2) << 16) +
  84670. (value.charCodeAt(3) << 24);
  84671. }
  84672. function Int32ToFourCC(value) {
  84673. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84674. }
  84675. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84676. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84677. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84678. var FOURCC_DX10 = FourCCToInt32("DX10");
  84679. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84680. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84681. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84682. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84683. var headerLengthInt = 31; // The header length in 32 bit ints
  84684. // Offsets into the header array
  84685. var off_magic = 0;
  84686. var off_size = 1;
  84687. var off_flags = 2;
  84688. var off_height = 3;
  84689. var off_width = 4;
  84690. var off_mipmapCount = 7;
  84691. var off_pfFlags = 20;
  84692. var off_pfFourCC = 21;
  84693. var off_RGBbpp = 22;
  84694. var off_RMask = 23;
  84695. var off_GMask = 24;
  84696. var off_BMask = 25;
  84697. var off_AMask = 26;
  84698. // var off_caps1 = 27;
  84699. var off_caps2 = 28;
  84700. // var off_caps3 = 29;
  84701. // var off_caps4 = 30;
  84702. var off_dxgiFormat = 32;
  84703. ;
  84704. var DDSTools = /** @class */ (function () {
  84705. function DDSTools() {
  84706. }
  84707. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84708. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84709. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84710. var mipmapCount = 1;
  84711. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84712. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84713. }
  84714. var fourCC = header[off_pfFourCC];
  84715. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84716. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84717. switch (fourCC) {
  84718. case FOURCC_D3DFMT_R16G16B16A16F:
  84719. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84720. break;
  84721. case FOURCC_D3DFMT_R32G32B32A32F:
  84722. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84723. break;
  84724. case FOURCC_DX10:
  84725. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84726. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84727. break;
  84728. }
  84729. }
  84730. return {
  84731. width: header[off_width],
  84732. height: header[off_height],
  84733. mipmapCount: mipmapCount,
  84734. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84735. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84736. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84737. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84738. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84739. dxgiFormat: dxgiFormat,
  84740. textureType: textureType
  84741. };
  84742. };
  84743. DDSTools._ToHalfFloat = function (value) {
  84744. if (!DDSTools._FloatView) {
  84745. DDSTools._FloatView = new Float32Array(1);
  84746. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84747. }
  84748. DDSTools._FloatView[0] = value;
  84749. var x = DDSTools._Int32View[0];
  84750. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84751. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84752. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84753. /* If zero, or denormal, or exponent underflows too much for a denormal
  84754. * half, return signed zero. */
  84755. if (e < 103) {
  84756. return bits;
  84757. }
  84758. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84759. if (e > 142) {
  84760. bits |= 0x7c00;
  84761. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84762. * not Inf, so make sure we set one mantissa bit too. */
  84763. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84764. return bits;
  84765. }
  84766. /* If exponent underflows but not too much, return a denormal */
  84767. if (e < 113) {
  84768. m |= 0x0800;
  84769. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84770. * to 1, which is OK. */
  84771. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84772. return bits;
  84773. }
  84774. bits |= ((e - 112) << 10) | (m >> 1);
  84775. bits += m & 1;
  84776. return bits;
  84777. };
  84778. DDSTools._FromHalfFloat = function (value) {
  84779. var s = (value & 0x8000) >> 15;
  84780. var e = (value & 0x7C00) >> 10;
  84781. var f = value & 0x03FF;
  84782. if (e === 0) {
  84783. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84784. }
  84785. else if (e == 0x1F) {
  84786. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84787. }
  84788. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84789. };
  84790. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84791. var destArray = new Float32Array(dataLength);
  84792. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84793. var index = 0;
  84794. for (var y = 0; y < height; y++) {
  84795. for (var x = 0; x < width; x++) {
  84796. var srcPos = (x + y * width) * 4;
  84797. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84798. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84799. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84800. if (DDSTools.StoreLODInAlphaChannel) {
  84801. destArray[index + 3] = lod;
  84802. }
  84803. else {
  84804. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84805. }
  84806. index += 4;
  84807. }
  84808. }
  84809. return destArray;
  84810. };
  84811. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84812. if (DDSTools.StoreLODInAlphaChannel) {
  84813. var destArray = new Uint16Array(dataLength);
  84814. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84815. var index = 0;
  84816. for (var y = 0; y < height; y++) {
  84817. for (var x = 0; x < width; x++) {
  84818. var srcPos = (x + y * width) * 4;
  84819. destArray[index] = srcData[srcPos];
  84820. destArray[index + 1] = srcData[srcPos + 1];
  84821. destArray[index + 2] = srcData[srcPos + 2];
  84822. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84823. index += 4;
  84824. }
  84825. }
  84826. return destArray;
  84827. }
  84828. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84829. };
  84830. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84831. if (DDSTools.StoreLODInAlphaChannel) {
  84832. var destArray = new Float32Array(dataLength);
  84833. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84834. var index = 0;
  84835. for (var y = 0; y < height; y++) {
  84836. for (var x = 0; x < width; x++) {
  84837. var srcPos = (x + y * width) * 4;
  84838. destArray[index] = srcData[srcPos];
  84839. destArray[index + 1] = srcData[srcPos + 1];
  84840. destArray[index + 2] = srcData[srcPos + 2];
  84841. destArray[index + 3] = lod;
  84842. index += 4;
  84843. }
  84844. }
  84845. return destArray;
  84846. }
  84847. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  84848. };
  84849. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84850. var destArray = new Uint8Array(dataLength);
  84851. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84852. var index = 0;
  84853. for (var y = 0; y < height; y++) {
  84854. for (var x = 0; x < width; x++) {
  84855. var srcPos = (x + y * width) * 4;
  84856. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  84857. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  84858. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  84859. if (DDSTools.StoreLODInAlphaChannel) {
  84860. destArray[index + 3] = lod;
  84861. }
  84862. else {
  84863. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  84864. }
  84865. index += 4;
  84866. }
  84867. }
  84868. return destArray;
  84869. };
  84870. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84871. var destArray = new Uint8Array(dataLength);
  84872. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84873. var index = 0;
  84874. for (var y = 0; y < height; y++) {
  84875. for (var x = 0; x < width; x++) {
  84876. var srcPos = (x + y * width) * 4;
  84877. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  84878. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  84879. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  84880. if (DDSTools.StoreLODInAlphaChannel) {
  84881. destArray[index + 3] = lod;
  84882. }
  84883. else {
  84884. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  84885. }
  84886. index += 4;
  84887. }
  84888. }
  84889. return destArray;
  84890. };
  84891. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  84892. var byteArray = new Uint8Array(dataLength);
  84893. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84894. var index = 0;
  84895. for (var y = 0; y < height; y++) {
  84896. for (var x = 0; x < width; x++) {
  84897. var srcPos = (x + y * width) * 4;
  84898. byteArray[index] = srcData[srcPos + rOffset];
  84899. byteArray[index + 1] = srcData[srcPos + gOffset];
  84900. byteArray[index + 2] = srcData[srcPos + bOffset];
  84901. byteArray[index + 3] = srcData[srcPos + aOffset];
  84902. index += 4;
  84903. }
  84904. }
  84905. return byteArray;
  84906. };
  84907. DDSTools._ExtractLongWordOrder = function (value) {
  84908. if (value === 0 || value === 255 || value === -16777216) {
  84909. return 0;
  84910. }
  84911. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  84912. };
  84913. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  84914. var byteArray = new Uint8Array(dataLength);
  84915. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84916. var index = 0;
  84917. for (var y = 0; y < height; y++) {
  84918. for (var x = 0; x < width; x++) {
  84919. var srcPos = (x + y * width) * 3;
  84920. byteArray[index] = srcData[srcPos + rOffset];
  84921. byteArray[index + 1] = srcData[srcPos + gOffset];
  84922. byteArray[index + 2] = srcData[srcPos + bOffset];
  84923. index += 3;
  84924. }
  84925. }
  84926. return byteArray;
  84927. };
  84928. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  84929. var byteArray = new Uint8Array(dataLength);
  84930. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84931. var index = 0;
  84932. for (var y = 0; y < height; y++) {
  84933. for (var x = 0; x < width; x++) {
  84934. var srcPos = (x + y * width);
  84935. byteArray[index] = srcData[srcPos];
  84936. index++;
  84937. }
  84938. }
  84939. return byteArray;
  84940. };
  84941. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84942. if (lodIndex === void 0) { lodIndex = -1; }
  84943. var sphericalPolynomialFaces = null;
  84944. if (info.sphericalPolynomial) {
  84945. sphericalPolynomialFaces = new Array();
  84946. }
  84947. var ext = engine.getCaps().s3tc;
  84948. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84949. var fourCC, width, height, dataLength = 0, dataOffset;
  84950. var byteArray, mipmapCount, mip;
  84951. var internalFormat = 0;
  84952. var format = 0;
  84953. var blockBytes = 1;
  84954. if (header[off_magic] !== DDS_MAGIC) {
  84955. BABYLON.Tools.Error("Invalid magic number in DDS header");
  84956. return;
  84957. }
  84958. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  84959. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  84960. return;
  84961. }
  84962. if (info.isCompressed && !ext) {
  84963. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  84964. return;
  84965. }
  84966. var bpp = header[off_RGBbpp];
  84967. dataOffset = header[off_size] + 4;
  84968. var computeFormats = false;
  84969. if (info.isFourCC) {
  84970. fourCC = header[off_pfFourCC];
  84971. switch (fourCC) {
  84972. case FOURCC_DXT1:
  84973. blockBytes = 8;
  84974. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  84975. break;
  84976. case FOURCC_DXT3:
  84977. blockBytes = 16;
  84978. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  84979. break;
  84980. case FOURCC_DXT5:
  84981. blockBytes = 16;
  84982. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  84983. break;
  84984. case FOURCC_D3DFMT_R16G16B16A16F:
  84985. computeFormats = true;
  84986. break;
  84987. case FOURCC_D3DFMT_R32G32B32A32F:
  84988. computeFormats = true;
  84989. break;
  84990. case FOURCC_DX10:
  84991. // There is an additionnal header so dataOffset need to be changed
  84992. dataOffset += 5 * 4; // 5 uints
  84993. var supported = false;
  84994. switch (info.dxgiFormat) {
  84995. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  84996. computeFormats = true;
  84997. supported = true;
  84998. break;
  84999. case DXGI_FORMAT_B8G8R8X8_UNORM:
  85000. info.isRGB = true;
  85001. info.isFourCC = false;
  85002. bpp = 32;
  85003. supported = true;
  85004. break;
  85005. }
  85006. if (supported) {
  85007. break;
  85008. }
  85009. default:
  85010. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  85011. return;
  85012. }
  85013. }
  85014. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  85015. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  85016. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  85017. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  85018. if (computeFormats) {
  85019. format = engine._getWebGLTextureType(info.textureType);
  85020. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85021. }
  85022. mipmapCount = 1;
  85023. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  85024. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85025. }
  85026. for (var face = 0; face < faces; face++) {
  85027. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  85028. width = header[off_width];
  85029. height = header[off_height];
  85030. for (mip = 0; mip < mipmapCount; ++mip) {
  85031. if (lodIndex === -1 || lodIndex === mip) {
  85032. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  85033. var i = (lodIndex === -1) ? mip : 0;
  85034. if (!info.isCompressed && info.isFourCC) {
  85035. dataLength = width * height * 4;
  85036. var floatArray = null;
  85037. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  85038. if (bpp === 128) {
  85039. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85040. if (sphericalPolynomialFaces && i == 0) {
  85041. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85042. }
  85043. }
  85044. else if (bpp === 64) {
  85045. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85046. if (sphericalPolynomialFaces && i == 0) {
  85047. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85048. }
  85049. }
  85050. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85051. format = engine._getWebGLTextureType(info.textureType);
  85052. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85053. }
  85054. else {
  85055. if (bpp === 128) {
  85056. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85057. if (sphericalPolynomialFaces && i == 0) {
  85058. sphericalPolynomialFaces.push(floatArray);
  85059. }
  85060. }
  85061. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  85062. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85063. if (sphericalPolynomialFaces && i == 0) {
  85064. sphericalPolynomialFaces.push(floatArray);
  85065. }
  85066. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85067. format = engine._getWebGLTextureType(info.textureType);
  85068. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85069. }
  85070. else { // 64
  85071. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85072. if (sphericalPolynomialFaces && i == 0) {
  85073. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85074. }
  85075. }
  85076. }
  85077. if (floatArray) {
  85078. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  85079. }
  85080. }
  85081. else if (info.isRGB) {
  85082. if (bpp === 24) {
  85083. dataLength = width * height * 3;
  85084. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  85085. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  85086. }
  85087. else { // 32
  85088. dataLength = width * height * 4;
  85089. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  85090. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  85091. }
  85092. }
  85093. else if (info.isLuminance) {
  85094. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  85095. var unpaddedRowSize = width;
  85096. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  85097. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  85098. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  85099. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  85100. }
  85101. else {
  85102. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  85103. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  85104. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  85105. }
  85106. }
  85107. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  85108. width *= 0.5;
  85109. height *= 0.5;
  85110. width = Math.max(1.0, width);
  85111. height = Math.max(1.0, height);
  85112. }
  85113. if (currentFace !== undefined) {
  85114. // Loading a single face
  85115. break;
  85116. }
  85117. }
  85118. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  85119. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  85120. size: header[off_width],
  85121. right: sphericalPolynomialFaces[0],
  85122. left: sphericalPolynomialFaces[1],
  85123. up: sphericalPolynomialFaces[2],
  85124. down: sphericalPolynomialFaces[3],
  85125. front: sphericalPolynomialFaces[4],
  85126. back: sphericalPolynomialFaces[5],
  85127. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  85128. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  85129. gammaSpace: false,
  85130. });
  85131. }
  85132. else {
  85133. info.sphericalPolynomial = undefined;
  85134. }
  85135. };
  85136. DDSTools.StoreLODInAlphaChannel = false;
  85137. return DDSTools;
  85138. }());
  85139. BABYLON.DDSTools = DDSTools;
  85140. })(BABYLON || (BABYLON = {}));
  85141. //# sourceMappingURL=babylon.dds.js.map
  85142. var BABYLON;
  85143. (function (BABYLON) {
  85144. /**
  85145. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  85146. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  85147. */
  85148. var KhronosTextureContainer = /** @class */ (function () {
  85149. /**
  85150. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  85151. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  85152. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  85153. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  85154. */
  85155. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  85156. this.arrayBuffer = arrayBuffer;
  85157. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  85158. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  85159. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  85160. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  85161. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  85162. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  85163. BABYLON.Tools.Error("texture missing KTX identifier");
  85164. return;
  85165. }
  85166. // load the reset of the header in native 32 bit int
  85167. var header = new Int32Array(this.arrayBuffer, 12, 13);
  85168. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  85169. var oppositeEndianess = header[0] === 0x01020304;
  85170. // read all the header elements in order they exist in the file, without modification (sans endainness)
  85171. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  85172. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  85173. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  85174. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  85175. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  85176. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  85177. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  85178. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  85179. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  85180. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  85181. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  85182. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  85183. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  85184. if (this.glType !== 0) {
  85185. BABYLON.Tools.Error("only compressed formats currently supported");
  85186. return;
  85187. }
  85188. else {
  85189. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  85190. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  85191. }
  85192. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  85193. BABYLON.Tools.Error("only 2D textures currently supported");
  85194. return;
  85195. }
  85196. if (this.numberOfArrayElements !== 0) {
  85197. BABYLON.Tools.Error("texture arrays not currently supported");
  85198. return;
  85199. }
  85200. if (this.numberOfFaces !== facesExpected) {
  85201. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  85202. return;
  85203. }
  85204. // we now have a completely validated file, so could use existence of loadType as success
  85205. // would need to make this more elaborate & adjust checks above to support more than one load type
  85206. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  85207. }
  85208. // not as fast hardware based, but will probably never need to use
  85209. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  85210. return ((val & 0xFF) << 24)
  85211. | ((val & 0xFF00) << 8)
  85212. | ((val >> 8) & 0xFF00)
  85213. | ((val >> 24) & 0xFF);
  85214. };
  85215. /**
  85216. * It is assumed that the texture has already been created & is currently bound
  85217. */
  85218. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  85219. switch (this.loadType) {
  85220. case KhronosTextureContainer.COMPRESSED_2D:
  85221. this._upload2DCompressedLevels(gl, loadMipmaps);
  85222. break;
  85223. case KhronosTextureContainer.TEX_2D:
  85224. case KhronosTextureContainer.COMPRESSED_3D:
  85225. case KhronosTextureContainer.TEX_3D:
  85226. }
  85227. };
  85228. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  85229. // initialize width & height for level 1
  85230. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  85231. var width = this.pixelWidth;
  85232. var height = this.pixelHeight;
  85233. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  85234. for (var level = 0; level < mipmapCount; level++) {
  85235. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  85236. for (var face = 0; face < this.numberOfFaces; face++) {
  85237. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  85238. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  85239. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  85240. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  85241. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  85242. }
  85243. width = Math.max(1.0, width * 0.5);
  85244. height = Math.max(1.0, height * 0.5);
  85245. }
  85246. };
  85247. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  85248. // load types
  85249. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  85250. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  85251. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  85252. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  85253. return KhronosTextureContainer;
  85254. }());
  85255. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  85256. })(BABYLON || (BABYLON = {}));
  85257. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  85258. var BABYLON;
  85259. (function (BABYLON) {
  85260. var Debug;
  85261. (function (Debug) {
  85262. /**
  85263. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  85264. */
  85265. var SkeletonViewer = /** @class */ (function () {
  85266. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  85267. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  85268. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  85269. this.skeleton = skeleton;
  85270. this.mesh = mesh;
  85271. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  85272. this.renderingGroupId = renderingGroupId;
  85273. this.color = BABYLON.Color3.White();
  85274. this._debugLines = new Array();
  85275. this._isEnabled = false;
  85276. this._scene = scene;
  85277. this.update();
  85278. this._renderFunction = this.update.bind(this);
  85279. }
  85280. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  85281. get: function () {
  85282. return this._isEnabled;
  85283. },
  85284. set: function (value) {
  85285. if (this._isEnabled === value) {
  85286. return;
  85287. }
  85288. this._isEnabled = value;
  85289. if (value) {
  85290. this._scene.registerBeforeRender(this._renderFunction);
  85291. }
  85292. else {
  85293. this._scene.unregisterBeforeRender(this._renderFunction);
  85294. }
  85295. },
  85296. enumerable: true,
  85297. configurable: true
  85298. });
  85299. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  85300. if (x === void 0) { x = 0; }
  85301. if (y === void 0) { y = 0; }
  85302. if (z === void 0) { z = 0; }
  85303. var tmat = BABYLON.Tmp.Matrix[0];
  85304. var parentBone = bone.getParent();
  85305. tmat.copyFrom(bone.getLocalMatrix());
  85306. if (x !== 0 || y !== 0 || z !== 0) {
  85307. var tmat2 = BABYLON.Tmp.Matrix[1];
  85308. BABYLON.Matrix.IdentityToRef(tmat2);
  85309. tmat2.m[12] = x;
  85310. tmat2.m[13] = y;
  85311. tmat2.m[14] = z;
  85312. tmat2.multiplyToRef(tmat, tmat);
  85313. }
  85314. if (parentBone) {
  85315. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  85316. }
  85317. tmat.multiplyToRef(meshMat, tmat);
  85318. position.x = tmat.m[12];
  85319. position.y = tmat.m[13];
  85320. position.z = tmat.m[14];
  85321. };
  85322. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  85323. var len = bones.length;
  85324. var meshPos = this.mesh.position;
  85325. for (var i = 0; i < len; i++) {
  85326. var bone = bones[i];
  85327. var points = this._debugLines[i];
  85328. if (!points) {
  85329. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85330. this._debugLines[i] = points;
  85331. }
  85332. this._getBonePosition(points[0], bone, meshMat);
  85333. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  85334. points[0].subtractInPlace(meshPos);
  85335. points[1].subtractInPlace(meshPos);
  85336. }
  85337. };
  85338. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  85339. var len = bones.length;
  85340. var boneNum = 0;
  85341. var meshPos = this.mesh.position;
  85342. for (var i = len - 1; i >= 0; i--) {
  85343. var childBone = bones[i];
  85344. var parentBone = childBone.getParent();
  85345. if (!parentBone) {
  85346. continue;
  85347. }
  85348. var points = this._debugLines[boneNum];
  85349. if (!points) {
  85350. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85351. this._debugLines[boneNum] = points;
  85352. }
  85353. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  85354. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  85355. points[0].subtractInPlace(meshPos);
  85356. points[1].subtractInPlace(meshPos);
  85357. boneNum++;
  85358. }
  85359. };
  85360. SkeletonViewer.prototype.update = function () {
  85361. if (this.autoUpdateBonesMatrices) {
  85362. this.skeleton.computeAbsoluteTransforms();
  85363. }
  85364. if (this.skeleton.bones[0].length === undefined) {
  85365. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85366. }
  85367. else {
  85368. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85369. }
  85370. if (!this._debugMesh) {
  85371. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  85372. this._debugMesh.renderingGroupId = this.renderingGroupId;
  85373. }
  85374. else {
  85375. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  85376. }
  85377. this._debugMesh.position.copyFrom(this.mesh.position);
  85378. this._debugMesh.color = this.color;
  85379. };
  85380. SkeletonViewer.prototype.dispose = function () {
  85381. if (this._debugMesh) {
  85382. this.isEnabled = false;
  85383. this._debugMesh.dispose();
  85384. this._debugMesh = null;
  85385. }
  85386. };
  85387. return SkeletonViewer;
  85388. }());
  85389. Debug.SkeletonViewer = SkeletonViewer;
  85390. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85391. })(BABYLON || (BABYLON = {}));
  85392. //# sourceMappingURL=babylon.skeletonViewer.js.map
  85393. /**
  85394. * Module Debug contains the (visual) components to debug a scene correctly
  85395. */
  85396. var BABYLON;
  85397. (function (BABYLON) {
  85398. var Debug;
  85399. (function (Debug) {
  85400. /**
  85401. * The Axes viewer will show 3 axes in a specific point in space
  85402. */
  85403. var AxesViewer = /** @class */ (function () {
  85404. function AxesViewer(scene, scaleLines) {
  85405. if (scaleLines === void 0) { scaleLines = 1; }
  85406. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85407. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85408. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85409. this.scaleLines = 1;
  85410. this.scaleLines = scaleLines;
  85411. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  85412. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  85413. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  85414. this._xmesh.renderingGroupId = 2;
  85415. this._ymesh.renderingGroupId = 2;
  85416. this._zmesh.renderingGroupId = 2;
  85417. this._xmesh.material.checkReadyOnlyOnce = true;
  85418. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  85419. this._ymesh.material.checkReadyOnlyOnce = true;
  85420. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  85421. this._zmesh.material.checkReadyOnlyOnce = true;
  85422. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  85423. this.scene = scene;
  85424. }
  85425. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  85426. var scaleLines = this.scaleLines;
  85427. if (this._xmesh) {
  85428. this._xmesh.position.copyFrom(position);
  85429. }
  85430. if (this._ymesh) {
  85431. this._ymesh.position.copyFrom(position);
  85432. }
  85433. if (this._zmesh) {
  85434. this._zmesh.position.copyFrom(position);
  85435. }
  85436. var point2 = this._xline[1];
  85437. point2.x = xaxis.x * scaleLines;
  85438. point2.y = xaxis.y * scaleLines;
  85439. point2.z = xaxis.z * scaleLines;
  85440. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  85441. point2 = this._yline[1];
  85442. point2.x = yaxis.x * scaleLines;
  85443. point2.y = yaxis.y * scaleLines;
  85444. point2.z = yaxis.z * scaleLines;
  85445. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  85446. point2 = this._zline[1];
  85447. point2.x = zaxis.x * scaleLines;
  85448. point2.y = zaxis.y * scaleLines;
  85449. point2.z = zaxis.z * scaleLines;
  85450. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  85451. };
  85452. AxesViewer.prototype.dispose = function () {
  85453. if (this._xmesh) {
  85454. this._xmesh.dispose();
  85455. }
  85456. if (this._ymesh) {
  85457. this._ymesh.dispose();
  85458. }
  85459. if (this._zmesh) {
  85460. this._zmesh.dispose();
  85461. }
  85462. this._xmesh = null;
  85463. this._ymesh = null;
  85464. this._zmesh = null;
  85465. this.scene = null;
  85466. };
  85467. return AxesViewer;
  85468. }());
  85469. Debug.AxesViewer = AxesViewer;
  85470. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85471. })(BABYLON || (BABYLON = {}));
  85472. //# sourceMappingURL=babylon.axesViewer.js.map
  85473. var BABYLON;
  85474. (function (BABYLON) {
  85475. var Debug;
  85476. (function (Debug) {
  85477. /**
  85478. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  85479. */
  85480. var BoneAxesViewer = /** @class */ (function (_super) {
  85481. __extends(BoneAxesViewer, _super);
  85482. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  85483. if (scaleLines === void 0) { scaleLines = 1; }
  85484. var _this = _super.call(this, scene, scaleLines) || this;
  85485. _this.pos = BABYLON.Vector3.Zero();
  85486. _this.xaxis = BABYLON.Vector3.Zero();
  85487. _this.yaxis = BABYLON.Vector3.Zero();
  85488. _this.zaxis = BABYLON.Vector3.Zero();
  85489. _this.mesh = mesh;
  85490. _this.bone = bone;
  85491. return _this;
  85492. }
  85493. BoneAxesViewer.prototype.update = function () {
  85494. if (!this.mesh || !this.bone) {
  85495. return;
  85496. }
  85497. var bone = this.bone;
  85498. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85499. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85500. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85501. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85502. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85503. };
  85504. BoneAxesViewer.prototype.dispose = function () {
  85505. if (this.mesh) {
  85506. this.mesh = null;
  85507. this.bone = null;
  85508. _super.prototype.dispose.call(this);
  85509. }
  85510. };
  85511. return BoneAxesViewer;
  85512. }(Debug.AxesViewer));
  85513. Debug.BoneAxesViewer = BoneAxesViewer;
  85514. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85515. })(BABYLON || (BABYLON = {}));
  85516. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85517. var BABYLON;
  85518. (function (BABYLON) {
  85519. var RayHelper = /** @class */ (function () {
  85520. function RayHelper(ray) {
  85521. this.ray = ray;
  85522. }
  85523. RayHelper.CreateAndShow = function (ray, scene, color) {
  85524. var helper = new RayHelper(ray);
  85525. helper.show(scene, color);
  85526. return helper;
  85527. };
  85528. RayHelper.prototype.show = function (scene, color) {
  85529. if (!this._renderFunction && this.ray) {
  85530. var ray = this.ray;
  85531. this._renderFunction = this._render.bind(this);
  85532. this._scene = scene;
  85533. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85534. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85535. if (this._renderFunction) {
  85536. this._scene.registerBeforeRender(this._renderFunction);
  85537. }
  85538. }
  85539. if (color && this._renderLine) {
  85540. this._renderLine.color.copyFrom(color);
  85541. }
  85542. };
  85543. RayHelper.prototype.hide = function () {
  85544. if (this._renderFunction && this._scene) {
  85545. this._scene.unregisterBeforeRender(this._renderFunction);
  85546. this._scene = null;
  85547. this._renderFunction = null;
  85548. if (this._renderLine) {
  85549. this._renderLine.dispose();
  85550. this._renderLine = null;
  85551. }
  85552. this._renderPoints = [];
  85553. }
  85554. };
  85555. RayHelper.prototype._render = function () {
  85556. var ray = this.ray;
  85557. if (!ray) {
  85558. return;
  85559. }
  85560. var point = this._renderPoints[1];
  85561. var len = Math.min(ray.length, 1000000);
  85562. point.copyFrom(ray.direction);
  85563. point.scaleInPlace(len);
  85564. point.addInPlace(ray.origin);
  85565. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85566. };
  85567. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85568. this._attachedToMesh = mesh;
  85569. var ray = this.ray;
  85570. if (!ray) {
  85571. return;
  85572. }
  85573. if (!ray.direction) {
  85574. ray.direction = BABYLON.Vector3.Zero();
  85575. }
  85576. if (!ray.origin) {
  85577. ray.origin = BABYLON.Vector3.Zero();
  85578. }
  85579. if (length) {
  85580. ray.length = length;
  85581. }
  85582. if (!meshSpaceOrigin) {
  85583. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85584. }
  85585. if (!meshSpaceDirection) {
  85586. // -1 so that this will work with Mesh.lookAt
  85587. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85588. }
  85589. if (!this._meshSpaceDirection) {
  85590. this._meshSpaceDirection = meshSpaceDirection.clone();
  85591. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85592. }
  85593. else {
  85594. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85595. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85596. }
  85597. if (!this._updateToMeshFunction) {
  85598. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85599. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85600. }
  85601. this._updateToMesh();
  85602. };
  85603. RayHelper.prototype.detachFromMesh = function () {
  85604. if (this._attachedToMesh) {
  85605. if (this._updateToMeshFunction) {
  85606. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85607. }
  85608. this._attachedToMesh = null;
  85609. this._updateToMeshFunction = null;
  85610. }
  85611. };
  85612. RayHelper.prototype._updateToMesh = function () {
  85613. var ray = this.ray;
  85614. if (!this._attachedToMesh || !ray) {
  85615. return;
  85616. }
  85617. if (this._attachedToMesh._isDisposed) {
  85618. this.detachFromMesh();
  85619. return;
  85620. }
  85621. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85622. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85623. };
  85624. RayHelper.prototype.dispose = function () {
  85625. this.hide();
  85626. this.detachFromMesh();
  85627. this.ray = null;
  85628. };
  85629. return RayHelper;
  85630. }());
  85631. BABYLON.RayHelper = RayHelper;
  85632. })(BABYLON || (BABYLON = {}));
  85633. //# sourceMappingURL=babylon.rayHelper.js.map
  85634. var BABYLON;
  85635. (function (BABYLON) {
  85636. // load the inspector using require, if not present in the global namespace.
  85637. var DebugLayer = /** @class */ (function () {
  85638. function DebugLayer(scene) {
  85639. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85640. this._scene = scene;
  85641. // load inspector using require, if it doesn't exist on the global namespace.
  85642. }
  85643. /** Creates the inspector window. */
  85644. DebugLayer.prototype._createInspector = function (config) {
  85645. if (config === void 0) { config = {}; }
  85646. var popup = config.popup || false;
  85647. var initialTab = config.initialTab || 0;
  85648. var parentElement = config.parentElement || null;
  85649. if (!this._inspector) {
  85650. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85651. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85652. } // else nothing to do,; instance is already existing
  85653. };
  85654. DebugLayer.prototype.isVisible = function () {
  85655. if (!this._inspector) {
  85656. return false;
  85657. }
  85658. return true;
  85659. };
  85660. DebugLayer.prototype.hide = function () {
  85661. if (this._inspector) {
  85662. try {
  85663. this._inspector.dispose();
  85664. }
  85665. catch (e) {
  85666. // If the inspector has been removed directly from the inspector tool
  85667. }
  85668. this._inspector = null;
  85669. }
  85670. };
  85671. DebugLayer.prototype.show = function (config) {
  85672. if (config === void 0) { config = {}; }
  85673. if (typeof this.BJSINSPECTOR == 'undefined') {
  85674. // Load inspector and add it to the DOM
  85675. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85676. }
  85677. else {
  85678. // Otherwise creates the inspector
  85679. this._createInspector(config);
  85680. }
  85681. };
  85682. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85683. return DebugLayer;
  85684. }());
  85685. BABYLON.DebugLayer = DebugLayer;
  85686. })(BABYLON || (BABYLON = {}));
  85687. //# sourceMappingURL=babylon.debugLayer.js.map
  85688. var BABYLON;
  85689. (function (BABYLON) {
  85690. var Debug;
  85691. (function (Debug) {
  85692. /**
  85693. * Used to show the physics impostor around the specific mesh.
  85694. */
  85695. var PhysicsViewer = /** @class */ (function () {
  85696. function PhysicsViewer(scene) {
  85697. this._impostors = [];
  85698. this._meshes = [];
  85699. this._numMeshes = 0;
  85700. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85701. var physicEngine = this._scene.getPhysicsEngine();
  85702. if (physicEngine) {
  85703. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85704. }
  85705. }
  85706. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85707. var plugin = this._physicsEnginePlugin;
  85708. for (var i = 0; i < this._numMeshes; i++) {
  85709. var impostor = this._impostors[i];
  85710. if (!impostor) {
  85711. continue;
  85712. }
  85713. if (impostor.isDisposed) {
  85714. this.hideImpostor(this._impostors[i--]);
  85715. }
  85716. else {
  85717. var mesh = this._meshes[i];
  85718. if (mesh && plugin) {
  85719. plugin.syncMeshWithImpostor(mesh, impostor);
  85720. }
  85721. }
  85722. }
  85723. };
  85724. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85725. if (!this._scene) {
  85726. return;
  85727. }
  85728. for (var i = 0; i < this._numMeshes; i++) {
  85729. if (this._impostors[i] == impostor) {
  85730. return;
  85731. }
  85732. }
  85733. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85734. if (debugMesh) {
  85735. this._impostors[this._numMeshes] = impostor;
  85736. this._meshes[this._numMeshes] = debugMesh;
  85737. if (this._numMeshes === 0) {
  85738. this._renderFunction = this._updateDebugMeshes.bind(this);
  85739. this._scene.registerBeforeRender(this._renderFunction);
  85740. }
  85741. this._numMeshes++;
  85742. }
  85743. };
  85744. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85745. if (!impostor || !this._scene) {
  85746. return;
  85747. }
  85748. var removed = false;
  85749. for (var i = 0; i < this._numMeshes; i++) {
  85750. if (this._impostors[i] == impostor) {
  85751. var mesh = this._meshes[i];
  85752. if (!mesh) {
  85753. continue;
  85754. }
  85755. this._scene.removeMesh(mesh);
  85756. mesh.dispose();
  85757. this._numMeshes--;
  85758. if (this._numMeshes > 0) {
  85759. this._meshes[i] = this._meshes[this._numMeshes];
  85760. this._impostors[i] = this._impostors[this._numMeshes];
  85761. this._meshes[this._numMeshes] = null;
  85762. this._impostors[this._numMeshes] = null;
  85763. }
  85764. else {
  85765. this._meshes[0] = null;
  85766. this._impostors[0] = null;
  85767. }
  85768. removed = true;
  85769. break;
  85770. }
  85771. }
  85772. if (removed && this._numMeshes === 0) {
  85773. this._scene.unregisterBeforeRender(this._renderFunction);
  85774. }
  85775. };
  85776. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85777. if (!this._debugMaterial) {
  85778. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85779. this._debugMaterial.wireframe = true;
  85780. }
  85781. return this._debugMaterial;
  85782. };
  85783. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85784. if (!this._debugBoxMesh) {
  85785. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85786. this._debugBoxMesh.renderingGroupId = 1;
  85787. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85788. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85789. scene.removeMesh(this._debugBoxMesh);
  85790. }
  85791. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85792. };
  85793. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  85794. if (!this._debugSphereMesh) {
  85795. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  85796. this._debugSphereMesh.renderingGroupId = 1;
  85797. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85798. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  85799. scene.removeMesh(this._debugSphereMesh);
  85800. }
  85801. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  85802. };
  85803. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  85804. var mesh = null;
  85805. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  85806. mesh = this._getDebugBoxMesh(scene);
  85807. impostor.getBoxSizeToRef(mesh.scaling);
  85808. }
  85809. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  85810. mesh = this._getDebugSphereMesh(scene);
  85811. var radius = impostor.getRadius();
  85812. mesh.scaling.x = radius * 2;
  85813. mesh.scaling.y = radius * 2;
  85814. mesh.scaling.z = radius * 2;
  85815. }
  85816. return mesh;
  85817. };
  85818. PhysicsViewer.prototype.dispose = function () {
  85819. for (var i = 0; i < this._numMeshes; i++) {
  85820. this.hideImpostor(this._impostors[i]);
  85821. }
  85822. if (this._debugBoxMesh) {
  85823. this._debugBoxMesh.dispose();
  85824. }
  85825. if (this._debugSphereMesh) {
  85826. this._debugSphereMesh.dispose();
  85827. }
  85828. if (this._debugMaterial) {
  85829. this._debugMaterial.dispose();
  85830. }
  85831. this._impostors.length = 0;
  85832. this._scene = null;
  85833. this._physicsEnginePlugin = null;
  85834. };
  85835. return PhysicsViewer;
  85836. }());
  85837. Debug.PhysicsViewer = PhysicsViewer;
  85838. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85839. })(BABYLON || (BABYLON = {}));
  85840. //# sourceMappingURL=babylon.physicsViewer.js.map
  85841. var BABYLON;
  85842. (function (BABYLON) {
  85843. var BoundingBoxRenderer = /** @class */ (function () {
  85844. function BoundingBoxRenderer(scene) {
  85845. this.frontColor = new BABYLON.Color3(1, 1, 1);
  85846. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  85847. this.showBackLines = true;
  85848. this.renderList = new BABYLON.SmartArray(32);
  85849. this._vertexBuffers = {};
  85850. this._scene = scene;
  85851. }
  85852. BoundingBoxRenderer.prototype._prepareRessources = function () {
  85853. if (this._colorShader) {
  85854. return;
  85855. }
  85856. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  85857. attributes: [BABYLON.VertexBuffer.PositionKind],
  85858. uniforms: ["world", "viewProjection", "color"]
  85859. });
  85860. var engine = this._scene.getEngine();
  85861. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  85862. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  85863. this._createIndexBuffer();
  85864. };
  85865. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  85866. var engine = this._scene.getEngine();
  85867. 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]);
  85868. };
  85869. BoundingBoxRenderer.prototype._rebuild = function () {
  85870. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85871. if (vb) {
  85872. vb._rebuild();
  85873. }
  85874. this._createIndexBuffer();
  85875. };
  85876. BoundingBoxRenderer.prototype.reset = function () {
  85877. this.renderList.reset();
  85878. };
  85879. BoundingBoxRenderer.prototype.render = function () {
  85880. if (this.renderList.length === 0) {
  85881. return;
  85882. }
  85883. this._prepareRessources();
  85884. if (!this._colorShader.isReady()) {
  85885. return;
  85886. }
  85887. var engine = this._scene.getEngine();
  85888. engine.setDepthWrite(false);
  85889. this._colorShader._preBind();
  85890. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  85891. var boundingBox = this.renderList.data[boundingBoxIndex];
  85892. var min = boundingBox.minimum;
  85893. var max = boundingBox.maximum;
  85894. var diff = max.subtract(min);
  85895. var median = min.add(diff.scale(0.5));
  85896. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85897. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85898. .multiply(boundingBox.getWorldMatrix());
  85899. // VBOs
  85900. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85901. if (this.showBackLines) {
  85902. // Back
  85903. engine.setDepthFunctionToGreaterOrEqual();
  85904. this._scene.resetCachedMaterial();
  85905. this._colorShader.setColor4("color", this.backColor.toColor4());
  85906. this._colorShader.bind(worldMatrix);
  85907. // Draw order
  85908. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85909. }
  85910. // Front
  85911. engine.setDepthFunctionToLess();
  85912. this._scene.resetCachedMaterial();
  85913. this._colorShader.setColor4("color", this.frontColor.toColor4());
  85914. this._colorShader.bind(worldMatrix);
  85915. // Draw order
  85916. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85917. }
  85918. this._colorShader.unbind();
  85919. engine.setDepthFunctionToLessOrEqual();
  85920. engine.setDepthWrite(true);
  85921. };
  85922. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  85923. this._prepareRessources();
  85924. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  85925. return;
  85926. }
  85927. var engine = this._scene.getEngine();
  85928. engine.setDepthWrite(false);
  85929. engine.setColorWrite(false);
  85930. this._colorShader._preBind();
  85931. var boundingBox = mesh._boundingInfo.boundingBox;
  85932. var min = boundingBox.minimum;
  85933. var max = boundingBox.maximum;
  85934. var diff = max.subtract(min);
  85935. var median = min.add(diff.scale(0.5));
  85936. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85937. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85938. .multiply(boundingBox.getWorldMatrix());
  85939. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85940. engine.setDepthFunctionToLess();
  85941. this._scene.resetCachedMaterial();
  85942. this._colorShader.bind(worldMatrix);
  85943. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85944. this._colorShader.unbind();
  85945. engine.setDepthFunctionToLessOrEqual();
  85946. engine.setDepthWrite(true);
  85947. engine.setColorWrite(true);
  85948. };
  85949. BoundingBoxRenderer.prototype.dispose = function () {
  85950. if (!this._colorShader) {
  85951. return;
  85952. }
  85953. this.renderList.dispose();
  85954. this._colorShader.dispose();
  85955. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85956. if (buffer) {
  85957. buffer.dispose();
  85958. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85959. }
  85960. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85961. };
  85962. return BoundingBoxRenderer;
  85963. }());
  85964. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  85965. })(BABYLON || (BABYLON = {}));
  85966. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  85967. var BABYLON;
  85968. (function (BABYLON) {
  85969. /**
  85970. * Defines a target to use with MorphTargetManager
  85971. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85972. */
  85973. var MorphTarget = /** @class */ (function () {
  85974. /**
  85975. * Creates a new MorphTarget
  85976. * @param name defines the name of the target
  85977. * @param influence defines the influence to use
  85978. */
  85979. function MorphTarget(
  85980. /** defines the name of the target */
  85981. name, influence, scene) {
  85982. if (influence === void 0) { influence = 0; }
  85983. if (scene === void 0) { scene = null; }
  85984. this.name = name;
  85985. /**
  85986. * Gets or sets the list of animations
  85987. */
  85988. this.animations = new Array();
  85989. this._positions = null;
  85990. this._normals = null;
  85991. this._tangents = null;
  85992. /**
  85993. * Observable raised when the influence changes
  85994. */
  85995. this.onInfluenceChanged = new BABYLON.Observable();
  85996. this._animationPropertiesOverride = null;
  85997. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85998. this.influence = influence;
  85999. }
  86000. Object.defineProperty(MorphTarget.prototype, "influence", {
  86001. /**
  86002. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  86003. */
  86004. get: function () {
  86005. return this._influence;
  86006. },
  86007. set: function (influence) {
  86008. if (this._influence === influence) {
  86009. return;
  86010. }
  86011. var previous = this._influence;
  86012. this._influence = influence;
  86013. if (this.onInfluenceChanged.hasObservers) {
  86014. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  86015. }
  86016. },
  86017. enumerable: true,
  86018. configurable: true
  86019. });
  86020. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  86021. /**
  86022. * Gets or sets the animation properties override
  86023. */
  86024. get: function () {
  86025. if (!this._animationPropertiesOverride && this._scene) {
  86026. return this._scene.animationPropertiesOverride;
  86027. }
  86028. return this._animationPropertiesOverride;
  86029. },
  86030. set: function (value) {
  86031. this._animationPropertiesOverride = value;
  86032. },
  86033. enumerable: true,
  86034. configurable: true
  86035. });
  86036. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  86037. /**
  86038. * Gets a boolean defining if the target contains position data
  86039. */
  86040. get: function () {
  86041. return !!this._positions;
  86042. },
  86043. enumerable: true,
  86044. configurable: true
  86045. });
  86046. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  86047. /**
  86048. * Gets a boolean defining if the target contains normal data
  86049. */
  86050. get: function () {
  86051. return !!this._normals;
  86052. },
  86053. enumerable: true,
  86054. configurable: true
  86055. });
  86056. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  86057. /**
  86058. * Gets a boolean defining if the target contains tangent data
  86059. */
  86060. get: function () {
  86061. return !!this._tangents;
  86062. },
  86063. enumerable: true,
  86064. configurable: true
  86065. });
  86066. /**
  86067. * Affects position data to this target
  86068. * @param data defines the position data to use
  86069. */
  86070. MorphTarget.prototype.setPositions = function (data) {
  86071. this._positions = data;
  86072. };
  86073. /**
  86074. * Gets the position data stored in this target
  86075. * @returns a FloatArray containing the position data (or null if not present)
  86076. */
  86077. MorphTarget.prototype.getPositions = function () {
  86078. return this._positions;
  86079. };
  86080. /**
  86081. * Affects normal data to this target
  86082. * @param data defines the normal data to use
  86083. */
  86084. MorphTarget.prototype.setNormals = function (data) {
  86085. this._normals = data;
  86086. };
  86087. /**
  86088. * Gets the normal data stored in this target
  86089. * @returns a FloatArray containing the normal data (or null if not present)
  86090. */
  86091. MorphTarget.prototype.getNormals = function () {
  86092. return this._normals;
  86093. };
  86094. /**
  86095. * Affects tangent data to this target
  86096. * @param data defines the tangent data to use
  86097. */
  86098. MorphTarget.prototype.setTangents = function (data) {
  86099. this._tangents = data;
  86100. };
  86101. /**
  86102. * Gets the tangent data stored in this target
  86103. * @returns a FloatArray containing the tangent data (or null if not present)
  86104. */
  86105. MorphTarget.prototype.getTangents = function () {
  86106. return this._tangents;
  86107. };
  86108. /**
  86109. * Serializes the current target into a Serialization object
  86110. * @returns the serialized object
  86111. */
  86112. MorphTarget.prototype.serialize = function () {
  86113. var serializationObject = {};
  86114. serializationObject.name = this.name;
  86115. serializationObject.influence = this.influence;
  86116. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  86117. if (this.hasNormals) {
  86118. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  86119. }
  86120. if (this.hasTangents) {
  86121. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  86122. }
  86123. // Animations
  86124. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  86125. return serializationObject;
  86126. };
  86127. // Statics
  86128. /**
  86129. * Creates a new target from serialized data
  86130. * @param serializationObject defines the serialized data to use
  86131. * @returns a new MorphTarget
  86132. */
  86133. MorphTarget.Parse = function (serializationObject) {
  86134. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  86135. result.setPositions(serializationObject.positions);
  86136. if (serializationObject.normals) {
  86137. result.setNormals(serializationObject.normals);
  86138. }
  86139. if (serializationObject.tangents) {
  86140. result.setTangents(serializationObject.tangents);
  86141. }
  86142. // Animations
  86143. if (serializationObject.animations) {
  86144. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  86145. var parsedAnimation = serializationObject.animations[animationIndex];
  86146. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  86147. }
  86148. }
  86149. return result;
  86150. };
  86151. /**
  86152. * Creates a MorphTarget from mesh data
  86153. * @param mesh defines the source mesh
  86154. * @param name defines the name to use for the new target
  86155. * @param influence defines the influence to attach to the target
  86156. * @returns a new MorphTarget
  86157. */
  86158. MorphTarget.FromMesh = function (mesh, name, influence) {
  86159. if (!name) {
  86160. name = mesh.name;
  86161. }
  86162. var result = new MorphTarget(name, influence, mesh.getScene());
  86163. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86164. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  86165. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  86166. }
  86167. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  86168. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  86169. }
  86170. return result;
  86171. };
  86172. return MorphTarget;
  86173. }());
  86174. BABYLON.MorphTarget = MorphTarget;
  86175. })(BABYLON || (BABYLON = {}));
  86176. //# sourceMappingURL=babylon.morphTarget.js.map
  86177. var BABYLON;
  86178. (function (BABYLON) {
  86179. /**
  86180. * This class is used to deform meshes using morphing between different targets
  86181. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  86182. */
  86183. var MorphTargetManager = /** @class */ (function () {
  86184. /**
  86185. * Creates a new MorphTargetManager
  86186. * @param scene defines the current scene
  86187. */
  86188. function MorphTargetManager(scene) {
  86189. if (scene === void 0) { scene = null; }
  86190. this._targets = new Array();
  86191. this._targetObservable = new Array();
  86192. this._activeTargets = new BABYLON.SmartArray(16);
  86193. this._supportsNormals = false;
  86194. this._supportsTangents = false;
  86195. this._vertexCount = 0;
  86196. this._uniqueId = 0;
  86197. this._tempInfluences = new Array();
  86198. if (!scene) {
  86199. scene = BABYLON.Engine.LastCreatedScene;
  86200. }
  86201. this._scene = scene;
  86202. if (this._scene) {
  86203. this._scene.morphTargetManagers.push(this);
  86204. this._uniqueId = this._scene.getUniqueId();
  86205. }
  86206. }
  86207. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  86208. /**
  86209. * Gets the unique ID of this manager
  86210. */
  86211. get: function () {
  86212. return this._uniqueId;
  86213. },
  86214. enumerable: true,
  86215. configurable: true
  86216. });
  86217. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  86218. /**
  86219. * Gets the number of vertices handled by this manager
  86220. */
  86221. get: function () {
  86222. return this._vertexCount;
  86223. },
  86224. enumerable: true,
  86225. configurable: true
  86226. });
  86227. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  86228. /**
  86229. * Gets a boolean indicating if this manager supports morphing of normals
  86230. */
  86231. get: function () {
  86232. return this._supportsNormals;
  86233. },
  86234. enumerable: true,
  86235. configurable: true
  86236. });
  86237. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  86238. /**
  86239. * Gets a boolean indicating if this manager supports morphing of tangents
  86240. */
  86241. get: function () {
  86242. return this._supportsTangents;
  86243. },
  86244. enumerable: true,
  86245. configurable: true
  86246. });
  86247. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  86248. /**
  86249. * Gets the number of targets stored in this manager
  86250. */
  86251. get: function () {
  86252. return this._targets.length;
  86253. },
  86254. enumerable: true,
  86255. configurable: true
  86256. });
  86257. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  86258. /**
  86259. * Gets the number of influencers (ie. the number of targets with influences > 0)
  86260. */
  86261. get: function () {
  86262. return this._activeTargets.length;
  86263. },
  86264. enumerable: true,
  86265. configurable: true
  86266. });
  86267. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  86268. /**
  86269. * Gets the list of influences (one per target)
  86270. */
  86271. get: function () {
  86272. return this._influences;
  86273. },
  86274. enumerable: true,
  86275. configurable: true
  86276. });
  86277. /**
  86278. * Gets the active target at specified index. An active target is a target with an influence > 0
  86279. * @param index defines the index to check
  86280. * @returns the requested target
  86281. */
  86282. MorphTargetManager.prototype.getActiveTarget = function (index) {
  86283. return this._activeTargets.data[index];
  86284. };
  86285. /**
  86286. * Gets the target at specified index
  86287. * @param index defines the index to check
  86288. * @returns the requested target
  86289. */
  86290. MorphTargetManager.prototype.getTarget = function (index) {
  86291. return this._targets[index];
  86292. };
  86293. /**
  86294. * Add a new target to this manager
  86295. * @param target defines the target to add
  86296. */
  86297. MorphTargetManager.prototype.addTarget = function (target) {
  86298. var _this = this;
  86299. this._targets.push(target);
  86300. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  86301. _this._syncActiveTargets(needUpdate);
  86302. }));
  86303. this._syncActiveTargets(true);
  86304. };
  86305. /**
  86306. * Removes a target from the manager
  86307. * @param target defines the target to remove
  86308. */
  86309. MorphTargetManager.prototype.removeTarget = function (target) {
  86310. var index = this._targets.indexOf(target);
  86311. if (index >= 0) {
  86312. this._targets.splice(index, 1);
  86313. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  86314. this._syncActiveTargets(true);
  86315. }
  86316. };
  86317. /**
  86318. * Serializes the current manager into a Serialization object
  86319. * @returns the serialized object
  86320. */
  86321. MorphTargetManager.prototype.serialize = function () {
  86322. var serializationObject = {};
  86323. serializationObject.id = this.uniqueId;
  86324. serializationObject.targets = [];
  86325. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86326. var target = _a[_i];
  86327. serializationObject.targets.push(target.serialize());
  86328. }
  86329. return serializationObject;
  86330. };
  86331. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  86332. var influenceCount = 0;
  86333. this._activeTargets.reset();
  86334. this._supportsNormals = true;
  86335. this._supportsTangents = true;
  86336. this._vertexCount = 0;
  86337. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86338. var target = _a[_i];
  86339. this._activeTargets.push(target);
  86340. this._tempInfluences[influenceCount++] = target.influence;
  86341. var positions = target.getPositions();
  86342. if (positions) {
  86343. this._supportsNormals = this._supportsNormals && target.hasNormals;
  86344. this._supportsTangents = this._supportsTangents && target.hasTangents;
  86345. var vertexCount = positions.length / 3;
  86346. if (this._vertexCount === 0) {
  86347. this._vertexCount = vertexCount;
  86348. }
  86349. else if (this._vertexCount !== vertexCount) {
  86350. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  86351. return;
  86352. }
  86353. }
  86354. }
  86355. if (!this._influences || this._influences.length !== influenceCount) {
  86356. this._influences = new Float32Array(influenceCount);
  86357. }
  86358. for (var index = 0; index < influenceCount; index++) {
  86359. this._influences[index] = this._tempInfluences[index];
  86360. }
  86361. if (needUpdate) {
  86362. this.synchronize();
  86363. }
  86364. };
  86365. /**
  86366. * Syncrhonize the targets with all the meshes using this morph target manager
  86367. */
  86368. MorphTargetManager.prototype.synchronize = function () {
  86369. if (!this._scene) {
  86370. return;
  86371. }
  86372. // Flag meshes as dirty to resync with the active targets
  86373. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  86374. var mesh = _a[_i];
  86375. if (mesh.morphTargetManager === this) {
  86376. mesh._syncGeometryWithMorphTargetManager();
  86377. }
  86378. }
  86379. };
  86380. // Statics
  86381. /**
  86382. * Creates a new MorphTargetManager from serialized data
  86383. * @param serializationObject defines the serialized data
  86384. * @param scene defines the hosting scene
  86385. * @returns the new MorphTargetManager
  86386. */
  86387. MorphTargetManager.Parse = function (serializationObject, scene) {
  86388. var result = new MorphTargetManager(scene);
  86389. result._uniqueId = serializationObject.id;
  86390. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  86391. var targetData = _a[_i];
  86392. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  86393. }
  86394. return result;
  86395. };
  86396. return MorphTargetManager;
  86397. }());
  86398. BABYLON.MorphTargetManager = MorphTargetManager;
  86399. })(BABYLON || (BABYLON = {}));
  86400. //# sourceMappingURL=babylon.morphTargetManager.js.map
  86401. var BABYLON;
  86402. (function (BABYLON) {
  86403. var Octree = /** @class */ (function () {
  86404. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  86405. if (maxDepth === void 0) { maxDepth = 2; }
  86406. this.maxDepth = maxDepth;
  86407. this.dynamicContent = new Array();
  86408. this._maxBlockCapacity = maxBlockCapacity || 64;
  86409. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  86410. this._creationFunc = creationFunc;
  86411. }
  86412. // Methods
  86413. Octree.prototype.update = function (worldMin, worldMax, entries) {
  86414. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  86415. };
  86416. Octree.prototype.addMesh = function (entry) {
  86417. for (var index = 0; index < this.blocks.length; index++) {
  86418. var block = this.blocks[index];
  86419. block.addEntry(entry);
  86420. }
  86421. };
  86422. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  86423. this._selectionContent.reset();
  86424. for (var index = 0; index < this.blocks.length; index++) {
  86425. var block = this.blocks[index];
  86426. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  86427. }
  86428. if (allowDuplicate) {
  86429. this._selectionContent.concat(this.dynamicContent);
  86430. }
  86431. else {
  86432. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86433. }
  86434. return this._selectionContent;
  86435. };
  86436. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  86437. this._selectionContent.reset();
  86438. for (var index = 0; index < this.blocks.length; index++) {
  86439. var block = this.blocks[index];
  86440. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  86441. }
  86442. if (allowDuplicate) {
  86443. this._selectionContent.concat(this.dynamicContent);
  86444. }
  86445. else {
  86446. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86447. }
  86448. return this._selectionContent;
  86449. };
  86450. Octree.prototype.intersectsRay = function (ray) {
  86451. this._selectionContent.reset();
  86452. for (var index = 0; index < this.blocks.length; index++) {
  86453. var block = this.blocks[index];
  86454. block.intersectsRay(ray, this._selectionContent);
  86455. }
  86456. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86457. return this._selectionContent;
  86458. };
  86459. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  86460. target.blocks = new Array();
  86461. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  86462. // Segmenting space
  86463. for (var x = 0; x < 2; x++) {
  86464. for (var y = 0; y < 2; y++) {
  86465. for (var z = 0; z < 2; z++) {
  86466. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  86467. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  86468. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  86469. block.addEntries(entries);
  86470. target.blocks.push(block);
  86471. }
  86472. }
  86473. }
  86474. };
  86475. Octree.CreationFuncForMeshes = function (entry, block) {
  86476. var boundingInfo = entry.getBoundingInfo();
  86477. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86478. block.entries.push(entry);
  86479. }
  86480. };
  86481. Octree.CreationFuncForSubMeshes = function (entry, block) {
  86482. var boundingInfo = entry.getBoundingInfo();
  86483. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86484. block.entries.push(entry);
  86485. }
  86486. };
  86487. return Octree;
  86488. }());
  86489. BABYLON.Octree = Octree;
  86490. })(BABYLON || (BABYLON = {}));
  86491. //# sourceMappingURL=babylon.octree.js.map
  86492. var BABYLON;
  86493. (function (BABYLON) {
  86494. var OctreeBlock = /** @class */ (function () {
  86495. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  86496. this.entries = new Array();
  86497. this._boundingVectors = new Array();
  86498. this._capacity = capacity;
  86499. this._depth = depth;
  86500. this._maxDepth = maxDepth;
  86501. this._creationFunc = creationFunc;
  86502. this._minPoint = minPoint;
  86503. this._maxPoint = maxPoint;
  86504. this._boundingVectors.push(minPoint.clone());
  86505. this._boundingVectors.push(maxPoint.clone());
  86506. this._boundingVectors.push(minPoint.clone());
  86507. this._boundingVectors[2].x = maxPoint.x;
  86508. this._boundingVectors.push(minPoint.clone());
  86509. this._boundingVectors[3].y = maxPoint.y;
  86510. this._boundingVectors.push(minPoint.clone());
  86511. this._boundingVectors[4].z = maxPoint.z;
  86512. this._boundingVectors.push(maxPoint.clone());
  86513. this._boundingVectors[5].z = minPoint.z;
  86514. this._boundingVectors.push(maxPoint.clone());
  86515. this._boundingVectors[6].x = minPoint.x;
  86516. this._boundingVectors.push(maxPoint.clone());
  86517. this._boundingVectors[7].y = minPoint.y;
  86518. }
  86519. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  86520. // Property
  86521. get: function () {
  86522. return this._capacity;
  86523. },
  86524. enumerable: true,
  86525. configurable: true
  86526. });
  86527. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  86528. get: function () {
  86529. return this._minPoint;
  86530. },
  86531. enumerable: true,
  86532. configurable: true
  86533. });
  86534. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  86535. get: function () {
  86536. return this._maxPoint;
  86537. },
  86538. enumerable: true,
  86539. configurable: true
  86540. });
  86541. // Methods
  86542. OctreeBlock.prototype.addEntry = function (entry) {
  86543. if (this.blocks) {
  86544. for (var index = 0; index < this.blocks.length; index++) {
  86545. var block = this.blocks[index];
  86546. block.addEntry(entry);
  86547. }
  86548. return;
  86549. }
  86550. this._creationFunc(entry, this);
  86551. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  86552. this.createInnerBlocks();
  86553. }
  86554. };
  86555. OctreeBlock.prototype.addEntries = function (entries) {
  86556. for (var index = 0; index < entries.length; index++) {
  86557. var mesh = entries[index];
  86558. this.addEntry(mesh);
  86559. }
  86560. };
  86561. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  86562. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  86563. if (this.blocks) {
  86564. for (var index = 0; index < this.blocks.length; index++) {
  86565. var block = this.blocks[index];
  86566. block.select(frustumPlanes, selection, allowDuplicate);
  86567. }
  86568. return;
  86569. }
  86570. if (allowDuplicate) {
  86571. selection.concat(this.entries);
  86572. }
  86573. else {
  86574. selection.concatWithNoDuplicate(this.entries);
  86575. }
  86576. }
  86577. };
  86578. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  86579. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  86580. if (this.blocks) {
  86581. for (var index = 0; index < this.blocks.length; index++) {
  86582. var block = this.blocks[index];
  86583. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  86584. }
  86585. return;
  86586. }
  86587. if (allowDuplicate) {
  86588. selection.concat(this.entries);
  86589. }
  86590. else {
  86591. selection.concatWithNoDuplicate(this.entries);
  86592. }
  86593. }
  86594. };
  86595. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  86596. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  86597. if (this.blocks) {
  86598. for (var index = 0; index < this.blocks.length; index++) {
  86599. var block = this.blocks[index];
  86600. block.intersectsRay(ray, selection);
  86601. }
  86602. return;
  86603. }
  86604. selection.concatWithNoDuplicate(this.entries);
  86605. }
  86606. };
  86607. OctreeBlock.prototype.createInnerBlocks = function () {
  86608. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  86609. };
  86610. return OctreeBlock;
  86611. }());
  86612. BABYLON.OctreeBlock = OctreeBlock;
  86613. })(BABYLON || (BABYLON = {}));
  86614. //# sourceMappingURL=babylon.octreeBlock.js.map
  86615. var BABYLON;
  86616. (function (BABYLON) {
  86617. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86618. __extends(VRDistortionCorrectionPostProcess, _super);
  86619. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86620. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86621. 'LensCenter',
  86622. 'Scale',
  86623. 'ScaleIn',
  86624. 'HmdWarpParam'
  86625. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86626. _this._isRightEye = isRightEye;
  86627. _this._distortionFactors = vrMetrics.distortionK;
  86628. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86629. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86630. _this.adaptScaleToCurrentViewport = true;
  86631. _this.onSizeChangedObservable.add(function () {
  86632. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86633. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86634. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86635. });
  86636. _this.onApplyObservable.add(function (effect) {
  86637. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86638. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86639. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86640. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86641. });
  86642. return _this;
  86643. }
  86644. return VRDistortionCorrectionPostProcess;
  86645. }(BABYLON.PostProcess));
  86646. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  86647. })(BABYLON || (BABYLON = {}));
  86648. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  86649. var BABYLON;
  86650. (function (BABYLON) {
  86651. /**
  86652. * Postprocess used to generate anaglyphic rendering
  86653. */
  86654. var AnaglyphPostProcess = /** @class */ (function (_super) {
  86655. __extends(AnaglyphPostProcess, _super);
  86656. /**
  86657. * Creates a new AnaglyphPostProcess
  86658. * @param name defines postprocess name
  86659. * @param options defines creation options or target ratio scale
  86660. * @param rigCameras defines cameras using this postprocess
  86661. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  86662. * @param engine defines hosting engine
  86663. * @param reusable defines if the postprocess will be reused multiple times per frame
  86664. */
  86665. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  86666. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  86667. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86668. _this.onApplyObservable.add(function (effect) {
  86669. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  86670. });
  86671. return _this;
  86672. }
  86673. return AnaglyphPostProcess;
  86674. }(BABYLON.PostProcess));
  86675. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  86676. })(BABYLON || (BABYLON = {}));
  86677. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  86678. var BABYLON;
  86679. (function (BABYLON) {
  86680. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  86681. __extends(StereoscopicInterlacePostProcess, _super);
  86682. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  86683. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  86684. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86685. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86686. _this.onSizeChangedObservable.add(function () {
  86687. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86688. });
  86689. _this.onApplyObservable.add(function (effect) {
  86690. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  86691. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  86692. });
  86693. return _this;
  86694. }
  86695. return StereoscopicInterlacePostProcess;
  86696. }(BABYLON.PostProcess));
  86697. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  86698. })(BABYLON || (BABYLON = {}));
  86699. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  86700. var BABYLON;
  86701. (function (BABYLON) {
  86702. /**
  86703. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  86704. * Screen rotation is taken into account.
  86705. */
  86706. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  86707. function FreeCameraDeviceOrientationInput() {
  86708. var _this = this;
  86709. this._screenOrientationAngle = 0;
  86710. this._screenQuaternion = new BABYLON.Quaternion();
  86711. this._alpha = 0;
  86712. this._beta = 0;
  86713. this._gamma = 0;
  86714. this._orientationChanged = function () {
  86715. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  86716. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  86717. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  86718. };
  86719. this._deviceOrientation = function (evt) {
  86720. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  86721. _this._beta = evt.beta !== null ? evt.beta : 0;
  86722. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  86723. };
  86724. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  86725. this._orientationChanged();
  86726. }
  86727. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  86728. get: function () {
  86729. return this._camera;
  86730. },
  86731. set: function (camera) {
  86732. this._camera = camera;
  86733. if (this._camera != null && !this._camera.rotationQuaternion) {
  86734. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  86735. }
  86736. },
  86737. enumerable: true,
  86738. configurable: true
  86739. });
  86740. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86741. window.addEventListener("orientationchange", this._orientationChanged);
  86742. window.addEventListener("deviceorientation", this._deviceOrientation);
  86743. //In certain cases, the attach control is called AFTER orientation was changed,
  86744. //So this is needed.
  86745. this._orientationChanged();
  86746. };
  86747. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  86748. window.removeEventListener("orientationchange", this._orientationChanged);
  86749. window.removeEventListener("deviceorientation", this._deviceOrientation);
  86750. };
  86751. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  86752. //if no device orientation provided, don't update the rotation.
  86753. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  86754. if (!this._alpha)
  86755. return;
  86756. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  86757. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  86758. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  86759. //Mirror on XY Plane
  86760. this._camera.rotationQuaternion.z *= -1;
  86761. this._camera.rotationQuaternion.w *= -1;
  86762. };
  86763. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  86764. return "FreeCameraDeviceOrientationInput";
  86765. };
  86766. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  86767. return "deviceOrientation";
  86768. };
  86769. return FreeCameraDeviceOrientationInput;
  86770. }());
  86771. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  86772. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  86773. })(BABYLON || (BABYLON = {}));
  86774. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  86775. var BABYLON;
  86776. (function (BABYLON) {
  86777. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  86778. function ArcRotateCameraVRDeviceOrientationInput() {
  86779. this.alphaCorrection = 1;
  86780. this.betaCorrection = 1;
  86781. this.gammaCorrection = 1;
  86782. this._alpha = 0;
  86783. this._gamma = 0;
  86784. this._dirty = false;
  86785. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  86786. }
  86787. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86788. this.camera.attachControl(element, noPreventDefault);
  86789. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  86790. };
  86791. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  86792. if (evt.alpha !== null) {
  86793. this._alpha = +evt.alpha | 0;
  86794. }
  86795. if (evt.gamma !== null) {
  86796. this._gamma = +evt.gamma | 0;
  86797. }
  86798. this._dirty = true;
  86799. };
  86800. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  86801. if (this._dirty) {
  86802. this._dirty = false;
  86803. if (this._gamma < 0) {
  86804. this._gamma = 180 + this._gamma;
  86805. }
  86806. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  86807. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  86808. }
  86809. };
  86810. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  86811. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  86812. };
  86813. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  86814. return "ArcRotateCameraVRDeviceOrientationInput";
  86815. };
  86816. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  86817. return "VRDeviceOrientation";
  86818. };
  86819. return ArcRotateCameraVRDeviceOrientationInput;
  86820. }());
  86821. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  86822. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  86823. })(BABYLON || (BABYLON = {}));
  86824. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  86825. var BABYLON;
  86826. (function (BABYLON) {
  86827. var VRCameraMetrics = /** @class */ (function () {
  86828. function VRCameraMetrics() {
  86829. this.compensateDistortion = true;
  86830. }
  86831. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  86832. get: function () {
  86833. return this.hResolution / (2 * this.vResolution);
  86834. },
  86835. enumerable: true,
  86836. configurable: true
  86837. });
  86838. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  86839. get: function () {
  86840. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  86841. },
  86842. enumerable: true,
  86843. configurable: true
  86844. });
  86845. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  86846. get: function () {
  86847. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86848. var h = (4 * meters) / this.hScreenSize;
  86849. return BABYLON.Matrix.Translation(h, 0, 0);
  86850. },
  86851. enumerable: true,
  86852. configurable: true
  86853. });
  86854. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  86855. get: function () {
  86856. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86857. var h = (4 * meters) / this.hScreenSize;
  86858. return BABYLON.Matrix.Translation(-h, 0, 0);
  86859. },
  86860. enumerable: true,
  86861. configurable: true
  86862. });
  86863. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  86864. get: function () {
  86865. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  86866. },
  86867. enumerable: true,
  86868. configurable: true
  86869. });
  86870. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  86871. get: function () {
  86872. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  86873. },
  86874. enumerable: true,
  86875. configurable: true
  86876. });
  86877. VRCameraMetrics.GetDefault = function () {
  86878. var result = new VRCameraMetrics();
  86879. result.hResolution = 1280;
  86880. result.vResolution = 800;
  86881. result.hScreenSize = 0.149759993;
  86882. result.vScreenSize = 0.0935999975;
  86883. result.vScreenCenter = 0.0467999987;
  86884. result.eyeToScreenDistance = 0.0410000011;
  86885. result.lensSeparationDistance = 0.0635000020;
  86886. result.interpupillaryDistance = 0.0640000030;
  86887. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  86888. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  86889. result.postProcessScaleFactor = 1.714605507808412;
  86890. result.lensCenterOffset = 0.151976421;
  86891. return result;
  86892. };
  86893. return VRCameraMetrics;
  86894. }());
  86895. BABYLON.VRCameraMetrics = VRCameraMetrics;
  86896. })(BABYLON || (BABYLON = {}));
  86897. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  86898. var BABYLON;
  86899. (function (BABYLON) {
  86900. /**
  86901. * This represents a WebVR camera.
  86902. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  86903. * @example http://doc.babylonjs.com/how_to/webvr_camera
  86904. */
  86905. var WebVRFreeCamera = /** @class */ (function (_super) {
  86906. __extends(WebVRFreeCamera, _super);
  86907. /**
  86908. * Instantiates a WebVRFreeCamera.
  86909. * @param name The name of the WebVRFreeCamera
  86910. * @param position The starting anchor position for the camera
  86911. * @param scene The scene the camera belongs to
  86912. * @param webVROptions a set of customizable options for the webVRCamera
  86913. */
  86914. function WebVRFreeCamera(name, position, scene, webVROptions) {
  86915. if (webVROptions === void 0) { webVROptions = {}; }
  86916. var _this = _super.call(this, name, position, scene) || this;
  86917. _this.webVROptions = webVROptions;
  86918. /**
  86919. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  86920. */
  86921. _this._vrDevice = null;
  86922. /**
  86923. * The rawPose of the vrDevice.
  86924. */
  86925. _this.rawPose = null;
  86926. _this._specsVersion = "1.1";
  86927. _this._attached = false;
  86928. _this._descendants = [];
  86929. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  86930. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  86931. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  86932. _this._standingMatrix = null;
  86933. /**
  86934. * Represents device position in babylon space.
  86935. */
  86936. _this.devicePosition = BABYLON.Vector3.Zero();
  86937. /**
  86938. * Represents device rotation in babylon space.
  86939. */
  86940. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  86941. /**
  86942. * The scale of the device to be used when translating from device space to babylon space.
  86943. */
  86944. _this.deviceScaleFactor = 1;
  86945. _this._deviceToWorld = BABYLON.Matrix.Identity();
  86946. _this._worldToDevice = BABYLON.Matrix.Identity();
  86947. /**
  86948. * References to the webVR controllers for the vrDevice.
  86949. */
  86950. _this.controllers = [];
  86951. /**
  86952. * Emits an event when a controller is attached.
  86953. */
  86954. _this.onControllersAttachedObservable = new BABYLON.Observable();
  86955. /**
  86956. * Emits an event when a controller's mesh has been loaded;
  86957. */
  86958. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86959. /**
  86960. * If the rig cameras be used as parent instead of this camera.
  86961. */
  86962. _this.rigParenting = true;
  86963. _this._defaultHeight = undefined;
  86964. _this._workingVector = BABYLON.Vector3.Zero();
  86965. _this._oneVector = BABYLON.Vector3.One();
  86966. _this._workingMatrix = BABYLON.Matrix.Identity();
  86967. _this._cache.position = BABYLON.Vector3.Zero();
  86968. if (webVROptions.defaultHeight) {
  86969. _this._defaultHeight = webVROptions.defaultHeight;
  86970. _this.position.y = _this._defaultHeight;
  86971. }
  86972. _this.minZ = 0.1;
  86973. //legacy support - the compensation boolean was removed.
  86974. if (arguments.length === 5) {
  86975. _this.webVROptions = arguments[4];
  86976. }
  86977. // default webVR options
  86978. if (_this.webVROptions.trackPosition == undefined) {
  86979. _this.webVROptions.trackPosition = true;
  86980. }
  86981. if (_this.webVROptions.controllerMeshes == undefined) {
  86982. _this.webVROptions.controllerMeshes = true;
  86983. }
  86984. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  86985. _this.webVROptions.defaultLightingOnControllers = true;
  86986. }
  86987. _this.rotationQuaternion = new BABYLON.Quaternion();
  86988. if (_this.webVROptions && _this.webVROptions.positionScale) {
  86989. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  86990. }
  86991. //enable VR
  86992. var engine = _this.getEngine();
  86993. _this._onVREnabled = function (success) { if (success) {
  86994. _this.initControllers();
  86995. } };
  86996. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  86997. engine.initWebVR().add(function (event) {
  86998. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  86999. return;
  87000. }
  87001. _this._vrDevice = event.vrDisplay;
  87002. //reset the rig parameters.
  87003. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  87004. if (_this._attached) {
  87005. _this.getEngine().enableVR();
  87006. }
  87007. });
  87008. if (typeof (VRFrameData) !== "undefined")
  87009. _this._frameData = new VRFrameData();
  87010. /**
  87011. * The idea behind the following lines:
  87012. * objects that have the camera as parent should actually have the rig cameras as a parent.
  87013. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  87014. * the second will not show it correctly.
  87015. *
  87016. * To solve this - each object that has the camera as parent will be added to a protected array.
  87017. * When the rig camera renders, it will take this array and set all of those to be its children.
  87018. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  87019. * Amazing!
  87020. */
  87021. scene.onBeforeCameraRenderObservable.add(function (camera) {
  87022. if (camera.parent === _this && _this.rigParenting) {
  87023. _this._descendants = _this.getDescendants(true, function (n) {
  87024. // don't take the cameras or the controllers!
  87025. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  87026. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  87027. return !isController && !isRigCamera;
  87028. });
  87029. _this._descendants.forEach(function (node) {
  87030. node.parent = camera;
  87031. });
  87032. }
  87033. });
  87034. scene.onAfterCameraRenderObservable.add(function (camera) {
  87035. if (camera.parent === _this && _this.rigParenting) {
  87036. _this._descendants.forEach(function (node) {
  87037. node.parent = _this;
  87038. });
  87039. }
  87040. });
  87041. return _this;
  87042. }
  87043. /**
  87044. * Gets the device distance from the ground in meters.
  87045. * @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.
  87046. */
  87047. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  87048. if (this._standingMatrix) {
  87049. // Add standing matrix offset to get real offset from ground in room
  87050. this._standingMatrix.getTranslationToRef(this._workingVector);
  87051. return this._deviceRoomPosition.y + this._workingVector.y;
  87052. }
  87053. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  87054. return this._defaultHeight || 0;
  87055. };
  87056. /**
  87057. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  87058. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  87059. */
  87060. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  87061. var _this = this;
  87062. if (callback === void 0) { callback = function (bool) { }; }
  87063. // Use standing matrix if available
  87064. this.getEngine().initWebVRAsync().then(function (result) {
  87065. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  87066. callback(false);
  87067. }
  87068. else {
  87069. _this._standingMatrix = new BABYLON.Matrix();
  87070. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  87071. if (!_this.getScene().useRightHandedSystem) {
  87072. [2, 6, 8, 9, 14].forEach(function (num) {
  87073. if (_this._standingMatrix) {
  87074. _this._standingMatrix.m[num] *= -1;
  87075. }
  87076. });
  87077. }
  87078. callback(true);
  87079. }
  87080. });
  87081. };
  87082. /**
  87083. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  87084. * @returns A promise with a boolean set to if the standing matrix is supported.
  87085. */
  87086. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  87087. var _this = this;
  87088. return new Promise(function (res, rej) {
  87089. _this.useStandingMatrix(function (supported) {
  87090. res(supported);
  87091. });
  87092. });
  87093. };
  87094. /**
  87095. * Disposes the camera
  87096. */
  87097. WebVRFreeCamera.prototype.dispose = function () {
  87098. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  87099. _super.prototype.dispose.call(this);
  87100. };
  87101. /**
  87102. * Gets a vrController by name.
  87103. * @param name The name of the controller to retreive
  87104. * @returns the controller matching the name specified or null if not found
  87105. */
  87106. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  87107. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  87108. var gp = _a[_i];
  87109. if (gp.hand === name) {
  87110. return gp;
  87111. }
  87112. }
  87113. return null;
  87114. };
  87115. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  87116. /**
  87117. * The controller corrisponding to the users left hand.
  87118. */
  87119. get: function () {
  87120. if (!this._leftController) {
  87121. this._leftController = this.getControllerByName("left");
  87122. }
  87123. return this._leftController;
  87124. },
  87125. enumerable: true,
  87126. configurable: true
  87127. });
  87128. ;
  87129. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  87130. /**
  87131. * The controller corrisponding to the users right hand.
  87132. */
  87133. get: function () {
  87134. if (!this._rightController) {
  87135. this._rightController = this.getControllerByName("right");
  87136. }
  87137. return this._rightController;
  87138. },
  87139. enumerable: true,
  87140. configurable: true
  87141. });
  87142. ;
  87143. /**
  87144. * Casts a ray forward from the vrCamera's gaze.
  87145. * @param length Length of the ray (default: 100)
  87146. * @returns the ray corrisponding to the gaze
  87147. */
  87148. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  87149. if (length === void 0) { length = 100; }
  87150. if (this.leftCamera) {
  87151. // Use left eye to avoid computation to compute center on every call
  87152. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  87153. }
  87154. else {
  87155. return _super.prototype.getForwardRay.call(this, length);
  87156. }
  87157. };
  87158. /**
  87159. * Updates the camera based on device's frame data
  87160. */
  87161. WebVRFreeCamera.prototype._checkInputs = function () {
  87162. if (this._vrDevice && this._vrDevice.isPresenting) {
  87163. this._vrDevice.getFrameData(this._frameData);
  87164. this.updateFromDevice(this._frameData.pose);
  87165. }
  87166. _super.prototype._checkInputs.call(this);
  87167. };
  87168. /**
  87169. * Updates the poseControlled values based on the input device pose.
  87170. * @param poseData Pose coming from the device
  87171. */
  87172. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  87173. if (poseData && poseData.orientation) {
  87174. this.rawPose = poseData;
  87175. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  87176. if (this.getScene().useRightHandedSystem) {
  87177. this._deviceRoomRotationQuaternion.z *= -1;
  87178. this._deviceRoomRotationQuaternion.w *= -1;
  87179. }
  87180. if (this.webVROptions.trackPosition && this.rawPose.position) {
  87181. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  87182. if (this.getScene().useRightHandedSystem) {
  87183. this._deviceRoomPosition.z *= -1;
  87184. }
  87185. }
  87186. }
  87187. };
  87188. /**
  87189. * WebVR's attach control will start broadcasting frames to the device.
  87190. * Note that in certain browsers (chrome for example) this function must be called
  87191. * within a user-interaction callback. Example:
  87192. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  87193. *
  87194. * @param element html element to attach the vrDevice to
  87195. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  87196. */
  87197. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  87198. _super.prototype.attachControl.call(this, element, noPreventDefault);
  87199. this._attached = true;
  87200. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  87201. if (this._vrDevice) {
  87202. this.getEngine().enableVR();
  87203. }
  87204. };
  87205. /**
  87206. * Detaches the camera from the html element and disables VR
  87207. *
  87208. * @param element html element to detach from
  87209. */
  87210. WebVRFreeCamera.prototype.detachControl = function (element) {
  87211. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  87212. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  87213. _super.prototype.detachControl.call(this, element);
  87214. this._attached = false;
  87215. this.getEngine().disableVR();
  87216. };
  87217. /**
  87218. * @returns the name of this class
  87219. */
  87220. WebVRFreeCamera.prototype.getClassName = function () {
  87221. return "WebVRFreeCamera";
  87222. };
  87223. /**
  87224. * Calls resetPose on the vrDisplay
  87225. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  87226. */
  87227. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  87228. //uses the vrDisplay's "resetPose()".
  87229. //pitch and roll won't be affected.
  87230. this._vrDevice.resetPose();
  87231. };
  87232. /**
  87233. * Updates the rig cameras (left and right eye)
  87234. */
  87235. WebVRFreeCamera.prototype._updateRigCameras = function () {
  87236. var camLeft = this._rigCameras[0];
  87237. var camRight = this._rigCameras[1];
  87238. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  87239. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  87240. camLeft.position.copyFrom(this._deviceRoomPosition);
  87241. camRight.position.copyFrom(this._deviceRoomPosition);
  87242. };
  87243. /**
  87244. * Updates the cached values of the camera
  87245. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  87246. */
  87247. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  87248. var _this = this;
  87249. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  87250. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  87251. if (!this.updateCacheCalled) {
  87252. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  87253. this.updateCacheCalled = true;
  87254. this.update();
  87255. }
  87256. // Set working vector to the device position in room space rotated by the new rotation
  87257. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  87258. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  87259. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  87260. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  87261. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  87262. // Add translation from anchor position
  87263. this._deviceToWorld.getTranslationToRef(this._workingVector);
  87264. this._workingVector.addInPlace(this.position);
  87265. this._workingVector.subtractInPlace(this._cache.position);
  87266. this._deviceToWorld.setTranslation(this._workingVector);
  87267. // Set an inverted matrix to be used when updating the camera
  87268. this._deviceToWorld.invertToRef(this._worldToDevice);
  87269. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  87270. this.controllers.forEach(function (controller) {
  87271. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  87272. controller.update();
  87273. });
  87274. }
  87275. if (!ignoreParentClass) {
  87276. _super.prototype._updateCache.call(this);
  87277. }
  87278. this.updateCacheCalled = false;
  87279. };
  87280. /**
  87281. * Updates the current device position and rotation in the babylon world
  87282. */
  87283. WebVRFreeCamera.prototype.update = function () {
  87284. // Get current device position in babylon world
  87285. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  87286. // Get current device rotation in babylon world
  87287. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  87288. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  87289. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  87290. _super.prototype.update.call(this);
  87291. };
  87292. /**
  87293. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  87294. * @returns an identity matrix
  87295. */
  87296. WebVRFreeCamera.prototype._getViewMatrix = function () {
  87297. return BABYLON.Matrix.Identity();
  87298. };
  87299. /**
  87300. * This function is called by the two RIG cameras.
  87301. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  87302. */
  87303. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  87304. var _this = this;
  87305. // Update the parent camera prior to using a child camera to avoid desynchronization
  87306. var parentCamera = this._cameraRigParams["parentCamera"];
  87307. parentCamera._updateCache();
  87308. //WebVR 1.1
  87309. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  87310. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  87311. if (!this.getScene().useRightHandedSystem) {
  87312. [2, 6, 8, 9, 14].forEach(function (num) {
  87313. _this._webvrViewMatrix.m[num] *= -1;
  87314. });
  87315. }
  87316. // update the camera rotation matrix
  87317. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  87318. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  87319. // Computing target and final matrix
  87320. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  87321. // should the view matrix be updated with scale and position offset?
  87322. if (parentCamera.deviceScaleFactor !== 1) {
  87323. this._webvrViewMatrix.invert();
  87324. // scale the position, if set
  87325. if (parentCamera.deviceScaleFactor) {
  87326. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  87327. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  87328. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  87329. }
  87330. this._webvrViewMatrix.invert();
  87331. }
  87332. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  87333. // Compute global position
  87334. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  87335. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  87336. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  87337. this._workingMatrix.getTranslationToRef(this._globalPosition);
  87338. this._markSyncedWithParent();
  87339. return this._webvrViewMatrix;
  87340. };
  87341. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  87342. var _this = this;
  87343. var parentCamera = this.parent;
  87344. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  87345. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  87346. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  87347. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  87348. //babylon compatible matrix
  87349. if (!this.getScene().useRightHandedSystem) {
  87350. [8, 9, 10, 11].forEach(function (num) {
  87351. _this._projectionMatrix.m[num] *= -1;
  87352. });
  87353. }
  87354. return this._projectionMatrix;
  87355. };
  87356. /**
  87357. * Initializes the controllers and their meshes
  87358. */
  87359. WebVRFreeCamera.prototype.initControllers = function () {
  87360. var _this = this;
  87361. this.controllers = [];
  87362. var manager = this.getScene().gamepadManager;
  87363. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  87364. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87365. var webVrController = gamepad;
  87366. if (webVrController.defaultModel) {
  87367. webVrController.defaultModel.setEnabled(false);
  87368. }
  87369. if (webVrController.hand === "right") {
  87370. _this._rightController = null;
  87371. }
  87372. if (webVrController.hand === "left") {
  87373. _this._leftController = null;
  87374. }
  87375. var controllerIndex = _this.controllers.indexOf(webVrController);
  87376. if (controllerIndex !== -1) {
  87377. _this.controllers.splice(controllerIndex, 1);
  87378. }
  87379. }
  87380. });
  87381. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  87382. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87383. var webVrController_1 = gamepad;
  87384. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  87385. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  87386. if (_this.webVROptions.controllerMeshes) {
  87387. if (webVrController_1.defaultModel) {
  87388. webVrController_1.defaultModel.setEnabled(true);
  87389. }
  87390. else {
  87391. // Load the meshes
  87392. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  87393. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  87394. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  87395. if (_this.webVROptions.defaultLightingOnControllers) {
  87396. if (!_this._lightOnControllers) {
  87397. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  87398. }
  87399. var activateLightOnSubMeshes_1 = function (mesh, light) {
  87400. var children = mesh.getChildren();
  87401. if (children.length !== 0) {
  87402. children.forEach(function (mesh) {
  87403. light.includedOnlyMeshes.push(mesh);
  87404. activateLightOnSubMeshes_1(mesh, light);
  87405. });
  87406. }
  87407. };
  87408. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  87409. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  87410. }
  87411. });
  87412. }
  87413. }
  87414. webVrController_1.attachToPoseControlledCamera(_this);
  87415. // since this is async - sanity check. Is the controller already stored?
  87416. if (_this.controllers.indexOf(webVrController_1) === -1) {
  87417. //add to the controllers array
  87418. _this.controllers.push(webVrController_1);
  87419. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  87420. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  87421. // So we're overriding setting left & right manually to be sure
  87422. var firstViveWandDetected = false;
  87423. for (var i = 0; i < _this.controllers.length; i++) {
  87424. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  87425. if (!firstViveWandDetected) {
  87426. firstViveWandDetected = true;
  87427. _this.controllers[i].hand = "left";
  87428. }
  87429. else {
  87430. _this.controllers[i].hand = "right";
  87431. }
  87432. }
  87433. }
  87434. //did we find enough controllers? Great! let the developer know.
  87435. if (_this.controllers.length >= 2) {
  87436. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  87437. }
  87438. }
  87439. }
  87440. });
  87441. };
  87442. return WebVRFreeCamera;
  87443. }(BABYLON.FreeCamera));
  87444. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  87445. })(BABYLON || (BABYLON = {}));
  87446. //# sourceMappingURL=babylon.webVRCamera.js.map
  87447. var BABYLON;
  87448. (function (BABYLON) {
  87449. // We're mainly based on the logic defined into the FreeCamera code
  87450. /**
  87451. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  87452. * being tilted forward or back and left or right.
  87453. */
  87454. var DeviceOrientationCamera = /** @class */ (function (_super) {
  87455. __extends(DeviceOrientationCamera, _super);
  87456. /**
  87457. * Creates a new device orientation camera
  87458. * @param name The name of the camera
  87459. * @param position The start position camera
  87460. * @param scene The scene the camera belongs to
  87461. */
  87462. function DeviceOrientationCamera(name, position, scene) {
  87463. var _this = _super.call(this, name, position, scene) || this;
  87464. _this._quaternionCache = new BABYLON.Quaternion();
  87465. _this.inputs.addDeviceOrientation();
  87466. return _this;
  87467. }
  87468. /**
  87469. * Gets the current instance class name ("DeviceOrientationCamera").
  87470. * This helps avoiding instanceof at run time.
  87471. * @returns the class name
  87472. */
  87473. DeviceOrientationCamera.prototype.getClassName = function () {
  87474. return "DeviceOrientationCamera";
  87475. };
  87476. /**
  87477. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  87478. */
  87479. DeviceOrientationCamera.prototype._checkInputs = function () {
  87480. _super.prototype._checkInputs.call(this);
  87481. this._quaternionCache.copyFrom(this.rotationQuaternion);
  87482. if (this._initialQuaternion) {
  87483. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87484. }
  87485. };
  87486. /**
  87487. * Reset the camera to its default orientation on the specified axis only.
  87488. * @param axis The axis to reset
  87489. */
  87490. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  87491. var _this = this;
  87492. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  87493. //can only work if this camera has a rotation quaternion already.
  87494. if (!this.rotationQuaternion)
  87495. return;
  87496. if (!this._initialQuaternion) {
  87497. this._initialQuaternion = new BABYLON.Quaternion();
  87498. }
  87499. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  87500. ['x', 'y', 'z'].forEach(function (axisName) {
  87501. if (!axis[axisName]) {
  87502. _this._initialQuaternion[axisName] = 0;
  87503. }
  87504. else {
  87505. _this._initialQuaternion[axisName] *= -1;
  87506. }
  87507. });
  87508. this._initialQuaternion.normalize();
  87509. //force rotation update
  87510. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87511. };
  87512. return DeviceOrientationCamera;
  87513. }(BABYLON.FreeCamera));
  87514. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  87515. })(BABYLON || (BABYLON = {}));
  87516. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  87517. var BABYLON;
  87518. (function (BABYLON) {
  87519. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  87520. __extends(VRDeviceOrientationFreeCamera, _super);
  87521. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87522. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87523. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87524. var _this = _super.call(this, name, position, scene) || this;
  87525. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87526. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87527. return _this;
  87528. }
  87529. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  87530. return "VRDeviceOrientationFreeCamera";
  87531. };
  87532. return VRDeviceOrientationFreeCamera;
  87533. }(BABYLON.DeviceOrientationCamera));
  87534. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  87535. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  87536. __extends(VRDeviceOrientationGamepadCamera, _super);
  87537. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87538. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87539. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87540. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  87541. _this.inputs.addGamepad();
  87542. return _this;
  87543. }
  87544. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  87545. return "VRDeviceOrientationGamepadCamera";
  87546. };
  87547. return VRDeviceOrientationGamepadCamera;
  87548. }(VRDeviceOrientationFreeCamera));
  87549. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  87550. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  87551. __extends(VRDeviceOrientationArcRotateCamera, _super);
  87552. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  87553. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87554. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87555. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87556. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87557. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87558. _this.inputs.addVRDeviceOrientation();
  87559. return _this;
  87560. }
  87561. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  87562. return "VRDeviceOrientationArcRotateCamera";
  87563. };
  87564. return VRDeviceOrientationArcRotateCamera;
  87565. }(BABYLON.ArcRotateCamera));
  87566. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  87567. })(BABYLON || (BABYLON = {}));
  87568. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  87569. var BABYLON;
  87570. (function (BABYLON) {
  87571. /**
  87572. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  87573. */
  87574. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  87575. __extends(AnaglyphFreeCamera, _super);
  87576. /**
  87577. * Creates a new AnaglyphFreeCamera
  87578. * @param name defines camera name
  87579. * @param position defines initial position
  87580. * @param interaxialDistance defines distance between each color axis
  87581. * @param scene defines the hosting scene
  87582. */
  87583. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  87584. var _this = _super.call(this, name, position, scene) || this;
  87585. _this.interaxialDistance = interaxialDistance;
  87586. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87587. return _this;
  87588. }
  87589. /**
  87590. * Gets camera class name
  87591. * @returns AnaglyphFreeCamera
  87592. */
  87593. AnaglyphFreeCamera.prototype.getClassName = function () {
  87594. return "AnaglyphFreeCamera";
  87595. };
  87596. return AnaglyphFreeCamera;
  87597. }(BABYLON.FreeCamera));
  87598. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  87599. /**
  87600. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  87601. */
  87602. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  87603. __extends(AnaglyphArcRotateCamera, _super);
  87604. /**
  87605. * Creates a new AnaglyphArcRotateCamera
  87606. * @param name defines camera name
  87607. * @param alpha defines alpha angle (in radians)
  87608. * @param beta defines beta angle (in radians)
  87609. * @param radius defines radius
  87610. * @param target defines camera target
  87611. * @param interaxialDistance defines distance between each color axis
  87612. * @param scene defines the hosting scene
  87613. */
  87614. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  87615. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87616. _this.interaxialDistance = interaxialDistance;
  87617. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87618. return _this;
  87619. }
  87620. /**
  87621. * Gets camera class name
  87622. * @returns AnaglyphArcRotateCamera
  87623. */
  87624. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87625. return "AnaglyphArcRotateCamera";
  87626. };
  87627. return AnaglyphArcRotateCamera;
  87628. }(BABYLON.ArcRotateCamera));
  87629. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87630. /**
  87631. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87632. */
  87633. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87634. __extends(AnaglyphGamepadCamera, _super);
  87635. /**
  87636. * Creates a new AnaglyphGamepadCamera
  87637. * @param name defines camera name
  87638. * @param position defines initial position
  87639. * @param interaxialDistance defines distance between each color axis
  87640. * @param scene defines the hosting scene
  87641. */
  87642. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  87643. var _this = _super.call(this, name, position, scene) || this;
  87644. _this.interaxialDistance = interaxialDistance;
  87645. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87646. return _this;
  87647. }
  87648. /**
  87649. * Gets camera class name
  87650. * @returns AnaglyphGamepadCamera
  87651. */
  87652. AnaglyphGamepadCamera.prototype.getClassName = function () {
  87653. return "AnaglyphGamepadCamera";
  87654. };
  87655. return AnaglyphGamepadCamera;
  87656. }(BABYLON.GamepadCamera));
  87657. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  87658. /**
  87659. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  87660. */
  87661. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  87662. __extends(AnaglyphUniversalCamera, _super);
  87663. /**
  87664. * Creates a new AnaglyphUniversalCamera
  87665. * @param name defines camera name
  87666. * @param position defines initial position
  87667. * @param interaxialDistance defines distance between each color axis
  87668. * @param scene defines the hosting scene
  87669. */
  87670. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  87671. var _this = _super.call(this, name, position, scene) || this;
  87672. _this.interaxialDistance = interaxialDistance;
  87673. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87674. return _this;
  87675. }
  87676. /**
  87677. * Gets camera class name
  87678. * @returns AnaglyphUniversalCamera
  87679. */
  87680. AnaglyphUniversalCamera.prototype.getClassName = function () {
  87681. return "AnaglyphUniversalCamera";
  87682. };
  87683. return AnaglyphUniversalCamera;
  87684. }(BABYLON.UniversalCamera));
  87685. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  87686. /**
  87687. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  87688. */
  87689. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  87690. __extends(StereoscopicFreeCamera, _super);
  87691. /**
  87692. * Creates a new StereoscopicFreeCamera
  87693. * @param name defines camera name
  87694. * @param position defines initial position
  87695. * @param interaxialDistance defines distance between each color axis
  87696. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87697. * @param scene defines the hosting scene
  87698. */
  87699. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87700. var _this = _super.call(this, name, position, scene) || this;
  87701. _this.interaxialDistance = interaxialDistance;
  87702. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87703. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87704. return _this;
  87705. }
  87706. /**
  87707. * Gets camera class name
  87708. * @returns StereoscopicFreeCamera
  87709. */
  87710. StereoscopicFreeCamera.prototype.getClassName = function () {
  87711. return "StereoscopicFreeCamera";
  87712. };
  87713. return StereoscopicFreeCamera;
  87714. }(BABYLON.FreeCamera));
  87715. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  87716. /**
  87717. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  87718. */
  87719. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  87720. __extends(StereoscopicArcRotateCamera, _super);
  87721. /**
  87722. * Creates a new StereoscopicArcRotateCamera
  87723. * @param name defines camera name
  87724. * @param alpha defines alpha angle (in radians)
  87725. * @param beta defines beta angle (in radians)
  87726. * @param radius defines radius
  87727. * @param target defines camera target
  87728. * @param interaxialDistance defines distance between each color axis
  87729. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87730. * @param scene defines the hosting scene
  87731. */
  87732. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  87733. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87734. _this.interaxialDistance = interaxialDistance;
  87735. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87736. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87737. return _this;
  87738. }
  87739. /**
  87740. * Gets camera class name
  87741. * @returns StereoscopicArcRotateCamera
  87742. */
  87743. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  87744. return "StereoscopicArcRotateCamera";
  87745. };
  87746. return StereoscopicArcRotateCamera;
  87747. }(BABYLON.ArcRotateCamera));
  87748. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  87749. /**
  87750. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  87751. */
  87752. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  87753. __extends(StereoscopicGamepadCamera, _super);
  87754. /**
  87755. * Creates a new StereoscopicGamepadCamera
  87756. * @param name defines camera name
  87757. * @param position defines initial position
  87758. * @param interaxialDistance defines distance between each color axis
  87759. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87760. * @param scene defines the hosting scene
  87761. */
  87762. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87763. var _this = _super.call(this, name, position, scene) || this;
  87764. _this.interaxialDistance = interaxialDistance;
  87765. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87766. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87767. return _this;
  87768. }
  87769. /**
  87770. * Gets camera class name
  87771. * @returns StereoscopicGamepadCamera
  87772. */
  87773. StereoscopicGamepadCamera.prototype.getClassName = function () {
  87774. return "StereoscopicGamepadCamera";
  87775. };
  87776. return StereoscopicGamepadCamera;
  87777. }(BABYLON.GamepadCamera));
  87778. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  87779. /**
  87780. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  87781. */
  87782. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  87783. __extends(StereoscopicUniversalCamera, _super);
  87784. /**
  87785. * Creates a new StereoscopicUniversalCamera
  87786. * @param name defines camera name
  87787. * @param position defines initial position
  87788. * @param interaxialDistance defines distance between each color axis
  87789. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87790. * @param scene defines the hosting scene
  87791. */
  87792. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87793. var _this = _super.call(this, name, position, scene) || this;
  87794. _this.interaxialDistance = interaxialDistance;
  87795. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87796. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87797. return _this;
  87798. }
  87799. /**
  87800. * Gets camera class name
  87801. * @returns StereoscopicUniversalCamera
  87802. */
  87803. StereoscopicUniversalCamera.prototype.getClassName = function () {
  87804. return "StereoscopicUniversalCamera";
  87805. };
  87806. return StereoscopicUniversalCamera;
  87807. }(BABYLON.UniversalCamera));
  87808. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  87809. })(BABYLON || (BABYLON = {}));
  87810. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  87811. var BABYLON;
  87812. (function (BABYLON) {
  87813. var VRExperienceHelperGazer = /** @class */ (function () {
  87814. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  87815. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  87816. this.scene = scene;
  87817. this._pointerDownOnMeshAsked = false;
  87818. this._isActionableMesh = false;
  87819. this._teleportationRequestInitiated = false;
  87820. this._teleportationBackRequestInitiated = false;
  87821. this._rotationRightAsked = false;
  87822. this._rotationLeftAsked = false;
  87823. this._dpadPressed = true;
  87824. this._activePointer = false;
  87825. this._id = VRExperienceHelperGazer._idCounter++;
  87826. // Gaze tracker
  87827. if (!gazeTrackerToClone) {
  87828. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  87829. this._gazeTracker.bakeCurrentTransformIntoVertices();
  87830. this._gazeTracker.isPickable = false;
  87831. this._gazeTracker.isVisible = false;
  87832. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  87833. targetMat.specularColor = BABYLON.Color3.Black();
  87834. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87835. targetMat.backFaceCulling = false;
  87836. this._gazeTracker.material = targetMat;
  87837. }
  87838. else {
  87839. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  87840. }
  87841. }
  87842. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  87843. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  87844. };
  87845. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  87846. this._pointerDownOnMeshAsked = true;
  87847. if (this._currentMeshSelected && this._currentHit) {
  87848. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  87849. }
  87850. };
  87851. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  87852. if (this._currentMeshSelected && this._currentHit) {
  87853. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  87854. }
  87855. this._pointerDownOnMeshAsked = false;
  87856. };
  87857. VRExperienceHelperGazer.prototype._activatePointer = function () {
  87858. this._activePointer = true;
  87859. };
  87860. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  87861. this._activePointer = false;
  87862. };
  87863. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  87864. if (distance === void 0) { distance = 100; }
  87865. };
  87866. VRExperienceHelperGazer.prototype.dispose = function () {
  87867. this._interactionsEnabled = false;
  87868. this._teleportationEnabled = false;
  87869. if (this._gazeTracker) {
  87870. this._gazeTracker.dispose();
  87871. }
  87872. };
  87873. VRExperienceHelperGazer._idCounter = 0;
  87874. return VRExperienceHelperGazer;
  87875. }());
  87876. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  87877. __extends(VRExperienceHelperControllerGazer, _super);
  87878. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  87879. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  87880. _this.webVRController = webVRController;
  87881. // Laser pointer
  87882. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  87883. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  87884. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87885. laserPointerMaterial.alpha = 0.6;
  87886. _this._laserPointer.material = laserPointerMaterial;
  87887. _this._laserPointer.rotation.x = Math.PI / 2;
  87888. _this._laserPointer.position.z = -0.5;
  87889. _this._laserPointer.isVisible = false;
  87890. if (!webVRController.mesh) {
  87891. // Create an empty mesh that is used prior to loading the high quality model
  87892. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  87893. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  87894. preloadPointerPose.rotation.x = -0.7;
  87895. preloadMesh.addChild(preloadPointerPose);
  87896. webVRController.attachToMesh(preloadMesh);
  87897. }
  87898. _this._setLaserPointerParent(webVRController.mesh);
  87899. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  87900. _this._setLaserPointerParent(mesh);
  87901. });
  87902. return _this;
  87903. }
  87904. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  87905. return this.webVRController.getForwardRay(length);
  87906. };
  87907. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  87908. _super.prototype._activatePointer.call(this);
  87909. this._laserPointer.isVisible = true;
  87910. };
  87911. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  87912. _super.prototype._deactivatePointer.call(this);
  87913. this._laserPointer.isVisible = false;
  87914. };
  87915. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  87916. this._laserPointer.material.emissiveColor = color;
  87917. };
  87918. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  87919. var makeNotPick = function (root) {
  87920. root.name += " laserPointer";
  87921. root.getChildMeshes().forEach(function (c) {
  87922. makeNotPick(c);
  87923. });
  87924. };
  87925. makeNotPick(mesh);
  87926. var childMeshes = mesh.getChildMeshes();
  87927. this.webVRController._pointingPoseNode = null;
  87928. for (var i = 0; i < childMeshes.length; i++) {
  87929. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  87930. mesh = childMeshes[i];
  87931. this.webVRController._pointingPoseNode = mesh;
  87932. break;
  87933. }
  87934. }
  87935. this._laserPointer.parent = mesh;
  87936. };
  87937. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  87938. if (distance === void 0) { distance = 100; }
  87939. this._laserPointer.scaling.y = distance;
  87940. this._laserPointer.position.z = -distance / 2;
  87941. };
  87942. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  87943. _super.prototype.dispose.call(this);
  87944. this._laserPointer.dispose();
  87945. if (this._meshAttachedObserver) {
  87946. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  87947. }
  87948. };
  87949. return VRExperienceHelperControllerGazer;
  87950. }(VRExperienceHelperGazer));
  87951. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  87952. __extends(VRExperienceHelperCameraGazer, _super);
  87953. function VRExperienceHelperCameraGazer(getCamera, scene) {
  87954. var _this = _super.call(this, scene) || this;
  87955. _this.getCamera = getCamera;
  87956. return _this;
  87957. }
  87958. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  87959. var camera = this.getCamera();
  87960. if (camera) {
  87961. return camera.getForwardRay(length);
  87962. }
  87963. else {
  87964. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  87965. }
  87966. };
  87967. return VRExperienceHelperCameraGazer;
  87968. }(VRExperienceHelperGazer));
  87969. /**
  87970. * Helps to quickly add VR support to an existing scene.
  87971. * See http://doc.babylonjs.com/how_to/webvr_helper
  87972. */
  87973. var VRExperienceHelper = /** @class */ (function () {
  87974. /**
  87975. * Instantiates a VRExperienceHelper.
  87976. * Helps to quickly add VR support to an existing scene.
  87977. * @param scene The scene the VRExperienceHelper belongs to.
  87978. * @param webVROptions Options to modify the vr experience helper's behavior.
  87979. */
  87980. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  87981. if (webVROptions === void 0) { webVROptions = {}; }
  87982. var _this = this;
  87983. this.webVROptions = webVROptions;
  87984. // Can the system support WebVR, even if a headset isn't plugged in?
  87985. this._webVRsupported = false;
  87986. // If WebVR is supported, is a headset plugged in and are we ready to present?
  87987. this._webVRready = false;
  87988. // Are we waiting for the requestPresent callback to complete?
  87989. this._webVRrequesting = false;
  87990. // Are we presenting to the headset right now?
  87991. this._webVRpresenting = false;
  87992. // Are we presenting in the fullscreen fallback?
  87993. this._fullscreenVRpresenting = false;
  87994. /**
  87995. * Observable raised when entering VR.
  87996. */
  87997. this.onEnteringVRObservable = new BABYLON.Observable();
  87998. /**
  87999. * Observable raised when exiting VR.
  88000. */
  88001. this.onExitingVRObservable = new BABYLON.Observable();
  88002. /**
  88003. * Observable raised when controller mesh is loaded.
  88004. */
  88005. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  88006. this._useCustomVRButton = false;
  88007. this._teleportationRequested = false;
  88008. this._teleportActive = false;
  88009. this._floorMeshesCollection = [];
  88010. this._rotationAllowed = true;
  88011. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  88012. this._isDefaultTeleportationTarget = true;
  88013. this._teleportationFillColor = "#444444";
  88014. this._teleportationBorderColor = "#FFFFFF";
  88015. this._rotationAngle = 0;
  88016. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  88017. this._padSensibilityUp = 0.65;
  88018. this._padSensibilityDown = 0.35;
  88019. this.leftController = null;
  88020. this.rightController = null;
  88021. /**
  88022. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  88023. */
  88024. this.onNewMeshSelected = new BABYLON.Observable();
  88025. /**
  88026. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  88027. */
  88028. this.onNewMeshPicked = new BABYLON.Observable();
  88029. /**
  88030. * Observable raised before camera teleportation
  88031. */
  88032. this.onBeforeCameraTeleport = new BABYLON.Observable();
  88033. /**
  88034. * Observable raised after camera teleportation
  88035. */
  88036. this.onAfterCameraTeleport = new BABYLON.Observable();
  88037. /**
  88038. * Observable raised when current selected mesh gets unselected
  88039. */
  88040. this.onSelectedMeshUnselected = new BABYLON.Observable();
  88041. /**
  88042. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  88043. */
  88044. this.teleportationEnabled = true;
  88045. this._teleportationInitialized = false;
  88046. this._interactionsEnabled = false;
  88047. this._interactionsRequested = false;
  88048. this._displayGaze = true;
  88049. this._displayLaserPointer = true;
  88050. this._onResize = function () {
  88051. _this.moveButtonToBottomRight();
  88052. if (_this._fullscreenVRpresenting && _this._webVRready) {
  88053. _this.exitVR();
  88054. }
  88055. };
  88056. this._onFullscreenChange = function () {
  88057. if (document.fullscreen !== undefined) {
  88058. _this._fullscreenVRpresenting = document.fullscreen;
  88059. }
  88060. else if (document.mozFullScreen !== undefined) {
  88061. _this._fullscreenVRpresenting = document.mozFullScreen;
  88062. }
  88063. else if (document.webkitIsFullScreen !== undefined) {
  88064. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  88065. }
  88066. else if (document.msIsFullScreen !== undefined) {
  88067. _this._fullscreenVRpresenting = document.msIsFullScreen;
  88068. }
  88069. if (!_this._fullscreenVRpresenting && _this._canvas) {
  88070. _this.exitVR();
  88071. if (!_this._useCustomVRButton) {
  88072. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  88073. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  88074. }
  88075. }
  88076. };
  88077. this.beforeRender = function () {
  88078. if (_this.leftController && _this.leftController._activePointer) {
  88079. _this._castRayAndSelectObject(_this.leftController);
  88080. }
  88081. if (_this.rightController && _this.rightController._activePointer) {
  88082. _this._castRayAndSelectObject(_this.rightController);
  88083. }
  88084. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  88085. _this._castRayAndSelectObject(_this._cameraGazer);
  88086. }
  88087. else {
  88088. _this._cameraGazer._gazeTracker.isVisible = false;
  88089. }
  88090. };
  88091. this._onNewGamepadConnected = function (gamepad) {
  88092. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  88093. if (gamepad.leftStick) {
  88094. gamepad.onleftstickchanged(function (stickValues) {
  88095. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  88096. // Listening to classic/xbox gamepad only if no VR controller is active
  88097. if ((!_this.leftController && !_this.rightController) ||
  88098. ((_this.leftController && !_this.leftController._activePointer) &&
  88099. (_this.rightController && !_this.rightController._activePointer))) {
  88100. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  88101. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  88102. }
  88103. }
  88104. });
  88105. }
  88106. if (gamepad.rightStick) {
  88107. gamepad.onrightstickchanged(function (stickValues) {
  88108. if (_this._teleportationInitialized) {
  88109. _this._checkRotate(stickValues, _this._cameraGazer);
  88110. }
  88111. });
  88112. }
  88113. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  88114. gamepad.onbuttondown(function (buttonPressed) {
  88115. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  88116. _this._cameraGazer._selectionPointerDown();
  88117. }
  88118. });
  88119. gamepad.onbuttonup(function (buttonPressed) {
  88120. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  88121. _this._cameraGazer._selectionPointerUp();
  88122. }
  88123. });
  88124. }
  88125. }
  88126. else {
  88127. var webVRController = gamepad;
  88128. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  88129. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  88130. _this.rightController = controller;
  88131. }
  88132. else {
  88133. _this.leftController = controller;
  88134. }
  88135. _this._tryEnableInteractionOnController(controller);
  88136. }
  88137. };
  88138. // 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
  88139. this._tryEnableInteractionOnController = function (controller) {
  88140. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  88141. _this._enableInteractionOnController(controller);
  88142. }
  88143. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  88144. _this._enableTeleportationOnController(controller);
  88145. }
  88146. };
  88147. this._onNewGamepadDisconnected = function (gamepad) {
  88148. if (gamepad instanceof BABYLON.WebVRController) {
  88149. if (gamepad.hand === "left" && _this.leftController != null) {
  88150. _this.leftController.dispose();
  88151. _this.leftController = null;
  88152. }
  88153. if (gamepad.hand === "right" && _this.rightController != null) {
  88154. _this.rightController.dispose();
  88155. _this.rightController = null;
  88156. }
  88157. }
  88158. };
  88159. this._workingVector = BABYLON.Vector3.Zero();
  88160. this._workingQuaternion = BABYLON.Quaternion.Identity();
  88161. this._workingMatrix = BABYLON.Matrix.Identity();
  88162. this._scene = scene;
  88163. this._canvas = scene.getEngine().getRenderingCanvas();
  88164. // Parse options
  88165. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  88166. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  88167. }
  88168. if (webVROptions.createDeviceOrientationCamera === undefined) {
  88169. webVROptions.createDeviceOrientationCamera = true;
  88170. }
  88171. if (webVROptions.laserToggle === undefined) {
  88172. webVROptions.laserToggle = true;
  88173. }
  88174. if (webVROptions.defaultHeight === undefined) {
  88175. webVROptions.defaultHeight = 1.7;
  88176. }
  88177. if (webVROptions.useCustomVRButton) {
  88178. this._useCustomVRButton = true;
  88179. if (webVROptions.customVRButton) {
  88180. this._btnVR = webVROptions.customVRButton;
  88181. }
  88182. }
  88183. if (webVROptions.rayLength) {
  88184. this._rayLength = webVROptions.rayLength;
  88185. }
  88186. this._defaultHeight = webVROptions.defaultHeight;
  88187. if (webVROptions.positionScale) {
  88188. this._rayLength *= webVROptions.positionScale;
  88189. this._defaultHeight *= webVROptions.positionScale;
  88190. }
  88191. // Set position
  88192. if (this._scene.activeCamera) {
  88193. this._position = this._scene.activeCamera.position.clone();
  88194. }
  88195. else {
  88196. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  88197. }
  88198. // Set non-vr camera
  88199. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  88200. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  88201. // Copy data from existing camera
  88202. if (this._scene.activeCamera) {
  88203. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88204. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  88205. // Set rotation from previous camera
  88206. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  88207. var targetCamera = this._scene.activeCamera;
  88208. if (targetCamera.rotationQuaternion) {
  88209. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  88210. }
  88211. else {
  88212. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  88213. }
  88214. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  88215. }
  88216. }
  88217. this._scene.activeCamera = this._deviceOrientationCamera;
  88218. if (this._canvas) {
  88219. this._scene.activeCamera.attachControl(this._canvas);
  88220. }
  88221. }
  88222. else {
  88223. this._existingCamera = this._scene.activeCamera;
  88224. }
  88225. // Create VR cameras
  88226. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  88227. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  88228. }
  88229. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  88230. this._webVRCamera.useStandingMatrix();
  88231. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  88232. // Create default button
  88233. if (!this._useCustomVRButton) {
  88234. this._btnVR = document.createElement("BUTTON");
  88235. this._btnVR.className = "babylonVRicon";
  88236. this._btnVR.id = "babylonVRiconbtn";
  88237. this._btnVR.title = "Click to switch to VR";
  88238. 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) }";
  88239. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  88240. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  88241. // css += ".babylonVRicon.vrdisplaysupported { }";
  88242. // css += ".babylonVRicon.vrdisplayready { }";
  88243. // css += ".babylonVRicon.vrdisplayrequesting { }";
  88244. var style = document.createElement('style');
  88245. style.appendChild(document.createTextNode(css));
  88246. document.getElementsByTagName('head')[0].appendChild(style);
  88247. this.moveButtonToBottomRight();
  88248. }
  88249. // VR button click event
  88250. if (this._btnVR) {
  88251. this._btnVR.addEventListener("click", function () {
  88252. if (!_this.isInVRMode) {
  88253. _this.enterVR();
  88254. }
  88255. else {
  88256. _this.exitVR();
  88257. }
  88258. });
  88259. }
  88260. // Window events
  88261. window.addEventListener("resize", this._onResize);
  88262. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  88263. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  88264. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  88265. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  88266. // Display vr button when headset is connected
  88267. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  88268. this.displayVRButton();
  88269. }
  88270. else {
  88271. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  88272. if (e.vrDisplay) {
  88273. _this.displayVRButton();
  88274. }
  88275. });
  88276. }
  88277. // Exiting VR mode using 'ESC' key on desktop
  88278. this._onKeyDown = function (event) {
  88279. if (event.keyCode === 27 && _this.isInVRMode) {
  88280. _this.exitVR();
  88281. }
  88282. };
  88283. document.addEventListener("keydown", this._onKeyDown);
  88284. // Exiting VR mode double tapping the touch screen
  88285. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  88286. if (_this.isInVRMode) {
  88287. _this.exitVR();
  88288. if (_this._fullscreenVRpresenting) {
  88289. _this._scene.getEngine().switchFullscreen(true);
  88290. }
  88291. }
  88292. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  88293. // Listen for WebVR display changes
  88294. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  88295. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  88296. this._onVRRequestPresentStart = function () {
  88297. _this._webVRrequesting = true;
  88298. _this.updateButtonVisibility();
  88299. };
  88300. this._onVRRequestPresentComplete = function (success) {
  88301. _this._webVRrequesting = false;
  88302. _this.updateButtonVisibility();
  88303. };
  88304. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  88305. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  88306. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  88307. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88308. scene.onDisposeObservable.add(function () {
  88309. _this.dispose();
  88310. });
  88311. // Gamepad connection events
  88312. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  88313. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  88314. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  88315. this.updateButtonVisibility();
  88316. //create easing functions
  88317. this._circleEase = new BABYLON.CircleEase();
  88318. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88319. if (this.webVROptions.floorMeshes) {
  88320. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  88321. }
  88322. }
  88323. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  88324. /** Return this.onEnteringVRObservable
  88325. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  88326. */
  88327. get: function () {
  88328. return this.onEnteringVRObservable;
  88329. },
  88330. enumerable: true,
  88331. configurable: true
  88332. });
  88333. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  88334. /** Return this.onExitingVRObservable
  88335. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  88336. */
  88337. get: function () {
  88338. return this.onExitingVRObservable;
  88339. },
  88340. enumerable: true,
  88341. configurable: true
  88342. });
  88343. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  88344. /** Return this.onControllerMeshLoadedObservable
  88345. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  88346. */
  88347. get: function () {
  88348. return this.onControllerMeshLoadedObservable;
  88349. },
  88350. enumerable: true,
  88351. configurable: true
  88352. });
  88353. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  88354. /**
  88355. * The mesh used to display where the user is going to teleport.
  88356. */
  88357. get: function () {
  88358. return this._teleportationTarget;
  88359. },
  88360. /**
  88361. * Sets the mesh to be used to display where the user is going to teleport.
  88362. */
  88363. set: function (value) {
  88364. if (value) {
  88365. value.name = "teleportationTarget";
  88366. this._isDefaultTeleportationTarget = false;
  88367. this._teleportationTarget = value;
  88368. }
  88369. },
  88370. enumerable: true,
  88371. configurable: true
  88372. });
  88373. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  88374. /**
  88375. * The mesh used to display where the user is selecting,
  88376. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  88377. * See http://doc.babylonjs.com/resources/baking_transformations
  88378. */
  88379. get: function () {
  88380. return this._cameraGazer._gazeTracker;
  88381. },
  88382. set: function (value) {
  88383. if (value) {
  88384. this._cameraGazer._gazeTracker = value;
  88385. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  88386. this._cameraGazer._gazeTracker.isPickable = false;
  88387. this._cameraGazer._gazeTracker.isVisible = false;
  88388. this._cameraGazer._gazeTracker.name = "gazeTracker";
  88389. if (this.leftController) {
  88390. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88391. }
  88392. if (this.rightController) {
  88393. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88394. }
  88395. }
  88396. },
  88397. enumerable: true,
  88398. configurable: true
  88399. });
  88400. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  88401. /**
  88402. * If the ray of the gaze should be displayed.
  88403. */
  88404. get: function () {
  88405. return this._displayGaze;
  88406. },
  88407. /**
  88408. * Sets if the ray of the gaze should be displayed.
  88409. */
  88410. set: function (value) {
  88411. this._displayGaze = value;
  88412. if (!value) {
  88413. this._cameraGazer._gazeTracker.isVisible = false;
  88414. if (this.leftController) {
  88415. this.leftController._gazeTracker.isVisible = false;
  88416. }
  88417. if (this.rightController) {
  88418. this.rightController._gazeTracker.isVisible = false;
  88419. }
  88420. }
  88421. },
  88422. enumerable: true,
  88423. configurable: true
  88424. });
  88425. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  88426. /**
  88427. * If the ray of the LaserPointer should be displayed.
  88428. */
  88429. get: function () {
  88430. return this._displayLaserPointer;
  88431. },
  88432. /**
  88433. * Sets if the ray of the LaserPointer should be displayed.
  88434. */
  88435. set: function (value) {
  88436. this._displayLaserPointer = value;
  88437. if (!value) {
  88438. if (this.rightController) {
  88439. this.rightController._deactivatePointer();
  88440. this.rightController._gazeTracker.isVisible = false;
  88441. }
  88442. if (this.leftController) {
  88443. this.leftController._deactivatePointer();
  88444. this.leftController._gazeTracker.isVisible = false;
  88445. }
  88446. }
  88447. else {
  88448. if (this.rightController) {
  88449. this.rightController._activatePointer();
  88450. }
  88451. if (this.leftController) {
  88452. this.leftController._activatePointer();
  88453. }
  88454. }
  88455. },
  88456. enumerable: true,
  88457. configurable: true
  88458. });
  88459. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  88460. /**
  88461. * The deviceOrientationCamera used as the camera when not in VR.
  88462. */
  88463. get: function () {
  88464. return this._deviceOrientationCamera;
  88465. },
  88466. enumerable: true,
  88467. configurable: true
  88468. });
  88469. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  88470. /**
  88471. * Based on the current WebVR support, returns the current VR camera used.
  88472. */
  88473. get: function () {
  88474. if (this._webVRready) {
  88475. return this._webVRCamera;
  88476. }
  88477. else {
  88478. return this._scene.activeCamera;
  88479. }
  88480. },
  88481. enumerable: true,
  88482. configurable: true
  88483. });
  88484. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  88485. /**
  88486. * The webVRCamera which is used when in VR.
  88487. */
  88488. get: function () {
  88489. return this._webVRCamera;
  88490. },
  88491. enumerable: true,
  88492. configurable: true
  88493. });
  88494. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  88495. /**
  88496. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  88497. */
  88498. get: function () {
  88499. return this._vrDeviceOrientationCamera;
  88500. },
  88501. enumerable: true,
  88502. configurable: true
  88503. });
  88504. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  88505. get: function () {
  88506. var result = this._cameraGazer._teleportationRequestInitiated
  88507. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  88508. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  88509. return result;
  88510. },
  88511. enumerable: true,
  88512. configurable: true
  88513. });
  88514. // Raised when one of the controller has loaded successfully its associated default mesh
  88515. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  88516. if (this.leftController && this.leftController.webVRController == webVRController) {
  88517. if (webVRController.mesh) {
  88518. this.leftController._setLaserPointerParent(webVRController.mesh);
  88519. }
  88520. }
  88521. if (this.rightController && this.rightController.webVRController == webVRController) {
  88522. if (webVRController.mesh) {
  88523. this.rightController._setLaserPointerParent(webVRController.mesh);
  88524. }
  88525. }
  88526. try {
  88527. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  88528. }
  88529. catch (err) {
  88530. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  88531. }
  88532. };
  88533. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  88534. /**
  88535. * Gets a value indicating if we are currently in VR mode.
  88536. */
  88537. get: function () {
  88538. return this._webVRpresenting || this._fullscreenVRpresenting;
  88539. },
  88540. enumerable: true,
  88541. configurable: true
  88542. });
  88543. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  88544. var vrDisplay = this._scene.getEngine().getVRDevice();
  88545. if (vrDisplay) {
  88546. var wasPresenting = this._webVRpresenting;
  88547. // A VR display is connected
  88548. this._webVRpresenting = vrDisplay.isPresenting;
  88549. if (wasPresenting && !this._webVRpresenting)
  88550. this.exitVR();
  88551. }
  88552. else {
  88553. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  88554. }
  88555. this.updateButtonVisibility();
  88556. };
  88557. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  88558. this._webVRsupported = eventArgs.vrSupported;
  88559. this._webVRready = !!eventArgs.vrDisplay;
  88560. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  88561. this.updateButtonVisibility();
  88562. };
  88563. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  88564. if (this._canvas && !this._useCustomVRButton) {
  88565. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  88566. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  88567. }
  88568. };
  88569. VRExperienceHelper.prototype.displayVRButton = function () {
  88570. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  88571. document.body.appendChild(this._btnVR);
  88572. this._btnVRDisplayed = true;
  88573. }
  88574. };
  88575. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  88576. if (!this._btnVR || this._useCustomVRButton) {
  88577. return;
  88578. }
  88579. this._btnVR.className = "babylonVRicon";
  88580. if (this.isInVRMode) {
  88581. this._btnVR.className += " vrdisplaypresenting";
  88582. }
  88583. else {
  88584. if (this._webVRready)
  88585. this._btnVR.className += " vrdisplayready";
  88586. if (this._webVRsupported)
  88587. this._btnVR.className += " vrdisplaysupported";
  88588. if (this._webVRrequesting)
  88589. this._btnVR.className += " vrdisplayrequesting";
  88590. }
  88591. };
  88592. /**
  88593. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  88594. * Otherwise, will use the fullscreen API.
  88595. */
  88596. VRExperienceHelper.prototype.enterVR = function () {
  88597. if (this.onEnteringVRObservable) {
  88598. try {
  88599. this.onEnteringVRObservable.notifyObservers(this);
  88600. }
  88601. catch (err) {
  88602. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  88603. }
  88604. }
  88605. if (this._scene.activeCamera) {
  88606. this._position = this._scene.activeCamera.position.clone();
  88607. // make sure that we return to the last active camera
  88608. this._existingCamera = this._scene.activeCamera;
  88609. }
  88610. if (this._webVRrequesting)
  88611. return;
  88612. // If WebVR is supported and a headset is connected
  88613. if (this._webVRready) {
  88614. if (!this._webVRpresenting) {
  88615. this._webVRCamera.position = this._position;
  88616. this._scene.activeCamera = this._webVRCamera;
  88617. }
  88618. }
  88619. else if (this._vrDeviceOrientationCamera) {
  88620. this._vrDeviceOrientationCamera.position = this._position;
  88621. if (this._scene.activeCamera) {
  88622. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88623. }
  88624. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  88625. this._scene.getEngine().switchFullscreen(true);
  88626. this.updateButtonVisibility();
  88627. }
  88628. if (this._scene.activeCamera && this._canvas) {
  88629. this._scene.activeCamera.attachControl(this._canvas);
  88630. }
  88631. if (this._interactionsEnabled) {
  88632. this._scene.registerBeforeRender(this.beforeRender);
  88633. }
  88634. };
  88635. /**
  88636. * Attempt to exit VR, or fullscreen.
  88637. */
  88638. VRExperienceHelper.prototype.exitVR = function () {
  88639. if (this.onExitingVRObservable) {
  88640. try {
  88641. this.onExitingVRObservable.notifyObservers(this);
  88642. }
  88643. catch (err) {
  88644. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  88645. }
  88646. }
  88647. if (this._webVRpresenting) {
  88648. this._scene.getEngine().disableVR();
  88649. }
  88650. if (this._scene.activeCamera) {
  88651. this._position = this._scene.activeCamera.position.clone();
  88652. }
  88653. if (this._deviceOrientationCamera) {
  88654. this._deviceOrientationCamera.position = this._position;
  88655. this._scene.activeCamera = this._deviceOrientationCamera;
  88656. if (this._canvas) {
  88657. this._scene.activeCamera.attachControl(this._canvas);
  88658. }
  88659. }
  88660. else if (this._existingCamera) {
  88661. this._existingCamera.position = this._position;
  88662. this._scene.activeCamera = this._existingCamera;
  88663. }
  88664. this.updateButtonVisibility();
  88665. if (this._interactionsEnabled) {
  88666. this._scene.unregisterBeforeRender(this.beforeRender);
  88667. }
  88668. // resize to update width and height when exiting vr exits fullscreen
  88669. this._scene.getEngine().resize();
  88670. };
  88671. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  88672. /**
  88673. * The position of the vr experience helper.
  88674. */
  88675. get: function () {
  88676. return this._position;
  88677. },
  88678. /**
  88679. * Sets the position of the vr experience helper.
  88680. */
  88681. set: function (value) {
  88682. this._position = value;
  88683. if (this._scene.activeCamera) {
  88684. this._scene.activeCamera.position = value;
  88685. }
  88686. },
  88687. enumerable: true,
  88688. configurable: true
  88689. });
  88690. /**
  88691. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  88692. */
  88693. VRExperienceHelper.prototype.enableInteractions = function () {
  88694. var _this = this;
  88695. if (!this._interactionsEnabled) {
  88696. this._interactionsRequested = true;
  88697. if (this.leftController) {
  88698. this._enableInteractionOnController(this.leftController);
  88699. }
  88700. if (this.rightController) {
  88701. this._enableInteractionOnController(this.rightController);
  88702. }
  88703. this.raySelectionPredicate = function (mesh) {
  88704. return mesh.isVisible;
  88705. };
  88706. this.meshSelectionPredicate = function (mesh) {
  88707. return true;
  88708. };
  88709. this._raySelectionPredicate = function (mesh) {
  88710. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  88711. && mesh.name.indexOf("teleportationTarget") === -1
  88712. && mesh.name.indexOf("torusTeleportation") === -1
  88713. && mesh.name.indexOf("laserPointer") === -1)) {
  88714. return _this.raySelectionPredicate(mesh);
  88715. }
  88716. return false;
  88717. };
  88718. this._interactionsEnabled = true;
  88719. }
  88720. };
  88721. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  88722. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  88723. if (this._floorMeshesCollection[i].id === mesh.id) {
  88724. return true;
  88725. }
  88726. }
  88727. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  88728. return true;
  88729. }
  88730. return false;
  88731. };
  88732. /**
  88733. * Adds a floor mesh to be used for teleportation.
  88734. * @param floorMesh the mesh to be used for teleportation.
  88735. */
  88736. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  88737. if (!this._floorMeshesCollection) {
  88738. return;
  88739. }
  88740. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  88741. return;
  88742. }
  88743. this._floorMeshesCollection.push(floorMesh);
  88744. };
  88745. /**
  88746. * Removes a floor mesh from being used for teleportation.
  88747. * @param floorMesh the mesh to be removed.
  88748. */
  88749. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  88750. if (!this._floorMeshesCollection) {
  88751. return;
  88752. }
  88753. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  88754. if (meshIndex !== -1) {
  88755. this._floorMeshesCollection.splice(meshIndex, 1);
  88756. }
  88757. };
  88758. /**
  88759. * Enables interactions and teleportation using the VR controllers and gaze.
  88760. * @param vrTeleportationOptions options to modify teleportation behavior.
  88761. */
  88762. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  88763. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  88764. if (!this._teleportationInitialized) {
  88765. this._teleportationRequested = true;
  88766. this.enableInteractions();
  88767. if (vrTeleportationOptions.floorMeshName) {
  88768. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  88769. }
  88770. if (vrTeleportationOptions.floorMeshes) {
  88771. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  88772. }
  88773. if (this.leftController != null) {
  88774. this._enableTeleportationOnController(this.leftController);
  88775. }
  88776. if (this.rightController != null) {
  88777. this._enableTeleportationOnController(this.rightController);
  88778. }
  88779. // Creates an image processing post process for the vignette not relying
  88780. // on the main scene configuration for image processing to reduce setup and spaces
  88781. // (gamma/linear) conflicts.
  88782. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  88783. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88784. imageProcessingConfiguration.vignetteEnabled = true;
  88785. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  88786. this._webVRCamera.detachPostProcess(this._postProcessMove);
  88787. this._teleportationInitialized = true;
  88788. if (this._isDefaultTeleportationTarget) {
  88789. this._createTeleportationCircles();
  88790. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  88791. }
  88792. }
  88793. };
  88794. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  88795. var _this = this;
  88796. var controllerMesh = controller.webVRController.mesh;
  88797. if (controllerMesh) {
  88798. controller._interactionsEnabled = true;
  88799. controller._activatePointer();
  88800. if (this.webVROptions.laserToggle) {
  88801. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  88802. // Enabling / disabling laserPointer
  88803. if (_this._displayLaserPointer && stateObject.value === 1) {
  88804. if (controller._activePointer) {
  88805. controller._deactivatePointer();
  88806. }
  88807. else {
  88808. controller._activatePointer();
  88809. }
  88810. if (_this.displayGaze) {
  88811. controller._gazeTracker.isVisible = controller._activePointer;
  88812. }
  88813. }
  88814. });
  88815. }
  88816. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  88817. if (!controller._pointerDownOnMeshAsked) {
  88818. if (stateObject.value > _this._padSensibilityUp) {
  88819. controller._selectionPointerDown();
  88820. }
  88821. }
  88822. else if (stateObject.value < _this._padSensibilityDown) {
  88823. controller._selectionPointerUp();
  88824. }
  88825. });
  88826. }
  88827. };
  88828. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  88829. // Dont teleport if another gaze already requested teleportation
  88830. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  88831. return;
  88832. }
  88833. if (!gazer._teleportationRequestInitiated) {
  88834. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  88835. gazer._activatePointer();
  88836. gazer._teleportationRequestInitiated = true;
  88837. }
  88838. }
  88839. else {
  88840. // Listening to the proper controller values changes to confirm teleportation
  88841. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  88842. if (this._teleportActive) {
  88843. this._teleportCamera(this._haloCenter);
  88844. }
  88845. gazer._teleportationRequestInitiated = false;
  88846. }
  88847. }
  88848. };
  88849. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  88850. // Only rotate when user is not currently selecting a teleportation location
  88851. if (gazer._teleportationRequestInitiated) {
  88852. return;
  88853. }
  88854. if (!gazer._rotationLeftAsked) {
  88855. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  88856. gazer._rotationLeftAsked = true;
  88857. if (this._rotationAllowed) {
  88858. this._rotateCamera(false);
  88859. }
  88860. }
  88861. }
  88862. else {
  88863. if (stateObject.x > -this._padSensibilityDown) {
  88864. gazer._rotationLeftAsked = false;
  88865. }
  88866. }
  88867. if (!gazer._rotationRightAsked) {
  88868. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  88869. gazer._rotationRightAsked = true;
  88870. if (this._rotationAllowed) {
  88871. this._rotateCamera(true);
  88872. }
  88873. }
  88874. }
  88875. else {
  88876. if (stateObject.x < this._padSensibilityDown) {
  88877. gazer._rotationRightAsked = false;
  88878. }
  88879. }
  88880. };
  88881. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  88882. // Only teleport backwards when user is not currently selecting a teleportation location
  88883. if (gazer._teleportationRequestInitiated) {
  88884. return;
  88885. }
  88886. // Teleport backwards
  88887. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  88888. if (!gazer._teleportationBackRequestInitiated) {
  88889. if (!this.currentVRCamera) {
  88890. return;
  88891. }
  88892. // Get rotation and position of the current camera
  88893. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  88894. var position = this.currentVRCamera.position;
  88895. // If the camera has device position, use that instead
  88896. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  88897. rotation = this.currentVRCamera.deviceRotationQuaternion;
  88898. position = this.currentVRCamera.devicePosition;
  88899. }
  88900. // Get matrix with only the y rotation of the device rotation
  88901. rotation.toEulerAnglesToRef(this._workingVector);
  88902. this._workingVector.z = 0;
  88903. this._workingVector.x = 0;
  88904. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  88905. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  88906. // Rotate backwards ray by device rotation to cast at the ground behind the user
  88907. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  88908. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  88909. var ray = new BABYLON.Ray(position, this._workingVector);
  88910. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88911. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  88912. this._teleportCamera(hit.pickedPoint);
  88913. }
  88914. gazer._teleportationBackRequestInitiated = true;
  88915. }
  88916. }
  88917. else {
  88918. gazer._teleportationBackRequestInitiated = false;
  88919. }
  88920. };
  88921. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  88922. var _this = this;
  88923. var controllerMesh = controller.webVRController.mesh;
  88924. if (controllerMesh) {
  88925. if (!controller._interactionsEnabled) {
  88926. this._enableInteractionOnController(controller);
  88927. }
  88928. controller._interactionsEnabled = true;
  88929. controller._teleportationEnabled = true;
  88930. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  88931. controller._dpadPressed = false;
  88932. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  88933. controller._dpadPressed = stateObject.pressed;
  88934. if (!controller._dpadPressed) {
  88935. controller._rotationLeftAsked = false;
  88936. controller._rotationRightAsked = false;
  88937. controller._teleportationBackRequestInitiated = false;
  88938. }
  88939. });
  88940. }
  88941. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  88942. if (_this.teleportationEnabled) {
  88943. _this._checkTeleportBackwards(stateObject, controller);
  88944. _this._checkTeleportWithRay(stateObject, controller);
  88945. }
  88946. _this._checkRotate(stateObject, controller);
  88947. });
  88948. }
  88949. };
  88950. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  88951. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  88952. this._teleportationTarget.isPickable = false;
  88953. var length = 512;
  88954. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  88955. dynamicTexture.hasAlpha = true;
  88956. var context = dynamicTexture.getContext();
  88957. var centerX = length / 2;
  88958. var centerY = length / 2;
  88959. var radius = 200;
  88960. context.beginPath();
  88961. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  88962. context.fillStyle = this._teleportationFillColor;
  88963. context.fill();
  88964. context.lineWidth = 10;
  88965. context.strokeStyle = this._teleportationBorderColor;
  88966. context.stroke();
  88967. context.closePath();
  88968. dynamicTexture.update();
  88969. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  88970. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  88971. this._teleportationTarget.material = teleportationCircleMaterial;
  88972. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  88973. torus.isPickable = false;
  88974. torus.parent = this._teleportationTarget;
  88975. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88976. var keys = [];
  88977. keys.push({
  88978. frame: 0,
  88979. value: 0
  88980. });
  88981. keys.push({
  88982. frame: 30,
  88983. value: 0.4
  88984. });
  88985. keys.push({
  88986. frame: 60,
  88987. value: 0
  88988. });
  88989. animationInnerCircle.setKeys(keys);
  88990. var easingFunction = new BABYLON.SineEase();
  88991. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88992. animationInnerCircle.setEasingFunction(easingFunction);
  88993. torus.animations = [];
  88994. torus.animations.push(animationInnerCircle);
  88995. this._scene.beginAnimation(torus, 0, 60, true);
  88996. this._hideTeleportationTarget();
  88997. };
  88998. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  88999. this._teleportActive = true;
  89000. if (this._teleportationInitialized) {
  89001. this._teleportationTarget.isVisible = true;
  89002. if (this._isDefaultTeleportationTarget) {
  89003. this._teleportationTarget.getChildren()[0].isVisible = true;
  89004. }
  89005. }
  89006. };
  89007. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  89008. this._teleportActive = false;
  89009. if (this._teleportationInitialized) {
  89010. this._teleportationTarget.isVisible = false;
  89011. if (this._isDefaultTeleportationTarget) {
  89012. this._teleportationTarget.getChildren()[0].isVisible = false;
  89013. }
  89014. }
  89015. };
  89016. VRExperienceHelper.prototype._rotateCamera = function (right) {
  89017. var _this = this;
  89018. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89019. return;
  89020. }
  89021. if (right) {
  89022. this._rotationAngle++;
  89023. }
  89024. else {
  89025. this._rotationAngle--;
  89026. }
  89027. this.currentVRCamera.animations = [];
  89028. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  89029. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89030. var animationRotationKeys = [];
  89031. animationRotationKeys.push({
  89032. frame: 0,
  89033. value: this.currentVRCamera.rotationQuaternion
  89034. });
  89035. animationRotationKeys.push({
  89036. frame: 6,
  89037. value: target
  89038. });
  89039. animationRotation.setKeys(animationRotationKeys);
  89040. animationRotation.setEasingFunction(this._circleEase);
  89041. this.currentVRCamera.animations.push(animationRotation);
  89042. this._postProcessMove.animations = [];
  89043. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89044. var vignetteWeightKeys = [];
  89045. vignetteWeightKeys.push({
  89046. frame: 0,
  89047. value: 0
  89048. });
  89049. vignetteWeightKeys.push({
  89050. frame: 3,
  89051. value: 4
  89052. });
  89053. vignetteWeightKeys.push({
  89054. frame: 6,
  89055. value: 0
  89056. });
  89057. animationPP.setKeys(vignetteWeightKeys);
  89058. animationPP.setEasingFunction(this._circleEase);
  89059. this._postProcessMove.animations.push(animationPP);
  89060. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89061. var vignetteStretchKeys = [];
  89062. vignetteStretchKeys.push({
  89063. frame: 0,
  89064. value: 0
  89065. });
  89066. vignetteStretchKeys.push({
  89067. frame: 3,
  89068. value: 10
  89069. });
  89070. vignetteStretchKeys.push({
  89071. frame: 6,
  89072. value: 0
  89073. });
  89074. animationPP2.setKeys(vignetteStretchKeys);
  89075. animationPP2.setEasingFunction(this._circleEase);
  89076. this._postProcessMove.animations.push(animationPP2);
  89077. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  89078. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  89079. this._postProcessMove.samples = 4;
  89080. this._webVRCamera.attachPostProcess(this._postProcessMove);
  89081. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  89082. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  89083. });
  89084. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  89085. };
  89086. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  89087. if (hit.pickedPoint) {
  89088. if (gazer._teleportationRequestInitiated) {
  89089. this._displayTeleportationTarget();
  89090. this._haloCenter.copyFrom(hit.pickedPoint);
  89091. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  89092. }
  89093. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  89094. if (pickNormal) {
  89095. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  89096. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  89097. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  89098. }
  89099. this._teleportationTarget.position.y += 0.1;
  89100. }
  89101. };
  89102. VRExperienceHelper.prototype._teleportCamera = function (location) {
  89103. var _this = this;
  89104. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89105. return;
  89106. }
  89107. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  89108. // offset of the headset from the anchor.
  89109. if (this.webVRCamera.leftCamera) {
  89110. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  89111. this._workingVector.subtractInPlace(this.webVRCamera.position);
  89112. location.subtractToRef(this._workingVector, this._workingVector);
  89113. }
  89114. else {
  89115. this._workingVector.copyFrom(location);
  89116. }
  89117. // Add height to account for user's height offset
  89118. if (this.isInVRMode) {
  89119. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  89120. }
  89121. else {
  89122. this._workingVector.y += this._defaultHeight;
  89123. }
  89124. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  89125. // Create animation from the camera's position to the new location
  89126. this.currentVRCamera.animations = [];
  89127. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89128. var animationCameraTeleportationKeys = [{
  89129. frame: 0,
  89130. value: this.currentVRCamera.position
  89131. },
  89132. {
  89133. frame: 11,
  89134. value: this._workingVector
  89135. }
  89136. ];
  89137. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  89138. animationCameraTeleportation.setEasingFunction(this._circleEase);
  89139. this.currentVRCamera.animations.push(animationCameraTeleportation);
  89140. this._postProcessMove.animations = [];
  89141. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89142. var vignetteWeightKeys = [];
  89143. vignetteWeightKeys.push({
  89144. frame: 0,
  89145. value: 0
  89146. });
  89147. vignetteWeightKeys.push({
  89148. frame: 5,
  89149. value: 8
  89150. });
  89151. vignetteWeightKeys.push({
  89152. frame: 11,
  89153. value: 0
  89154. });
  89155. animationPP.setKeys(vignetteWeightKeys);
  89156. this._postProcessMove.animations.push(animationPP);
  89157. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  89158. var vignetteStretchKeys = [];
  89159. vignetteStretchKeys.push({
  89160. frame: 0,
  89161. value: 0
  89162. });
  89163. vignetteStretchKeys.push({
  89164. frame: 5,
  89165. value: 10
  89166. });
  89167. vignetteStretchKeys.push({
  89168. frame: 11,
  89169. value: 0
  89170. });
  89171. animationPP2.setKeys(vignetteStretchKeys);
  89172. this._postProcessMove.animations.push(animationPP2);
  89173. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  89174. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  89175. this._webVRCamera.attachPostProcess(this._postProcessMove);
  89176. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  89177. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  89178. });
  89179. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  89180. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  89181. });
  89182. this._hideTeleportationTarget();
  89183. };
  89184. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  89185. if (normal) {
  89186. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  89187. if (angle < Math.PI / 2) {
  89188. normal.scaleInPlace(-1);
  89189. }
  89190. }
  89191. return normal;
  89192. };
  89193. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  89194. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  89195. return;
  89196. }
  89197. var ray = gazer._getForwardRay(this._rayLength);
  89198. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  89199. // Moving the gazeTracker on the mesh face targetted
  89200. if (hit && hit.pickedPoint) {
  89201. if (this._displayGaze) {
  89202. var multiplier = 1;
  89203. gazer._gazeTracker.isVisible = true;
  89204. if (gazer._isActionableMesh) {
  89205. multiplier = 3;
  89206. }
  89207. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  89208. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  89209. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  89210. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  89211. // To avoid z-fighting
  89212. var deltaFighting = 0.002;
  89213. if (pickNormal) {
  89214. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  89215. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  89216. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  89217. }
  89218. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  89219. if (gazer._gazeTracker.position.x < 0) {
  89220. gazer._gazeTracker.position.x += deltaFighting;
  89221. }
  89222. else {
  89223. gazer._gazeTracker.position.x -= deltaFighting;
  89224. }
  89225. if (gazer._gazeTracker.position.y < 0) {
  89226. gazer._gazeTracker.position.y += deltaFighting;
  89227. }
  89228. else {
  89229. gazer._gazeTracker.position.y -= deltaFighting;
  89230. }
  89231. if (gazer._gazeTracker.position.z < 0) {
  89232. gazer._gazeTracker.position.z += deltaFighting;
  89233. }
  89234. else {
  89235. gazer._gazeTracker.position.z -= deltaFighting;
  89236. }
  89237. }
  89238. // Changing the size of the laser pointer based on the distance from the targetted point
  89239. gazer._updatePointerDistance(hit.distance);
  89240. }
  89241. else {
  89242. gazer._updatePointerDistance();
  89243. gazer._gazeTracker.isVisible = false;
  89244. }
  89245. if (hit && hit.pickedMesh) {
  89246. gazer._currentHit = hit;
  89247. if (gazer._pointerDownOnMeshAsked) {
  89248. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  89249. }
  89250. // The object selected is the floor, we're in a teleportation scenario
  89251. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  89252. // Moving the teleportation area to this targetted point
  89253. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  89254. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  89255. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89256. }
  89257. gazer._currentMeshSelected = null;
  89258. if (gazer._teleportationRequestInitiated) {
  89259. this._moveTeleportationSelectorTo(hit, gazer, ray);
  89260. }
  89261. return;
  89262. }
  89263. // If not, we're in a selection scenario
  89264. //this._teleportationAllowed = false;
  89265. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  89266. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  89267. this.onNewMeshPicked.notifyObservers(hit);
  89268. gazer._currentMeshSelected = hit.pickedMesh;
  89269. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  89270. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  89271. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  89272. gazer._isActionableMesh = true;
  89273. }
  89274. else {
  89275. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89276. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89277. gazer._isActionableMesh = false;
  89278. }
  89279. try {
  89280. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  89281. }
  89282. catch (err) {
  89283. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  89284. }
  89285. }
  89286. else {
  89287. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89288. gazer._currentMeshSelected = null;
  89289. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89290. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89291. }
  89292. }
  89293. }
  89294. else {
  89295. gazer._currentHit = null;
  89296. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89297. gazer._currentMeshSelected = null;
  89298. //this._teleportationAllowed = false;
  89299. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89300. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89301. }
  89302. };
  89303. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  89304. if (mesh) {
  89305. this.onSelectedMeshUnselected.notifyObservers(mesh);
  89306. }
  89307. };
  89308. /**
  89309. * Sets the color of the laser ray from the vr controllers.
  89310. * @param color new color for the ray.
  89311. */
  89312. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  89313. if (this.leftController) {
  89314. this.leftController._setLaserPointerColor(color);
  89315. }
  89316. if (this.rightController) {
  89317. this.rightController._setLaserPointerColor(color);
  89318. }
  89319. };
  89320. /**
  89321. * Sets the color of the ray from the vr headsets gaze.
  89322. * @param color new color for the ray.
  89323. */
  89324. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  89325. if (!this._cameraGazer._gazeTracker.material) {
  89326. return;
  89327. }
  89328. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  89329. if (this.leftController) {
  89330. this.leftController._gazeTracker.material.emissiveColor = color;
  89331. }
  89332. if (this.rightController) {
  89333. this.rightController._gazeTracker.material.emissiveColor = color;
  89334. }
  89335. };
  89336. /**
  89337. * Exits VR and disposes of the vr experience helper
  89338. */
  89339. VRExperienceHelper.prototype.dispose = function () {
  89340. if (this.isInVRMode) {
  89341. this.exitVR();
  89342. }
  89343. if (this._postProcessMove) {
  89344. this._postProcessMove.dispose();
  89345. }
  89346. if (this._webVRCamera) {
  89347. this._webVRCamera.dispose();
  89348. }
  89349. if (this._vrDeviceOrientationCamera) {
  89350. this._vrDeviceOrientationCamera.dispose();
  89351. }
  89352. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  89353. document.body.removeChild(this._btnVR);
  89354. }
  89355. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  89356. this._deviceOrientationCamera.dispose();
  89357. }
  89358. if (this._cameraGazer) {
  89359. this._cameraGazer.dispose();
  89360. }
  89361. if (this.leftController) {
  89362. this.leftController.dispose();
  89363. }
  89364. if (this.rightController) {
  89365. this.rightController.dispose();
  89366. }
  89367. if (this._teleportationTarget) {
  89368. this._teleportationTarget.dispose();
  89369. }
  89370. this._floorMeshesCollection = [];
  89371. document.removeEventListener("keydown", this._onKeyDown);
  89372. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89373. window.removeEventListener("resize", this._onResize);
  89374. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  89375. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  89376. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  89377. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  89378. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  89379. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  89380. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  89381. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89382. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  89383. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  89384. this._scene.unregisterBeforeRender(this.beforeRender);
  89385. };
  89386. /**
  89387. * Gets the name of the VRExperienceHelper class
  89388. * @returns "VRExperienceHelper"
  89389. */
  89390. VRExperienceHelper.prototype.getClassName = function () {
  89391. return "VRExperienceHelper";
  89392. };
  89393. return VRExperienceHelper;
  89394. }());
  89395. BABYLON.VRExperienceHelper = VRExperienceHelper;
  89396. })(BABYLON || (BABYLON = {}));
  89397. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  89398. // Mainly based on these 2 articles :
  89399. // 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
  89400. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  89401. var BABYLON;
  89402. (function (BABYLON) {
  89403. /**
  89404. * Defines the potential axis of a Joystick
  89405. */
  89406. var JoystickAxis;
  89407. (function (JoystickAxis) {
  89408. /** X axis */
  89409. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  89410. /** Y axis */
  89411. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  89412. /** Z axis */
  89413. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  89414. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  89415. /**
  89416. * Class used to define virtual joystick (used in touch mode)
  89417. */
  89418. var VirtualJoystick = /** @class */ (function () {
  89419. /**
  89420. * Creates a new virtual joystick
  89421. * @param leftJoystick defines that the joystick is for left hand (false by default)
  89422. */
  89423. function VirtualJoystick(leftJoystick) {
  89424. var _this = this;
  89425. if (leftJoystick) {
  89426. this._leftJoystick = true;
  89427. }
  89428. else {
  89429. this._leftJoystick = false;
  89430. }
  89431. VirtualJoystick._globalJoystickIndex++;
  89432. // By default left & right arrow keys are moving the X
  89433. // and up & down keys are moving the Y
  89434. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89435. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89436. this.reverseLeftRight = false;
  89437. this.reverseUpDown = false;
  89438. // collections of pointers
  89439. this._touches = new BABYLON.StringDictionary();
  89440. this.deltaPosition = BABYLON.Vector3.Zero();
  89441. this._joystickSensibility = 25;
  89442. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89443. this._onResize = function (evt) {
  89444. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89445. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89446. if (VirtualJoystick.vjCanvas) {
  89447. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  89448. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  89449. }
  89450. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  89451. };
  89452. // injecting a canvas element on top of the canvas 3D game
  89453. if (!VirtualJoystick.vjCanvas) {
  89454. window.addEventListener("resize", this._onResize, false);
  89455. VirtualJoystick.vjCanvas = document.createElement("canvas");
  89456. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89457. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89458. VirtualJoystick.vjCanvas.width = window.innerWidth;
  89459. VirtualJoystick.vjCanvas.height = window.innerHeight;
  89460. VirtualJoystick.vjCanvas.style.width = "100%";
  89461. VirtualJoystick.vjCanvas.style.height = "100%";
  89462. VirtualJoystick.vjCanvas.style.position = "absolute";
  89463. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  89464. VirtualJoystick.vjCanvas.style.top = "0px";
  89465. VirtualJoystick.vjCanvas.style.left = "0px";
  89466. VirtualJoystick.vjCanvas.style.zIndex = "5";
  89467. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  89468. // Support for jQuery PEP polyfill
  89469. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  89470. var context = VirtualJoystick.vjCanvas.getContext('2d');
  89471. if (!context) {
  89472. throw new Error("Unable to create canvas for virtual joystick");
  89473. }
  89474. VirtualJoystick.vjCanvasContext = context;
  89475. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  89476. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89477. document.body.appendChild(VirtualJoystick.vjCanvas);
  89478. }
  89479. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  89480. this.pressed = false;
  89481. // default joystick color
  89482. this._joystickColor = "cyan";
  89483. this._joystickPointerID = -1;
  89484. // current joystick position
  89485. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  89486. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  89487. // origin joystick position
  89488. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  89489. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  89490. this._onPointerDownHandlerRef = function (evt) {
  89491. _this._onPointerDown(evt);
  89492. };
  89493. this._onPointerMoveHandlerRef = function (evt) {
  89494. _this._onPointerMove(evt);
  89495. };
  89496. this._onPointerUpHandlerRef = function (evt) {
  89497. _this._onPointerUp(evt);
  89498. };
  89499. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  89500. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  89501. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  89502. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  89503. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  89504. evt.preventDefault(); // Disables system menu
  89505. }, false);
  89506. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89507. }
  89508. /**
  89509. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  89510. * @param newJoystickSensibility defines the new sensibility
  89511. */
  89512. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  89513. this._joystickSensibility = newJoystickSensibility;
  89514. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89515. };
  89516. VirtualJoystick.prototype._onPointerDown = function (e) {
  89517. var positionOnScreenCondition;
  89518. e.preventDefault();
  89519. if (this._leftJoystick === true) {
  89520. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  89521. }
  89522. else {
  89523. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  89524. }
  89525. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  89526. // First contact will be dedicated to the virtual joystick
  89527. this._joystickPointerID = e.pointerId;
  89528. this._joystickPointerStartPos.x = e.clientX;
  89529. this._joystickPointerStartPos.y = e.clientY;
  89530. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  89531. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  89532. this._deltaJoystickVector.x = 0;
  89533. this._deltaJoystickVector.y = 0;
  89534. this.pressed = true;
  89535. this._touches.add(e.pointerId.toString(), e);
  89536. }
  89537. else {
  89538. // You can only trigger the action buttons with a joystick declared
  89539. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  89540. this._action();
  89541. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  89542. }
  89543. }
  89544. };
  89545. VirtualJoystick.prototype._onPointerMove = function (e) {
  89546. // If the current pointer is the one associated to the joystick (first touch contact)
  89547. if (this._joystickPointerID == e.pointerId) {
  89548. this._joystickPointerPos.x = e.clientX;
  89549. this._joystickPointerPos.y = e.clientY;
  89550. this._deltaJoystickVector = this._joystickPointerPos.clone();
  89551. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  89552. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  89553. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  89554. switch (this._axisTargetedByLeftAndRight) {
  89555. case JoystickAxis.X:
  89556. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  89557. break;
  89558. case JoystickAxis.Y:
  89559. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  89560. break;
  89561. case JoystickAxis.Z:
  89562. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  89563. break;
  89564. }
  89565. var directionUpDown = this.reverseUpDown ? 1 : -1;
  89566. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  89567. switch (this._axisTargetedByUpAndDown) {
  89568. case JoystickAxis.X:
  89569. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  89570. break;
  89571. case JoystickAxis.Y:
  89572. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  89573. break;
  89574. case JoystickAxis.Z:
  89575. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  89576. break;
  89577. }
  89578. }
  89579. else {
  89580. var data = this._touches.get(e.pointerId.toString());
  89581. if (data) {
  89582. data.x = e.clientX;
  89583. data.y = e.clientY;
  89584. }
  89585. }
  89586. };
  89587. VirtualJoystick.prototype._onPointerUp = function (e) {
  89588. if (this._joystickPointerID == e.pointerId) {
  89589. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  89590. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  89591. this._joystickPointerID = -1;
  89592. this.pressed = false;
  89593. }
  89594. else {
  89595. var touch = this._touches.get(e.pointerId.toString());
  89596. if (touch) {
  89597. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89598. }
  89599. }
  89600. this._deltaJoystickVector.x = 0;
  89601. this._deltaJoystickVector.y = 0;
  89602. this._touches.remove(e.pointerId.toString());
  89603. };
  89604. /**
  89605. * Change the color of the virtual joystick
  89606. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  89607. */
  89608. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  89609. this._joystickColor = newColor;
  89610. };
  89611. /**
  89612. * Defines a callback to call when the joystick is touched
  89613. * @param action defines the callback
  89614. */
  89615. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  89616. this._action = action;
  89617. };
  89618. /**
  89619. * Defines which axis you'd like to control for left & right
  89620. * @param axis defines the axis to use
  89621. */
  89622. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  89623. switch (axis) {
  89624. case JoystickAxis.X:
  89625. case JoystickAxis.Y:
  89626. case JoystickAxis.Z:
  89627. this._axisTargetedByLeftAndRight = axis;
  89628. break;
  89629. default:
  89630. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89631. break;
  89632. }
  89633. };
  89634. /**
  89635. * Defines which axis you'd like to control for up & down
  89636. * @param axis defines the axis to use
  89637. */
  89638. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  89639. switch (axis) {
  89640. case JoystickAxis.X:
  89641. case JoystickAxis.Y:
  89642. case JoystickAxis.Z:
  89643. this._axisTargetedByUpAndDown = axis;
  89644. break;
  89645. default:
  89646. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89647. break;
  89648. }
  89649. };
  89650. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  89651. var _this = this;
  89652. if (this.pressed) {
  89653. this._touches.forEach(function (key, touch) {
  89654. if (touch.pointerId === _this._joystickPointerID) {
  89655. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  89656. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  89657. VirtualJoystick.vjCanvasContext.beginPath();
  89658. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89659. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89660. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  89661. VirtualJoystick.vjCanvasContext.stroke();
  89662. VirtualJoystick.vjCanvasContext.closePath();
  89663. VirtualJoystick.vjCanvasContext.beginPath();
  89664. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89665. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89666. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  89667. VirtualJoystick.vjCanvasContext.stroke();
  89668. VirtualJoystick.vjCanvasContext.closePath();
  89669. VirtualJoystick.vjCanvasContext.beginPath();
  89670. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89671. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  89672. VirtualJoystick.vjCanvasContext.stroke();
  89673. VirtualJoystick.vjCanvasContext.closePath();
  89674. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  89675. }
  89676. else {
  89677. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89678. VirtualJoystick.vjCanvasContext.beginPath();
  89679. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  89680. VirtualJoystick.vjCanvasContext.beginPath();
  89681. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  89682. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89683. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  89684. VirtualJoystick.vjCanvasContext.stroke();
  89685. VirtualJoystick.vjCanvasContext.closePath();
  89686. touch.prevX = touch.x;
  89687. touch.prevY = touch.y;
  89688. }
  89689. ;
  89690. });
  89691. }
  89692. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89693. };
  89694. /**
  89695. * Release internal HTML canvas
  89696. */
  89697. VirtualJoystick.prototype.releaseCanvas = function () {
  89698. if (VirtualJoystick.vjCanvas) {
  89699. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  89700. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  89701. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  89702. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  89703. window.removeEventListener("resize", this._onResize);
  89704. document.body.removeChild(VirtualJoystick.vjCanvas);
  89705. VirtualJoystick.vjCanvas = null;
  89706. }
  89707. };
  89708. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  89709. VirtualJoystick._globalJoystickIndex = 0;
  89710. return VirtualJoystick;
  89711. }());
  89712. BABYLON.VirtualJoystick = VirtualJoystick;
  89713. })(BABYLON || (BABYLON = {}));
  89714. //# sourceMappingURL=babylon.virtualJoystick.js.map
  89715. var BABYLON;
  89716. (function (BABYLON) {
  89717. // We're mainly based on the logic defined into the FreeCamera code
  89718. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  89719. __extends(VirtualJoysticksCamera, _super);
  89720. function VirtualJoysticksCamera(name, position, scene) {
  89721. var _this = _super.call(this, name, position, scene) || this;
  89722. _this.inputs.addVirtualJoystick();
  89723. return _this;
  89724. }
  89725. VirtualJoysticksCamera.prototype.getClassName = function () {
  89726. return "VirtualJoysticksCamera";
  89727. };
  89728. return VirtualJoysticksCamera;
  89729. }(BABYLON.FreeCamera));
  89730. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  89731. })(BABYLON || (BABYLON = {}));
  89732. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  89733. var BABYLON;
  89734. (function (BABYLON) {
  89735. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  89736. function FreeCameraVirtualJoystickInput() {
  89737. }
  89738. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  89739. return this._leftjoystick;
  89740. };
  89741. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  89742. return this._rightjoystick;
  89743. };
  89744. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  89745. if (this._leftjoystick) {
  89746. var camera = this.camera;
  89747. var speed = camera._computeLocalCameraSpeed() * 50;
  89748. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  89749. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  89750. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  89751. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  89752. if (!this._leftjoystick.pressed) {
  89753. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  89754. }
  89755. if (!this._rightjoystick.pressed) {
  89756. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  89757. }
  89758. }
  89759. };
  89760. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  89761. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  89762. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  89763. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  89764. this._leftjoystick.setJoystickSensibility(0.15);
  89765. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  89766. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  89767. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  89768. this._rightjoystick.reverseUpDown = true;
  89769. this._rightjoystick.setJoystickSensibility(0.05);
  89770. this._rightjoystick.setJoystickColor("yellow");
  89771. };
  89772. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  89773. this._leftjoystick.releaseCanvas();
  89774. this._rightjoystick.releaseCanvas();
  89775. };
  89776. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  89777. return "FreeCameraVirtualJoystickInput";
  89778. };
  89779. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  89780. return "virtualJoystick";
  89781. };
  89782. return FreeCameraVirtualJoystickInput;
  89783. }());
  89784. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  89785. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  89786. })(BABYLON || (BABYLON = {}));
  89787. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  89788. var BABYLON;
  89789. (function (BABYLON) {
  89790. var SimplificationSettings = /** @class */ (function () {
  89791. function SimplificationSettings(quality, distance, optimizeMesh) {
  89792. this.quality = quality;
  89793. this.distance = distance;
  89794. this.optimizeMesh = optimizeMesh;
  89795. }
  89796. return SimplificationSettings;
  89797. }());
  89798. BABYLON.SimplificationSettings = SimplificationSettings;
  89799. var SimplificationQueue = /** @class */ (function () {
  89800. function SimplificationQueue() {
  89801. this.running = false;
  89802. this._simplificationArray = [];
  89803. }
  89804. SimplificationQueue.prototype.addTask = function (task) {
  89805. this._simplificationArray.push(task);
  89806. };
  89807. SimplificationQueue.prototype.executeNext = function () {
  89808. var task = this._simplificationArray.pop();
  89809. if (task) {
  89810. this.running = true;
  89811. this.runSimplification(task);
  89812. }
  89813. else {
  89814. this.running = false;
  89815. }
  89816. };
  89817. SimplificationQueue.prototype.runSimplification = function (task) {
  89818. var _this = this;
  89819. if (task.parallelProcessing) {
  89820. //parallel simplifier
  89821. task.settings.forEach(function (setting) {
  89822. var simplifier = _this.getSimplifier(task);
  89823. simplifier.simplify(setting, function (newMesh) {
  89824. task.mesh.addLODLevel(setting.distance, newMesh);
  89825. newMesh.isVisible = true;
  89826. //check if it is the last
  89827. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  89828. //all done, run the success callback.
  89829. task.successCallback();
  89830. }
  89831. _this.executeNext();
  89832. });
  89833. });
  89834. }
  89835. else {
  89836. //single simplifier.
  89837. var simplifier = this.getSimplifier(task);
  89838. var runDecimation = function (setting, callback) {
  89839. simplifier.simplify(setting, function (newMesh) {
  89840. task.mesh.addLODLevel(setting.distance, newMesh);
  89841. newMesh.isVisible = true;
  89842. //run the next quality level
  89843. callback();
  89844. });
  89845. };
  89846. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  89847. runDecimation(task.settings[loop.index], function () {
  89848. loop.executeNext();
  89849. });
  89850. }, function () {
  89851. //execution ended, run the success callback.
  89852. if (task.successCallback) {
  89853. task.successCallback();
  89854. }
  89855. _this.executeNext();
  89856. });
  89857. }
  89858. };
  89859. SimplificationQueue.prototype.getSimplifier = function (task) {
  89860. switch (task.simplificationType) {
  89861. case SimplificationType.QUADRATIC:
  89862. default:
  89863. return new QuadraticErrorSimplification(task.mesh);
  89864. }
  89865. };
  89866. return SimplificationQueue;
  89867. }());
  89868. BABYLON.SimplificationQueue = SimplificationQueue;
  89869. /**
  89870. * The implemented types of simplification
  89871. * At the moment only Quadratic Error Decimation is implemented
  89872. */
  89873. var SimplificationType;
  89874. (function (SimplificationType) {
  89875. /** Quadratic error decimation */
  89876. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  89877. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  89878. var DecimationTriangle = /** @class */ (function () {
  89879. function DecimationTriangle(vertices) {
  89880. this.vertices = vertices;
  89881. this.error = new Array(4);
  89882. this.deleted = false;
  89883. this.isDirty = false;
  89884. this.deletePending = false;
  89885. this.borderFactor = 0;
  89886. }
  89887. return DecimationTriangle;
  89888. }());
  89889. BABYLON.DecimationTriangle = DecimationTriangle;
  89890. var DecimationVertex = /** @class */ (function () {
  89891. function DecimationVertex(position, id) {
  89892. this.position = position;
  89893. this.id = id;
  89894. this.isBorder = true;
  89895. this.q = new QuadraticMatrix();
  89896. this.triangleCount = 0;
  89897. this.triangleStart = 0;
  89898. this.originalOffsets = [];
  89899. }
  89900. DecimationVertex.prototype.updatePosition = function (newPosition) {
  89901. this.position.copyFrom(newPosition);
  89902. };
  89903. return DecimationVertex;
  89904. }());
  89905. BABYLON.DecimationVertex = DecimationVertex;
  89906. var QuadraticMatrix = /** @class */ (function () {
  89907. function QuadraticMatrix(data) {
  89908. this.data = new Array(10);
  89909. for (var i = 0; i < 10; ++i) {
  89910. if (data && data[i]) {
  89911. this.data[i] = data[i];
  89912. }
  89913. else {
  89914. this.data[i] = 0;
  89915. }
  89916. }
  89917. }
  89918. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  89919. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  89920. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  89921. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  89922. return det;
  89923. };
  89924. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  89925. for (var i = 0; i < 10; ++i) {
  89926. this.data[i] += matrix.data[i];
  89927. }
  89928. };
  89929. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  89930. for (var i = 0; i < 10; ++i) {
  89931. this.data[i] += data[i];
  89932. }
  89933. };
  89934. QuadraticMatrix.prototype.add = function (matrix) {
  89935. var m = new QuadraticMatrix();
  89936. for (var i = 0; i < 10; ++i) {
  89937. m.data[i] = this.data[i] + matrix.data[i];
  89938. }
  89939. return m;
  89940. };
  89941. QuadraticMatrix.FromData = function (a, b, c, d) {
  89942. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  89943. };
  89944. //returning an array to avoid garbage collection
  89945. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  89946. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  89947. };
  89948. return QuadraticMatrix;
  89949. }());
  89950. BABYLON.QuadraticMatrix = QuadraticMatrix;
  89951. var Reference = /** @class */ (function () {
  89952. function Reference(vertexId, triangleId) {
  89953. this.vertexId = vertexId;
  89954. this.triangleId = triangleId;
  89955. }
  89956. return Reference;
  89957. }());
  89958. BABYLON.Reference = Reference;
  89959. /**
  89960. * An implementation of the Quadratic Error simplification algorithm.
  89961. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  89962. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  89963. * @author RaananW
  89964. */
  89965. var QuadraticErrorSimplification = /** @class */ (function () {
  89966. function QuadraticErrorSimplification(_mesh) {
  89967. this._mesh = _mesh;
  89968. this.syncIterations = 5000;
  89969. this.aggressiveness = 7;
  89970. this.decimationIterations = 100;
  89971. this.boundingBoxEpsilon = BABYLON.Epsilon;
  89972. }
  89973. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  89974. var _this = this;
  89975. this.initDecimatedMesh();
  89976. //iterating through the submeshes array, one after the other.
  89977. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  89978. _this.initWithMesh(loop.index, function () {
  89979. _this.runDecimation(settings, loop.index, function () {
  89980. loop.executeNext();
  89981. });
  89982. }, settings.optimizeMesh);
  89983. }, function () {
  89984. setTimeout(function () {
  89985. successCallback(_this._reconstructedMesh);
  89986. }, 0);
  89987. });
  89988. };
  89989. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  89990. var _this = this;
  89991. var targetCount = ~~(this.triangles.length * settings.quality);
  89992. var deletedTriangles = 0;
  89993. var triangleCount = this.triangles.length;
  89994. var iterationFunction = function (iteration, callback) {
  89995. setTimeout(function () {
  89996. if (iteration % 5 === 0) {
  89997. _this.updateMesh(iteration === 0);
  89998. }
  89999. for (var i = 0; i < _this.triangles.length; ++i) {
  90000. _this.triangles[i].isDirty = false;
  90001. }
  90002. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  90003. var trianglesIterator = function (i) {
  90004. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  90005. var t = _this.triangles[tIdx];
  90006. if (!t)
  90007. return;
  90008. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  90009. return;
  90010. }
  90011. for (var j = 0; j < 3; ++j) {
  90012. if (t.error[j] < threshold) {
  90013. var deleted0 = [];
  90014. var deleted1 = [];
  90015. var v0 = t.vertices[j];
  90016. var v1 = t.vertices[(j + 1) % 3];
  90017. if (v0.isBorder || v1.isBorder)
  90018. continue;
  90019. var p = BABYLON.Vector3.Zero();
  90020. var n = BABYLON.Vector3.Zero();
  90021. var uv = BABYLON.Vector2.Zero();
  90022. var color = new BABYLON.Color4(0, 0, 0, 1);
  90023. _this.calculateError(v0, v1, p, n, uv, color);
  90024. var delTr = new Array();
  90025. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  90026. continue;
  90027. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  90028. continue;
  90029. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  90030. continue;
  90031. var uniqueArray = new Array();
  90032. delTr.forEach(function (deletedT) {
  90033. if (uniqueArray.indexOf(deletedT) === -1) {
  90034. deletedT.deletePending = true;
  90035. uniqueArray.push(deletedT);
  90036. }
  90037. });
  90038. if (uniqueArray.length % 2 !== 0) {
  90039. continue;
  90040. }
  90041. v0.q = v1.q.add(v0.q);
  90042. v0.updatePosition(p);
  90043. var tStart = _this.references.length;
  90044. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  90045. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  90046. var tCount = _this.references.length - tStart;
  90047. if (tCount <= v0.triangleCount) {
  90048. if (tCount) {
  90049. for (var c = 0; c < tCount; c++) {
  90050. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  90051. }
  90052. }
  90053. }
  90054. else {
  90055. v0.triangleStart = tStart;
  90056. }
  90057. v0.triangleCount = tCount;
  90058. break;
  90059. }
  90060. }
  90061. };
  90062. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  90063. }, 0);
  90064. };
  90065. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  90066. if (triangleCount - deletedTriangles <= targetCount)
  90067. loop.breakLoop();
  90068. else {
  90069. iterationFunction(loop.index, function () {
  90070. loop.executeNext();
  90071. });
  90072. }
  90073. }, function () {
  90074. setTimeout(function () {
  90075. //reconstruct this part of the mesh
  90076. _this.reconstructMesh(submeshIndex);
  90077. successCallback();
  90078. }, 0);
  90079. });
  90080. };
  90081. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  90082. var _this = this;
  90083. this.vertices = [];
  90084. this.triangles = [];
  90085. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  90086. var indices = this._mesh.getIndices();
  90087. var submesh = this._mesh.subMeshes[submeshIndex];
  90088. var findInVertices = function (positionToSearch) {
  90089. if (optimizeMesh) {
  90090. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  90091. if (_this.vertices[ii].position.equals(positionToSearch)) {
  90092. return _this.vertices[ii];
  90093. }
  90094. }
  90095. }
  90096. return null;
  90097. };
  90098. var vertexReferences = [];
  90099. var vertexInit = function (i) {
  90100. if (!positionData) {
  90101. return;
  90102. }
  90103. var offset = i + submesh.verticesStart;
  90104. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  90105. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  90106. vertex.originalOffsets.push(offset);
  90107. if (vertex.id === _this.vertices.length) {
  90108. _this.vertices.push(vertex);
  90109. }
  90110. vertexReferences.push(vertex.id);
  90111. };
  90112. //var totalVertices = mesh.getTotalVertices();
  90113. var totalVertices = submesh.verticesCount;
  90114. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  90115. var indicesInit = function (i) {
  90116. if (!indices) {
  90117. return;
  90118. }
  90119. var offset = (submesh.indexStart / 3) + i;
  90120. var pos = (offset * 3);
  90121. var i0 = indices[pos + 0];
  90122. var i1 = indices[pos + 1];
  90123. var i2 = indices[pos + 2];
  90124. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  90125. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  90126. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  90127. var triangle = new DecimationTriangle([v0, v1, v2]);
  90128. triangle.originalOffset = pos;
  90129. _this.triangles.push(triangle);
  90130. };
  90131. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  90132. _this.init(callback);
  90133. });
  90134. });
  90135. };
  90136. QuadraticErrorSimplification.prototype.init = function (callback) {
  90137. var _this = this;
  90138. var triangleInit1 = function (i) {
  90139. var t = _this.triangles[i];
  90140. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  90141. for (var j = 0; j < 3; j++) {
  90142. 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))));
  90143. }
  90144. };
  90145. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  90146. var triangleInit2 = function (i) {
  90147. var t = _this.triangles[i];
  90148. for (var j = 0; j < 3; ++j) {
  90149. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  90150. }
  90151. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  90152. };
  90153. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  90154. callback();
  90155. });
  90156. });
  90157. };
  90158. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  90159. var newTriangles = [];
  90160. var i;
  90161. for (i = 0; i < this.vertices.length; ++i) {
  90162. this.vertices[i].triangleCount = 0;
  90163. }
  90164. var t;
  90165. var j;
  90166. for (i = 0; i < this.triangles.length; ++i) {
  90167. if (!this.triangles[i].deleted) {
  90168. t = this.triangles[i];
  90169. for (j = 0; j < 3; ++j) {
  90170. t.vertices[j].triangleCount = 1;
  90171. }
  90172. newTriangles.push(t);
  90173. }
  90174. }
  90175. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  90176. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  90177. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  90178. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  90179. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  90180. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  90181. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  90182. var vertexCount = 0;
  90183. for (i = 0; i < this.vertices.length; ++i) {
  90184. var vertex = this.vertices[i];
  90185. vertex.id = vertexCount;
  90186. if (vertex.triangleCount) {
  90187. vertex.originalOffsets.forEach(function (originalOffset) {
  90188. if (!normalData) {
  90189. return;
  90190. }
  90191. newPositionData.push(vertex.position.x);
  90192. newPositionData.push(vertex.position.y);
  90193. newPositionData.push(vertex.position.z);
  90194. newNormalData.push(normalData[originalOffset * 3]);
  90195. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  90196. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  90197. if (uvs && uvs.length) {
  90198. newUVsData.push(uvs[(originalOffset * 2)]);
  90199. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  90200. }
  90201. else if (colorsData && colorsData.length) {
  90202. newColorsData.push(colorsData[(originalOffset * 4)]);
  90203. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  90204. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  90205. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  90206. }
  90207. ++vertexCount;
  90208. });
  90209. }
  90210. }
  90211. var startingIndex = this._reconstructedMesh.getTotalIndices();
  90212. var startingVertex = this._reconstructedMesh.getTotalVertices();
  90213. var submeshesArray = this._reconstructedMesh.subMeshes;
  90214. this._reconstructedMesh.subMeshes = [];
  90215. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  90216. var originalIndices = this._mesh.getIndices();
  90217. for (i = 0; i < newTriangles.length; ++i) {
  90218. t = newTriangles[i]; //now get the new referencing point for each vertex
  90219. [0, 1, 2].forEach(function (idx) {
  90220. var id = originalIndices[t.originalOffset + idx];
  90221. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  90222. if (offset < 0)
  90223. offset = 0;
  90224. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  90225. });
  90226. }
  90227. //overwriting the old vertex buffers and indices.
  90228. this._reconstructedMesh.setIndices(newIndicesArray);
  90229. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  90230. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  90231. if (newUVsData.length > 0)
  90232. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  90233. if (newColorsData.length > 0)
  90234. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  90235. //create submesh
  90236. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  90237. if (submeshIndex > 0) {
  90238. this._reconstructedMesh.subMeshes = [];
  90239. submeshesArray.forEach(function (submesh) {
  90240. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  90241. });
  90242. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  90243. }
  90244. };
  90245. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  90246. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  90247. this._reconstructedMesh.material = this._mesh.material;
  90248. this._reconstructedMesh.parent = this._mesh.parent;
  90249. this._reconstructedMesh.isVisible = false;
  90250. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  90251. };
  90252. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  90253. for (var i = 0; i < vertex1.triangleCount; ++i) {
  90254. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  90255. if (t.deleted)
  90256. continue;
  90257. var s = this.references[vertex1.triangleStart + i].vertexId;
  90258. var v1 = t.vertices[(s + 1) % 3];
  90259. var v2 = t.vertices[(s + 2) % 3];
  90260. if ((v1 === vertex2 || v2 === vertex2)) {
  90261. deletedArray[i] = true;
  90262. delTr.push(t);
  90263. continue;
  90264. }
  90265. var d1 = v1.position.subtract(point);
  90266. d1 = d1.normalize();
  90267. var d2 = v2.position.subtract(point);
  90268. d2 = d2.normalize();
  90269. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  90270. return true;
  90271. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  90272. deletedArray[i] = false;
  90273. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  90274. return true;
  90275. }
  90276. return false;
  90277. };
  90278. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  90279. var newDeleted = deletedTriangles;
  90280. for (var i = 0; i < vertex.triangleCount; ++i) {
  90281. var ref = this.references[vertex.triangleStart + i];
  90282. var t = this.triangles[ref.triangleId];
  90283. if (t.deleted)
  90284. continue;
  90285. if (deletedArray[i] && t.deletePending) {
  90286. t.deleted = true;
  90287. newDeleted++;
  90288. continue;
  90289. }
  90290. t.vertices[ref.vertexId] = origVertex;
  90291. t.isDirty = true;
  90292. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  90293. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  90294. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  90295. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  90296. this.references.push(ref);
  90297. }
  90298. return newDeleted;
  90299. };
  90300. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  90301. for (var i = 0; i < this.vertices.length; ++i) {
  90302. var vCount = [];
  90303. var vId = [];
  90304. var v = this.vertices[i];
  90305. var j;
  90306. for (j = 0; j < v.triangleCount; ++j) {
  90307. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  90308. for (var ii = 0; ii < 3; ii++) {
  90309. var ofs = 0;
  90310. var vv = triangle.vertices[ii];
  90311. while (ofs < vCount.length) {
  90312. if (vId[ofs] === vv.id)
  90313. break;
  90314. ++ofs;
  90315. }
  90316. if (ofs === vCount.length) {
  90317. vCount.push(1);
  90318. vId.push(vv.id);
  90319. }
  90320. else {
  90321. vCount[ofs]++;
  90322. }
  90323. }
  90324. }
  90325. for (j = 0; j < vCount.length; ++j) {
  90326. if (vCount[j] === 1) {
  90327. this.vertices[vId[j]].isBorder = true;
  90328. }
  90329. else {
  90330. this.vertices[vId[j]].isBorder = false;
  90331. }
  90332. }
  90333. }
  90334. };
  90335. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  90336. if (identifyBorders === void 0) { identifyBorders = false; }
  90337. var i;
  90338. if (!identifyBorders) {
  90339. var newTrianglesVector = [];
  90340. for (i = 0; i < this.triangles.length; ++i) {
  90341. if (!this.triangles[i].deleted) {
  90342. newTrianglesVector.push(this.triangles[i]);
  90343. }
  90344. }
  90345. this.triangles = newTrianglesVector;
  90346. }
  90347. for (i = 0; i < this.vertices.length; ++i) {
  90348. this.vertices[i].triangleCount = 0;
  90349. this.vertices[i].triangleStart = 0;
  90350. }
  90351. var t;
  90352. var j;
  90353. var v;
  90354. for (i = 0; i < this.triangles.length; ++i) {
  90355. t = this.triangles[i];
  90356. for (j = 0; j < 3; ++j) {
  90357. v = t.vertices[j];
  90358. v.triangleCount++;
  90359. }
  90360. }
  90361. var tStart = 0;
  90362. for (i = 0; i < this.vertices.length; ++i) {
  90363. this.vertices[i].triangleStart = tStart;
  90364. tStart += this.vertices[i].triangleCount;
  90365. this.vertices[i].triangleCount = 0;
  90366. }
  90367. var newReferences = new Array(this.triangles.length * 3);
  90368. for (i = 0; i < this.triangles.length; ++i) {
  90369. t = this.triangles[i];
  90370. for (j = 0; j < 3; ++j) {
  90371. v = t.vertices[j];
  90372. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  90373. v.triangleCount++;
  90374. }
  90375. }
  90376. this.references = newReferences;
  90377. if (identifyBorders) {
  90378. this.identifyBorder();
  90379. }
  90380. };
  90381. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  90382. var x = point.x;
  90383. var y = point.y;
  90384. var z = point.z;
  90385. 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
  90386. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  90387. };
  90388. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  90389. var q = vertex1.q.add(vertex2.q);
  90390. var border = vertex1.isBorder && vertex2.isBorder;
  90391. var error = 0;
  90392. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  90393. if (qDet !== 0 && !border) {
  90394. if (!pointResult) {
  90395. pointResult = BABYLON.Vector3.Zero();
  90396. }
  90397. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  90398. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  90399. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  90400. error = this.vertexError(q, pointResult);
  90401. }
  90402. else {
  90403. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  90404. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  90405. var error1 = this.vertexError(q, vertex1.position);
  90406. var error2 = this.vertexError(q, vertex2.position);
  90407. var error3 = this.vertexError(q, p3);
  90408. error = Math.min(error1, error2, error3);
  90409. if (error === error1) {
  90410. if (pointResult) {
  90411. pointResult.copyFrom(vertex1.position);
  90412. }
  90413. }
  90414. else if (error === error2) {
  90415. if (pointResult) {
  90416. pointResult.copyFrom(vertex2.position);
  90417. }
  90418. }
  90419. else {
  90420. if (pointResult) {
  90421. pointResult.copyFrom(p3);
  90422. }
  90423. }
  90424. }
  90425. return error;
  90426. };
  90427. return QuadraticErrorSimplification;
  90428. }());
  90429. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  90430. })(BABYLON || (BABYLON = {}));
  90431. //# sourceMappingURL=babylon.meshSimplification.js.map
  90432. var BABYLON;
  90433. (function (BABYLON) {
  90434. var MeshLODLevel = /** @class */ (function () {
  90435. function MeshLODLevel(distance, mesh) {
  90436. this.distance = distance;
  90437. this.mesh = mesh;
  90438. }
  90439. return MeshLODLevel;
  90440. }());
  90441. BABYLON.MeshLODLevel = MeshLODLevel;
  90442. })(BABYLON || (BABYLON = {}));
  90443. //# sourceMappingURL=babylon.meshLODLevel.js.map
  90444. var BABYLON;
  90445. (function (BABYLON) {
  90446. /**
  90447. * Defines the root class used to create scene optimization to use with SceneOptimizer
  90448. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90449. */
  90450. var SceneOptimization = /** @class */ (function () {
  90451. /**
  90452. * Creates the SceneOptimization object
  90453. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90454. * @param desc defines the description associated with the optimization
  90455. */
  90456. function SceneOptimization(
  90457. /**
  90458. * Defines the priority of this optimization (0 by default which means first in the list)
  90459. */
  90460. priority) {
  90461. if (priority === void 0) { priority = 0; }
  90462. this.priority = priority;
  90463. }
  90464. /**
  90465. * Gets a string describing the action executed by the current optimization
  90466. * @returns description string
  90467. */
  90468. SceneOptimization.prototype.getDescription = function () {
  90469. return "";
  90470. };
  90471. /**
  90472. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90473. * @param scene defines the current scene where to apply this optimization
  90474. * @param optimizer defines the current optimizer
  90475. * @returns true if everything that can be done was applied
  90476. */
  90477. SceneOptimization.prototype.apply = function (scene, optimizer) {
  90478. return true;
  90479. };
  90480. ;
  90481. return SceneOptimization;
  90482. }());
  90483. BABYLON.SceneOptimization = SceneOptimization;
  90484. /**
  90485. * Defines an optimization used to reduce the size of render target textures
  90486. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90487. */
  90488. var TextureOptimization = /** @class */ (function (_super) {
  90489. __extends(TextureOptimization, _super);
  90490. /**
  90491. * Creates the TextureOptimization object
  90492. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90493. * @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
  90494. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90495. */
  90496. function TextureOptimization(
  90497. /**
  90498. * Defines the priority of this optimization (0 by default which means first in the list)
  90499. */
  90500. priority,
  90501. /**
  90502. * 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
  90503. */
  90504. maximumSize,
  90505. /**
  90506. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90507. */
  90508. step) {
  90509. if (priority === void 0) { priority = 0; }
  90510. if (maximumSize === void 0) { maximumSize = 1024; }
  90511. if (step === void 0) { step = 0.5; }
  90512. var _this = _super.call(this, priority) || this;
  90513. _this.priority = priority;
  90514. _this.maximumSize = maximumSize;
  90515. _this.step = step;
  90516. return _this;
  90517. }
  90518. /**
  90519. * Gets a string describing the action executed by the current optimization
  90520. * @returns description string
  90521. */
  90522. TextureOptimization.prototype.getDescription = function () {
  90523. return "Reducing render target texture size to " + this.maximumSize;
  90524. };
  90525. /**
  90526. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90527. * @param scene defines the current scene where to apply this optimization
  90528. * @param optimizer defines the current optimizer
  90529. * @returns true if everything that can be done was applied
  90530. */
  90531. TextureOptimization.prototype.apply = function (scene, optimizer) {
  90532. var allDone = true;
  90533. for (var index = 0; index < scene.textures.length; index++) {
  90534. var texture = scene.textures[index];
  90535. if (!texture.canRescale || texture.getContext) {
  90536. continue;
  90537. }
  90538. var currentSize = texture.getSize();
  90539. var maxDimension = Math.max(currentSize.width, currentSize.height);
  90540. if (maxDimension > this.maximumSize) {
  90541. texture.scale(this.step);
  90542. allDone = false;
  90543. }
  90544. }
  90545. return allDone;
  90546. };
  90547. return TextureOptimization;
  90548. }(SceneOptimization));
  90549. BABYLON.TextureOptimization = TextureOptimization;
  90550. /**
  90551. * Defines an optimization used to increase or decrease the rendering resolution
  90552. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90553. */
  90554. var HardwareScalingOptimization = /** @class */ (function (_super) {
  90555. __extends(HardwareScalingOptimization, _super);
  90556. /**
  90557. * Creates the HardwareScalingOptimization object
  90558. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90559. * @param maximumScale defines the maximum scale to use (2 by default)
  90560. * @param step defines the step to use between two passes (0.5 by default)
  90561. */
  90562. function HardwareScalingOptimization(
  90563. /**
  90564. * Defines the priority of this optimization (0 by default which means first in the list)
  90565. */
  90566. priority,
  90567. /**
  90568. * Defines the maximum scale to use (2 by default)
  90569. */
  90570. maximumScale,
  90571. /**
  90572. * Defines the step to use between two passes (0.5 by default)
  90573. */
  90574. step) {
  90575. if (priority === void 0) { priority = 0; }
  90576. if (maximumScale === void 0) { maximumScale = 2; }
  90577. if (step === void 0) { step = 0.25; }
  90578. var _this = _super.call(this, priority) || this;
  90579. _this.priority = priority;
  90580. _this.maximumScale = maximumScale;
  90581. _this.step = step;
  90582. _this._currentScale = -1;
  90583. _this._directionOffset = 1;
  90584. return _this;
  90585. }
  90586. /**
  90587. * Gets a string describing the action executed by the current optimization
  90588. * @return description string
  90589. */
  90590. HardwareScalingOptimization.prototype.getDescription = function () {
  90591. return "Setting hardware scaling level to " + this._currentScale;
  90592. };
  90593. /**
  90594. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90595. * @param scene defines the current scene where to apply this optimization
  90596. * @param optimizer defines the current optimizer
  90597. * @returns true if everything that can be done was applied
  90598. */
  90599. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  90600. if (this._currentScale === -1) {
  90601. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  90602. if (this._currentScale > this.maximumScale) {
  90603. this._directionOffset = -1;
  90604. }
  90605. }
  90606. this._currentScale += this._directionOffset * this.step;
  90607. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  90608. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  90609. };
  90610. ;
  90611. return HardwareScalingOptimization;
  90612. }(SceneOptimization));
  90613. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  90614. /**
  90615. * Defines an optimization used to remove shadows
  90616. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90617. */
  90618. var ShadowsOptimization = /** @class */ (function (_super) {
  90619. __extends(ShadowsOptimization, _super);
  90620. function ShadowsOptimization() {
  90621. return _super !== null && _super.apply(this, arguments) || this;
  90622. }
  90623. /**
  90624. * Gets a string describing the action executed by the current optimization
  90625. * @return description string
  90626. */
  90627. ShadowsOptimization.prototype.getDescription = function () {
  90628. return "Turning shadows on/off";
  90629. };
  90630. /**
  90631. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90632. * @param scene defines the current scene where to apply this optimization
  90633. * @param optimizer defines the current optimizer
  90634. * @returns true if everything that can be done was applied
  90635. */
  90636. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  90637. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90638. return true;
  90639. };
  90640. ;
  90641. return ShadowsOptimization;
  90642. }(SceneOptimization));
  90643. BABYLON.ShadowsOptimization = ShadowsOptimization;
  90644. /**
  90645. * Defines an optimization used to turn post-processes off
  90646. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90647. */
  90648. var PostProcessesOptimization = /** @class */ (function (_super) {
  90649. __extends(PostProcessesOptimization, _super);
  90650. function PostProcessesOptimization() {
  90651. return _super !== null && _super.apply(this, arguments) || this;
  90652. }
  90653. /**
  90654. * Gets a string describing the action executed by the current optimization
  90655. * @return description string
  90656. */
  90657. PostProcessesOptimization.prototype.getDescription = function () {
  90658. return "Turning post-processes on/off";
  90659. };
  90660. /**
  90661. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90662. * @param scene defines the current scene where to apply this optimization
  90663. * @param optimizer defines the current optimizer
  90664. * @returns true if everything that can be done was applied
  90665. */
  90666. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  90667. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  90668. return true;
  90669. };
  90670. ;
  90671. return PostProcessesOptimization;
  90672. }(SceneOptimization));
  90673. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  90674. /**
  90675. * Defines an optimization used to turn lens flares off
  90676. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90677. */
  90678. var LensFlaresOptimization = /** @class */ (function (_super) {
  90679. __extends(LensFlaresOptimization, _super);
  90680. function LensFlaresOptimization() {
  90681. return _super !== null && _super.apply(this, arguments) || this;
  90682. }
  90683. /**
  90684. * Gets a string describing the action executed by the current optimization
  90685. * @return description string
  90686. */
  90687. LensFlaresOptimization.prototype.getDescription = function () {
  90688. return "Turning lens flares on/off";
  90689. };
  90690. /**
  90691. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90692. * @param scene defines the current scene where to apply this optimization
  90693. * @param optimizer defines the current optimizer
  90694. * @returns true if everything that can be done was applied
  90695. */
  90696. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  90697. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  90698. return true;
  90699. };
  90700. ;
  90701. return LensFlaresOptimization;
  90702. }(SceneOptimization));
  90703. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  90704. /**
  90705. * Defines an optimization based on user defined callback.
  90706. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90707. */
  90708. var CustomOptimization = /** @class */ (function (_super) {
  90709. __extends(CustomOptimization, _super);
  90710. function CustomOptimization() {
  90711. return _super !== null && _super.apply(this, arguments) || this;
  90712. }
  90713. /**
  90714. * Gets a string describing the action executed by the current optimization
  90715. * @returns description string
  90716. */
  90717. CustomOptimization.prototype.getDescription = function () {
  90718. if (this.onGetDescription) {
  90719. return this.onGetDescription();
  90720. }
  90721. return "Running user defined callback";
  90722. };
  90723. /**
  90724. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90725. * @param scene defines the current scene where to apply this optimization
  90726. * @param optimizer defines the current optimizer
  90727. * @returns true if everything that can be done was applied
  90728. */
  90729. CustomOptimization.prototype.apply = function (scene, optimizer) {
  90730. if (this.onApply) {
  90731. return this.onApply(scene, optimizer);
  90732. }
  90733. return true;
  90734. };
  90735. ;
  90736. return CustomOptimization;
  90737. }(SceneOptimization));
  90738. BABYLON.CustomOptimization = CustomOptimization;
  90739. /**
  90740. * Defines an optimization used to turn particles off
  90741. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90742. */
  90743. var ParticlesOptimization = /** @class */ (function (_super) {
  90744. __extends(ParticlesOptimization, _super);
  90745. function ParticlesOptimization() {
  90746. return _super !== null && _super.apply(this, arguments) || this;
  90747. }
  90748. /**
  90749. * Gets a string describing the action executed by the current optimization
  90750. * @return description string
  90751. */
  90752. ParticlesOptimization.prototype.getDescription = function () {
  90753. return "Turning particles on/off";
  90754. };
  90755. /**
  90756. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90757. * @param scene defines the current scene where to apply this optimization
  90758. * @param optimizer defines the current optimizer
  90759. * @returns true if everything that can be done was applied
  90760. */
  90761. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  90762. scene.particlesEnabled = optimizer.isInImprovementMode;
  90763. return true;
  90764. };
  90765. ;
  90766. return ParticlesOptimization;
  90767. }(SceneOptimization));
  90768. BABYLON.ParticlesOptimization = ParticlesOptimization;
  90769. /**
  90770. * Defines an optimization used to turn render targets off
  90771. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90772. */
  90773. var RenderTargetsOptimization = /** @class */ (function (_super) {
  90774. __extends(RenderTargetsOptimization, _super);
  90775. function RenderTargetsOptimization() {
  90776. return _super !== null && _super.apply(this, arguments) || this;
  90777. }
  90778. /**
  90779. * Gets a string describing the action executed by the current optimization
  90780. * @return description string
  90781. */
  90782. RenderTargetsOptimization.prototype.getDescription = function () {
  90783. return "Turning render targets off";
  90784. };
  90785. /**
  90786. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90787. * @param scene defines the current scene where to apply this optimization
  90788. * @param optimizer defines the current optimizer
  90789. * @returns true if everything that can be done was applied
  90790. */
  90791. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  90792. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  90793. return true;
  90794. };
  90795. ;
  90796. return RenderTargetsOptimization;
  90797. }(SceneOptimization));
  90798. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  90799. /**
  90800. * Defines an optimization used to merge meshes with compatible materials
  90801. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90802. */
  90803. var MergeMeshesOptimization = /** @class */ (function (_super) {
  90804. __extends(MergeMeshesOptimization, _super);
  90805. function MergeMeshesOptimization() {
  90806. var _this = _super !== null && _super.apply(this, arguments) || this;
  90807. _this._canBeMerged = function (abstractMesh) {
  90808. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  90809. return false;
  90810. }
  90811. var mesh = abstractMesh;
  90812. if (!mesh.isVisible || !mesh.isEnabled()) {
  90813. return false;
  90814. }
  90815. if (mesh.instances.length > 0) {
  90816. return false;
  90817. }
  90818. if (mesh.skeleton || mesh.hasLODLevels) {
  90819. return false;
  90820. }
  90821. if (mesh.parent) {
  90822. return false;
  90823. }
  90824. return true;
  90825. };
  90826. return _this;
  90827. }
  90828. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  90829. /**
  90830. * Gets or sets a boolean which defines if optimization octree has to be updated
  90831. */
  90832. get: function () {
  90833. return MergeMeshesOptimization._UpdateSelectionTree;
  90834. },
  90835. /**
  90836. * Gets or sets a boolean which defines if optimization octree has to be updated
  90837. */
  90838. set: function (value) {
  90839. MergeMeshesOptimization._UpdateSelectionTree = value;
  90840. },
  90841. enumerable: true,
  90842. configurable: true
  90843. });
  90844. /**
  90845. * Gets a string describing the action executed by the current optimization
  90846. * @return description string
  90847. */
  90848. MergeMeshesOptimization.prototype.getDescription = function () {
  90849. return "Merging similar meshes together";
  90850. };
  90851. /**
  90852. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90853. * @param scene defines the current scene where to apply this optimization
  90854. * @param optimizer defines the current optimizer
  90855. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  90856. * @returns true if everything that can be done was applied
  90857. */
  90858. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  90859. var globalPool = scene.meshes.slice(0);
  90860. var globalLength = globalPool.length;
  90861. for (var index = 0; index < globalLength; index++) {
  90862. var currentPool = new Array();
  90863. var current = globalPool[index];
  90864. // Checks
  90865. if (!this._canBeMerged(current)) {
  90866. continue;
  90867. }
  90868. currentPool.push(current);
  90869. // Find compatible meshes
  90870. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  90871. var otherMesh = globalPool[subIndex];
  90872. if (!this._canBeMerged(otherMesh)) {
  90873. continue;
  90874. }
  90875. if (otherMesh.material !== current.material) {
  90876. continue;
  90877. }
  90878. if (otherMesh.checkCollisions !== current.checkCollisions) {
  90879. continue;
  90880. }
  90881. currentPool.push(otherMesh);
  90882. globalLength--;
  90883. globalPool.splice(subIndex, 1);
  90884. subIndex--;
  90885. }
  90886. if (currentPool.length < 2) {
  90887. continue;
  90888. }
  90889. // Merge meshes
  90890. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  90891. }
  90892. if (updateSelectionTree != undefined) {
  90893. if (updateSelectionTree) {
  90894. scene.createOrUpdateSelectionOctree();
  90895. }
  90896. }
  90897. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  90898. scene.createOrUpdateSelectionOctree();
  90899. }
  90900. return true;
  90901. };
  90902. ;
  90903. MergeMeshesOptimization._UpdateSelectionTree = false;
  90904. return MergeMeshesOptimization;
  90905. }(SceneOptimization));
  90906. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  90907. /**
  90908. * Defines a list of options used by SceneOptimizer
  90909. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90910. */
  90911. var SceneOptimizerOptions = /** @class */ (function () {
  90912. /**
  90913. * Creates a new list of options used by SceneOptimizer
  90914. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  90915. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  90916. */
  90917. function SceneOptimizerOptions(
  90918. /**
  90919. * Defines the target frame rate to reach (60 by default)
  90920. */
  90921. targetFrameRate,
  90922. /**
  90923. * Defines the interval between two checkes (2000ms by default)
  90924. */
  90925. trackerDuration) {
  90926. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  90927. if (trackerDuration === void 0) { trackerDuration = 2000; }
  90928. this.targetFrameRate = targetFrameRate;
  90929. this.trackerDuration = trackerDuration;
  90930. /**
  90931. * Gets the list of optimizations to apply
  90932. */
  90933. this.optimizations = new Array();
  90934. }
  90935. /**
  90936. * Add a new optimization
  90937. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  90938. * @returns the current SceneOptimizerOptions
  90939. */
  90940. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  90941. this.optimizations.push(optimization);
  90942. return this;
  90943. };
  90944. /**
  90945. * Add a new custom optimization
  90946. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  90947. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  90948. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90949. * @returns the current SceneOptimizerOptions
  90950. */
  90951. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  90952. if (priority === void 0) { priority = 0; }
  90953. var optimization = new CustomOptimization(priority);
  90954. optimization.onApply = onApply;
  90955. optimization.onGetDescription = onGetDescription;
  90956. this.optimizations.push(optimization);
  90957. return this;
  90958. };
  90959. /**
  90960. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  90961. * @param targetFrameRate defines the target frame rate (60 by default)
  90962. * @returns a SceneOptimizerOptions object
  90963. */
  90964. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  90965. var result = new SceneOptimizerOptions(targetFrameRate);
  90966. var priority = 0;
  90967. result.addOptimization(new MergeMeshesOptimization(priority));
  90968. result.addOptimization(new ShadowsOptimization(priority));
  90969. result.addOptimization(new LensFlaresOptimization(priority));
  90970. // Next priority
  90971. priority++;
  90972. result.addOptimization(new PostProcessesOptimization(priority));
  90973. result.addOptimization(new ParticlesOptimization(priority));
  90974. // Next priority
  90975. priority++;
  90976. result.addOptimization(new TextureOptimization(priority, 1024));
  90977. return result;
  90978. };
  90979. /**
  90980. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  90981. * @param targetFrameRate defines the target frame rate (60 by default)
  90982. * @returns a SceneOptimizerOptions object
  90983. */
  90984. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  90985. var result = new SceneOptimizerOptions(targetFrameRate);
  90986. var priority = 0;
  90987. result.addOptimization(new MergeMeshesOptimization(priority));
  90988. result.addOptimization(new ShadowsOptimization(priority));
  90989. result.addOptimization(new LensFlaresOptimization(priority));
  90990. // Next priority
  90991. priority++;
  90992. result.addOptimization(new PostProcessesOptimization(priority));
  90993. result.addOptimization(new ParticlesOptimization(priority));
  90994. // Next priority
  90995. priority++;
  90996. result.addOptimization(new TextureOptimization(priority, 512));
  90997. // Next priority
  90998. priority++;
  90999. result.addOptimization(new RenderTargetsOptimization(priority));
  91000. // Next priority
  91001. priority++;
  91002. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  91003. return result;
  91004. };
  91005. /**
  91006. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  91007. * @param targetFrameRate defines the target frame rate (60 by default)
  91008. * @returns a SceneOptimizerOptions object
  91009. */
  91010. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  91011. var result = new SceneOptimizerOptions(targetFrameRate);
  91012. var priority = 0;
  91013. result.addOptimization(new MergeMeshesOptimization(priority));
  91014. result.addOptimization(new ShadowsOptimization(priority));
  91015. result.addOptimization(new LensFlaresOptimization(priority));
  91016. // Next priority
  91017. priority++;
  91018. result.addOptimization(new PostProcessesOptimization(priority));
  91019. result.addOptimization(new ParticlesOptimization(priority));
  91020. // Next priority
  91021. priority++;
  91022. result.addOptimization(new TextureOptimization(priority, 256));
  91023. // Next priority
  91024. priority++;
  91025. result.addOptimization(new RenderTargetsOptimization(priority));
  91026. // Next priority
  91027. priority++;
  91028. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  91029. return result;
  91030. };
  91031. return SceneOptimizerOptions;
  91032. }());
  91033. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  91034. /**
  91035. * Class used to run optimizations in order to reach a target frame rate
  91036. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91037. */
  91038. var SceneOptimizer = /** @class */ (function () {
  91039. /**
  91040. * Creates a new SceneOptimizer
  91041. * @param scene defines the scene to work on
  91042. * @param options defines the options to use with the SceneOptimizer
  91043. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  91044. * @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)
  91045. */
  91046. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  91047. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  91048. if (improvementMode === void 0) { improvementMode = false; }
  91049. var _this = this;
  91050. this._isRunning = false;
  91051. this._currentPriorityLevel = 0;
  91052. this._targetFrameRate = 60;
  91053. this._trackerDuration = 2000;
  91054. this._currentFrameRate = 0;
  91055. this._improvementMode = false;
  91056. /**
  91057. * Defines an observable called when the optimizer reaches the target frame rate
  91058. */
  91059. this.onSuccessObservable = new BABYLON.Observable();
  91060. /**
  91061. * Defines an observable called when the optimizer enables an optimization
  91062. */
  91063. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  91064. /**
  91065. * Defines an observable called when the optimizer is not able to reach the target frame rate
  91066. */
  91067. this.onFailureObservable = new BABYLON.Observable();
  91068. if (!options) {
  91069. this._options = new SceneOptimizerOptions();
  91070. }
  91071. else {
  91072. this._options = options;
  91073. }
  91074. if (this._options.targetFrameRate) {
  91075. this._targetFrameRate = this._options.targetFrameRate;
  91076. }
  91077. if (this._options.trackerDuration) {
  91078. this._trackerDuration = this._options.trackerDuration;
  91079. }
  91080. if (autoGeneratePriorities) {
  91081. var priority = 0;
  91082. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  91083. var optim = _a[_i];
  91084. optim.priority = priority++;
  91085. }
  91086. }
  91087. this._improvementMode = improvementMode;
  91088. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91089. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  91090. _this._sceneDisposeObserver = null;
  91091. _this.dispose();
  91092. });
  91093. }
  91094. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  91095. /**
  91096. * Gets a boolean indicating if the optimizer is in improvement mode
  91097. */
  91098. get: function () {
  91099. return this._improvementMode;
  91100. },
  91101. enumerable: true,
  91102. configurable: true
  91103. });
  91104. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  91105. /**
  91106. * Gets the current priority level (0 at start)
  91107. */
  91108. get: function () {
  91109. return this._currentPriorityLevel;
  91110. },
  91111. enumerable: true,
  91112. configurable: true
  91113. });
  91114. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  91115. /**
  91116. * Gets the current frame rate checked by the SceneOptimizer
  91117. */
  91118. get: function () {
  91119. return this._currentFrameRate;
  91120. },
  91121. enumerable: true,
  91122. configurable: true
  91123. });
  91124. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  91125. /**
  91126. * Gets or sets the current target frame rate (60 by default)
  91127. */
  91128. get: function () {
  91129. return this._targetFrameRate;
  91130. },
  91131. /**
  91132. * Gets or sets the current target frame rate (60 by default)
  91133. */
  91134. set: function (value) {
  91135. this._targetFrameRate = value;
  91136. },
  91137. enumerable: true,
  91138. configurable: true
  91139. });
  91140. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  91141. /**
  91142. * Gets or sets the current interval between two checks (every 2000ms by default)
  91143. */
  91144. get: function () {
  91145. return this._trackerDuration;
  91146. },
  91147. /**
  91148. * Gets or sets the current interval between two checks (every 2000ms by default)
  91149. */
  91150. set: function (value) {
  91151. this._trackerDuration = value;
  91152. },
  91153. enumerable: true,
  91154. configurable: true
  91155. });
  91156. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  91157. /**
  91158. * Gets the list of active optimizations
  91159. */
  91160. get: function () {
  91161. return this._options.optimizations;
  91162. },
  91163. enumerable: true,
  91164. configurable: true
  91165. });
  91166. /**
  91167. * Stops the current optimizer
  91168. */
  91169. SceneOptimizer.prototype.stop = function () {
  91170. this._isRunning = false;
  91171. };
  91172. /**
  91173. * Reset the optimizer to initial step (current priority level = 0)
  91174. */
  91175. SceneOptimizer.prototype.reset = function () {
  91176. this._currentPriorityLevel = 0;
  91177. };
  91178. /**
  91179. * Start the optimizer. By default it will try to reach a specific framerate
  91180. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  91181. */
  91182. SceneOptimizer.prototype.start = function () {
  91183. var _this = this;
  91184. if (this._isRunning) {
  91185. return;
  91186. }
  91187. this._isRunning = true;
  91188. // Let's wait for the scene to be ready before running our check
  91189. this._scene.executeWhenReady(function () {
  91190. setTimeout(function () {
  91191. _this._checkCurrentState();
  91192. }, _this._trackerDuration);
  91193. });
  91194. };
  91195. SceneOptimizer.prototype._checkCurrentState = function () {
  91196. var _this = this;
  91197. if (!this._isRunning) {
  91198. return;
  91199. }
  91200. var scene = this._scene;
  91201. var options = this._options;
  91202. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  91203. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  91204. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  91205. this._isRunning = false;
  91206. this.onSuccessObservable.notifyObservers(this);
  91207. return;
  91208. }
  91209. // Apply current level of optimizations
  91210. var allDone = true;
  91211. var noOptimizationApplied = true;
  91212. for (var index = 0; index < options.optimizations.length; index++) {
  91213. var optimization = options.optimizations[index];
  91214. if (optimization.priority === this._currentPriorityLevel) {
  91215. noOptimizationApplied = false;
  91216. allDone = allDone && optimization.apply(scene, this);
  91217. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  91218. }
  91219. }
  91220. // If no optimization was applied, this is a failure :(
  91221. if (noOptimizationApplied) {
  91222. this._isRunning = false;
  91223. this.onFailureObservable.notifyObservers(this);
  91224. return;
  91225. }
  91226. // If all optimizations were done, move to next level
  91227. if (allDone) {
  91228. this._currentPriorityLevel++;
  91229. }
  91230. // Let's the system running for a specific amount of time before checking FPS
  91231. scene.executeWhenReady(function () {
  91232. setTimeout(function () {
  91233. _this._checkCurrentState();
  91234. }, _this._trackerDuration);
  91235. });
  91236. };
  91237. /**
  91238. * Release all resources
  91239. */
  91240. SceneOptimizer.prototype.dispose = function () {
  91241. this.stop();
  91242. this.onSuccessObservable.clear();
  91243. this.onFailureObservable.clear();
  91244. this.onNewOptimizationAppliedObservable.clear();
  91245. if (this._sceneDisposeObserver) {
  91246. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  91247. }
  91248. };
  91249. /**
  91250. * Helper function to create a SceneOptimizer with one single line of code
  91251. * @param scene defines the scene to work on
  91252. * @param options defines the options to use with the SceneOptimizer
  91253. * @param onSuccess defines a callback to call on success
  91254. * @param onFailure defines a callback to call on failure
  91255. * @returns the new SceneOptimizer object
  91256. */
  91257. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  91258. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  91259. if (onSuccess) {
  91260. optimizer.onSuccessObservable.add(function () {
  91261. onSuccess();
  91262. });
  91263. }
  91264. if (onFailure) {
  91265. optimizer.onFailureObservable.add(function () {
  91266. onFailure();
  91267. });
  91268. }
  91269. optimizer.start();
  91270. return optimizer;
  91271. };
  91272. return SceneOptimizer;
  91273. }());
  91274. BABYLON.SceneOptimizer = SceneOptimizer;
  91275. })(BABYLON || (BABYLON = {}));
  91276. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  91277. var BABYLON;
  91278. (function (BABYLON) {
  91279. var OutlineRenderer = /** @class */ (function () {
  91280. function OutlineRenderer(scene) {
  91281. this.zOffset = 1;
  91282. this._scene = scene;
  91283. }
  91284. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  91285. var _this = this;
  91286. if (useOverlay === void 0) { useOverlay = false; }
  91287. var scene = this._scene;
  91288. var engine = this._scene.getEngine();
  91289. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91290. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  91291. return;
  91292. }
  91293. var mesh = subMesh.getRenderingMesh();
  91294. var material = subMesh.getMaterial();
  91295. if (!material || !scene.activeCamera) {
  91296. return;
  91297. }
  91298. engine.enableEffect(this._effect);
  91299. // Logarithmic depth
  91300. if (material.useLogarithmicDepth) {
  91301. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  91302. }
  91303. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  91304. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  91305. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  91306. // Bones
  91307. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91308. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91309. }
  91310. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  91311. // Alpha test
  91312. if (material && material.needAlphaTesting()) {
  91313. var alphaTexture = material.getAlphaTestTexture();
  91314. if (alphaTexture) {
  91315. this._effect.setTexture("diffuseSampler", alphaTexture);
  91316. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  91317. }
  91318. }
  91319. engine.setZOffset(-this.zOffset);
  91320. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  91321. engine.setZOffset(0);
  91322. };
  91323. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  91324. var defines = [];
  91325. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  91326. var mesh = subMesh.getMesh();
  91327. var material = subMesh.getMaterial();
  91328. if (material) {
  91329. // Alpha test
  91330. if (material.needAlphaTesting()) {
  91331. defines.push("#define ALPHATEST");
  91332. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91333. attribs.push(BABYLON.VertexBuffer.UVKind);
  91334. defines.push("#define UV1");
  91335. }
  91336. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  91337. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91338. defines.push("#define UV2");
  91339. }
  91340. }
  91341. //Logarithmic depth
  91342. if (material.useLogarithmicDepth) {
  91343. defines.push("#define LOGARITHMICDEPTH");
  91344. }
  91345. }
  91346. // Bones
  91347. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91348. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91349. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91350. if (mesh.numBoneInfluencers > 4) {
  91351. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91352. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91353. }
  91354. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91355. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  91356. }
  91357. else {
  91358. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91359. }
  91360. // Instances
  91361. if (useInstances) {
  91362. defines.push("#define INSTANCES");
  91363. attribs.push("world0");
  91364. attribs.push("world1");
  91365. attribs.push("world2");
  91366. attribs.push("world3");
  91367. }
  91368. // Get correct effect
  91369. var join = defines.join("\n");
  91370. if (this._cachedDefines !== join) {
  91371. this._cachedDefines = join;
  91372. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  91373. }
  91374. return this._effect.isReady();
  91375. };
  91376. return OutlineRenderer;
  91377. }());
  91378. BABYLON.OutlineRenderer = OutlineRenderer;
  91379. })(BABYLON || (BABYLON = {}));
  91380. //# sourceMappingURL=babylon.outlineRenderer.js.map
  91381. var BABYLON;
  91382. (function (BABYLON) {
  91383. var FaceAdjacencies = /** @class */ (function () {
  91384. function FaceAdjacencies() {
  91385. this.edges = new Array();
  91386. this.edgesConnectedCount = 0;
  91387. }
  91388. return FaceAdjacencies;
  91389. }());
  91390. var EdgesRenderer = /** @class */ (function () {
  91391. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  91392. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  91393. if (epsilon === void 0) { epsilon = 0.95; }
  91394. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  91395. this.edgesWidthScalerForOrthographic = 1000.0;
  91396. this.edgesWidthScalerForPerspective = 50.0;
  91397. this._linesPositions = new Array();
  91398. this._linesNormals = new Array();
  91399. this._linesIndices = new Array();
  91400. this._buffers = {};
  91401. this._checkVerticesInsteadOfIndices = false;
  91402. this._source = source;
  91403. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  91404. this._epsilon = epsilon;
  91405. this._prepareRessources();
  91406. this._generateEdgesLines();
  91407. }
  91408. EdgesRenderer.prototype._prepareRessources = function () {
  91409. if (this._lineShader) {
  91410. return;
  91411. }
  91412. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  91413. attributes: ["position", "normal"],
  91414. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  91415. });
  91416. this._lineShader.disableDepthWrite = true;
  91417. this._lineShader.backFaceCulling = false;
  91418. };
  91419. EdgesRenderer.prototype._rebuild = function () {
  91420. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91421. if (buffer) {
  91422. buffer._rebuild();
  91423. }
  91424. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91425. if (buffer) {
  91426. buffer._rebuild();
  91427. }
  91428. var scene = this._source.getScene();
  91429. var engine = scene.getEngine();
  91430. this._ib = engine.createIndexBuffer(this._linesIndices);
  91431. };
  91432. EdgesRenderer.prototype.dispose = function () {
  91433. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91434. if (buffer) {
  91435. buffer.dispose();
  91436. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  91437. }
  91438. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91439. if (buffer) {
  91440. buffer.dispose();
  91441. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  91442. }
  91443. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  91444. this._lineShader.dispose();
  91445. };
  91446. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  91447. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  91448. return 0;
  91449. }
  91450. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  91451. return 1;
  91452. }
  91453. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  91454. return 2;
  91455. }
  91456. return -1;
  91457. };
  91458. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  91459. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  91460. return 0;
  91461. }
  91462. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  91463. return 1;
  91464. }
  91465. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  91466. return 2;
  91467. }
  91468. return -1;
  91469. };
  91470. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  91471. var needToCreateLine;
  91472. if (edge === undefined) {
  91473. needToCreateLine = true;
  91474. }
  91475. else {
  91476. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  91477. needToCreateLine = dotProduct < this._epsilon;
  91478. }
  91479. if (needToCreateLine) {
  91480. var offset = this._linesPositions.length / 3;
  91481. var normal = p0.subtract(p1);
  91482. normal.normalize();
  91483. // Positions
  91484. this._linesPositions.push(p0.x);
  91485. this._linesPositions.push(p0.y);
  91486. this._linesPositions.push(p0.z);
  91487. this._linesPositions.push(p0.x);
  91488. this._linesPositions.push(p0.y);
  91489. this._linesPositions.push(p0.z);
  91490. this._linesPositions.push(p1.x);
  91491. this._linesPositions.push(p1.y);
  91492. this._linesPositions.push(p1.z);
  91493. this._linesPositions.push(p1.x);
  91494. this._linesPositions.push(p1.y);
  91495. this._linesPositions.push(p1.z);
  91496. // Normals
  91497. this._linesNormals.push(p1.x);
  91498. this._linesNormals.push(p1.y);
  91499. this._linesNormals.push(p1.z);
  91500. this._linesNormals.push(-1);
  91501. this._linesNormals.push(p1.x);
  91502. this._linesNormals.push(p1.y);
  91503. this._linesNormals.push(p1.z);
  91504. this._linesNormals.push(1);
  91505. this._linesNormals.push(p0.x);
  91506. this._linesNormals.push(p0.y);
  91507. this._linesNormals.push(p0.z);
  91508. this._linesNormals.push(-1);
  91509. this._linesNormals.push(p0.x);
  91510. this._linesNormals.push(p0.y);
  91511. this._linesNormals.push(p0.z);
  91512. this._linesNormals.push(1);
  91513. // Indices
  91514. this._linesIndices.push(offset);
  91515. this._linesIndices.push(offset + 1);
  91516. this._linesIndices.push(offset + 2);
  91517. this._linesIndices.push(offset);
  91518. this._linesIndices.push(offset + 2);
  91519. this._linesIndices.push(offset + 3);
  91520. }
  91521. };
  91522. EdgesRenderer.prototype._generateEdgesLines = function () {
  91523. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91524. var indices = this._source.getIndices();
  91525. if (!indices || !positions) {
  91526. return;
  91527. }
  91528. // First let's find adjacencies
  91529. var adjacencies = new Array();
  91530. var faceNormals = new Array();
  91531. var index;
  91532. var faceAdjacencies;
  91533. // Prepare faces
  91534. for (index = 0; index < indices.length; index += 3) {
  91535. faceAdjacencies = new FaceAdjacencies();
  91536. var p0Index = indices[index];
  91537. var p1Index = indices[index + 1];
  91538. var p2Index = indices[index + 2];
  91539. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  91540. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  91541. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  91542. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  91543. faceNormal.normalize();
  91544. faceNormals.push(faceNormal);
  91545. adjacencies.push(faceAdjacencies);
  91546. }
  91547. // Scan
  91548. for (index = 0; index < adjacencies.length; index++) {
  91549. faceAdjacencies = adjacencies[index];
  91550. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  91551. var otherFaceAdjacencies = adjacencies[otherIndex];
  91552. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  91553. break;
  91554. }
  91555. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  91556. continue;
  91557. }
  91558. var otherP0 = indices[otherIndex * 3];
  91559. var otherP1 = indices[otherIndex * 3 + 1];
  91560. var otherP2 = indices[otherIndex * 3 + 2];
  91561. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  91562. var otherEdgeIndex = 0;
  91563. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  91564. continue;
  91565. }
  91566. switch (edgeIndex) {
  91567. case 0:
  91568. if (this._checkVerticesInsteadOfIndices) {
  91569. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91570. }
  91571. else {
  91572. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  91573. }
  91574. break;
  91575. case 1:
  91576. if (this._checkVerticesInsteadOfIndices) {
  91577. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91578. }
  91579. else {
  91580. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  91581. }
  91582. break;
  91583. case 2:
  91584. if (this._checkVerticesInsteadOfIndices) {
  91585. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91586. }
  91587. else {
  91588. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  91589. }
  91590. break;
  91591. }
  91592. if (otherEdgeIndex === -1) {
  91593. continue;
  91594. }
  91595. faceAdjacencies.edges[edgeIndex] = otherIndex;
  91596. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  91597. faceAdjacencies.edgesConnectedCount++;
  91598. otherFaceAdjacencies.edgesConnectedCount++;
  91599. if (faceAdjacencies.edgesConnectedCount === 3) {
  91600. break;
  91601. }
  91602. }
  91603. }
  91604. }
  91605. // Create lines
  91606. for (index = 0; index < adjacencies.length; index++) {
  91607. // 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
  91608. var current = adjacencies[index];
  91609. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  91610. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  91611. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  91612. }
  91613. // Merge into a single mesh
  91614. var engine = this._source.getScene().getEngine();
  91615. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  91616. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  91617. this._ib = engine.createIndexBuffer(this._linesIndices);
  91618. this._indicesCount = this._linesIndices.length;
  91619. };
  91620. EdgesRenderer.prototype.render = function () {
  91621. var scene = this._source.getScene();
  91622. if (!this._lineShader.isReady() || !scene.activeCamera) {
  91623. return;
  91624. }
  91625. var engine = scene.getEngine();
  91626. this._lineShader._preBind();
  91627. // VBOs
  91628. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  91629. scene.resetCachedMaterial();
  91630. this._lineShader.setColor4("color", this._source.edgesColor);
  91631. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  91632. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  91633. }
  91634. else {
  91635. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  91636. }
  91637. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  91638. this._lineShader.bind(this._source.getWorldMatrix());
  91639. // Draw order
  91640. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  91641. this._lineShader.unbind();
  91642. engine.setDepthWrite(true);
  91643. };
  91644. return EdgesRenderer;
  91645. }());
  91646. BABYLON.EdgesRenderer = EdgesRenderer;
  91647. })(BABYLON || (BABYLON = {}));
  91648. //# sourceMappingURL=babylon.edgesRenderer.js.map
  91649. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91650. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91651. s = arguments[i];
  91652. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91653. t[p] = s[p];
  91654. }
  91655. return t;
  91656. };
  91657. var BABYLON;
  91658. (function (BABYLON) {
  91659. /**
  91660. * The effect layer Helps adding post process effect blended with the main pass.
  91661. *
  91662. * This can be for instance use to generate glow or higlight effects on the scene.
  91663. *
  91664. * The effect layer class can not be used directly and is intented to inherited from to be
  91665. * customized per effects.
  91666. */
  91667. var EffectLayer = /** @class */ (function () {
  91668. /**
  91669. * Instantiates a new effect Layer and references it in the scene.
  91670. * @param name The name of the layer
  91671. * @param scene The scene to use the layer in
  91672. */
  91673. function EffectLayer(
  91674. /** The Friendly of the effect in the scene */
  91675. name, scene) {
  91676. this._vertexBuffers = {};
  91677. this._maxSize = 0;
  91678. this._mainTextureDesiredSize = { width: 0, height: 0 };
  91679. this._shouldRender = true;
  91680. this._postProcesses = [];
  91681. this._textures = [];
  91682. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  91683. /**
  91684. * The clear color of the texture used to generate the glow map.
  91685. */
  91686. this.neutralColor = new BABYLON.Color4();
  91687. /**
  91688. * Specifies wether the highlight layer is enabled or not.
  91689. */
  91690. this.isEnabled = true;
  91691. /**
  91692. * An event triggered when the effect layer has been disposed.
  91693. */
  91694. this.onDisposeObservable = new BABYLON.Observable();
  91695. /**
  91696. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  91697. */
  91698. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  91699. /**
  91700. * An event triggered when the generated texture is being merged in the scene.
  91701. */
  91702. this.onBeforeComposeObservable = new BABYLON.Observable();
  91703. /**
  91704. * An event triggered when the generated texture has been merged in the scene.
  91705. */
  91706. this.onAfterComposeObservable = new BABYLON.Observable();
  91707. /**
  91708. * An event triggered when the efffect layer changes its size.
  91709. */
  91710. this.onSizeChangedObservable = new BABYLON.Observable();
  91711. this.name = name;
  91712. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91713. this._engine = scene.getEngine();
  91714. this._maxSize = this._engine.getCaps().maxTextureSize;
  91715. this._scene.effectLayers.push(this);
  91716. // Generate Buffers
  91717. this._generateIndexBuffer();
  91718. this._genrateVertexBuffer();
  91719. }
  91720. Object.defineProperty(EffectLayer.prototype, "camera", {
  91721. /**
  91722. * Gets the camera attached to the layer.
  91723. */
  91724. get: function () {
  91725. return this._effectLayerOptions.camera;
  91726. },
  91727. enumerable: true,
  91728. configurable: true
  91729. });
  91730. /**
  91731. * Initializes the effect layer with the required options.
  91732. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  91733. */
  91734. EffectLayer.prototype._init = function (options) {
  91735. // Adapt options
  91736. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91737. this._setMainTextureSize();
  91738. this._createMainTexture();
  91739. this._createTextureAndPostProcesses();
  91740. this._mergeEffect = this._createMergeEffect();
  91741. };
  91742. /**
  91743. * Generates the index buffer of the full screen quad blending to the main canvas.
  91744. */
  91745. EffectLayer.prototype._generateIndexBuffer = function () {
  91746. // Indices
  91747. var indices = [];
  91748. indices.push(0);
  91749. indices.push(1);
  91750. indices.push(2);
  91751. indices.push(0);
  91752. indices.push(2);
  91753. indices.push(3);
  91754. this._indexBuffer = this._engine.createIndexBuffer(indices);
  91755. };
  91756. /**
  91757. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  91758. */
  91759. EffectLayer.prototype._genrateVertexBuffer = function () {
  91760. // VBO
  91761. var vertices = [];
  91762. vertices.push(1, 1);
  91763. vertices.push(-1, 1);
  91764. vertices.push(-1, -1);
  91765. vertices.push(1, -1);
  91766. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91767. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91768. };
  91769. /**
  91770. * Sets the main texture desired size which is the closest power of two
  91771. * of the engine canvas size.
  91772. */
  91773. EffectLayer.prototype._setMainTextureSize = function () {
  91774. if (this._effectLayerOptions.mainTextureFixedSize) {
  91775. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  91776. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  91777. }
  91778. else {
  91779. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  91780. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  91781. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  91782. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  91783. }
  91784. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  91785. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  91786. };
  91787. /**
  91788. * Creates the main texture for the effect layer.
  91789. */
  91790. EffectLayer.prototype._createMainTexture = function () {
  91791. var _this = this;
  91792. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  91793. width: this._mainTextureDesiredSize.width,
  91794. height: this._mainTextureDesiredSize.height
  91795. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91796. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  91797. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91798. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91799. this._mainTexture.anisotropicFilteringLevel = 1;
  91800. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91801. this._mainTexture.renderParticles = false;
  91802. this._mainTexture.renderList = null;
  91803. this._mainTexture.ignoreCameraViewport = true;
  91804. // Custom render function
  91805. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  91806. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  91807. var index;
  91808. var engine = _this._scene.getEngine();
  91809. if (depthOnlySubMeshes.length) {
  91810. engine.setColorWrite(false);
  91811. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  91812. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  91813. }
  91814. engine.setColorWrite(true);
  91815. }
  91816. for (index = 0; index < opaqueSubMeshes.length; index++) {
  91817. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  91818. }
  91819. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  91820. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  91821. }
  91822. for (index = 0; index < transparentSubMeshes.length; index++) {
  91823. _this._renderSubMesh(transparentSubMeshes.data[index]);
  91824. }
  91825. };
  91826. this._mainTexture.onClearObservable.add(function (engine) {
  91827. engine.clear(_this.neutralColor, true, true, true);
  91828. });
  91829. };
  91830. /**
  91831. * Checks for the readiness of the element composing the layer.
  91832. * @param subMesh the mesh to check for
  91833. * @param useInstances specify wether or not to use instances to render the mesh
  91834. * @param emissiveTexture the associated emissive texture used to generate the glow
  91835. * @return true if ready otherwise, false
  91836. */
  91837. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  91838. var material = subMesh.getMaterial();
  91839. if (!material) {
  91840. return false;
  91841. }
  91842. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  91843. return false;
  91844. }
  91845. var defines = [];
  91846. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91847. var mesh = subMesh.getMesh();
  91848. var uv1 = false;
  91849. var uv2 = false;
  91850. // Alpha test
  91851. if (material && material.needAlphaTesting()) {
  91852. var alphaTexture = material.getAlphaTestTexture();
  91853. if (alphaTexture) {
  91854. defines.push("#define ALPHATEST");
  91855. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91856. alphaTexture.coordinatesIndex === 1) {
  91857. defines.push("#define DIFFUSEUV2");
  91858. uv2 = true;
  91859. }
  91860. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91861. defines.push("#define DIFFUSEUV1");
  91862. uv1 = true;
  91863. }
  91864. }
  91865. }
  91866. // Emissive
  91867. if (emissiveTexture) {
  91868. defines.push("#define EMISSIVE");
  91869. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91870. emissiveTexture.coordinatesIndex === 1) {
  91871. defines.push("#define EMISSIVEUV2");
  91872. uv2 = true;
  91873. }
  91874. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91875. defines.push("#define EMISSIVEUV1");
  91876. uv1 = true;
  91877. }
  91878. }
  91879. if (uv1) {
  91880. attribs.push(BABYLON.VertexBuffer.UVKind);
  91881. defines.push("#define UV1");
  91882. }
  91883. if (uv2) {
  91884. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91885. defines.push("#define UV2");
  91886. }
  91887. // Bones
  91888. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91889. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91890. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91891. if (mesh.numBoneInfluencers > 4) {
  91892. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91893. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91894. }
  91895. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91896. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  91897. }
  91898. else {
  91899. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91900. }
  91901. // Morph targets
  91902. var manager = mesh.morphTargetManager;
  91903. var morphInfluencers = 0;
  91904. if (manager) {
  91905. if (manager.numInfluencers > 0) {
  91906. defines.push("#define MORPHTARGETS");
  91907. morphInfluencers = manager.numInfluencers;
  91908. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  91909. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  91910. }
  91911. }
  91912. // Instances
  91913. if (useInstances) {
  91914. defines.push("#define INSTANCES");
  91915. attribs.push("world0");
  91916. attribs.push("world1");
  91917. attribs.push("world2");
  91918. attribs.push("world3");
  91919. }
  91920. // Get correct effect
  91921. var join = defines.join("\n");
  91922. if (this._cachedDefines !== join) {
  91923. this._cachedDefines = join;
  91924. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  91925. }
  91926. return this._effectLayerMapGenerationEffect.isReady();
  91927. };
  91928. /**
  91929. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  91930. */
  91931. EffectLayer.prototype.render = function () {
  91932. var currentEffect = this._mergeEffect;
  91933. // Check
  91934. if (!currentEffect.isReady())
  91935. return;
  91936. for (var i = 0; i < this._postProcesses.length; i++) {
  91937. if (!this._postProcesses[i].isReady()) {
  91938. return;
  91939. }
  91940. }
  91941. var engine = this._scene.getEngine();
  91942. this.onBeforeComposeObservable.notifyObservers(this);
  91943. // Render
  91944. engine.enableEffect(currentEffect);
  91945. engine.setState(false);
  91946. // VBOs
  91947. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91948. // Cache
  91949. var previousAlphaMode = engine.getAlphaMode();
  91950. // Go Blend.
  91951. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  91952. // Blends the map on the main canvas.
  91953. this._internalRender(currentEffect);
  91954. // Restore Alpha
  91955. engine.setAlphaMode(previousAlphaMode);
  91956. this.onAfterComposeObservable.notifyObservers(this);
  91957. // Handle size changes.
  91958. var size = this._mainTexture.getSize();
  91959. this._setMainTextureSize();
  91960. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  91961. // Recreate RTT and post processes on size change.
  91962. this.onSizeChangedObservable.notifyObservers(this);
  91963. this._disposeTextureAndPostProcesses();
  91964. this._createMainTexture();
  91965. this._createTextureAndPostProcesses();
  91966. }
  91967. };
  91968. /**
  91969. * Determine if a given mesh will be used in the current effect.
  91970. * @param mesh mesh to test
  91971. * @returns true if the mesh will be used
  91972. */
  91973. EffectLayer.prototype.hasMesh = function (mesh) {
  91974. return true;
  91975. };
  91976. /**
  91977. * Returns true if the layer contains information to display, otherwise false.
  91978. * @returns true if the glow layer should be rendered
  91979. */
  91980. EffectLayer.prototype.shouldRender = function () {
  91981. return this.isEnabled && this._shouldRender;
  91982. };
  91983. /**
  91984. * Returns true if the mesh should render, otherwise false.
  91985. * @param mesh The mesh to render
  91986. * @returns true if it should render otherwise false
  91987. */
  91988. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  91989. return true;
  91990. };
  91991. /**
  91992. * Returns true if the mesh should render, otherwise false.
  91993. * @param mesh The mesh to render
  91994. * @returns true if it should render otherwise false
  91995. */
  91996. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  91997. return true;
  91998. };
  91999. /**
  92000. * Renders the submesh passed in parameter to the generation map.
  92001. */
  92002. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  92003. var _this = this;
  92004. if (!this.shouldRender()) {
  92005. return;
  92006. }
  92007. var material = subMesh.getMaterial();
  92008. var mesh = subMesh.getRenderingMesh();
  92009. var scene = this._scene;
  92010. var engine = scene.getEngine();
  92011. if (!material) {
  92012. return;
  92013. }
  92014. // Do not block in blend mode.
  92015. if (material.needAlphaBlendingForMesh(mesh)) {
  92016. return;
  92017. }
  92018. // Culling
  92019. engine.setState(material.backFaceCulling);
  92020. // Managing instances
  92021. var batch = mesh._getInstancesRenderList(subMesh._id);
  92022. if (batch.mustReturn) {
  92023. return;
  92024. }
  92025. // Early Exit per mesh
  92026. if (!this._shouldRenderMesh(mesh)) {
  92027. return;
  92028. }
  92029. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  92030. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  92031. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  92032. engine.enableEffect(this._effectLayerMapGenerationEffect);
  92033. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  92034. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  92035. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  92036. // Alpha test
  92037. if (material && material.needAlphaTesting()) {
  92038. var alphaTexture = material.getAlphaTestTexture();
  92039. if (alphaTexture) {
  92040. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  92041. var textureMatrix = alphaTexture.getTextureMatrix();
  92042. if (textureMatrix) {
  92043. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  92044. }
  92045. }
  92046. }
  92047. // Glow emissive only
  92048. if (this._emissiveTextureAndColor.texture) {
  92049. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  92050. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  92051. }
  92052. // Bones
  92053. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  92054. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  92055. }
  92056. // Morph targets
  92057. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  92058. // Draw
  92059. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  92060. }
  92061. else {
  92062. // Need to reset refresh rate of the shadowMap
  92063. this._mainTexture.resetRefreshCounter();
  92064. }
  92065. };
  92066. /**
  92067. * Rebuild the required buffers.
  92068. * @hidden Internal use only.
  92069. */
  92070. EffectLayer.prototype._rebuild = function () {
  92071. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92072. if (vb) {
  92073. vb._rebuild();
  92074. }
  92075. this._generateIndexBuffer();
  92076. };
  92077. /**
  92078. * Dispose only the render target textures and post process.
  92079. */
  92080. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  92081. this._mainTexture.dispose();
  92082. for (var i = 0; i < this._postProcesses.length; i++) {
  92083. if (this._postProcesses[i]) {
  92084. this._postProcesses[i].dispose();
  92085. }
  92086. }
  92087. this._postProcesses = [];
  92088. for (var i = 0; i < this._textures.length; i++) {
  92089. if (this._textures[i]) {
  92090. this._textures[i].dispose();
  92091. }
  92092. }
  92093. this._textures = [];
  92094. };
  92095. /**
  92096. * Dispose the highlight layer and free resources.
  92097. */
  92098. EffectLayer.prototype.dispose = function () {
  92099. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  92100. if (vertexBuffer) {
  92101. vertexBuffer.dispose();
  92102. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  92103. }
  92104. if (this._indexBuffer) {
  92105. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  92106. this._indexBuffer = null;
  92107. }
  92108. // Clean textures and post processes
  92109. this._disposeTextureAndPostProcesses();
  92110. // Remove from scene
  92111. var index = this._scene.effectLayers.indexOf(this, 0);
  92112. if (index > -1) {
  92113. this._scene.effectLayers.splice(index, 1);
  92114. }
  92115. // Callback
  92116. this.onDisposeObservable.notifyObservers(this);
  92117. this.onDisposeObservable.clear();
  92118. this.onBeforeRenderMainTextureObservable.clear();
  92119. this.onBeforeComposeObservable.clear();
  92120. this.onAfterComposeObservable.clear();
  92121. this.onSizeChangedObservable.clear();
  92122. };
  92123. /**
  92124. * Gets the class name of the effect layer
  92125. * @returns the string with the class name of the effect layer
  92126. */
  92127. EffectLayer.prototype.getClassName = function () {
  92128. return "EffectLayer";
  92129. };
  92130. /**
  92131. * Creates an effect layer from parsed effect layer data
  92132. * @param parsedEffectLayer defines effect layer data
  92133. * @param scene defines the current scene
  92134. * @param rootUrl defines the root URL containing the effect layer information
  92135. * @returns a parsed effect Layer
  92136. */
  92137. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  92138. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  92139. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  92140. };
  92141. __decorate([
  92142. BABYLON.serialize()
  92143. ], EffectLayer.prototype, "name", void 0);
  92144. __decorate([
  92145. BABYLON.serializeAsColor4()
  92146. ], EffectLayer.prototype, "neutralColor", void 0);
  92147. __decorate([
  92148. BABYLON.serialize()
  92149. ], EffectLayer.prototype, "isEnabled", void 0);
  92150. __decorate([
  92151. BABYLON.serializeAsCameraReference()
  92152. ], EffectLayer.prototype, "camera", null);
  92153. return EffectLayer;
  92154. }());
  92155. BABYLON.EffectLayer = EffectLayer;
  92156. })(BABYLON || (BABYLON = {}));
  92157. //# sourceMappingURL=babylon.effectLayer.js.map
  92158. var BABYLON;
  92159. (function (BABYLON) {
  92160. /**
  92161. * Special Glow Blur post process only blurring the alpha channel
  92162. * It enforces keeping the most luminous color in the color channel.
  92163. */
  92164. var GlowBlurPostProcess = /** @class */ (function (_super) {
  92165. __extends(GlowBlurPostProcess, _super);
  92166. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  92167. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  92168. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  92169. _this.direction = direction;
  92170. _this.kernel = kernel;
  92171. _this.onApplyObservable.add(function (effect) {
  92172. effect.setFloat2("screenSize", _this.width, _this.height);
  92173. effect.setVector2("direction", _this.direction);
  92174. effect.setFloat("blurWidth", _this.kernel);
  92175. });
  92176. return _this;
  92177. }
  92178. return GlowBlurPostProcess;
  92179. }(BABYLON.PostProcess));
  92180. /**
  92181. * The highlight layer Helps adding a glow effect around a mesh.
  92182. *
  92183. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92184. * glowy meshes to your scene.
  92185. *
  92186. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  92187. */
  92188. var HighlightLayer = /** @class */ (function (_super) {
  92189. __extends(HighlightLayer, _super);
  92190. /**
  92191. * Instantiates a new highlight Layer and references it to the scene..
  92192. * @param name The name of the layer
  92193. * @param scene The scene to use the layer in
  92194. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  92195. */
  92196. function HighlightLayer(name, scene, options) {
  92197. var _this = _super.call(this, name, scene) || this;
  92198. _this.name = name;
  92199. /**
  92200. * Specifies whether or not the inner glow is ACTIVE in the layer.
  92201. */
  92202. _this.innerGlow = true;
  92203. /**
  92204. * Specifies whether or not the outer glow is ACTIVE in the layer.
  92205. */
  92206. _this.outerGlow = true;
  92207. /**
  92208. * An event triggered when the highlight layer is being blurred.
  92209. */
  92210. _this.onBeforeBlurObservable = new BABYLON.Observable();
  92211. /**
  92212. * An event triggered when the highlight layer has been blurred.
  92213. */
  92214. _this.onAfterBlurObservable = new BABYLON.Observable();
  92215. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  92216. _this._meshes = {};
  92217. _this._excludedMeshes = {};
  92218. _this.neutralColor = HighlightLayer.NeutralColor;
  92219. // Warn on stencil
  92220. if (!_this._engine.isStencilEnable) {
  92221. 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 }");
  92222. }
  92223. // Adapt options
  92224. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  92225. // Initialize the layer
  92226. _this._init({
  92227. alphaBlendingMode: _this._options.alphaBlendingMode,
  92228. camera: _this._options.camera,
  92229. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92230. mainTextureRatio: _this._options.mainTextureRatio
  92231. });
  92232. // Do not render as long as no meshes have been added
  92233. _this._shouldRender = false;
  92234. return _this;
  92235. }
  92236. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  92237. /**
  92238. * Gets the horizontal size of the blur.
  92239. */
  92240. get: function () {
  92241. return this._horizontalBlurPostprocess.kernel;
  92242. },
  92243. /**
  92244. * Specifies the horizontal size of the blur.
  92245. */
  92246. set: function (value) {
  92247. this._horizontalBlurPostprocess.kernel = value;
  92248. },
  92249. enumerable: true,
  92250. configurable: true
  92251. });
  92252. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  92253. /**
  92254. * Gets the vertical size of the blur.
  92255. */
  92256. get: function () {
  92257. return this._verticalBlurPostprocess.kernel;
  92258. },
  92259. /**
  92260. * Specifies the vertical size of the blur.
  92261. */
  92262. set: function (value) {
  92263. this._verticalBlurPostprocess.kernel = value;
  92264. },
  92265. enumerable: true,
  92266. configurable: true
  92267. });
  92268. /**
  92269. * Get the effect name of the layer.
  92270. * @return The effect name
  92271. */
  92272. HighlightLayer.prototype.getEffectName = function () {
  92273. return HighlightLayer.EffectName;
  92274. };
  92275. /**
  92276. * Create the merge effect. This is the shader use to blit the information back
  92277. * to the main canvas at the end of the scene rendering.
  92278. */
  92279. HighlightLayer.prototype._createMergeEffect = function () {
  92280. // Effect
  92281. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  92282. };
  92283. /**
  92284. * Creates the render target textures and post processes used in the highlight layer.
  92285. */
  92286. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  92287. var _this = this;
  92288. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  92289. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  92290. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92291. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92292. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  92293. width: blurTextureWidth,
  92294. height: blurTextureHeight
  92295. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92296. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92297. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92298. this._blurTexture.anisotropicFilteringLevel = 16;
  92299. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  92300. this._blurTexture.renderParticles = false;
  92301. this._blurTexture.ignoreCameraViewport = true;
  92302. this._textures = [this._blurTexture];
  92303. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  92304. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92305. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  92306. effect.setTexture("textureSampler", _this._mainTexture);
  92307. });
  92308. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92309. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92310. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  92311. });
  92312. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92313. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  92314. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  92315. });
  92316. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92317. }
  92318. else {
  92319. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  92320. width: blurTextureWidth,
  92321. height: blurTextureHeight
  92322. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92323. this._horizontalBlurPostprocess.width = blurTextureWidth;
  92324. this._horizontalBlurPostprocess.height = blurTextureHeight;
  92325. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92326. effect.setTexture("textureSampler", _this._mainTexture);
  92327. });
  92328. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  92329. width: blurTextureWidth,
  92330. height: blurTextureHeight
  92331. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92332. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92333. }
  92334. this._mainTexture.onAfterUnbindObservable.add(function () {
  92335. _this.onBeforeBlurObservable.notifyObservers(_this);
  92336. var internalTexture = _this._blurTexture.getInternalTexture();
  92337. if (internalTexture) {
  92338. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  92339. }
  92340. _this.onAfterBlurObservable.notifyObservers(_this);
  92341. });
  92342. // Prevent autoClear.
  92343. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92344. };
  92345. /**
  92346. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92347. */
  92348. HighlightLayer.prototype.needStencil = function () {
  92349. return true;
  92350. };
  92351. /**
  92352. * Checks for the readiness of the element composing the layer.
  92353. * @param subMesh the mesh to check for
  92354. * @param useInstances specify wether or not to use instances to render the mesh
  92355. * @param emissiveTexture the associated emissive texture used to generate the glow
  92356. * @return true if ready otherwise, false
  92357. */
  92358. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  92359. var material = subMesh.getMaterial();
  92360. var mesh = subMesh.getRenderingMesh();
  92361. if (!material || !mesh || !this._meshes) {
  92362. return false;
  92363. }
  92364. var emissiveTexture = null;
  92365. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92366. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92367. emissiveTexture = material.emissiveTexture;
  92368. }
  92369. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92370. };
  92371. /**
  92372. * Implementation specific of rendering the generating effect on the main canvas.
  92373. * @param effect The effect used to render through
  92374. */
  92375. HighlightLayer.prototype._internalRender = function (effect) {
  92376. // Texture
  92377. effect.setTexture("textureSampler", this._blurTexture);
  92378. // Cache
  92379. var engine = this._engine;
  92380. var previousStencilBuffer = engine.getStencilBuffer();
  92381. var previousStencilFunction = engine.getStencilFunction();
  92382. var previousStencilMask = engine.getStencilMask();
  92383. var previousStencilOperationPass = engine.getStencilOperationPass();
  92384. var previousStencilOperationFail = engine.getStencilOperationFail();
  92385. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  92386. var previousStencilReference = engine.getStencilFunctionReference();
  92387. // Stencil operations
  92388. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  92389. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  92390. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  92391. // Draw order
  92392. engine.setStencilMask(0x00);
  92393. engine.setStencilBuffer(true);
  92394. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  92395. // 2 passes inner outer
  92396. if (this.outerGlow) {
  92397. effect.setFloat("offset", 0);
  92398. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  92399. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92400. }
  92401. if (this.innerGlow) {
  92402. effect.setFloat("offset", 1);
  92403. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  92404. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92405. }
  92406. // Restore Cache
  92407. engine.setStencilFunction(previousStencilFunction);
  92408. engine.setStencilMask(previousStencilMask);
  92409. engine.setStencilBuffer(previousStencilBuffer);
  92410. engine.setStencilOperationPass(previousStencilOperationPass);
  92411. engine.setStencilOperationFail(previousStencilOperationFail);
  92412. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  92413. engine.setStencilFunctionReference(previousStencilReference);
  92414. };
  92415. /**
  92416. * Returns true if the layer contains information to display, otherwise false.
  92417. */
  92418. HighlightLayer.prototype.shouldRender = function () {
  92419. if (_super.prototype.shouldRender.call(this)) {
  92420. return this._meshes ? true : false;
  92421. }
  92422. return false;
  92423. };
  92424. /**
  92425. * Returns true if the mesh should render, otherwise false.
  92426. * @param mesh The mesh to render
  92427. * @returns true if it should render otherwise false
  92428. */
  92429. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  92430. // Excluded Mesh
  92431. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  92432. return false;
  92433. }
  92434. ;
  92435. return true;
  92436. };
  92437. /**
  92438. * Sets the required values for both the emissive texture and and the main color.
  92439. */
  92440. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92441. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92442. if (highlightLayerMesh) {
  92443. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  92444. }
  92445. else {
  92446. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92447. }
  92448. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92449. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92450. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  92451. }
  92452. else {
  92453. this._emissiveTextureAndColor.texture = null;
  92454. }
  92455. };
  92456. /**
  92457. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  92458. * @param mesh The mesh to exclude from the highlight layer
  92459. */
  92460. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  92461. if (!this._excludedMeshes) {
  92462. return;
  92463. }
  92464. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92465. if (!meshExcluded) {
  92466. this._excludedMeshes[mesh.uniqueId] = {
  92467. mesh: mesh,
  92468. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  92469. mesh.getEngine().setStencilBuffer(false);
  92470. }),
  92471. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  92472. mesh.getEngine().setStencilBuffer(true);
  92473. }),
  92474. };
  92475. }
  92476. };
  92477. /**
  92478. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  92479. * @param mesh The mesh to highlight
  92480. */
  92481. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  92482. if (!this._excludedMeshes) {
  92483. return;
  92484. }
  92485. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92486. if (meshExcluded) {
  92487. if (meshExcluded.beforeRender) {
  92488. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  92489. }
  92490. if (meshExcluded.afterRender) {
  92491. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  92492. }
  92493. }
  92494. this._excludedMeshes[mesh.uniqueId] = null;
  92495. };
  92496. /**
  92497. * Determine if a given mesh will be highlighted by the current HighlightLayer
  92498. * @param mesh mesh to test
  92499. * @returns true if the mesh will be highlighted by the current HighlightLayer
  92500. */
  92501. HighlightLayer.prototype.hasMesh = function (mesh) {
  92502. if (!this._meshes) {
  92503. return false;
  92504. }
  92505. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  92506. };
  92507. /**
  92508. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  92509. * @param mesh The mesh to highlight
  92510. * @param color The color of the highlight
  92511. * @param glowEmissiveOnly Extract the glow from the emissive texture
  92512. */
  92513. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  92514. var _this = this;
  92515. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  92516. if (!this._meshes) {
  92517. return;
  92518. }
  92519. var meshHighlight = this._meshes[mesh.uniqueId];
  92520. if (meshHighlight) {
  92521. meshHighlight.color = color;
  92522. }
  92523. else {
  92524. this._meshes[mesh.uniqueId] = {
  92525. mesh: mesh,
  92526. color: color,
  92527. // Lambda required for capture due to Observable this context
  92528. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  92529. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  92530. _this._defaultStencilReference(mesh);
  92531. }
  92532. else {
  92533. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  92534. }
  92535. }),
  92536. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  92537. glowEmissiveOnly: glowEmissiveOnly
  92538. };
  92539. }
  92540. this._shouldRender = true;
  92541. };
  92542. /**
  92543. * Remove a mesh from the highlight layer in order to make it stop glowing.
  92544. * @param mesh The mesh to highlight
  92545. */
  92546. HighlightLayer.prototype.removeMesh = function (mesh) {
  92547. if (!this._meshes) {
  92548. return;
  92549. }
  92550. var meshHighlight = this._meshes[mesh.uniqueId];
  92551. if (meshHighlight) {
  92552. if (meshHighlight.observerHighlight) {
  92553. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92554. }
  92555. if (meshHighlight.observerDefault) {
  92556. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92557. }
  92558. delete this._meshes[mesh.uniqueId];
  92559. }
  92560. this._shouldRender = false;
  92561. for (var meshHighlightToCheck in this._meshes) {
  92562. if (this._meshes[meshHighlightToCheck]) {
  92563. this._shouldRender = true;
  92564. break;
  92565. }
  92566. }
  92567. };
  92568. /**
  92569. * Force the stencil to the normal expected value for none glowing parts
  92570. */
  92571. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  92572. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  92573. };
  92574. /**
  92575. * Free any resources and references associated to a mesh.
  92576. * Internal use
  92577. * @param mesh The mesh to free.
  92578. */
  92579. HighlightLayer.prototype._disposeMesh = function (mesh) {
  92580. this.removeMesh(mesh);
  92581. this.removeExcludedMesh(mesh);
  92582. };
  92583. /**
  92584. * Dispose the highlight layer and free resources.
  92585. */
  92586. HighlightLayer.prototype.dispose = function () {
  92587. if (this._meshes) {
  92588. // Clean mesh references
  92589. for (var id in this._meshes) {
  92590. var meshHighlight = this._meshes[id];
  92591. if (meshHighlight && meshHighlight.mesh) {
  92592. if (meshHighlight.observerHighlight) {
  92593. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92594. }
  92595. if (meshHighlight.observerDefault) {
  92596. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92597. }
  92598. }
  92599. }
  92600. this._meshes = null;
  92601. }
  92602. if (this._excludedMeshes) {
  92603. for (var id in this._excludedMeshes) {
  92604. var meshHighlight = this._excludedMeshes[id];
  92605. if (meshHighlight) {
  92606. if (meshHighlight.beforeRender) {
  92607. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  92608. }
  92609. if (meshHighlight.afterRender) {
  92610. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  92611. }
  92612. }
  92613. }
  92614. this._excludedMeshes = null;
  92615. }
  92616. _super.prototype.dispose.call(this);
  92617. };
  92618. /**
  92619. * Gets the class name of the effect layer
  92620. * @returns the string with the class name of the effect layer
  92621. */
  92622. HighlightLayer.prototype.getClassName = function () {
  92623. return "HighlightLayer";
  92624. };
  92625. /**
  92626. * Serializes this Highlight layer
  92627. * @returns a serialized Highlight layer object
  92628. */
  92629. HighlightLayer.prototype.serialize = function () {
  92630. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92631. serializationObject.customType = "BABYLON.HighlightLayer";
  92632. // Highlighted meshes
  92633. serializationObject.meshes = [];
  92634. if (this._meshes) {
  92635. for (var m in this._meshes) {
  92636. var mesh = this._meshes[m];
  92637. if (mesh) {
  92638. serializationObject.meshes.push({
  92639. glowEmissiveOnly: mesh.glowEmissiveOnly,
  92640. color: mesh.color.asArray(),
  92641. meshId: mesh.mesh.id
  92642. });
  92643. }
  92644. }
  92645. }
  92646. // Excluded meshes
  92647. serializationObject.excludedMeshes = [];
  92648. if (this._excludedMeshes) {
  92649. for (var e in this._excludedMeshes) {
  92650. var excludedMesh = this._excludedMeshes[e];
  92651. if (excludedMesh) {
  92652. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  92653. }
  92654. }
  92655. }
  92656. return serializationObject;
  92657. };
  92658. /**
  92659. * Creates a Highlight layer from parsed Highlight layer data
  92660. * @param parsedHightlightLayer defines the Highlight layer data
  92661. * @param scene defines the current scene
  92662. * @param rootUrl defines the root URL containing the Highlight layer information
  92663. * @returns a parsed Highlight layer
  92664. */
  92665. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  92666. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  92667. var index;
  92668. // Excluded meshes
  92669. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  92670. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  92671. if (mesh) {
  92672. hl.addExcludedMesh(mesh);
  92673. }
  92674. }
  92675. // Included meshes
  92676. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  92677. var highlightedMesh = parsedHightlightLayer.meshes[index];
  92678. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  92679. if (mesh) {
  92680. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  92681. }
  92682. }
  92683. return hl;
  92684. };
  92685. /**
  92686. * Effect Name of the highlight layer.
  92687. */
  92688. HighlightLayer.EffectName = "HighlightLayer";
  92689. /**
  92690. * The neutral color used during the preparation of the glow effect.
  92691. * This is black by default as the blend operation is a blend operation.
  92692. */
  92693. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  92694. /**
  92695. * Stencil value used for glowing meshes.
  92696. */
  92697. HighlightLayer.GlowingMeshStencilReference = 0x02;
  92698. /**
  92699. * Stencil value used for the other meshes in the scene.
  92700. */
  92701. HighlightLayer.NormalMeshStencilReference = 0x01;
  92702. __decorate([
  92703. BABYLON.serialize()
  92704. ], HighlightLayer.prototype, "innerGlow", void 0);
  92705. __decorate([
  92706. BABYLON.serialize()
  92707. ], HighlightLayer.prototype, "outerGlow", void 0);
  92708. __decorate([
  92709. BABYLON.serialize()
  92710. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  92711. __decorate([
  92712. BABYLON.serialize()
  92713. ], HighlightLayer.prototype, "blurVerticalSize", null);
  92714. __decorate([
  92715. BABYLON.serialize("options")
  92716. ], HighlightLayer.prototype, "_options", void 0);
  92717. return HighlightLayer;
  92718. }(BABYLON.EffectLayer));
  92719. BABYLON.HighlightLayer = HighlightLayer;
  92720. })(BABYLON || (BABYLON = {}));
  92721. //# sourceMappingURL=babylon.highlightLayer.js.map
  92722. var BABYLON;
  92723. (function (BABYLON) {
  92724. /**
  92725. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  92726. *
  92727. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92728. * glowy meshes to your scene.
  92729. *
  92730. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  92731. */
  92732. var GlowLayer = /** @class */ (function (_super) {
  92733. __extends(GlowLayer, _super);
  92734. /**
  92735. * Instantiates a new glow Layer and references it to the scene.
  92736. * @param name The name of the layer
  92737. * @param scene The scene to use the layer in
  92738. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  92739. */
  92740. function GlowLayer(name, scene, options) {
  92741. var _this = _super.call(this, name, scene) || this;
  92742. _this._intensity = 1.0;
  92743. _this._includedOnlyMeshes = [];
  92744. _this._excludedMeshes = [];
  92745. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  92746. // Adapt options
  92747. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  92748. // Initialize the layer
  92749. _this._init({
  92750. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  92751. camera: _this._options.camera,
  92752. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92753. mainTextureRatio: _this._options.mainTextureRatio
  92754. });
  92755. return _this;
  92756. }
  92757. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  92758. /**
  92759. * Gets the kernel size of the blur.
  92760. */
  92761. get: function () {
  92762. return this._horizontalBlurPostprocess1.kernel;
  92763. },
  92764. /**
  92765. * Sets the kernel size of the blur.
  92766. */
  92767. set: function (value) {
  92768. this._horizontalBlurPostprocess1.kernel = value;
  92769. this._verticalBlurPostprocess1.kernel = value;
  92770. this._horizontalBlurPostprocess2.kernel = value;
  92771. this._verticalBlurPostprocess2.kernel = value;
  92772. },
  92773. enumerable: true,
  92774. configurable: true
  92775. });
  92776. Object.defineProperty(GlowLayer.prototype, "intensity", {
  92777. /**
  92778. * Gets the glow intensity.
  92779. */
  92780. get: function () {
  92781. return this._intensity;
  92782. },
  92783. /**
  92784. * Sets the glow intensity.
  92785. */
  92786. set: function (value) {
  92787. this._intensity = value;
  92788. },
  92789. enumerable: true,
  92790. configurable: true
  92791. });
  92792. /**
  92793. * Get the effect name of the layer.
  92794. * @return The effect name
  92795. */
  92796. GlowLayer.prototype.getEffectName = function () {
  92797. return GlowLayer.EffectName;
  92798. };
  92799. /**
  92800. * Create the merge effect. This is the shader use to blit the information back
  92801. * to the main canvas at the end of the scene rendering.
  92802. */
  92803. GlowLayer.prototype._createMergeEffect = function () {
  92804. // Effect
  92805. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  92806. };
  92807. /**
  92808. * Creates the render target textures and post processes used in the glow layer.
  92809. */
  92810. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  92811. var _this = this;
  92812. var blurTextureWidth = this._mainTextureDesiredSize.width;
  92813. var blurTextureHeight = this._mainTextureDesiredSize.height;
  92814. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92815. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92816. var textureType = 0;
  92817. if (this._engine.getCaps().textureHalfFloatRender) {
  92818. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92819. }
  92820. else {
  92821. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92822. }
  92823. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  92824. width: blurTextureWidth,
  92825. height: blurTextureHeight
  92826. }, this._scene, false, true, textureType);
  92827. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92828. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92829. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92830. this._blurTexture1.renderParticles = false;
  92831. this._blurTexture1.ignoreCameraViewport = true;
  92832. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  92833. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  92834. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  92835. width: blurTextureWidth2,
  92836. height: blurTextureHeight2
  92837. }, this._scene, false, true, textureType);
  92838. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92839. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92840. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92841. this._blurTexture2.renderParticles = false;
  92842. this._blurTexture2.ignoreCameraViewport = true;
  92843. this._textures = [this._blurTexture1, this._blurTexture2];
  92844. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92845. width: blurTextureWidth,
  92846. height: blurTextureHeight
  92847. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92848. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  92849. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  92850. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  92851. effect.setTexture("textureSampler", _this._mainTexture);
  92852. });
  92853. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92854. width: blurTextureWidth,
  92855. height: blurTextureHeight
  92856. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92857. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92858. width: blurTextureWidth2,
  92859. height: blurTextureHeight2
  92860. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92861. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  92862. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  92863. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  92864. effect.setTexture("textureSampler", _this._blurTexture1);
  92865. });
  92866. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92867. width: blurTextureWidth2,
  92868. height: blurTextureHeight2
  92869. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92870. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92871. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  92872. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92873. this._mainTexture.samples = this._options.mainTextureSamples;
  92874. this._mainTexture.onAfterUnbindObservable.add(function () {
  92875. var internalTexture = _this._blurTexture1.getInternalTexture();
  92876. if (internalTexture) {
  92877. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  92878. internalTexture = _this._blurTexture2.getInternalTexture();
  92879. if (internalTexture) {
  92880. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  92881. }
  92882. }
  92883. });
  92884. // Prevent autoClear.
  92885. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92886. };
  92887. /**
  92888. * Checks for the readiness of the element composing the layer.
  92889. * @param subMesh the mesh to check for
  92890. * @param useInstances specify wether or not to use instances to render the mesh
  92891. * @param emissiveTexture the associated emissive texture used to generate the glow
  92892. * @return true if ready otherwise, false
  92893. */
  92894. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  92895. var material = subMesh.getMaterial();
  92896. var mesh = subMesh.getRenderingMesh();
  92897. if (!material || !mesh) {
  92898. return false;
  92899. }
  92900. var emissiveTexture = material.emissiveTexture;
  92901. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92902. };
  92903. /**
  92904. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92905. */
  92906. GlowLayer.prototype.needStencil = function () {
  92907. return false;
  92908. };
  92909. /**
  92910. * Implementation specific of rendering the generating effect on the main canvas.
  92911. * @param effect The effect used to render through
  92912. */
  92913. GlowLayer.prototype._internalRender = function (effect) {
  92914. // Texture
  92915. effect.setTexture("textureSampler", this._blurTexture1);
  92916. effect.setTexture("textureSampler2", this._blurTexture2);
  92917. effect.setFloat("offset", this._intensity);
  92918. // Cache
  92919. var engine = this._engine;
  92920. var previousStencilBuffer = engine.getStencilBuffer();
  92921. // Draw order
  92922. engine.setStencilBuffer(false);
  92923. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92924. // Draw order
  92925. engine.setStencilBuffer(previousStencilBuffer);
  92926. };
  92927. /**
  92928. * Sets the required values for both the emissive texture and and the main color.
  92929. */
  92930. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92931. var textureLevel = 1.0;
  92932. if (this.customEmissiveTextureSelector) {
  92933. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  92934. }
  92935. else {
  92936. if (material) {
  92937. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92938. if (this._emissiveTextureAndColor.texture) {
  92939. textureLevel = this._emissiveTextureAndColor.texture.level;
  92940. }
  92941. }
  92942. else {
  92943. this._emissiveTextureAndColor.texture = null;
  92944. }
  92945. }
  92946. if (this.customEmissiveColorSelector) {
  92947. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  92948. }
  92949. else {
  92950. if (material.emissiveColor) {
  92951. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  92952. }
  92953. else {
  92954. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92955. }
  92956. }
  92957. };
  92958. /**
  92959. * Returns true if the mesh should render, otherwise false.
  92960. * @param mesh The mesh to render
  92961. * @returns true if it should render otherwise false
  92962. */
  92963. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  92964. return this.hasMesh(mesh);
  92965. };
  92966. /**
  92967. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  92968. * @param mesh The mesh to exclude from the glow layer
  92969. */
  92970. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  92971. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  92972. this._excludedMeshes.push(mesh.uniqueId);
  92973. }
  92974. };
  92975. /**
  92976. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  92977. * @param mesh The mesh to remove
  92978. */
  92979. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  92980. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  92981. if (index !== -1) {
  92982. this._excludedMeshes.splice(index, 1);
  92983. }
  92984. };
  92985. /**
  92986. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  92987. * @param mesh The mesh to include in the glow layer
  92988. */
  92989. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  92990. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  92991. this._includedOnlyMeshes.push(mesh.uniqueId);
  92992. }
  92993. };
  92994. /**
  92995. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  92996. * @param mesh The mesh to remove
  92997. */
  92998. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  92999. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  93000. if (index !== -1) {
  93001. this._includedOnlyMeshes.splice(index, 1);
  93002. }
  93003. };
  93004. /**
  93005. * Determine if a given mesh will be used in the glow layer
  93006. * @param mesh The mesh to test
  93007. * @returns true if the mesh will be highlighted by the current glow layer
  93008. */
  93009. GlowLayer.prototype.hasMesh = function (mesh) {
  93010. // Included Mesh
  93011. if (this._includedOnlyMeshes.length) {
  93012. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  93013. }
  93014. ;
  93015. // Excluded Mesh
  93016. if (this._excludedMeshes.length) {
  93017. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  93018. }
  93019. ;
  93020. return true;
  93021. };
  93022. /**
  93023. * Free any resources and references associated to a mesh.
  93024. * Internal use
  93025. * @param mesh The mesh to free.
  93026. */
  93027. GlowLayer.prototype._disposeMesh = function (mesh) {
  93028. this.removeIncludedOnlyMesh(mesh);
  93029. this.removeExcludedMesh(mesh);
  93030. };
  93031. /**
  93032. * Gets the class name of the effect layer
  93033. * @returns the string with the class name of the effect layer
  93034. */
  93035. GlowLayer.prototype.getClassName = function () {
  93036. return "GlowLayer";
  93037. };
  93038. /**
  93039. * Serializes this glow layer
  93040. * @returns a serialized glow layer object
  93041. */
  93042. GlowLayer.prototype.serialize = function () {
  93043. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  93044. serializationObject.customType = "BABYLON.GlowLayer";
  93045. var index;
  93046. // Included meshes
  93047. serializationObject.includedMeshes = [];
  93048. if (this._includedOnlyMeshes.length) {
  93049. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  93050. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  93051. if (mesh) {
  93052. serializationObject.includedMeshes.push(mesh.id);
  93053. }
  93054. }
  93055. }
  93056. // Excluded meshes
  93057. serializationObject.excludedMeshes = [];
  93058. if (this._excludedMeshes.length) {
  93059. for (index = 0; index < this._excludedMeshes.length; index++) {
  93060. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  93061. if (mesh) {
  93062. serializationObject.excludedMeshes.push(mesh.id);
  93063. }
  93064. }
  93065. }
  93066. return serializationObject;
  93067. };
  93068. /**
  93069. * Creates a Glow Layer from parsed glow layer data
  93070. * @param parsedGlowLayer defines glow layer data
  93071. * @param scene defines the current scene
  93072. * @param rootUrl defines the root URL containing the glow layer information
  93073. * @returns a parsed Glow Layer
  93074. */
  93075. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  93076. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  93077. var index;
  93078. // Excluded meshes
  93079. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  93080. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  93081. if (mesh) {
  93082. gl.addExcludedMesh(mesh);
  93083. }
  93084. }
  93085. // Included meshes
  93086. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  93087. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  93088. if (mesh) {
  93089. gl.addIncludedOnlyMesh(mesh);
  93090. }
  93091. }
  93092. return gl;
  93093. };
  93094. /**
  93095. * Effect Name of the layer.
  93096. */
  93097. GlowLayer.EffectName = "GlowLayer";
  93098. /**
  93099. * The default blur kernel size used for the glow.
  93100. */
  93101. GlowLayer.DefaultBlurKernelSize = 32;
  93102. /**
  93103. * The default texture size ratio used for the glow.
  93104. */
  93105. GlowLayer.DefaultTextureRatio = 0.5;
  93106. __decorate([
  93107. BABYLON.serialize()
  93108. ], GlowLayer.prototype, "blurKernelSize", null);
  93109. __decorate([
  93110. BABYLON.serialize()
  93111. ], GlowLayer.prototype, "intensity", null);
  93112. __decorate([
  93113. BABYLON.serialize("options")
  93114. ], GlowLayer.prototype, "_options", void 0);
  93115. return GlowLayer;
  93116. }(BABYLON.EffectLayer));
  93117. BABYLON.GlowLayer = GlowLayer;
  93118. })(BABYLON || (BABYLON = {}));
  93119. //# sourceMappingURL=babylon.glowLayer.js.map
  93120. var BABYLON;
  93121. (function (BABYLON) {
  93122. /**
  93123. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  93124. */
  93125. var AssetTaskState;
  93126. (function (AssetTaskState) {
  93127. /**
  93128. * Initialization
  93129. */
  93130. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  93131. /**
  93132. * Running
  93133. */
  93134. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  93135. /**
  93136. * Done
  93137. */
  93138. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  93139. /**
  93140. * Error
  93141. */
  93142. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  93143. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  93144. /**
  93145. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  93146. */
  93147. var AbstractAssetTask = /** @class */ (function () {
  93148. /**
  93149. * Creates a new {BABYLON.AssetsManager}
  93150. * @param name defines the name of the task
  93151. */
  93152. function AbstractAssetTask(
  93153. /**
  93154. * Task name
  93155. */ name) {
  93156. this.name = name;
  93157. this._isCompleted = false;
  93158. this._taskState = AssetTaskState.INIT;
  93159. }
  93160. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  93161. /**
  93162. * Get if the task is completed
  93163. */
  93164. get: function () {
  93165. return this._isCompleted;
  93166. },
  93167. enumerable: true,
  93168. configurable: true
  93169. });
  93170. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  93171. /**
  93172. * Gets the current state of the task
  93173. */
  93174. get: function () {
  93175. return this._taskState;
  93176. },
  93177. enumerable: true,
  93178. configurable: true
  93179. });
  93180. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  93181. /**
  93182. * Gets the current error object (if task is in error)
  93183. */
  93184. get: function () {
  93185. return this._errorObject;
  93186. },
  93187. enumerable: true,
  93188. configurable: true
  93189. });
  93190. /**
  93191. * Internal only
  93192. * @hidden
  93193. */
  93194. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  93195. if (this._errorObject) {
  93196. return;
  93197. }
  93198. this._errorObject = {
  93199. message: message,
  93200. exception: exception
  93201. };
  93202. };
  93203. /**
  93204. * Execute the current task
  93205. * @param scene defines the scene where you want your assets to be loaded
  93206. * @param onSuccess is a callback called when the task is successfully executed
  93207. * @param onError is a callback called if an error occurs
  93208. */
  93209. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93210. var _this = this;
  93211. this._taskState = AssetTaskState.RUNNING;
  93212. this.runTask(scene, function () {
  93213. _this.onDoneCallback(onSuccess, onError);
  93214. }, function (msg, exception) {
  93215. _this.onErrorCallback(onError, msg, exception);
  93216. });
  93217. };
  93218. /**
  93219. * Execute the current task
  93220. * @param scene defines the scene where you want your assets to be loaded
  93221. * @param onSuccess is a callback called when the task is successfully executed
  93222. * @param onError is a callback called if an error occurs
  93223. */
  93224. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93225. throw new Error("runTask is not implemented");
  93226. };
  93227. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  93228. this._taskState = AssetTaskState.ERROR;
  93229. this._errorObject = {
  93230. message: message,
  93231. exception: exception
  93232. };
  93233. if (this.onError) {
  93234. this.onError(this, message, exception);
  93235. }
  93236. onError();
  93237. };
  93238. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  93239. try {
  93240. this._taskState = AssetTaskState.DONE;
  93241. this._isCompleted = true;
  93242. if (this.onSuccess) {
  93243. this.onSuccess(this);
  93244. }
  93245. onSuccess();
  93246. }
  93247. catch (e) {
  93248. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  93249. }
  93250. };
  93251. return AbstractAssetTask;
  93252. }());
  93253. BABYLON.AbstractAssetTask = AbstractAssetTask;
  93254. /**
  93255. * Class used to share progress information about assets loading
  93256. */
  93257. var AssetsProgressEvent = /** @class */ (function () {
  93258. /**
  93259. * Creates a {BABYLON.AssetsProgressEvent}
  93260. * @param remainingCount defines the number of remaining tasks to process
  93261. * @param totalCount defines the total number of tasks
  93262. * @param task defines the task that was just processed
  93263. */
  93264. function AssetsProgressEvent(remainingCount, totalCount, task) {
  93265. this.remainingCount = remainingCount;
  93266. this.totalCount = totalCount;
  93267. this.task = task;
  93268. }
  93269. return AssetsProgressEvent;
  93270. }());
  93271. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  93272. /**
  93273. * Define a task used by {BABYLON.AssetsManager} to load meshes
  93274. */
  93275. var MeshAssetTask = /** @class */ (function (_super) {
  93276. __extends(MeshAssetTask, _super);
  93277. /**
  93278. * Creates a new {BABYLON.MeshAssetTask}
  93279. * @param name defines the name of the task
  93280. * @param meshesNames defines the list of mesh's names you want to load
  93281. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  93282. * @param sceneFilename defines the filename of the scene to load from
  93283. */
  93284. function MeshAssetTask(
  93285. /**
  93286. * Defines the name of the task
  93287. */
  93288. name,
  93289. /**
  93290. * Defines the list of mesh's names you want to load
  93291. */
  93292. meshesNames,
  93293. /**
  93294. * Defines the root url to use as a base to load your meshes and associated resources
  93295. */
  93296. rootUrl,
  93297. /**
  93298. * Defines the filename of the scene to load from
  93299. */
  93300. sceneFilename) {
  93301. var _this = _super.call(this, name) || this;
  93302. _this.name = name;
  93303. _this.meshesNames = meshesNames;
  93304. _this.rootUrl = rootUrl;
  93305. _this.sceneFilename = sceneFilename;
  93306. return _this;
  93307. }
  93308. /**
  93309. * Execute the current task
  93310. * @param scene defines the scene where you want your assets to be loaded
  93311. * @param onSuccess is a callback called when the task is successfully executed
  93312. * @param onError is a callback called if an error occurs
  93313. */
  93314. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93315. var _this = this;
  93316. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  93317. _this.loadedMeshes = meshes;
  93318. _this.loadedParticleSystems = particleSystems;
  93319. _this.loadedSkeletons = skeletons;
  93320. onSuccess();
  93321. }, null, function (scene, message, exception) {
  93322. onError(message, exception);
  93323. });
  93324. };
  93325. return MeshAssetTask;
  93326. }(AbstractAssetTask));
  93327. BABYLON.MeshAssetTask = MeshAssetTask;
  93328. /**
  93329. * Define a task used by {BABYLON.AssetsManager} to load text content
  93330. */
  93331. var TextFileAssetTask = /** @class */ (function (_super) {
  93332. __extends(TextFileAssetTask, _super);
  93333. /**
  93334. * Creates a new TextFileAssetTask object
  93335. * @param name defines the name of the task
  93336. * @param url defines the location of the file to load
  93337. */
  93338. function TextFileAssetTask(
  93339. /**
  93340. * Defines the name of the task
  93341. */
  93342. name,
  93343. /**
  93344. * Defines the location of the file to load
  93345. */
  93346. url) {
  93347. var _this = _super.call(this, name) || this;
  93348. _this.name = name;
  93349. _this.url = url;
  93350. return _this;
  93351. }
  93352. /**
  93353. * Execute the current task
  93354. * @param scene defines the scene where you want your assets to be loaded
  93355. * @param onSuccess is a callback called when the task is successfully executed
  93356. * @param onError is a callback called if an error occurs
  93357. */
  93358. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93359. var _this = this;
  93360. scene._loadFile(this.url, function (data) {
  93361. _this.text = data;
  93362. onSuccess();
  93363. }, undefined, false, false, function (request, exception) {
  93364. if (request) {
  93365. onError(request.status + " " + request.statusText, exception);
  93366. }
  93367. });
  93368. };
  93369. return TextFileAssetTask;
  93370. }(AbstractAssetTask));
  93371. BABYLON.TextFileAssetTask = TextFileAssetTask;
  93372. /**
  93373. * Define a task used by {BABYLON.AssetsManager} to load binary data
  93374. */
  93375. var BinaryFileAssetTask = /** @class */ (function (_super) {
  93376. __extends(BinaryFileAssetTask, _super);
  93377. /**
  93378. * Creates a new BinaryFileAssetTask object
  93379. * @param name defines the name of the new task
  93380. * @param url defines the location of the file to load
  93381. */
  93382. function BinaryFileAssetTask(
  93383. /**
  93384. * Defines the name of the task
  93385. */
  93386. name,
  93387. /**
  93388. * Defines the location of the file to load
  93389. */
  93390. url) {
  93391. var _this = _super.call(this, name) || this;
  93392. _this.name = name;
  93393. _this.url = url;
  93394. return _this;
  93395. }
  93396. /**
  93397. * Execute the current task
  93398. * @param scene defines the scene where you want your assets to be loaded
  93399. * @param onSuccess is a callback called when the task is successfully executed
  93400. * @param onError is a callback called if an error occurs
  93401. */
  93402. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93403. var _this = this;
  93404. scene._loadFile(this.url, function (data) {
  93405. _this.data = data;
  93406. onSuccess();
  93407. }, undefined, true, true, function (request, exception) {
  93408. if (request) {
  93409. onError(request.status + " " + request.statusText, exception);
  93410. }
  93411. });
  93412. };
  93413. return BinaryFileAssetTask;
  93414. }(AbstractAssetTask));
  93415. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  93416. /**
  93417. * Define a task used by {BABYLON.AssetsManager} to load images
  93418. */
  93419. var ImageAssetTask = /** @class */ (function (_super) {
  93420. __extends(ImageAssetTask, _super);
  93421. /**
  93422. * Creates a new ImageAssetTask
  93423. * @param name defines the name of the task
  93424. * @param url defines the location of the image to load
  93425. */
  93426. function ImageAssetTask(
  93427. /**
  93428. * Defines the name of the task
  93429. */
  93430. name,
  93431. /**
  93432. * Defines the location of the image to load
  93433. */
  93434. url) {
  93435. var _this = _super.call(this, name) || this;
  93436. _this.name = name;
  93437. _this.url = url;
  93438. return _this;
  93439. }
  93440. /**
  93441. * Execute the current task
  93442. * @param scene defines the scene where you want your assets to be loaded
  93443. * @param onSuccess is a callback called when the task is successfully executed
  93444. * @param onError is a callback called if an error occurs
  93445. */
  93446. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93447. var _this = this;
  93448. var img = new Image();
  93449. BABYLON.Tools.SetCorsBehavior(this.url, img);
  93450. img.onload = function () {
  93451. _this.image = img;
  93452. onSuccess();
  93453. };
  93454. img.onerror = function (err) {
  93455. onError("Error loading image", err);
  93456. };
  93457. img.src = this.url;
  93458. };
  93459. return ImageAssetTask;
  93460. }(AbstractAssetTask));
  93461. BABYLON.ImageAssetTask = ImageAssetTask;
  93462. /**
  93463. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  93464. */
  93465. var TextureAssetTask = /** @class */ (function (_super) {
  93466. __extends(TextureAssetTask, _super);
  93467. /**
  93468. * Creates a new TextureAssetTask object
  93469. * @param name defines the name of the task
  93470. * @param url defines the location of the file to load
  93471. * @param noMipmap defines if mipmap should not be generated (default is false)
  93472. * @param invertY defines if texture must be inverted on Y axis (default is false)
  93473. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93474. */
  93475. function TextureAssetTask(
  93476. /**
  93477. * Defines the name of the task
  93478. */
  93479. name,
  93480. /**
  93481. * Defines the location of the file to load
  93482. */
  93483. url,
  93484. /**
  93485. * Defines if mipmap should not be generated (default is false)
  93486. */
  93487. noMipmap,
  93488. /**
  93489. * Defines if texture must be inverted on Y axis (default is false)
  93490. */
  93491. invertY,
  93492. /**
  93493. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93494. */
  93495. samplingMode) {
  93496. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93497. var _this = _super.call(this, name) || this;
  93498. _this.name = name;
  93499. _this.url = url;
  93500. _this.noMipmap = noMipmap;
  93501. _this.invertY = invertY;
  93502. _this.samplingMode = samplingMode;
  93503. return _this;
  93504. }
  93505. /**
  93506. * Execute the current task
  93507. * @param scene defines the scene where you want your assets to be loaded
  93508. * @param onSuccess is a callback called when the task is successfully executed
  93509. * @param onError is a callback called if an error occurs
  93510. */
  93511. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93512. var onload = function () {
  93513. onSuccess();
  93514. };
  93515. var onerror = function (message, exception) {
  93516. onError(message, exception);
  93517. };
  93518. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  93519. };
  93520. return TextureAssetTask;
  93521. }(AbstractAssetTask));
  93522. BABYLON.TextureAssetTask = TextureAssetTask;
  93523. /**
  93524. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  93525. */
  93526. var CubeTextureAssetTask = /** @class */ (function (_super) {
  93527. __extends(CubeTextureAssetTask, _super);
  93528. /**
  93529. * Creates a new CubeTextureAssetTask
  93530. * @param name defines the name of the task
  93531. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93532. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93533. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93534. * @param files defines the explicit list of files (undefined by default)
  93535. */
  93536. function CubeTextureAssetTask(
  93537. /**
  93538. * Defines the name of the task
  93539. */
  93540. name,
  93541. /**
  93542. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93543. */
  93544. url,
  93545. /**
  93546. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93547. */
  93548. extensions,
  93549. /**
  93550. * Defines if mipmaps should not be generated (default is false)
  93551. */
  93552. noMipmap,
  93553. /**
  93554. * Defines the explicit list of files (undefined by default)
  93555. */
  93556. files) {
  93557. var _this = _super.call(this, name) || this;
  93558. _this.name = name;
  93559. _this.url = url;
  93560. _this.extensions = extensions;
  93561. _this.noMipmap = noMipmap;
  93562. _this.files = files;
  93563. return _this;
  93564. }
  93565. /**
  93566. * Execute the current task
  93567. * @param scene defines the scene where you want your assets to be loaded
  93568. * @param onSuccess is a callback called when the task is successfully executed
  93569. * @param onError is a callback called if an error occurs
  93570. */
  93571. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93572. var onload = function () {
  93573. onSuccess();
  93574. };
  93575. var onerror = function (message, exception) {
  93576. onError(message, exception);
  93577. };
  93578. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  93579. };
  93580. return CubeTextureAssetTask;
  93581. }(AbstractAssetTask));
  93582. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  93583. /**
  93584. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  93585. */
  93586. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  93587. __extends(HDRCubeTextureAssetTask, _super);
  93588. /**
  93589. * Creates a new HDRCubeTextureAssetTask object
  93590. * @param name defines the name of the task
  93591. * @param url defines the location of the file to load
  93592. * @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.
  93593. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93594. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93595. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  93596. * @param reserved Internal use only
  93597. */
  93598. function HDRCubeTextureAssetTask(
  93599. /**
  93600. * Defines the name of the task
  93601. */
  93602. name,
  93603. /**
  93604. * Defines the location of the file to load
  93605. */
  93606. url,
  93607. /**
  93608. * Defines the desired size (the more it increases the longer the generation will be)
  93609. */
  93610. size,
  93611. /**
  93612. * Defines if mipmaps should not be generated (default is false)
  93613. */
  93614. noMipmap,
  93615. /**
  93616. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93617. */
  93618. generateHarmonics,
  93619. /**
  93620. * 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)
  93621. */
  93622. gammaSpace,
  93623. /**
  93624. * Internal Use Only
  93625. */
  93626. reserved) {
  93627. if (noMipmap === void 0) { noMipmap = false; }
  93628. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93629. if (gammaSpace === void 0) { gammaSpace = false; }
  93630. if (reserved === void 0) { reserved = false; }
  93631. var _this = _super.call(this, name) || this;
  93632. _this.name = name;
  93633. _this.url = url;
  93634. _this.size = size;
  93635. _this.noMipmap = noMipmap;
  93636. _this.generateHarmonics = generateHarmonics;
  93637. _this.gammaSpace = gammaSpace;
  93638. _this.reserved = reserved;
  93639. return _this;
  93640. }
  93641. /**
  93642. * Execute the current task
  93643. * @param scene defines the scene where you want your assets to be loaded
  93644. * @param onSuccess is a callback called when the task is successfully executed
  93645. * @param onError is a callback called if an error occurs
  93646. */
  93647. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93648. var onload = function () {
  93649. onSuccess();
  93650. };
  93651. var onerror = function (message, exception) {
  93652. onError(message, exception);
  93653. };
  93654. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  93655. };
  93656. return HDRCubeTextureAssetTask;
  93657. }(AbstractAssetTask));
  93658. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  93659. /**
  93660. * This class can be used to easily import assets into a scene
  93661. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  93662. */
  93663. var AssetsManager = /** @class */ (function () {
  93664. /**
  93665. * Creates a new AssetsManager
  93666. * @param scene defines the scene to work on
  93667. */
  93668. function AssetsManager(scene) {
  93669. this._isLoading = false;
  93670. this._tasks = new Array();
  93671. this._waitingTasksCount = 0;
  93672. this._totalTasksCount = 0;
  93673. /**
  93674. * Observable called when all tasks are processed
  93675. */
  93676. this.onTaskSuccessObservable = new BABYLON.Observable();
  93677. /**
  93678. * Observable called when a task had an error
  93679. */
  93680. this.onTaskErrorObservable = new BABYLON.Observable();
  93681. /**
  93682. * Observable called when a task is successful
  93683. */
  93684. this.onTasksDoneObservable = new BABYLON.Observable();
  93685. /**
  93686. * Observable called when a task is done (whatever the result is)
  93687. */
  93688. this.onProgressObservable = new BABYLON.Observable();
  93689. /**
  93690. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  93691. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  93692. */
  93693. this.useDefaultLoadingScreen = true;
  93694. this._scene = scene;
  93695. }
  93696. /**
  93697. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  93698. * @param taskName defines the name of the new task
  93699. * @param meshesNames defines the name of meshes to load
  93700. * @param rootUrl defines the root url to use to locate files
  93701. * @param sceneFilename defines the filename of the scene file
  93702. * @returns a new {BABYLON.MeshAssetTask} object
  93703. */
  93704. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  93705. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  93706. this._tasks.push(task);
  93707. return task;
  93708. };
  93709. /**
  93710. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  93711. * @param taskName defines the name of the new task
  93712. * @param url defines the url of the file to load
  93713. * @returns a new {BABYLON.TextFileAssetTask} object
  93714. */
  93715. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  93716. var task = new TextFileAssetTask(taskName, url);
  93717. this._tasks.push(task);
  93718. return task;
  93719. };
  93720. /**
  93721. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  93722. * @param taskName defines the name of the new task
  93723. * @param url defines the url of the file to load
  93724. * @returns a new {BABYLON.BinaryFileAssetTask} object
  93725. */
  93726. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  93727. var task = new BinaryFileAssetTask(taskName, url);
  93728. this._tasks.push(task);
  93729. return task;
  93730. };
  93731. /**
  93732. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  93733. * @param taskName defines the name of the new task
  93734. * @param url defines the url of the file to load
  93735. * @returns a new {BABYLON.ImageAssetTask} object
  93736. */
  93737. AssetsManager.prototype.addImageTask = function (taskName, url) {
  93738. var task = new ImageAssetTask(taskName, url);
  93739. this._tasks.push(task);
  93740. return task;
  93741. };
  93742. /**
  93743. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  93744. * @param taskName defines the name of the new task
  93745. * @param url defines the url of the file to load
  93746. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93747. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  93748. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  93749. * @returns a new {BABYLON.TextureAssetTask} object
  93750. */
  93751. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  93752. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93753. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  93754. this._tasks.push(task);
  93755. return task;
  93756. };
  93757. /**
  93758. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  93759. * @param taskName defines the name of the new task
  93760. * @param url defines the url of the file to load
  93761. * @param extensions defines the extension to use to load the cube map (can be null)
  93762. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93763. * @param files defines the list of files to load (can be null)
  93764. * @returns a new {BABYLON.CubeTextureAssetTask} object
  93765. */
  93766. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  93767. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  93768. this._tasks.push(task);
  93769. return task;
  93770. };
  93771. /**
  93772. *
  93773. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  93774. * @param taskName defines the name of the new task
  93775. * @param url defines the url of the file to load
  93776. * @param size defines the size you want for the cubemap (can be null)
  93777. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93778. * @param generateHarmonics defines if you want to automatically generate (true by default)
  93779. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  93780. * @param reserved Internal use only
  93781. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  93782. */
  93783. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  93784. if (noMipmap === void 0) { noMipmap = false; }
  93785. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93786. if (gammaSpace === void 0) { gammaSpace = false; }
  93787. if (reserved === void 0) { reserved = false; }
  93788. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  93789. this._tasks.push(task);
  93790. return task;
  93791. };
  93792. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  93793. var _this = this;
  93794. this._waitingTasksCount--;
  93795. try {
  93796. if (task.taskState === AssetTaskState.DONE) {
  93797. // Let's remove successfull tasks
  93798. BABYLON.Tools.SetImmediate(function () {
  93799. var index = _this._tasks.indexOf(task);
  93800. if (index > -1) {
  93801. _this._tasks.splice(index, 1);
  93802. }
  93803. });
  93804. }
  93805. if (this.onProgress) {
  93806. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  93807. }
  93808. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  93809. }
  93810. catch (e) {
  93811. BABYLON.Tools.Error("Error running progress callbacks.");
  93812. console.log(e);
  93813. }
  93814. if (this._waitingTasksCount === 0) {
  93815. try {
  93816. if (this.onFinish) {
  93817. this.onFinish(this._tasks);
  93818. }
  93819. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93820. }
  93821. catch (e) {
  93822. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  93823. console.log(e);
  93824. }
  93825. this._isLoading = false;
  93826. this._scene.getEngine().hideLoadingUI();
  93827. }
  93828. };
  93829. AssetsManager.prototype._runTask = function (task) {
  93830. var _this = this;
  93831. var done = function () {
  93832. try {
  93833. if (_this.onTaskSuccess) {
  93834. _this.onTaskSuccess(task);
  93835. }
  93836. _this.onTaskSuccessObservable.notifyObservers(task);
  93837. _this._decreaseWaitingTasksCount(task);
  93838. }
  93839. catch (e) {
  93840. error("Error executing task success callbacks", e);
  93841. }
  93842. };
  93843. var error = function (message, exception) {
  93844. task._setErrorObject(message, exception);
  93845. if (_this.onTaskError) {
  93846. _this.onTaskError(task);
  93847. }
  93848. _this.onTaskErrorObservable.notifyObservers(task);
  93849. _this._decreaseWaitingTasksCount(task);
  93850. };
  93851. task.run(this._scene, done, error);
  93852. };
  93853. /**
  93854. * Reset the {BABYLON.AssetsManager} and remove all tasks
  93855. * @return the current instance of the {BABYLON.AssetsManager}
  93856. */
  93857. AssetsManager.prototype.reset = function () {
  93858. this._isLoading = false;
  93859. this._tasks = new Array();
  93860. return this;
  93861. };
  93862. /**
  93863. * Start the loading process
  93864. * @return the current instance of the {BABYLON.AssetsManager}
  93865. */
  93866. AssetsManager.prototype.load = function () {
  93867. if (this._isLoading) {
  93868. return this;
  93869. }
  93870. this._isLoading = true;
  93871. this._waitingTasksCount = this._tasks.length;
  93872. this._totalTasksCount = this._tasks.length;
  93873. if (this._waitingTasksCount === 0) {
  93874. this._isLoading = false;
  93875. if (this.onFinish) {
  93876. this.onFinish(this._tasks);
  93877. }
  93878. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93879. return this;
  93880. }
  93881. if (this.useDefaultLoadingScreen) {
  93882. this._scene.getEngine().displayLoadingUI();
  93883. }
  93884. for (var index = 0; index < this._tasks.length; index++) {
  93885. var task = this._tasks[index];
  93886. this._runTask(task);
  93887. }
  93888. return this;
  93889. };
  93890. return AssetsManager;
  93891. }());
  93892. BABYLON.AssetsManager = AssetsManager;
  93893. })(BABYLON || (BABYLON = {}));
  93894. //# sourceMappingURL=babylon.assetsManager.js.map
  93895. var BABYLON;
  93896. (function (BABYLON) {
  93897. var serializedGeometries = [];
  93898. var serializeGeometry = function (geometry, serializationGeometries) {
  93899. if (serializedGeometries[geometry.id]) {
  93900. return;
  93901. }
  93902. if (geometry.doNotSerialize) {
  93903. return;
  93904. }
  93905. if (geometry instanceof BABYLON.BoxGeometry) {
  93906. serializationGeometries.boxes.push(geometry.serialize());
  93907. }
  93908. else if (geometry instanceof BABYLON.SphereGeometry) {
  93909. serializationGeometries.spheres.push(geometry.serialize());
  93910. }
  93911. else if (geometry instanceof BABYLON.CylinderGeometry) {
  93912. serializationGeometries.cylinders.push(geometry.serialize());
  93913. }
  93914. else if (geometry instanceof BABYLON.TorusGeometry) {
  93915. serializationGeometries.toruses.push(geometry.serialize());
  93916. }
  93917. else if (geometry instanceof BABYLON.GroundGeometry) {
  93918. serializationGeometries.grounds.push(geometry.serialize());
  93919. }
  93920. else if (geometry instanceof BABYLON.Plane) {
  93921. serializationGeometries.planes.push(geometry.serialize());
  93922. }
  93923. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  93924. serializationGeometries.torusKnots.push(geometry.serialize());
  93925. }
  93926. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  93927. throw new Error("Unknown primitive type");
  93928. }
  93929. else {
  93930. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  93931. }
  93932. serializedGeometries[geometry.id] = true;
  93933. };
  93934. var serializeMesh = function (mesh, serializationScene) {
  93935. var serializationObject = {};
  93936. // Geometry
  93937. var geometry = mesh._geometry;
  93938. if (geometry) {
  93939. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  93940. // 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
  93941. serializeGeometry(geometry, serializationScene.geometries);
  93942. }
  93943. }
  93944. // Custom
  93945. if (mesh.serialize) {
  93946. mesh.serialize(serializationObject);
  93947. }
  93948. return serializationObject;
  93949. };
  93950. var finalizeSingleMesh = function (mesh, serializationObject) {
  93951. //only works if the mesh is already loaded
  93952. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93953. //serialize material
  93954. if (mesh.material) {
  93955. if (mesh.material instanceof BABYLON.StandardMaterial) {
  93956. serializationObject.materials = serializationObject.materials || [];
  93957. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93958. serializationObject.materials.push(mesh.material.serialize());
  93959. }
  93960. }
  93961. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  93962. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  93963. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93964. serializationObject.multiMaterials.push(mesh.material.serialize());
  93965. }
  93966. }
  93967. }
  93968. //serialize geometry
  93969. var geometry = mesh._geometry;
  93970. if (geometry) {
  93971. if (!serializationObject.geometries) {
  93972. serializationObject.geometries = {};
  93973. serializationObject.geometries.boxes = [];
  93974. serializationObject.geometries.spheres = [];
  93975. serializationObject.geometries.cylinders = [];
  93976. serializationObject.geometries.toruses = [];
  93977. serializationObject.geometries.grounds = [];
  93978. serializationObject.geometries.planes = [];
  93979. serializationObject.geometries.torusKnots = [];
  93980. serializationObject.geometries.vertexData = [];
  93981. }
  93982. serializeGeometry(geometry, serializationObject.geometries);
  93983. }
  93984. // Skeletons
  93985. if (mesh.skeleton) {
  93986. serializationObject.skeletons = serializationObject.skeletons || [];
  93987. serializationObject.skeletons.push(mesh.skeleton.serialize());
  93988. }
  93989. //serialize the actual mesh
  93990. serializationObject.meshes = serializationObject.meshes || [];
  93991. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93992. }
  93993. };
  93994. var SceneSerializer = /** @class */ (function () {
  93995. function SceneSerializer() {
  93996. }
  93997. SceneSerializer.ClearCache = function () {
  93998. serializedGeometries = [];
  93999. };
  94000. SceneSerializer.Serialize = function (scene) {
  94001. var serializationObject = {};
  94002. SceneSerializer.ClearCache();
  94003. // Scene
  94004. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  94005. serializationObject.autoClear = scene.autoClear;
  94006. serializationObject.clearColor = scene.clearColor.asArray();
  94007. serializationObject.ambientColor = scene.ambientColor.asArray();
  94008. serializationObject.gravity = scene.gravity.asArray();
  94009. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  94010. serializationObject.workerCollisions = scene.workerCollisions;
  94011. // Fog
  94012. if (scene.fogMode && scene.fogMode !== 0) {
  94013. serializationObject.fogMode = scene.fogMode;
  94014. serializationObject.fogColor = scene.fogColor.asArray();
  94015. serializationObject.fogStart = scene.fogStart;
  94016. serializationObject.fogEnd = scene.fogEnd;
  94017. serializationObject.fogDensity = scene.fogDensity;
  94018. }
  94019. //Physics
  94020. if (scene.isPhysicsEnabled()) {
  94021. var physicEngine = scene.getPhysicsEngine();
  94022. if (physicEngine) {
  94023. serializationObject.physicsEnabled = true;
  94024. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  94025. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  94026. }
  94027. }
  94028. // Metadata
  94029. if (scene.metadata) {
  94030. serializationObject.metadata = scene.metadata;
  94031. }
  94032. // Morph targets
  94033. serializationObject.morphTargetManagers = [];
  94034. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  94035. var abstractMesh = _a[_i];
  94036. var manager = abstractMesh.morphTargetManager;
  94037. if (manager) {
  94038. serializationObject.morphTargetManagers.push(manager.serialize());
  94039. }
  94040. }
  94041. // Lights
  94042. serializationObject.lights = [];
  94043. var index;
  94044. var light;
  94045. for (index = 0; index < scene.lights.length; index++) {
  94046. light = scene.lights[index];
  94047. if (!light.doNotSerialize) {
  94048. serializationObject.lights.push(light.serialize());
  94049. }
  94050. }
  94051. // Cameras
  94052. serializationObject.cameras = [];
  94053. for (index = 0; index < scene.cameras.length; index++) {
  94054. var camera = scene.cameras[index];
  94055. if (!camera.doNotSerialize) {
  94056. serializationObject.cameras.push(camera.serialize());
  94057. }
  94058. }
  94059. if (scene.activeCamera) {
  94060. serializationObject.activeCameraID = scene.activeCamera.id;
  94061. }
  94062. // Animations
  94063. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  94064. // Materials
  94065. serializationObject.materials = [];
  94066. serializationObject.multiMaterials = [];
  94067. var material;
  94068. for (index = 0; index < scene.materials.length; index++) {
  94069. material = scene.materials[index];
  94070. if (!material.doNotSerialize) {
  94071. serializationObject.materials.push(material.serialize());
  94072. }
  94073. }
  94074. // MultiMaterials
  94075. serializationObject.multiMaterials = [];
  94076. for (index = 0; index < scene.multiMaterials.length; index++) {
  94077. var multiMaterial = scene.multiMaterials[index];
  94078. serializationObject.multiMaterials.push(multiMaterial.serialize());
  94079. }
  94080. // Environment texture
  94081. if (scene.environmentTexture) {
  94082. serializationObject.environmentTexture = scene.environmentTexture.name;
  94083. }
  94084. // Skeletons
  94085. serializationObject.skeletons = [];
  94086. for (index = 0; index < scene.skeletons.length; index++) {
  94087. var skeleton = scene.skeletons[index];
  94088. if (!skeleton.doNotSerialize) {
  94089. serializationObject.skeletons.push(skeleton.serialize());
  94090. }
  94091. }
  94092. // Transform nodes
  94093. serializationObject.transformNodes = [];
  94094. for (index = 0; index < scene.transformNodes.length; index++) {
  94095. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  94096. }
  94097. // Geometries
  94098. serializationObject.geometries = {};
  94099. serializationObject.geometries.boxes = [];
  94100. serializationObject.geometries.spheres = [];
  94101. serializationObject.geometries.cylinders = [];
  94102. serializationObject.geometries.toruses = [];
  94103. serializationObject.geometries.grounds = [];
  94104. serializationObject.geometries.planes = [];
  94105. serializationObject.geometries.torusKnots = [];
  94106. serializationObject.geometries.vertexData = [];
  94107. serializedGeometries = [];
  94108. var geometries = scene.getGeometries();
  94109. for (index = 0; index < geometries.length; index++) {
  94110. var geometry = geometries[index];
  94111. if (geometry.isReady()) {
  94112. serializeGeometry(geometry, serializationObject.geometries);
  94113. }
  94114. }
  94115. // Meshes
  94116. serializationObject.meshes = [];
  94117. for (index = 0; index < scene.meshes.length; index++) {
  94118. var abstractMesh = scene.meshes[index];
  94119. if (abstractMesh instanceof BABYLON.Mesh) {
  94120. var mesh = abstractMesh;
  94121. if (!mesh.doNotSerialize) {
  94122. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  94123. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  94124. }
  94125. }
  94126. }
  94127. }
  94128. // Particles Systems
  94129. serializationObject.particleSystems = [];
  94130. for (index = 0; index < scene.particleSystems.length; index++) {
  94131. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  94132. }
  94133. // Lens flares
  94134. serializationObject.lensFlareSystems = [];
  94135. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  94136. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  94137. }
  94138. // Shadows
  94139. serializationObject.shadowGenerators = [];
  94140. for (index = 0; index < scene.lights.length; index++) {
  94141. light = scene.lights[index];
  94142. var shadowGenerator = light.getShadowGenerator();
  94143. if (shadowGenerator) {
  94144. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  94145. }
  94146. }
  94147. // Action Manager
  94148. if (scene.actionManager) {
  94149. serializationObject.actions = scene.actionManager.serialize("scene");
  94150. }
  94151. // Audio
  94152. serializationObject.sounds = [];
  94153. for (index = 0; index < scene.soundTracks.length; index++) {
  94154. var soundtrack = scene.soundTracks[index];
  94155. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  94156. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  94157. }
  94158. }
  94159. // Effect layers
  94160. serializationObject.effectLayers = [];
  94161. for (index = 0; index < scene.effectLayers.length; index++) {
  94162. var layer = scene.effectLayers[index];
  94163. if (layer.serialize) {
  94164. serializationObject.effectLayers.push(layer.serialize());
  94165. }
  94166. }
  94167. return serializationObject;
  94168. };
  94169. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  94170. if (withParents === void 0) { withParents = false; }
  94171. if (withChildren === void 0) { withChildren = false; }
  94172. var serializationObject = {};
  94173. SceneSerializer.ClearCache();
  94174. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  94175. if (withParents || withChildren) {
  94176. //deliberate for loop! not for each, appended should be processed as well.
  94177. for (var i = 0; i < toSerialize.length; ++i) {
  94178. if (withChildren) {
  94179. toSerialize[i].getDescendants().forEach(function (node) {
  94180. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  94181. toSerialize.push(node);
  94182. }
  94183. });
  94184. }
  94185. //make sure the array doesn't contain the object already
  94186. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  94187. toSerialize.push(toSerialize[i].parent);
  94188. }
  94189. }
  94190. }
  94191. toSerialize.forEach(function (mesh) {
  94192. finalizeSingleMesh(mesh, serializationObject);
  94193. });
  94194. return serializationObject;
  94195. };
  94196. return SceneSerializer;
  94197. }());
  94198. BABYLON.SceneSerializer = SceneSerializer;
  94199. })(BABYLON || (BABYLON = {}));
  94200. //# sourceMappingURL=babylon.sceneSerializer.js.map
  94201. var BABYLON;
  94202. (function (BABYLON) {
  94203. var ReflectionProbe = /** @class */ (function () {
  94204. function ReflectionProbe(name, size, scene, generateMipMaps) {
  94205. if (generateMipMaps === void 0) { generateMipMaps = true; }
  94206. var _this = this;
  94207. this.name = name;
  94208. this._viewMatrix = BABYLON.Matrix.Identity();
  94209. this._target = BABYLON.Vector3.Zero();
  94210. this._add = BABYLON.Vector3.Zero();
  94211. this._invertYAxis = false;
  94212. this.position = BABYLON.Vector3.Zero();
  94213. this._scene = scene;
  94214. this._scene.reflectionProbes.push(this);
  94215. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  94216. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  94217. switch (faceIndex) {
  94218. case 0:
  94219. _this._add.copyFromFloats(1, 0, 0);
  94220. break;
  94221. case 1:
  94222. _this._add.copyFromFloats(-1, 0, 0);
  94223. break;
  94224. case 2:
  94225. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  94226. break;
  94227. case 3:
  94228. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  94229. break;
  94230. case 4:
  94231. _this._add.copyFromFloats(0, 0, 1);
  94232. break;
  94233. case 5:
  94234. _this._add.copyFromFloats(0, 0, -1);
  94235. break;
  94236. }
  94237. if (_this._attachedMesh) {
  94238. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  94239. }
  94240. _this.position.addToRef(_this._add, _this._target);
  94241. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  94242. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  94243. scene._forcedViewPosition = _this.position;
  94244. });
  94245. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  94246. scene._forcedViewPosition = null;
  94247. scene.updateTransformMatrix(true);
  94248. });
  94249. if (scene.activeCamera) {
  94250. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  94251. }
  94252. }
  94253. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  94254. get: function () {
  94255. return this._renderTargetTexture.samples;
  94256. },
  94257. set: function (value) {
  94258. this._renderTargetTexture.samples = value;
  94259. },
  94260. enumerable: true,
  94261. configurable: true
  94262. });
  94263. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  94264. get: function () {
  94265. return this._renderTargetTexture.refreshRate;
  94266. },
  94267. set: function (value) {
  94268. this._renderTargetTexture.refreshRate = value;
  94269. },
  94270. enumerable: true,
  94271. configurable: true
  94272. });
  94273. ReflectionProbe.prototype.getScene = function () {
  94274. return this._scene;
  94275. };
  94276. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  94277. get: function () {
  94278. return this._renderTargetTexture;
  94279. },
  94280. enumerable: true,
  94281. configurable: true
  94282. });
  94283. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  94284. get: function () {
  94285. return this._renderTargetTexture.renderList;
  94286. },
  94287. enumerable: true,
  94288. configurable: true
  94289. });
  94290. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  94291. this._attachedMesh = mesh;
  94292. };
  94293. /**
  94294. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  94295. *
  94296. * @param renderingGroupId The rendering group id corresponding to its index
  94297. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  94298. */
  94299. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  94300. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  94301. };
  94302. ReflectionProbe.prototype.dispose = function () {
  94303. var index = this._scene.reflectionProbes.indexOf(this);
  94304. if (index !== -1) {
  94305. // Remove from the scene if found
  94306. this._scene.reflectionProbes.splice(index, 1);
  94307. }
  94308. if (this._renderTargetTexture) {
  94309. this._renderTargetTexture.dispose();
  94310. this._renderTargetTexture = null;
  94311. }
  94312. };
  94313. return ReflectionProbe;
  94314. }());
  94315. BABYLON.ReflectionProbe = ReflectionProbe;
  94316. })(BABYLON || (BABYLON = {}));
  94317. //# sourceMappingURL=babylon.reflectionProbe.js.map
  94318. var BABYLON;
  94319. (function (BABYLON) {
  94320. var Layer = /** @class */ (function () {
  94321. function Layer(name, imgUrl, scene, isBackground, color) {
  94322. this.name = name;
  94323. this.scale = new BABYLON.Vector2(1, 1);
  94324. this.offset = new BABYLON.Vector2(0, 0);
  94325. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  94326. this.layerMask = 0x0FFFFFFF;
  94327. this._vertexBuffers = {};
  94328. // Events
  94329. /**
  94330. * An event triggered when the layer is disposed.
  94331. */
  94332. this.onDisposeObservable = new BABYLON.Observable();
  94333. /**
  94334. * An event triggered before rendering the scene
  94335. */
  94336. this.onBeforeRenderObservable = new BABYLON.Observable();
  94337. /**
  94338. * An event triggered after rendering the scene
  94339. */
  94340. this.onAfterRenderObservable = new BABYLON.Observable();
  94341. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  94342. this.isBackground = isBackground === undefined ? true : isBackground;
  94343. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  94344. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  94345. this._scene.layers.push(this);
  94346. var engine = this._scene.getEngine();
  94347. // VBO
  94348. var vertices = [];
  94349. vertices.push(1, 1);
  94350. vertices.push(-1, 1);
  94351. vertices.push(-1, -1);
  94352. vertices.push(1, -1);
  94353. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  94354. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  94355. this._createIndexBuffer();
  94356. // Effects
  94357. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  94358. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  94359. }
  94360. Object.defineProperty(Layer.prototype, "onDispose", {
  94361. set: function (callback) {
  94362. if (this._onDisposeObserver) {
  94363. this.onDisposeObservable.remove(this._onDisposeObserver);
  94364. }
  94365. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  94366. },
  94367. enumerable: true,
  94368. configurable: true
  94369. });
  94370. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  94371. set: function (callback) {
  94372. if (this._onBeforeRenderObserver) {
  94373. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  94374. }
  94375. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  94376. },
  94377. enumerable: true,
  94378. configurable: true
  94379. });
  94380. Object.defineProperty(Layer.prototype, "onAfterRender", {
  94381. set: function (callback) {
  94382. if (this._onAfterRenderObserver) {
  94383. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  94384. }
  94385. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  94386. },
  94387. enumerable: true,
  94388. configurable: true
  94389. });
  94390. Layer.prototype._createIndexBuffer = function () {
  94391. var engine = this._scene.getEngine();
  94392. // Indices
  94393. var indices = [];
  94394. indices.push(0);
  94395. indices.push(1);
  94396. indices.push(2);
  94397. indices.push(0);
  94398. indices.push(2);
  94399. indices.push(3);
  94400. this._indexBuffer = engine.createIndexBuffer(indices);
  94401. };
  94402. Layer.prototype._rebuild = function () {
  94403. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94404. if (vb) {
  94405. vb._rebuild();
  94406. }
  94407. this._createIndexBuffer();
  94408. };
  94409. Layer.prototype.render = function () {
  94410. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  94411. // Check
  94412. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  94413. return;
  94414. var engine = this._scene.getEngine();
  94415. this.onBeforeRenderObservable.notifyObservers(this);
  94416. // Render
  94417. engine.enableEffect(currentEffect);
  94418. engine.setState(false);
  94419. // Texture
  94420. currentEffect.setTexture("textureSampler", this.texture);
  94421. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  94422. // Color
  94423. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  94424. // Scale / offset
  94425. currentEffect.setVector2("offset", this.offset);
  94426. currentEffect.setVector2("scale", this.scale);
  94427. // VBOs
  94428. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  94429. // Draw order
  94430. if (!this.alphaTest) {
  94431. engine.setAlphaMode(this.alphaBlendingMode);
  94432. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94433. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  94434. }
  94435. else {
  94436. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94437. }
  94438. this.onAfterRenderObservable.notifyObservers(this);
  94439. };
  94440. Layer.prototype.dispose = function () {
  94441. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94442. if (vertexBuffer) {
  94443. vertexBuffer.dispose();
  94444. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94445. }
  94446. if (this._indexBuffer) {
  94447. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94448. this._indexBuffer = null;
  94449. }
  94450. if (this.texture) {
  94451. this.texture.dispose();
  94452. this.texture = null;
  94453. }
  94454. // Remove from scene
  94455. var index = this._scene.layers.indexOf(this);
  94456. this._scene.layers.splice(index, 1);
  94457. // Callback
  94458. this.onDisposeObservable.notifyObservers(this);
  94459. this.onDisposeObservable.clear();
  94460. this.onAfterRenderObservable.clear();
  94461. this.onBeforeRenderObservable.clear();
  94462. };
  94463. return Layer;
  94464. }());
  94465. BABYLON.Layer = Layer;
  94466. })(BABYLON || (BABYLON = {}));
  94467. //# sourceMappingURL=babylon.layer.js.map
  94468. var BABYLON;
  94469. (function (BABYLON) {
  94470. var TextureTools = /** @class */ (function () {
  94471. function TextureTools() {
  94472. }
  94473. /**
  94474. * Uses the GPU to create a copy texture rescaled at a given size
  94475. * @param texture Texture to copy from
  94476. * @param width Desired width
  94477. * @param height Desired height
  94478. * @return Generated texture
  94479. */
  94480. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  94481. if (useBilinearMode === void 0) { useBilinearMode = true; }
  94482. var scene = texture.getScene();
  94483. var engine = scene.getEngine();
  94484. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  94485. rtt.wrapU = texture.wrapU;
  94486. rtt.wrapV = texture.wrapV;
  94487. rtt.uOffset = texture.uOffset;
  94488. rtt.vOffset = texture.vOffset;
  94489. rtt.uScale = texture.uScale;
  94490. rtt.vScale = texture.vScale;
  94491. rtt.uAng = texture.uAng;
  94492. rtt.vAng = texture.vAng;
  94493. rtt.wAng = texture.wAng;
  94494. rtt.coordinatesIndex = texture.coordinatesIndex;
  94495. rtt.level = texture.level;
  94496. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  94497. rtt._texture.isReady = false;
  94498. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94499. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94500. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94501. passPostProcess.getEffect().executeWhenCompiled(function () {
  94502. passPostProcess.onApply = function (effect) {
  94503. effect.setTexture("textureSampler", texture);
  94504. };
  94505. var internalTexture = rtt.getInternalTexture();
  94506. if (internalTexture) {
  94507. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  94508. engine.unBindFramebuffer(internalTexture);
  94509. rtt.disposeFramebufferObjects();
  94510. passPostProcess.dispose();
  94511. internalTexture.isReady = true;
  94512. }
  94513. });
  94514. return rtt;
  94515. };
  94516. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  94517. if (!scene._environmentBRDFTexture) {
  94518. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94519. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94520. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94521. scene._environmentBRDFTexture = texture;
  94522. }
  94523. return scene._environmentBRDFTexture;
  94524. };
  94525. 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=";
  94526. return TextureTools;
  94527. }());
  94528. BABYLON.TextureTools = TextureTools;
  94529. })(BABYLON || (BABYLON = {}));
  94530. //# sourceMappingURL=babylon.textureTools.js.map
  94531. var BABYLON;
  94532. (function (BABYLON) {
  94533. var FramingBehavior = /** @class */ (function () {
  94534. function FramingBehavior() {
  94535. this._mode = FramingBehavior.FitFrustumSidesMode;
  94536. this._radiusScale = 1.0;
  94537. this._positionScale = 0.5;
  94538. this._defaultElevation = 0.3;
  94539. this._elevationReturnTime = 1500;
  94540. this._elevationReturnWaitTime = 1000;
  94541. this._zoomStopsAnimation = false;
  94542. this._framingTime = 1500;
  94543. this._isPointerDown = false;
  94544. this._lastInteractionTime = -Infinity;
  94545. // Framing control
  94546. this._animatables = new Array();
  94547. this._betaIsAnimating = false;
  94548. }
  94549. Object.defineProperty(FramingBehavior.prototype, "name", {
  94550. get: function () {
  94551. return "Framing";
  94552. },
  94553. enumerable: true,
  94554. configurable: true
  94555. });
  94556. Object.defineProperty(FramingBehavior.prototype, "mode", {
  94557. /**
  94558. * Gets current mode used by the behavior.
  94559. */
  94560. get: function () {
  94561. return this._mode;
  94562. },
  94563. /**
  94564. * Sets the current mode used by the behavior
  94565. */
  94566. set: function (mode) {
  94567. this._mode = mode;
  94568. },
  94569. enumerable: true,
  94570. configurable: true
  94571. });
  94572. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  94573. /**
  94574. * Gets the scale applied to the radius
  94575. */
  94576. get: function () {
  94577. return this._radiusScale;
  94578. },
  94579. /**
  94580. * Sets the scale applied to the radius (1 by default)
  94581. */
  94582. set: function (radius) {
  94583. this._radiusScale = radius;
  94584. },
  94585. enumerable: true,
  94586. configurable: true
  94587. });
  94588. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  94589. /**
  94590. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94591. */
  94592. get: function () {
  94593. return this._positionScale;
  94594. },
  94595. /**
  94596. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94597. */
  94598. set: function (scale) {
  94599. this._positionScale = scale;
  94600. },
  94601. enumerable: true,
  94602. configurable: true
  94603. });
  94604. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  94605. /**
  94606. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94607. * behaviour is triggered, in radians.
  94608. */
  94609. get: function () {
  94610. return this._defaultElevation;
  94611. },
  94612. /**
  94613. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94614. * behaviour is triggered, in radians.
  94615. */
  94616. set: function (elevation) {
  94617. this._defaultElevation = elevation;
  94618. },
  94619. enumerable: true,
  94620. configurable: true
  94621. });
  94622. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  94623. /**
  94624. * Gets the time (in milliseconds) taken to return to the default beta position.
  94625. * Negative value indicates camera should not return to default.
  94626. */
  94627. get: function () {
  94628. return this._elevationReturnTime;
  94629. },
  94630. /**
  94631. * Sets the time (in milliseconds) taken to return to the default beta position.
  94632. * Negative value indicates camera should not return to default.
  94633. */
  94634. set: function (speed) {
  94635. this._elevationReturnTime = speed;
  94636. },
  94637. enumerable: true,
  94638. configurable: true
  94639. });
  94640. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  94641. /**
  94642. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94643. */
  94644. get: function () {
  94645. return this._elevationReturnWaitTime;
  94646. },
  94647. /**
  94648. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94649. */
  94650. set: function (time) {
  94651. this._elevationReturnWaitTime = time;
  94652. },
  94653. enumerable: true,
  94654. configurable: true
  94655. });
  94656. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  94657. /**
  94658. * Gets the flag that indicates if user zooming should stop animation.
  94659. */
  94660. get: function () {
  94661. return this._zoomStopsAnimation;
  94662. },
  94663. /**
  94664. * Sets the flag that indicates if user zooming should stop animation.
  94665. */
  94666. set: function (flag) {
  94667. this._zoomStopsAnimation = flag;
  94668. },
  94669. enumerable: true,
  94670. configurable: true
  94671. });
  94672. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  94673. /**
  94674. * Gets the transition time when framing the mesh, in milliseconds
  94675. */
  94676. get: function () {
  94677. return this._framingTime;
  94678. },
  94679. /**
  94680. * Sets the transition time when framing the mesh, in milliseconds
  94681. */
  94682. set: function (time) {
  94683. this._framingTime = time;
  94684. },
  94685. enumerable: true,
  94686. configurable: true
  94687. });
  94688. FramingBehavior.prototype.init = function () {
  94689. // Do notihng
  94690. };
  94691. FramingBehavior.prototype.attach = function (camera) {
  94692. var _this = this;
  94693. this._attachedCamera = camera;
  94694. var scene = this._attachedCamera.getScene();
  94695. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  94696. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94697. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94698. _this._isPointerDown = true;
  94699. return;
  94700. }
  94701. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94702. _this._isPointerDown = false;
  94703. }
  94704. });
  94705. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94706. if (mesh) {
  94707. _this.zoomOnMesh(mesh);
  94708. }
  94709. });
  94710. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94711. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94712. _this._applyUserInteraction();
  94713. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  94714. // back to the default position after a given timeout
  94715. _this._maintainCameraAboveGround();
  94716. });
  94717. };
  94718. FramingBehavior.prototype.detach = function () {
  94719. if (!this._attachedCamera) {
  94720. return;
  94721. }
  94722. var scene = this._attachedCamera.getScene();
  94723. if (this._onPrePointerObservableObserver) {
  94724. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94725. }
  94726. if (this._onAfterCheckInputsObserver) {
  94727. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94728. }
  94729. if (this._onMeshTargetChangedObserver) {
  94730. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94731. }
  94732. this._attachedCamera = null;
  94733. };
  94734. /**
  94735. * Targets the given mesh and updates zoom level accordingly.
  94736. * @param mesh The mesh to target.
  94737. * @param radius Optional. If a cached radius position already exists, overrides default.
  94738. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94739. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94740. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94741. */
  94742. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94743. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94744. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94745. mesh.computeWorldMatrix(true);
  94746. var boundingBox = mesh.getBoundingInfo().boundingBox;
  94747. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  94748. };
  94749. /**
  94750. * Targets the given mesh with its children and updates zoom level accordingly.
  94751. * @param mesh The mesh to target.
  94752. * @param radius Optional. If a cached radius position already exists, overrides default.
  94753. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94754. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94755. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94756. */
  94757. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94758. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94759. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94760. mesh.computeWorldMatrix(true);
  94761. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  94762. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  94763. };
  94764. /**
  94765. * Targets the given meshes with their children and updates zoom level accordingly.
  94766. * @param meshes The mesh to target.
  94767. * @param radius Optional. If a cached radius position already exists, overrides default.
  94768. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94769. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94770. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94771. */
  94772. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  94773. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94774. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94775. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  94776. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  94777. for (var i = 0; i < meshes.length; i++) {
  94778. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  94779. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  94780. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  94781. }
  94782. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  94783. };
  94784. /**
  94785. * Targets the given mesh and updates zoom level accordingly.
  94786. * @param mesh The mesh to target.
  94787. * @param radius Optional. If a cached radius position already exists, overrides default.
  94788. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94789. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94790. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94791. */
  94792. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  94793. var _this = this;
  94794. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94795. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94796. var zoomTarget;
  94797. if (!this._attachedCamera) {
  94798. return;
  94799. }
  94800. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  94801. var bottom = minimumWorld.y;
  94802. var top = maximumWorld.y;
  94803. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  94804. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  94805. if (focusOnOriginXZ) {
  94806. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  94807. }
  94808. else {
  94809. var centerWorld = minimumWorld.add(radiusWorld);
  94810. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  94811. }
  94812. if (!this._vectorTransition) {
  94813. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  94814. }
  94815. this._betaIsAnimating = true;
  94816. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  94817. if (animatable) {
  94818. this._animatables.push(animatable);
  94819. }
  94820. // sets the radius and lower radius bounds
  94821. // Small delta ensures camera is not always at lower zoom limit.
  94822. var radius = 0;
  94823. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  94824. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94825. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  94826. radius = position;
  94827. }
  94828. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94829. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94830. if (this._attachedCamera.lowerRadiusLimit === null) {
  94831. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  94832. }
  94833. }
  94834. // Set sensibilities
  94835. var extend = maximumWorld.subtract(minimumWorld).length();
  94836. this._attachedCamera.panningSensibility = 5000 / extend;
  94837. this._attachedCamera.wheelPrecision = 100 / radius;
  94838. // transition to new radius
  94839. if (!this._radiusTransition) {
  94840. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94841. }
  94842. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  94843. _this.stopAllAnimations();
  94844. if (onAnimationEnd) {
  94845. onAnimationEnd();
  94846. }
  94847. if (_this._attachedCamera) {
  94848. _this._attachedCamera.storeState();
  94849. }
  94850. });
  94851. if (animatable) {
  94852. this._animatables.push(animatable);
  94853. }
  94854. };
  94855. /**
  94856. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  94857. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  94858. * frustum width.
  94859. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  94860. * to fully enclose the mesh in the viewing frustum.
  94861. */
  94862. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  94863. var size = maximumWorld.subtract(minimumWorld);
  94864. var boxVectorGlobalDiagonal = size.length();
  94865. var frustumSlope = this._getFrustumSlope();
  94866. // Formula for setting distance
  94867. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  94868. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  94869. // Horizon distance
  94870. var radius = radiusWithoutFraming * this._radiusScale;
  94871. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  94872. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  94873. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  94874. var camera = this._attachedCamera;
  94875. if (!camera) {
  94876. return 0;
  94877. }
  94878. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94879. // Don't exceed the requested limit
  94880. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  94881. }
  94882. // Don't exceed the upper radius limit
  94883. if (camera.upperRadiusLimit) {
  94884. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  94885. }
  94886. return distance;
  94887. };
  94888. /**
  94889. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  94890. * is automatically returned to its default position (expected to be above ground plane).
  94891. */
  94892. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  94893. var _this = this;
  94894. if (this._elevationReturnTime < 0) {
  94895. return;
  94896. }
  94897. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  94898. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  94899. var limitBeta = Math.PI * 0.5;
  94900. // Bring the camera back up if below the ground plane
  94901. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  94902. this._betaIsAnimating = true;
  94903. //Transition to new position
  94904. this.stopAllAnimations();
  94905. if (!this._betaTransition) {
  94906. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94907. }
  94908. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  94909. _this._clearAnimationLocks();
  94910. _this.stopAllAnimations();
  94911. });
  94912. if (animatabe) {
  94913. this._animatables.push(animatabe);
  94914. }
  94915. }
  94916. };
  94917. /**
  94918. * Returns the frustum slope based on the canvas ratio and camera FOV
  94919. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  94920. */
  94921. FramingBehavior.prototype._getFrustumSlope = function () {
  94922. // Calculate the viewport ratio
  94923. // Aspect Ratio is Height/Width.
  94924. var camera = this._attachedCamera;
  94925. if (!camera) {
  94926. return BABYLON.Vector2.Zero();
  94927. }
  94928. var engine = camera.getScene().getEngine();
  94929. var aspectRatio = engine.getAspectRatio(camera);
  94930. // Camera FOV is the vertical field of view (top-bottom) in radians.
  94931. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  94932. var frustumSlopeY = Math.tan(camera.fov / 2);
  94933. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  94934. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  94935. // along the forward vector.
  94936. var frustumSlopeX = frustumSlopeY * aspectRatio;
  94937. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  94938. };
  94939. /**
  94940. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  94941. */
  94942. FramingBehavior.prototype._clearAnimationLocks = function () {
  94943. this._betaIsAnimating = false;
  94944. };
  94945. /**
  94946. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94947. */
  94948. FramingBehavior.prototype._applyUserInteraction = function () {
  94949. if (this.isUserIsMoving) {
  94950. this._lastInteractionTime = BABYLON.Tools.Now;
  94951. this.stopAllAnimations();
  94952. this._clearAnimationLocks();
  94953. }
  94954. };
  94955. /**
  94956. * Stops and removes all animations that have been applied to the camera
  94957. */
  94958. FramingBehavior.prototype.stopAllAnimations = function () {
  94959. if (this._attachedCamera) {
  94960. this._attachedCamera.animations = [];
  94961. }
  94962. while (this._animatables.length) {
  94963. if (this._animatables[0]) {
  94964. this._animatables[0].onAnimationEnd = null;
  94965. this._animatables[0].stop();
  94966. }
  94967. this._animatables.shift();
  94968. }
  94969. };
  94970. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  94971. /**
  94972. * Gets a value indicating if the user is moving the camera
  94973. */
  94974. get: function () {
  94975. if (!this._attachedCamera) {
  94976. return false;
  94977. }
  94978. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94979. this._attachedCamera.inertialBetaOffset !== 0 ||
  94980. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94981. this._attachedCamera.inertialPanningX !== 0 ||
  94982. this._attachedCamera.inertialPanningY !== 0 ||
  94983. this._isPointerDown;
  94984. },
  94985. enumerable: true,
  94986. configurable: true
  94987. });
  94988. /**
  94989. * The easing function used by animations
  94990. */
  94991. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  94992. /**
  94993. * The easing mode used by animations
  94994. */
  94995. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  94996. // Statics
  94997. /**
  94998. * The camera can move all the way towards the mesh.
  94999. */
  95000. FramingBehavior.IgnoreBoundsSizeMode = 0;
  95001. /**
  95002. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  95003. */
  95004. FramingBehavior.FitFrustumSidesMode = 1;
  95005. return FramingBehavior;
  95006. }());
  95007. BABYLON.FramingBehavior = FramingBehavior;
  95008. })(BABYLON || (BABYLON = {}));
  95009. //# sourceMappingURL=babylon.framingBehavior.js.map
  95010. var BABYLON;
  95011. (function (BABYLON) {
  95012. /**
  95013. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  95014. */
  95015. var BouncingBehavior = /** @class */ (function () {
  95016. function BouncingBehavior() {
  95017. /**
  95018. * The duration of the animation, in milliseconds
  95019. */
  95020. this.transitionDuration = 450;
  95021. /**
  95022. * Length of the distance animated by the transition when lower radius is reached
  95023. */
  95024. this.lowerRadiusTransitionRange = 2;
  95025. /**
  95026. * Length of the distance animated by the transition when upper radius is reached
  95027. */
  95028. this.upperRadiusTransitionRange = -2;
  95029. this._autoTransitionRange = false;
  95030. // Animations
  95031. this._radiusIsAnimating = false;
  95032. this._radiusBounceTransition = null;
  95033. this._animatables = new Array();
  95034. }
  95035. Object.defineProperty(BouncingBehavior.prototype, "name", {
  95036. get: function () {
  95037. return "Bouncing";
  95038. },
  95039. enumerable: true,
  95040. configurable: true
  95041. });
  95042. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  95043. /**
  95044. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  95045. */
  95046. get: function () {
  95047. return this._autoTransitionRange;
  95048. },
  95049. /**
  95050. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  95051. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  95052. */
  95053. set: function (value) {
  95054. var _this = this;
  95055. if (this._autoTransitionRange === value) {
  95056. return;
  95057. }
  95058. this._autoTransitionRange = value;
  95059. var camera = this._attachedCamera;
  95060. if (!camera) {
  95061. return;
  95062. }
  95063. if (value) {
  95064. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  95065. if (!mesh) {
  95066. return;
  95067. }
  95068. mesh.computeWorldMatrix(true);
  95069. var diagonal = mesh.getBoundingInfo().diagonalLength;
  95070. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  95071. _this.upperRadiusTransitionRange = diagonal * 0.05;
  95072. });
  95073. }
  95074. else if (this._onMeshTargetChangedObserver) {
  95075. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  95076. }
  95077. },
  95078. enumerable: true,
  95079. configurable: true
  95080. });
  95081. BouncingBehavior.prototype.init = function () {
  95082. // Do notihng
  95083. };
  95084. BouncingBehavior.prototype.attach = function (camera) {
  95085. var _this = this;
  95086. this._attachedCamera = camera;
  95087. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95088. if (!_this._attachedCamera) {
  95089. return;
  95090. }
  95091. // Add the bounce animation to the lower radius limit
  95092. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  95093. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  95094. }
  95095. // Add the bounce animation to the upper radius limit
  95096. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  95097. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  95098. }
  95099. });
  95100. };
  95101. BouncingBehavior.prototype.detach = function () {
  95102. if (!this._attachedCamera) {
  95103. return;
  95104. }
  95105. if (this._onAfterCheckInputsObserver) {
  95106. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95107. }
  95108. if (this._onMeshTargetChangedObserver) {
  95109. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  95110. }
  95111. this._attachedCamera = null;
  95112. };
  95113. /**
  95114. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  95115. * @param radiusLimit The limit to check against.
  95116. * @return Bool to indicate if at limit.
  95117. */
  95118. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  95119. if (!this._attachedCamera) {
  95120. return false;
  95121. }
  95122. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  95123. return true;
  95124. }
  95125. return false;
  95126. };
  95127. /**
  95128. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  95129. * @param radiusDelta The delta by which to animate to. Can be negative.
  95130. */
  95131. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  95132. var _this = this;
  95133. if (!this._attachedCamera) {
  95134. return;
  95135. }
  95136. if (!this._radiusBounceTransition) {
  95137. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  95138. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  95139. }
  95140. // Prevent zoom until bounce has completed
  95141. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  95142. this._attachedCamera.wheelPrecision = Infinity;
  95143. this._attachedCamera.inertialRadiusOffset = 0;
  95144. // Animate to the radius limit
  95145. this.stopAllAnimations();
  95146. this._radiusIsAnimating = true;
  95147. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  95148. if (animatable) {
  95149. this._animatables.push(animatable);
  95150. }
  95151. };
  95152. /**
  95153. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  95154. */
  95155. BouncingBehavior.prototype._clearAnimationLocks = function () {
  95156. this._radiusIsAnimating = false;
  95157. if (this._attachedCamera) {
  95158. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  95159. }
  95160. };
  95161. /**
  95162. * Stops and removes all animations that have been applied to the camera
  95163. */
  95164. BouncingBehavior.prototype.stopAllAnimations = function () {
  95165. if (this._attachedCamera) {
  95166. this._attachedCamera.animations = [];
  95167. }
  95168. while (this._animatables.length) {
  95169. this._animatables[0].onAnimationEnd = null;
  95170. this._animatables[0].stop();
  95171. this._animatables.shift();
  95172. }
  95173. };
  95174. /**
  95175. * The easing function used by animations
  95176. */
  95177. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  95178. /**
  95179. * The easing mode used by animations
  95180. */
  95181. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  95182. return BouncingBehavior;
  95183. }());
  95184. BABYLON.BouncingBehavior = BouncingBehavior;
  95185. })(BABYLON || (BABYLON = {}));
  95186. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  95187. var BABYLON;
  95188. (function (BABYLON) {
  95189. var AutoRotationBehavior = /** @class */ (function () {
  95190. function AutoRotationBehavior() {
  95191. this._zoomStopsAnimation = false;
  95192. this._idleRotationSpeed = 0.05;
  95193. this._idleRotationWaitTime = 2000;
  95194. this._idleRotationSpinupTime = 2000;
  95195. this._isPointerDown = false;
  95196. this._lastFrameTime = null;
  95197. this._lastInteractionTime = -Infinity;
  95198. this._cameraRotationSpeed = 0;
  95199. this._lastFrameRadius = 0;
  95200. }
  95201. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  95202. get: function () {
  95203. return "AutoRotation";
  95204. },
  95205. enumerable: true,
  95206. configurable: true
  95207. });
  95208. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  95209. /**
  95210. * Gets the flag that indicates if user zooming should stop animation.
  95211. */
  95212. get: function () {
  95213. return this._zoomStopsAnimation;
  95214. },
  95215. /**
  95216. * Sets the flag that indicates if user zooming should stop animation.
  95217. */
  95218. set: function (flag) {
  95219. this._zoomStopsAnimation = flag;
  95220. },
  95221. enumerable: true,
  95222. configurable: true
  95223. });
  95224. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  95225. /**
  95226. * Gets the default speed at which the camera rotates around the model.
  95227. */
  95228. get: function () {
  95229. return this._idleRotationSpeed;
  95230. },
  95231. /**
  95232. * Sets the default speed at which the camera rotates around the model.
  95233. */
  95234. set: function (speed) {
  95235. this._idleRotationSpeed = speed;
  95236. },
  95237. enumerable: true,
  95238. configurable: true
  95239. });
  95240. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  95241. /**
  95242. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  95243. */
  95244. get: function () {
  95245. return this._idleRotationWaitTime;
  95246. },
  95247. /**
  95248. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  95249. */
  95250. set: function (time) {
  95251. this._idleRotationWaitTime = time;
  95252. },
  95253. enumerable: true,
  95254. configurable: true
  95255. });
  95256. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  95257. /**
  95258. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  95259. */
  95260. get: function () {
  95261. return this._idleRotationSpinupTime;
  95262. },
  95263. /**
  95264. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  95265. */
  95266. set: function (time) {
  95267. this._idleRotationSpinupTime = time;
  95268. },
  95269. enumerable: true,
  95270. configurable: true
  95271. });
  95272. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  95273. /**
  95274. * Gets a value indicating if the camera is currently rotating because of this behavior
  95275. */
  95276. get: function () {
  95277. return Math.abs(this._cameraRotationSpeed) > 0;
  95278. },
  95279. enumerable: true,
  95280. configurable: true
  95281. });
  95282. AutoRotationBehavior.prototype.init = function () {
  95283. // Do notihng
  95284. };
  95285. AutoRotationBehavior.prototype.attach = function (camera) {
  95286. var _this = this;
  95287. this._attachedCamera = camera;
  95288. var scene = this._attachedCamera.getScene();
  95289. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  95290. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  95291. _this._isPointerDown = true;
  95292. return;
  95293. }
  95294. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  95295. _this._isPointerDown = false;
  95296. }
  95297. });
  95298. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95299. var now = BABYLON.Tools.Now;
  95300. var dt = 0;
  95301. if (_this._lastFrameTime != null) {
  95302. dt = now - _this._lastFrameTime;
  95303. }
  95304. _this._lastFrameTime = now;
  95305. // Stop the animation if there is user interaction and the animation should stop for this interaction
  95306. _this._applyUserInteraction();
  95307. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  95308. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  95309. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  95310. // Step camera rotation by rotation speed
  95311. if (_this._attachedCamera) {
  95312. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  95313. }
  95314. });
  95315. };
  95316. AutoRotationBehavior.prototype.detach = function () {
  95317. if (!this._attachedCamera) {
  95318. return;
  95319. }
  95320. var scene = this._attachedCamera.getScene();
  95321. if (this._onPrePointerObservableObserver) {
  95322. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  95323. }
  95324. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95325. this._attachedCamera = null;
  95326. };
  95327. /**
  95328. * Returns true if user is scrolling.
  95329. * @return true if user is scrolling.
  95330. */
  95331. AutoRotationBehavior.prototype._userIsZooming = function () {
  95332. if (!this._attachedCamera) {
  95333. return false;
  95334. }
  95335. return this._attachedCamera.inertialRadiusOffset !== 0;
  95336. };
  95337. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  95338. if (!this._attachedCamera) {
  95339. return false;
  95340. }
  95341. var zoomHasHitLimit = false;
  95342. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  95343. zoomHasHitLimit = true;
  95344. }
  95345. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  95346. this._lastFrameRadius = this._attachedCamera.radius;
  95347. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  95348. };
  95349. /**
  95350. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  95351. */
  95352. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  95353. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  95354. this._lastInteractionTime = BABYLON.Tools.Now;
  95355. }
  95356. };
  95357. // Tools
  95358. AutoRotationBehavior.prototype._userIsMoving = function () {
  95359. if (!this._attachedCamera) {
  95360. return false;
  95361. }
  95362. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  95363. this._attachedCamera.inertialBetaOffset !== 0 ||
  95364. this._attachedCamera.inertialRadiusOffset !== 0 ||
  95365. this._attachedCamera.inertialPanningX !== 0 ||
  95366. this._attachedCamera.inertialPanningY !== 0 ||
  95367. this._isPointerDown;
  95368. };
  95369. return AutoRotationBehavior;
  95370. }());
  95371. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  95372. })(BABYLON || (BABYLON = {}));
  95373. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  95374. var BABYLON;
  95375. (function (BABYLON) {
  95376. var NullEngineOptions = /** @class */ (function () {
  95377. function NullEngineOptions() {
  95378. this.renderWidth = 512;
  95379. this.renderHeight = 256;
  95380. this.textureSize = 512;
  95381. this.deterministicLockstep = false;
  95382. this.lockstepMaxSteps = 4;
  95383. }
  95384. return NullEngineOptions;
  95385. }());
  95386. BABYLON.NullEngineOptions = NullEngineOptions;
  95387. /**
  95388. * The null engine class provides support for headless version of babylon.js.
  95389. * This can be used in server side scenario or for testing purposes
  95390. */
  95391. var NullEngine = /** @class */ (function (_super) {
  95392. __extends(NullEngine, _super);
  95393. function NullEngine(options) {
  95394. if (options === void 0) { options = new NullEngineOptions(); }
  95395. var _this = _super.call(this, null) || this;
  95396. if (options.deterministicLockstep === undefined) {
  95397. options.deterministicLockstep = false;
  95398. }
  95399. if (options.lockstepMaxSteps === undefined) {
  95400. options.lockstepMaxSteps = 4;
  95401. }
  95402. _this._options = options;
  95403. // Init caps
  95404. // We consider we are on a webgl1 capable device
  95405. _this._caps = new BABYLON.EngineCapabilities();
  95406. _this._caps.maxTexturesImageUnits = 16;
  95407. _this._caps.maxVertexTextureImageUnits = 16;
  95408. _this._caps.maxTextureSize = 512;
  95409. _this._caps.maxCubemapTextureSize = 512;
  95410. _this._caps.maxRenderTextureSize = 512;
  95411. _this._caps.maxVertexAttribs = 16;
  95412. _this._caps.maxVaryingVectors = 16;
  95413. _this._caps.maxFragmentUniformVectors = 16;
  95414. _this._caps.maxVertexUniformVectors = 16;
  95415. // Extensions
  95416. _this._caps.standardDerivatives = false;
  95417. _this._caps.astc = null;
  95418. _this._caps.s3tc = null;
  95419. _this._caps.pvrtc = null;
  95420. _this._caps.etc1 = null;
  95421. _this._caps.etc2 = null;
  95422. _this._caps.textureAnisotropicFilterExtension = null;
  95423. _this._caps.maxAnisotropy = 0;
  95424. _this._caps.uintIndices = false;
  95425. _this._caps.fragmentDepthSupported = false;
  95426. _this._caps.highPrecisionShaderSupported = true;
  95427. _this._caps.colorBufferFloat = false;
  95428. _this._caps.textureFloat = false;
  95429. _this._caps.textureFloatLinearFiltering = false;
  95430. _this._caps.textureFloatRender = false;
  95431. _this._caps.textureHalfFloat = false;
  95432. _this._caps.textureHalfFloatLinearFiltering = false;
  95433. _this._caps.textureHalfFloatRender = false;
  95434. _this._caps.textureLOD = false;
  95435. _this._caps.drawBuffersExtension = false;
  95436. _this._caps.depthTextureExtension = false;
  95437. _this._caps.vertexArrayObject = false;
  95438. _this._caps.instancedArrays = false;
  95439. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  95440. // Wrappers
  95441. if (typeof URL === "undefined") {
  95442. URL = {
  95443. createObjectURL: function () { },
  95444. revokeObjectURL: function () { }
  95445. };
  95446. }
  95447. if (typeof Blob === "undefined") {
  95448. Blob = function () { };
  95449. }
  95450. return _this;
  95451. }
  95452. NullEngine.prototype.isDeterministicLockStep = function () {
  95453. return this._options.deterministicLockstep;
  95454. };
  95455. NullEngine.prototype.getLockstepMaxSteps = function () {
  95456. return this._options.lockstepMaxSteps;
  95457. };
  95458. NullEngine.prototype.getHardwareScalingLevel = function () {
  95459. return 1.0;
  95460. };
  95461. NullEngine.prototype.createVertexBuffer = function (vertices) {
  95462. return {
  95463. capacity: 0,
  95464. references: 1,
  95465. is32Bits: false
  95466. };
  95467. };
  95468. NullEngine.prototype.createIndexBuffer = function (indices) {
  95469. return {
  95470. capacity: 0,
  95471. references: 1,
  95472. is32Bits: false
  95473. };
  95474. };
  95475. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  95476. if (stencil === void 0) { stencil = false; }
  95477. };
  95478. NullEngine.prototype.getRenderWidth = function (useScreen) {
  95479. if (useScreen === void 0) { useScreen = false; }
  95480. if (!useScreen && this._currentRenderTarget) {
  95481. return this._currentRenderTarget.width;
  95482. }
  95483. return this._options.renderWidth;
  95484. };
  95485. NullEngine.prototype.getRenderHeight = function (useScreen) {
  95486. if (useScreen === void 0) { useScreen = false; }
  95487. if (!useScreen && this._currentRenderTarget) {
  95488. return this._currentRenderTarget.height;
  95489. }
  95490. return this._options.renderHeight;
  95491. };
  95492. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  95493. this._cachedViewport = viewport;
  95494. };
  95495. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  95496. return {
  95497. transformFeedback: null,
  95498. __SPECTOR_rebuildProgram: null
  95499. };
  95500. };
  95501. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  95502. return [];
  95503. };
  95504. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  95505. return [];
  95506. };
  95507. NullEngine.prototype.bindSamplers = function (effect) {
  95508. this._currentEffect = null;
  95509. };
  95510. NullEngine.prototype.enableEffect = function (effect) {
  95511. this._currentEffect = effect;
  95512. if (effect.onBind) {
  95513. effect.onBind(effect);
  95514. }
  95515. effect.onBindObservable.notifyObservers(effect);
  95516. };
  95517. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  95518. if (zOffset === void 0) { zOffset = 0; }
  95519. if (reverseSide === void 0) { reverseSide = false; }
  95520. };
  95521. NullEngine.prototype.setIntArray = function (uniform, array) {
  95522. };
  95523. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  95524. };
  95525. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  95526. };
  95527. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  95528. };
  95529. NullEngine.prototype.setFloatArray = function (uniform, array) {
  95530. };
  95531. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  95532. };
  95533. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  95534. };
  95535. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  95536. };
  95537. NullEngine.prototype.setArray = function (uniform, array) {
  95538. };
  95539. NullEngine.prototype.setArray2 = function (uniform, array) {
  95540. };
  95541. NullEngine.prototype.setArray3 = function (uniform, array) {
  95542. };
  95543. NullEngine.prototype.setArray4 = function (uniform, array) {
  95544. };
  95545. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  95546. };
  95547. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  95548. };
  95549. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  95550. };
  95551. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  95552. };
  95553. NullEngine.prototype.setFloat = function (uniform, value) {
  95554. };
  95555. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  95556. };
  95557. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  95558. };
  95559. NullEngine.prototype.setBool = function (uniform, bool) {
  95560. };
  95561. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  95562. };
  95563. NullEngine.prototype.setColor3 = function (uniform, color3) {
  95564. };
  95565. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  95566. };
  95567. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  95568. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  95569. if (this._alphaMode === mode) {
  95570. return;
  95571. }
  95572. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  95573. if (!noDepthWriteChange) {
  95574. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  95575. }
  95576. this._alphaMode = mode;
  95577. };
  95578. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  95579. };
  95580. NullEngine.prototype.wipeCaches = function (bruteForce) {
  95581. if (this.preventCacheWipeBetweenFrames) {
  95582. return;
  95583. }
  95584. this.resetTextureCache();
  95585. this._currentEffect = null;
  95586. if (bruteForce) {
  95587. this._currentProgram = null;
  95588. this._stencilState.reset();
  95589. this._depthCullingState.reset();
  95590. this._alphaState.reset();
  95591. }
  95592. this._cachedVertexBuffers = null;
  95593. this._cachedIndexBuffer = null;
  95594. this._cachedEffectForVertexBuffers = null;
  95595. };
  95596. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  95597. };
  95598. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  95599. };
  95600. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  95601. };
  95602. NullEngine.prototype._createTexture = function () {
  95603. return {};
  95604. };
  95605. NullEngine.prototype._releaseTexture = function (texture) {
  95606. };
  95607. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  95608. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95609. if (onLoad === void 0) { onLoad = null; }
  95610. if (onError === void 0) { onError = null; }
  95611. if (buffer === void 0) { buffer = null; }
  95612. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  95613. var url = String(urlArg);
  95614. texture.url = url;
  95615. texture.generateMipMaps = !noMipmap;
  95616. texture.samplingMode = samplingMode;
  95617. texture.invertY = invertY;
  95618. texture.baseWidth = this._options.textureSize;
  95619. texture.baseHeight = this._options.textureSize;
  95620. texture.width = this._options.textureSize;
  95621. texture.height = this._options.textureSize;
  95622. if (format) {
  95623. texture.format = format;
  95624. }
  95625. texture.isReady = true;
  95626. if (onLoad) {
  95627. onLoad();
  95628. }
  95629. this._internalTexturesCache.push(texture);
  95630. return texture;
  95631. };
  95632. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  95633. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  95634. if (options !== undefined && typeof options === "object") {
  95635. fullOptions.generateMipMaps = options.generateMipMaps;
  95636. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  95637. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  95638. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  95639. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  95640. }
  95641. else {
  95642. fullOptions.generateMipMaps = options;
  95643. fullOptions.generateDepthBuffer = true;
  95644. fullOptions.generateStencilBuffer = false;
  95645. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95646. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  95647. }
  95648. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  95649. var width = size.width || size;
  95650. var height = size.height || size;
  95651. texture._depthStencilBuffer = {};
  95652. texture._framebuffer = {};
  95653. texture.baseWidth = width;
  95654. texture.baseHeight = height;
  95655. texture.width = width;
  95656. texture.height = height;
  95657. texture.isReady = true;
  95658. texture.samples = 1;
  95659. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  95660. texture.samplingMode = fullOptions.samplingMode;
  95661. texture.type = fullOptions.type;
  95662. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  95663. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  95664. this._internalTexturesCache.push(texture);
  95665. return texture;
  95666. };
  95667. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  95668. texture.samplingMode = samplingMode;
  95669. };
  95670. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  95671. if (this._currentRenderTarget) {
  95672. this.unBindFramebuffer(this._currentRenderTarget);
  95673. }
  95674. this._currentRenderTarget = texture;
  95675. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  95676. if (this._cachedViewport && !forceFullscreenViewport) {
  95677. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  95678. }
  95679. };
  95680. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  95681. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  95682. this._currentRenderTarget = null;
  95683. if (onBeforeUnbind) {
  95684. if (texture._MSAAFramebuffer) {
  95685. this._currentFramebuffer = texture._framebuffer;
  95686. }
  95687. onBeforeUnbind();
  95688. }
  95689. this._currentFramebuffer = null;
  95690. };
  95691. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  95692. var vbo = {
  95693. capacity: 1,
  95694. references: 1,
  95695. is32Bits: false
  95696. };
  95697. return vbo;
  95698. };
  95699. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  95700. if (offset === void 0) { offset = 0; }
  95701. };
  95702. /**
  95703. * Updates a dynamic vertex buffer.
  95704. * @param vertexBuffer the vertex buffer to update
  95705. * @param data the data used to update the vertex buffer
  95706. * @param byteOffset the byte offset of the data (optional)
  95707. * @param byteLength the byte length of the data (optional)
  95708. */
  95709. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  95710. };
  95711. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  95712. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  95713. this._boundTexturesCache[this._activeChannel] = texture;
  95714. }
  95715. };
  95716. NullEngine.prototype._bindTexture = function (channel, texture) {
  95717. if (channel < 0) {
  95718. return;
  95719. }
  95720. this._bindTextureDirectly(0, texture);
  95721. };
  95722. NullEngine.prototype._releaseBuffer = function (buffer) {
  95723. buffer.references--;
  95724. if (buffer.references === 0) {
  95725. return true;
  95726. }
  95727. return false;
  95728. };
  95729. NullEngine.prototype.releaseEffects = function () {
  95730. };
  95731. return NullEngine;
  95732. }(BABYLON.Engine));
  95733. BABYLON.NullEngine = NullEngine;
  95734. })(BABYLON || (BABYLON = {}));
  95735. //# sourceMappingURL=babylon.nullEngine.js.map
  95736. var BABYLON;
  95737. (function (BABYLON) {
  95738. /**
  95739. * This class can be used to get instrumentation data from a Babylon engine
  95740. */
  95741. var EngineInstrumentation = /** @class */ (function () {
  95742. function EngineInstrumentation(engine) {
  95743. this.engine = engine;
  95744. this._captureGPUFrameTime = false;
  95745. this._gpuFrameTime = new BABYLON.PerfCounter();
  95746. this._captureShaderCompilationTime = false;
  95747. this._shaderCompilationTime = new BABYLON.PerfCounter();
  95748. // Observers
  95749. this._onBeginFrameObserver = null;
  95750. this._onEndFrameObserver = null;
  95751. this._onBeforeShaderCompilationObserver = null;
  95752. this._onAfterShaderCompilationObserver = null;
  95753. }
  95754. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  95755. // Properties
  95756. /**
  95757. * Gets the perf counter used for GPU frame time
  95758. */
  95759. get: function () {
  95760. return this._gpuFrameTime;
  95761. },
  95762. enumerable: true,
  95763. configurable: true
  95764. });
  95765. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  95766. /**
  95767. * Gets the GPU frame time capture status
  95768. */
  95769. get: function () {
  95770. return this._captureGPUFrameTime;
  95771. },
  95772. /**
  95773. * Enable or disable the GPU frame time capture
  95774. */
  95775. set: function (value) {
  95776. var _this = this;
  95777. if (value === this._captureGPUFrameTime) {
  95778. return;
  95779. }
  95780. this._captureGPUFrameTime = value;
  95781. if (value) {
  95782. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  95783. if (!_this._gpuFrameTimeToken) {
  95784. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  95785. }
  95786. });
  95787. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  95788. if (!_this._gpuFrameTimeToken) {
  95789. return;
  95790. }
  95791. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  95792. if (time > -1) {
  95793. _this._gpuFrameTimeToken = null;
  95794. _this._gpuFrameTime.fetchNewFrame();
  95795. _this._gpuFrameTime.addCount(time, true);
  95796. }
  95797. });
  95798. }
  95799. else {
  95800. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95801. this._onBeginFrameObserver = null;
  95802. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95803. this._onEndFrameObserver = null;
  95804. }
  95805. },
  95806. enumerable: true,
  95807. configurable: true
  95808. });
  95809. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  95810. /**
  95811. * Gets the perf counter used for shader compilation time
  95812. */
  95813. get: function () {
  95814. return this._shaderCompilationTime;
  95815. },
  95816. enumerable: true,
  95817. configurable: true
  95818. });
  95819. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  95820. /**
  95821. * Gets the shader compilation time capture status
  95822. */
  95823. get: function () {
  95824. return this._captureShaderCompilationTime;
  95825. },
  95826. /**
  95827. * Enable or disable the shader compilation time capture
  95828. */
  95829. set: function (value) {
  95830. var _this = this;
  95831. if (value === this._captureShaderCompilationTime) {
  95832. return;
  95833. }
  95834. this._captureShaderCompilationTime = value;
  95835. if (value) {
  95836. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  95837. _this._shaderCompilationTime.fetchNewFrame();
  95838. _this._shaderCompilationTime.beginMonitoring();
  95839. });
  95840. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  95841. _this._shaderCompilationTime.endMonitoring();
  95842. });
  95843. }
  95844. else {
  95845. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95846. this._onBeforeShaderCompilationObserver = null;
  95847. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95848. this._onAfterShaderCompilationObserver = null;
  95849. }
  95850. },
  95851. enumerable: true,
  95852. configurable: true
  95853. });
  95854. EngineInstrumentation.prototype.dispose = function () {
  95855. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95856. this._onBeginFrameObserver = null;
  95857. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95858. this._onEndFrameObserver = null;
  95859. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95860. this._onBeforeShaderCompilationObserver = null;
  95861. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95862. this._onAfterShaderCompilationObserver = null;
  95863. this.engine = null;
  95864. };
  95865. return EngineInstrumentation;
  95866. }());
  95867. BABYLON.EngineInstrumentation = EngineInstrumentation;
  95868. })(BABYLON || (BABYLON = {}));
  95869. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  95870. var BABYLON;
  95871. (function (BABYLON) {
  95872. /**
  95873. * This class can be used to get instrumentation data from a Babylon engine
  95874. */
  95875. var SceneInstrumentation = /** @class */ (function () {
  95876. function SceneInstrumentation(scene) {
  95877. var _this = this;
  95878. this.scene = scene;
  95879. this._captureActiveMeshesEvaluationTime = false;
  95880. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  95881. this._captureRenderTargetsRenderTime = false;
  95882. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  95883. this._captureFrameTime = false;
  95884. this._frameTime = new BABYLON.PerfCounter();
  95885. this._captureRenderTime = false;
  95886. this._renderTime = new BABYLON.PerfCounter();
  95887. this._captureInterFrameTime = false;
  95888. this._interFrameTime = new BABYLON.PerfCounter();
  95889. this._captureParticlesRenderTime = false;
  95890. this._particlesRenderTime = new BABYLON.PerfCounter();
  95891. this._captureSpritesRenderTime = false;
  95892. this._spritesRenderTime = new BABYLON.PerfCounter();
  95893. this._capturePhysicsTime = false;
  95894. this._physicsTime = new BABYLON.PerfCounter();
  95895. this._captureAnimationsTime = false;
  95896. this._animationsTime = new BABYLON.PerfCounter();
  95897. // Observers
  95898. this._onBeforeActiveMeshesEvaluationObserver = null;
  95899. this._onAfterActiveMeshesEvaluationObserver = null;
  95900. this._onBeforeRenderTargetsRenderObserver = null;
  95901. this._onAfterRenderTargetsRenderObserver = null;
  95902. this._onAfterRenderObserver = null;
  95903. this._onBeforeDrawPhaseObserver = null;
  95904. this._onAfterDrawPhaseObserver = null;
  95905. this._onBeforeAnimationsObserver = null;
  95906. this._onBeforeParticlesRenderingObserver = null;
  95907. this._onAfterParticlesRenderingObserver = null;
  95908. this._onBeforeSpritesRenderingObserver = null;
  95909. this._onAfterSpritesRenderingObserver = null;
  95910. this._onBeforePhysicsObserver = null;
  95911. this._onAfterPhysicsObserver = null;
  95912. this._onAfterAnimationsObserver = null;
  95913. // Before render
  95914. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  95915. if (_this._captureActiveMeshesEvaluationTime) {
  95916. _this._activeMeshesEvaluationTime.fetchNewFrame();
  95917. }
  95918. if (_this._captureRenderTargetsRenderTime) {
  95919. _this._renderTargetsRenderTime.fetchNewFrame();
  95920. }
  95921. if (_this._captureFrameTime) {
  95922. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  95923. _this._frameTime.beginMonitoring();
  95924. }
  95925. if (_this._captureInterFrameTime) {
  95926. _this._interFrameTime.endMonitoring();
  95927. }
  95928. if (_this._captureParticlesRenderTime) {
  95929. _this._particlesRenderTime.fetchNewFrame();
  95930. }
  95931. if (_this._captureSpritesRenderTime) {
  95932. _this._spritesRenderTime.fetchNewFrame();
  95933. }
  95934. if (_this._captureAnimationsTime) {
  95935. _this._animationsTime.beginMonitoring();
  95936. }
  95937. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  95938. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  95939. });
  95940. // After render
  95941. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  95942. if (_this._captureFrameTime) {
  95943. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  95944. _this._frameTime.endMonitoring();
  95945. }
  95946. if (_this._captureRenderTime) {
  95947. _this._renderTime.endMonitoring(false);
  95948. }
  95949. if (_this._captureInterFrameTime) {
  95950. _this._interFrameTime.beginMonitoring();
  95951. }
  95952. });
  95953. }
  95954. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  95955. // Properties
  95956. /**
  95957. * Gets the perf counter used for active meshes evaluation time
  95958. */
  95959. get: function () {
  95960. return this._activeMeshesEvaluationTime;
  95961. },
  95962. enumerable: true,
  95963. configurable: true
  95964. });
  95965. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  95966. /**
  95967. * Gets the active meshes evaluation time capture status
  95968. */
  95969. get: function () {
  95970. return this._captureActiveMeshesEvaluationTime;
  95971. },
  95972. /**
  95973. * Enable or disable the active meshes evaluation time capture
  95974. */
  95975. set: function (value) {
  95976. var _this = this;
  95977. if (value === this._captureActiveMeshesEvaluationTime) {
  95978. return;
  95979. }
  95980. this._captureActiveMeshesEvaluationTime = value;
  95981. if (value) {
  95982. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  95983. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  95984. _this._activeMeshesEvaluationTime.beginMonitoring();
  95985. });
  95986. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  95987. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  95988. _this._activeMeshesEvaluationTime.endMonitoring();
  95989. });
  95990. }
  95991. else {
  95992. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95993. this._onBeforeActiveMeshesEvaluationObserver = null;
  95994. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95995. this._onAfterActiveMeshesEvaluationObserver = null;
  95996. }
  95997. },
  95998. enumerable: true,
  95999. configurable: true
  96000. });
  96001. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  96002. /**
  96003. * Gets the perf counter used for render targets render time
  96004. */
  96005. get: function () {
  96006. return this._renderTargetsRenderTime;
  96007. },
  96008. enumerable: true,
  96009. configurable: true
  96010. });
  96011. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  96012. /**
  96013. * Gets the render targets render time capture status
  96014. */
  96015. get: function () {
  96016. return this._captureRenderTargetsRenderTime;
  96017. },
  96018. /**
  96019. * Enable or disable the render targets render time capture
  96020. */
  96021. set: function (value) {
  96022. var _this = this;
  96023. if (value === this._captureRenderTargetsRenderTime) {
  96024. return;
  96025. }
  96026. this._captureRenderTargetsRenderTime = value;
  96027. if (value) {
  96028. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  96029. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  96030. _this._renderTargetsRenderTime.beginMonitoring();
  96031. });
  96032. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  96033. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  96034. _this._renderTargetsRenderTime.endMonitoring(false);
  96035. });
  96036. }
  96037. else {
  96038. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  96039. this._onBeforeRenderTargetsRenderObserver = null;
  96040. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  96041. this._onAfterRenderTargetsRenderObserver = null;
  96042. }
  96043. },
  96044. enumerable: true,
  96045. configurable: true
  96046. });
  96047. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  96048. /**
  96049. * Gets the perf counter used for particles render time
  96050. */
  96051. get: function () {
  96052. return this._particlesRenderTime;
  96053. },
  96054. enumerable: true,
  96055. configurable: true
  96056. });
  96057. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  96058. /**
  96059. * Gets the particles render time capture status
  96060. */
  96061. get: function () {
  96062. return this._captureParticlesRenderTime;
  96063. },
  96064. /**
  96065. * Enable or disable the particles render time capture
  96066. */
  96067. set: function (value) {
  96068. var _this = this;
  96069. if (value === this._captureParticlesRenderTime) {
  96070. return;
  96071. }
  96072. this._captureParticlesRenderTime = value;
  96073. if (value) {
  96074. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  96075. BABYLON.Tools.StartPerformanceCounter("Particles");
  96076. _this._particlesRenderTime.beginMonitoring();
  96077. });
  96078. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  96079. BABYLON.Tools.EndPerformanceCounter("Particles");
  96080. _this._particlesRenderTime.endMonitoring(false);
  96081. });
  96082. }
  96083. else {
  96084. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  96085. this._onBeforeParticlesRenderingObserver = null;
  96086. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  96087. this._onAfterParticlesRenderingObserver = null;
  96088. }
  96089. },
  96090. enumerable: true,
  96091. configurable: true
  96092. });
  96093. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  96094. /**
  96095. * Gets the perf counter used for sprites render time
  96096. */
  96097. get: function () {
  96098. return this._spritesRenderTime;
  96099. },
  96100. enumerable: true,
  96101. configurable: true
  96102. });
  96103. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  96104. /**
  96105. * Gets the sprites render time capture status
  96106. */
  96107. get: function () {
  96108. return this._captureSpritesRenderTime;
  96109. },
  96110. /**
  96111. * Enable or disable the sprites render time capture
  96112. */
  96113. set: function (value) {
  96114. var _this = this;
  96115. if (value === this._captureSpritesRenderTime) {
  96116. return;
  96117. }
  96118. this._captureSpritesRenderTime = value;
  96119. if (value) {
  96120. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  96121. BABYLON.Tools.StartPerformanceCounter("Sprites");
  96122. _this._spritesRenderTime.beginMonitoring();
  96123. });
  96124. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  96125. BABYLON.Tools.EndPerformanceCounter("Sprites");
  96126. _this._spritesRenderTime.endMonitoring(false);
  96127. });
  96128. }
  96129. else {
  96130. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  96131. this._onBeforeSpritesRenderingObserver = null;
  96132. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  96133. this._onAfterSpritesRenderingObserver = null;
  96134. }
  96135. },
  96136. enumerable: true,
  96137. configurable: true
  96138. });
  96139. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  96140. /**
  96141. * Gets the perf counter used for physics time
  96142. */
  96143. get: function () {
  96144. return this._physicsTime;
  96145. },
  96146. enumerable: true,
  96147. configurable: true
  96148. });
  96149. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  96150. /**
  96151. * Gets the physics time capture status
  96152. */
  96153. get: function () {
  96154. return this._capturePhysicsTime;
  96155. },
  96156. /**
  96157. * Enable or disable the physics time capture
  96158. */
  96159. set: function (value) {
  96160. var _this = this;
  96161. if (value === this._capturePhysicsTime) {
  96162. return;
  96163. }
  96164. this._capturePhysicsTime = value;
  96165. if (value) {
  96166. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  96167. BABYLON.Tools.StartPerformanceCounter("Physics");
  96168. _this._physicsTime.beginMonitoring();
  96169. });
  96170. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  96171. BABYLON.Tools.EndPerformanceCounter("Physics");
  96172. _this._physicsTime.endMonitoring();
  96173. });
  96174. }
  96175. else {
  96176. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  96177. this._onBeforePhysicsObserver = null;
  96178. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  96179. this._onAfterPhysicsObserver = null;
  96180. }
  96181. },
  96182. enumerable: true,
  96183. configurable: true
  96184. });
  96185. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  96186. /**
  96187. * Gets the perf counter used for animations time
  96188. */
  96189. get: function () {
  96190. return this._animationsTime;
  96191. },
  96192. enumerable: true,
  96193. configurable: true
  96194. });
  96195. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  96196. /**
  96197. * Gets the animations time capture status
  96198. */
  96199. get: function () {
  96200. return this._captureAnimationsTime;
  96201. },
  96202. /**
  96203. * Enable or disable the animations time capture
  96204. */
  96205. set: function (value) {
  96206. var _this = this;
  96207. if (value === this._captureAnimationsTime) {
  96208. return;
  96209. }
  96210. this._captureAnimationsTime = value;
  96211. if (value) {
  96212. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  96213. _this._animationsTime.endMonitoring();
  96214. });
  96215. }
  96216. else {
  96217. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  96218. this._onAfterAnimationsObserver = null;
  96219. }
  96220. },
  96221. enumerable: true,
  96222. configurable: true
  96223. });
  96224. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  96225. /**
  96226. * Gets the perf counter used for frame time capture
  96227. */
  96228. get: function () {
  96229. return this._frameTime;
  96230. },
  96231. enumerable: true,
  96232. configurable: true
  96233. });
  96234. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  96235. /**
  96236. * Gets the frame time capture status
  96237. */
  96238. get: function () {
  96239. return this._captureFrameTime;
  96240. },
  96241. /**
  96242. * Enable or disable the frame time capture
  96243. */
  96244. set: function (value) {
  96245. this._captureFrameTime = value;
  96246. },
  96247. enumerable: true,
  96248. configurable: true
  96249. });
  96250. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  96251. /**
  96252. * Gets the perf counter used for inter-frames time capture
  96253. */
  96254. get: function () {
  96255. return this._interFrameTime;
  96256. },
  96257. enumerable: true,
  96258. configurable: true
  96259. });
  96260. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  96261. /**
  96262. * Gets the inter-frames time capture status
  96263. */
  96264. get: function () {
  96265. return this._captureInterFrameTime;
  96266. },
  96267. /**
  96268. * Enable or disable the inter-frames time capture
  96269. */
  96270. set: function (value) {
  96271. this._captureInterFrameTime = value;
  96272. },
  96273. enumerable: true,
  96274. configurable: true
  96275. });
  96276. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  96277. /**
  96278. * Gets the perf counter used for render time capture
  96279. */
  96280. get: function () {
  96281. return this._renderTime;
  96282. },
  96283. enumerable: true,
  96284. configurable: true
  96285. });
  96286. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  96287. /**
  96288. * Gets the render time capture status
  96289. */
  96290. get: function () {
  96291. return this._captureRenderTime;
  96292. },
  96293. /**
  96294. * Enable or disable the render time capture
  96295. */
  96296. set: function (value) {
  96297. var _this = this;
  96298. if (value === this._captureRenderTime) {
  96299. return;
  96300. }
  96301. this._captureRenderTime = value;
  96302. if (value) {
  96303. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  96304. _this._renderTime.beginMonitoring();
  96305. BABYLON.Tools.StartPerformanceCounter("Main render");
  96306. });
  96307. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  96308. _this._renderTime.endMonitoring(false);
  96309. BABYLON.Tools.EndPerformanceCounter("Main render");
  96310. });
  96311. }
  96312. else {
  96313. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96314. this._onBeforeDrawPhaseObserver = null;
  96315. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96316. this._onAfterDrawPhaseObserver = null;
  96317. }
  96318. },
  96319. enumerable: true,
  96320. configurable: true
  96321. });
  96322. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  96323. /**
  96324. * Gets the perf counter used for draw calls
  96325. */
  96326. get: function () {
  96327. return this.scene.getEngine()._drawCalls;
  96328. },
  96329. enumerable: true,
  96330. configurable: true
  96331. });
  96332. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  96333. /**
  96334. * Gets the perf counter used for texture collisions
  96335. */
  96336. get: function () {
  96337. return this.scene.getEngine()._textureCollisions;
  96338. },
  96339. enumerable: true,
  96340. configurable: true
  96341. });
  96342. SceneInstrumentation.prototype.dispose = function () {
  96343. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96344. this._onAfterRenderObserver = null;
  96345. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  96346. this._onBeforeActiveMeshesEvaluationObserver = null;
  96347. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  96348. this._onAfterActiveMeshesEvaluationObserver = null;
  96349. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  96350. this._onBeforeRenderTargetsRenderObserver = null;
  96351. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  96352. this._onAfterRenderTargetsRenderObserver = null;
  96353. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  96354. this._onBeforeAnimationsObserver = null;
  96355. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  96356. this._onBeforeParticlesRenderingObserver = null;
  96357. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  96358. this._onAfterParticlesRenderingObserver = null;
  96359. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  96360. this._onBeforeSpritesRenderingObserver = null;
  96361. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  96362. this._onAfterSpritesRenderingObserver = null;
  96363. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96364. this._onBeforeDrawPhaseObserver = null;
  96365. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96366. this._onAfterDrawPhaseObserver = null;
  96367. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  96368. this._onBeforePhysicsObserver = null;
  96369. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  96370. this._onAfterPhysicsObserver = null;
  96371. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  96372. this._onAfterAnimationsObserver = null;
  96373. this.scene = null;
  96374. };
  96375. return SceneInstrumentation;
  96376. }());
  96377. BABYLON.SceneInstrumentation = SceneInstrumentation;
  96378. })(BABYLON || (BABYLON = {}));
  96379. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  96380. var BABYLON;
  96381. (function (BABYLON) {
  96382. /**
  96383. * @hidden
  96384. **/
  96385. var _TimeToken = /** @class */ (function () {
  96386. function _TimeToken() {
  96387. this._timeElapsedQueryEnded = false;
  96388. }
  96389. return _TimeToken;
  96390. }());
  96391. BABYLON._TimeToken = _TimeToken;
  96392. })(BABYLON || (BABYLON = {}));
  96393. //# sourceMappingURL=babylon.timeToken.js.map
  96394. var BABYLON;
  96395. (function (BABYLON) {
  96396. /**
  96397. * Background material defines definition.
  96398. * @hidden Mainly internal Use
  96399. */
  96400. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  96401. __extends(BackgroundMaterialDefines, _super);
  96402. /**
  96403. * Constructor of the defines.
  96404. */
  96405. function BackgroundMaterialDefines() {
  96406. var _this = _super.call(this) || this;
  96407. /**
  96408. * True if the diffuse texture is in use.
  96409. */
  96410. _this.DIFFUSE = false;
  96411. /**
  96412. * The direct UV channel to use.
  96413. */
  96414. _this.DIFFUSEDIRECTUV = 0;
  96415. /**
  96416. * True if the diffuse texture is in gamma space.
  96417. */
  96418. _this.GAMMADIFFUSE = false;
  96419. /**
  96420. * True if the diffuse texture has opacity in the alpha channel.
  96421. */
  96422. _this.DIFFUSEHASALPHA = false;
  96423. /**
  96424. * True if you want the material to fade to transparent at grazing angle.
  96425. */
  96426. _this.OPACITYFRESNEL = false;
  96427. /**
  96428. * True if an extra blur needs to be added in the reflection.
  96429. */
  96430. _this.REFLECTIONBLUR = false;
  96431. /**
  96432. * True if you want the material to fade to reflection at grazing angle.
  96433. */
  96434. _this.REFLECTIONFRESNEL = false;
  96435. /**
  96436. * True if you want the material to falloff as far as you move away from the scene center.
  96437. */
  96438. _this.REFLECTIONFALLOFF = false;
  96439. /**
  96440. * False if the current Webgl implementation does not support the texture lod extension.
  96441. */
  96442. _this.TEXTURELODSUPPORT = false;
  96443. /**
  96444. * True to ensure the data are premultiplied.
  96445. */
  96446. _this.PREMULTIPLYALPHA = false;
  96447. /**
  96448. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  96449. */
  96450. _this.USERGBCOLOR = false;
  96451. /**
  96452. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  96453. * stays aligned with the desired configuration.
  96454. */
  96455. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  96456. /**
  96457. * True to add noise in order to reduce the banding effect.
  96458. */
  96459. _this.NOISE = false;
  96460. /**
  96461. * is the reflection texture in BGR color scheme?
  96462. * Mainly used to solve a bug in ios10 video tag
  96463. */
  96464. _this.REFLECTIONBGR = false;
  96465. _this.IMAGEPROCESSING = false;
  96466. _this.VIGNETTE = false;
  96467. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  96468. _this.VIGNETTEBLENDMODEOPAQUE = false;
  96469. _this.TONEMAPPING = false;
  96470. _this.CONTRAST = false;
  96471. _this.COLORCURVES = false;
  96472. _this.COLORGRADING = false;
  96473. _this.COLORGRADING3D = false;
  96474. _this.SAMPLER3DGREENDEPTH = false;
  96475. _this.SAMPLER3DBGRMAP = false;
  96476. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  96477. _this.EXPOSURE = false;
  96478. // Reflection.
  96479. _this.REFLECTION = false;
  96480. _this.REFLECTIONMAP_3D = false;
  96481. _this.REFLECTIONMAP_SPHERICAL = false;
  96482. _this.REFLECTIONMAP_PLANAR = false;
  96483. _this.REFLECTIONMAP_CUBIC = false;
  96484. _this.REFLECTIONMAP_PROJECTION = false;
  96485. _this.REFLECTIONMAP_SKYBOX = false;
  96486. _this.REFLECTIONMAP_EXPLICIT = false;
  96487. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96488. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96489. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96490. _this.INVERTCUBICMAP = false;
  96491. _this.REFLECTIONMAP_OPPOSITEZ = false;
  96492. _this.LODINREFLECTIONALPHA = false;
  96493. _this.GAMMAREFLECTION = false;
  96494. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  96495. // Default BJS.
  96496. _this.MAINUV1 = false;
  96497. _this.MAINUV2 = false;
  96498. _this.UV1 = false;
  96499. _this.UV2 = false;
  96500. _this.CLIPPLANE = false;
  96501. _this.POINTSIZE = false;
  96502. _this.FOG = false;
  96503. _this.NORMAL = false;
  96504. _this.NUM_BONE_INFLUENCERS = 0;
  96505. _this.BonesPerMesh = 0;
  96506. _this.INSTANCES = false;
  96507. _this.SHADOWFLOAT = false;
  96508. _this.rebuild();
  96509. return _this;
  96510. }
  96511. return BackgroundMaterialDefines;
  96512. }(BABYLON.MaterialDefines));
  96513. /**
  96514. * Background material used to create an efficient environement around your scene.
  96515. */
  96516. var BackgroundMaterial = /** @class */ (function (_super) {
  96517. __extends(BackgroundMaterial, _super);
  96518. /**
  96519. * Instantiates a Background Material in the given scene
  96520. * @param name The friendly name of the material
  96521. * @param scene The scene to add the material to
  96522. */
  96523. function BackgroundMaterial(name, scene) {
  96524. var _this = _super.call(this, name, scene) || this;
  96525. /**
  96526. * Key light Color (multiply against the environement texture)
  96527. */
  96528. _this.primaryColor = BABYLON.Color3.White();
  96529. _this._primaryColorShadowLevel = 0;
  96530. _this._primaryColorHighlightLevel = 0;
  96531. /**
  96532. * Reflection Texture used in the material.
  96533. * Should be author in a specific way for the best result (refer to the documentation).
  96534. */
  96535. _this.reflectionTexture = null;
  96536. /**
  96537. * Reflection Texture level of blur.
  96538. *
  96539. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  96540. * texture twice.
  96541. */
  96542. _this.reflectionBlur = 0;
  96543. /**
  96544. * Diffuse Texture used in the material.
  96545. * Should be author in a specific way for the best result (refer to the documentation).
  96546. */
  96547. _this.diffuseTexture = null;
  96548. _this._shadowLights = null;
  96549. /**
  96550. * Specify the list of lights casting shadow on the material.
  96551. * All scene shadow lights will be included if null.
  96552. */
  96553. _this.shadowLights = null;
  96554. /**
  96555. * Helps adjusting the shadow to a softer level if required.
  96556. * 0 means black shadows and 1 means no shadows.
  96557. */
  96558. _this.shadowLevel = 0;
  96559. /**
  96560. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  96561. * It is usually zero but might be interesting to modify according to your setup.
  96562. */
  96563. _this.sceneCenter = BABYLON.Vector3.Zero();
  96564. /**
  96565. * This helps specifying that the material is falling off to the sky box at grazing angle.
  96566. * This helps ensuring a nice transition when the camera goes under the ground.
  96567. */
  96568. _this.opacityFresnel = true;
  96569. /**
  96570. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  96571. * This helps adding a mirror texture on the ground.
  96572. */
  96573. _this.reflectionFresnel = false;
  96574. /**
  96575. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  96576. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  96577. */
  96578. _this.reflectionFalloffDistance = 0.0;
  96579. /**
  96580. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  96581. */
  96582. _this.reflectionAmount = 1.0;
  96583. /**
  96584. * This specifies the weight of the reflection at grazing angle.
  96585. */
  96586. _this.reflectionReflectance0 = 0.05;
  96587. /**
  96588. * This specifies the weight of the reflection at a perpendicular point of view.
  96589. */
  96590. _this.reflectionReflectance90 = 0.5;
  96591. /**
  96592. * Helps to directly use the maps channels instead of their level.
  96593. */
  96594. _this.useRGBColor = true;
  96595. /**
  96596. * This helps reducing the banding effect that could occur on the background.
  96597. */
  96598. _this.enableNoise = false;
  96599. _this._fovMultiplier = 1.0;
  96600. /**
  96601. * Enable the FOV adjustment feature controlled by fovMultiplier.
  96602. */
  96603. _this.useEquirectangularFOV = false;
  96604. _this._maxSimultaneousLights = 4;
  96605. /**
  96606. * Number of Simultaneous lights allowed on the material.
  96607. */
  96608. _this.maxSimultaneousLights = 4;
  96609. /**
  96610. * Keep track of the image processing observer to allow dispose and replace.
  96611. */
  96612. _this._imageProcessingObserver = null;
  96613. /**
  96614. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  96615. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  96616. */
  96617. _this.switchToBGR = false;
  96618. // Temp values kept as cache in the material.
  96619. _this._renderTargets = new BABYLON.SmartArray(16);
  96620. _this._reflectionControls = BABYLON.Vector4.Zero();
  96621. _this._white = BABYLON.Color3.White();
  96622. _this._primaryShadowColor = BABYLON.Color3.Black();
  96623. _this._primaryHighlightColor = BABYLON.Color3.Black();
  96624. // Setup the default processing configuration to the scene.
  96625. _this._attachImageProcessingConfiguration(null);
  96626. _this.getRenderTargetTextures = function () {
  96627. _this._renderTargets.reset();
  96628. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  96629. _this._renderTargets.push(_this._diffuseTexture);
  96630. }
  96631. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  96632. _this._renderTargets.push(_this._reflectionTexture);
  96633. }
  96634. return _this._renderTargets;
  96635. };
  96636. return _this;
  96637. }
  96638. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  96639. /**
  96640. * Experimental Internal Use Only.
  96641. *
  96642. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  96643. * This acts as a helper to set the primary color to a more "human friendly" value.
  96644. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  96645. * output color as close as possible from the chosen value.
  96646. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  96647. * part of lighting setup.)
  96648. */
  96649. get: function () {
  96650. return this.__perceptualColor;
  96651. },
  96652. set: function (value) {
  96653. this.__perceptualColor = value;
  96654. this._computePrimaryColorFromPerceptualColor();
  96655. this._markAllSubMeshesAsLightsDirty();
  96656. },
  96657. enumerable: true,
  96658. configurable: true
  96659. });
  96660. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  96661. /**
  96662. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  96663. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  96664. */
  96665. get: function () {
  96666. return this._primaryColorShadowLevel;
  96667. },
  96668. set: function (value) {
  96669. this._primaryColorShadowLevel = value;
  96670. this._computePrimaryColors();
  96671. this._markAllSubMeshesAsLightsDirty();
  96672. },
  96673. enumerable: true,
  96674. configurable: true
  96675. });
  96676. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  96677. /**
  96678. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  96679. * The primary color is used at the level chosen to define what the white area would look.
  96680. */
  96681. get: function () {
  96682. return this._primaryColorHighlightLevel;
  96683. },
  96684. set: function (value) {
  96685. this._primaryColorHighlightLevel = value;
  96686. this._computePrimaryColors();
  96687. this._markAllSubMeshesAsLightsDirty();
  96688. },
  96689. enumerable: true,
  96690. configurable: true
  96691. });
  96692. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  96693. /**
  96694. * Sets the reflection reflectance fresnel values according to the default standard
  96695. * empirically know to work well :-)
  96696. */
  96697. set: function (value) {
  96698. var reflectionWeight = value;
  96699. if (reflectionWeight < 0.5) {
  96700. reflectionWeight = reflectionWeight * 2.0;
  96701. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  96702. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  96703. }
  96704. else {
  96705. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  96706. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  96707. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  96708. }
  96709. },
  96710. enumerable: true,
  96711. configurable: true
  96712. });
  96713. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  96714. /**
  96715. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96716. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  96717. * Recommended to be keep at 1.0 except for special cases.
  96718. */
  96719. get: function () {
  96720. return this._fovMultiplier;
  96721. },
  96722. set: function (value) {
  96723. if (isNaN(value)) {
  96724. value = 1.0;
  96725. }
  96726. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  96727. },
  96728. enumerable: true,
  96729. configurable: true
  96730. });
  96731. /**
  96732. * Attaches a new image processing configuration to the PBR Material.
  96733. * @param configuration (if null the scene configuration will be use)
  96734. */
  96735. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  96736. var _this = this;
  96737. if (configuration === this._imageProcessingConfiguration) {
  96738. return;
  96739. }
  96740. // Detaches observer.
  96741. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96742. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96743. }
  96744. // Pick the scene configuration if needed.
  96745. if (!configuration) {
  96746. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  96747. }
  96748. else {
  96749. this._imageProcessingConfiguration = configuration;
  96750. }
  96751. // Attaches observer.
  96752. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  96753. _this._computePrimaryColorFromPerceptualColor();
  96754. _this._markAllSubMeshesAsImageProcessingDirty();
  96755. });
  96756. };
  96757. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  96758. /**
  96759. * Gets the image processing configuration used either in this material.
  96760. */
  96761. get: function () {
  96762. return this._imageProcessingConfiguration;
  96763. },
  96764. /**
  96765. * Sets the Default image processing configuration used either in the this material.
  96766. *
  96767. * If sets to null, the scene one is in use.
  96768. */
  96769. set: function (value) {
  96770. this._attachImageProcessingConfiguration(value);
  96771. // Ensure the effect will be rebuilt.
  96772. this._markAllSubMeshesAsTexturesDirty();
  96773. },
  96774. enumerable: true,
  96775. configurable: true
  96776. });
  96777. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  96778. /**
  96779. * Gets wether the color curves effect is enabled.
  96780. */
  96781. get: function () {
  96782. return this.imageProcessingConfiguration.colorCurvesEnabled;
  96783. },
  96784. /**
  96785. * Sets wether the color curves effect is enabled.
  96786. */
  96787. set: function (value) {
  96788. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  96789. },
  96790. enumerable: true,
  96791. configurable: true
  96792. });
  96793. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  96794. /**
  96795. * Gets wether the color grading effect is enabled.
  96796. */
  96797. get: function () {
  96798. return this.imageProcessingConfiguration.colorGradingEnabled;
  96799. },
  96800. /**
  96801. * Gets wether the color grading effect is enabled.
  96802. */
  96803. set: function (value) {
  96804. this.imageProcessingConfiguration.colorGradingEnabled = value;
  96805. },
  96806. enumerable: true,
  96807. configurable: true
  96808. });
  96809. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  96810. /**
  96811. * Gets wether tonemapping is enabled or not.
  96812. */
  96813. get: function () {
  96814. return this._imageProcessingConfiguration.toneMappingEnabled;
  96815. },
  96816. /**
  96817. * Sets wether tonemapping is enabled or not
  96818. */
  96819. set: function (value) {
  96820. this._imageProcessingConfiguration.toneMappingEnabled = value;
  96821. },
  96822. enumerable: true,
  96823. configurable: true
  96824. });
  96825. ;
  96826. ;
  96827. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  96828. /**
  96829. * The camera exposure used on this material.
  96830. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96831. * This corresponds to a photographic exposure.
  96832. */
  96833. get: function () {
  96834. return this._imageProcessingConfiguration.exposure;
  96835. },
  96836. /**
  96837. * The camera exposure used on this material.
  96838. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96839. * This corresponds to a photographic exposure.
  96840. */
  96841. set: function (value) {
  96842. this._imageProcessingConfiguration.exposure = value;
  96843. },
  96844. enumerable: true,
  96845. configurable: true
  96846. });
  96847. ;
  96848. ;
  96849. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  96850. /**
  96851. * Gets The camera contrast used on this material.
  96852. */
  96853. get: function () {
  96854. return this._imageProcessingConfiguration.contrast;
  96855. },
  96856. /**
  96857. * Sets The camera contrast used on this material.
  96858. */
  96859. set: function (value) {
  96860. this._imageProcessingConfiguration.contrast = value;
  96861. },
  96862. enumerable: true,
  96863. configurable: true
  96864. });
  96865. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  96866. /**
  96867. * Gets the Color Grading 2D Lookup Texture.
  96868. */
  96869. get: function () {
  96870. return this._imageProcessingConfiguration.colorGradingTexture;
  96871. },
  96872. /**
  96873. * Sets the Color Grading 2D Lookup Texture.
  96874. */
  96875. set: function (value) {
  96876. this.imageProcessingConfiguration.colorGradingTexture = value;
  96877. },
  96878. enumerable: true,
  96879. configurable: true
  96880. });
  96881. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  96882. /**
  96883. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96884. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96885. * 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;
  96886. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96887. */
  96888. get: function () {
  96889. return this.imageProcessingConfiguration.colorCurves;
  96890. },
  96891. /**
  96892. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96893. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96894. * 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;
  96895. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96896. */
  96897. set: function (value) {
  96898. this.imageProcessingConfiguration.colorCurves = value;
  96899. },
  96900. enumerable: true,
  96901. configurable: true
  96902. });
  96903. /**
  96904. * The entire material has been created in order to prevent overdraw.
  96905. * @returns false
  96906. */
  96907. BackgroundMaterial.prototype.needAlphaTesting = function () {
  96908. return true;
  96909. };
  96910. /**
  96911. * The entire material has been created in order to prevent overdraw.
  96912. * @returns true if blending is enable
  96913. */
  96914. BackgroundMaterial.prototype.needAlphaBlending = function () {
  96915. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  96916. };
  96917. /**
  96918. * Checks wether the material is ready to be rendered for a given mesh.
  96919. * @param mesh The mesh to render
  96920. * @param subMesh The submesh to check against
  96921. * @param useInstances Specify wether or not the material is used with instances
  96922. * @returns true if all the dependencies are ready (Textures, Effects...)
  96923. */
  96924. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  96925. var _this = this;
  96926. if (useInstances === void 0) { useInstances = false; }
  96927. if (subMesh.effect && this.isFrozen) {
  96928. if (this._wasPreviouslyReady) {
  96929. return true;
  96930. }
  96931. }
  96932. if (!subMesh._materialDefines) {
  96933. subMesh._materialDefines = new BackgroundMaterialDefines();
  96934. }
  96935. var scene = this.getScene();
  96936. var defines = subMesh._materialDefines;
  96937. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  96938. if (defines._renderId === scene.getRenderId()) {
  96939. return true;
  96940. }
  96941. }
  96942. var engine = scene.getEngine();
  96943. // Lights
  96944. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  96945. defines._needNormals = true;
  96946. // Textures
  96947. if (defines._areTexturesDirty) {
  96948. defines._needUVs = false;
  96949. if (scene.texturesEnabled) {
  96950. if (scene.getEngine().getCaps().textureLOD) {
  96951. defines.TEXTURELODSUPPORT = true;
  96952. }
  96953. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96954. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  96955. return false;
  96956. }
  96957. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  96958. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  96959. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  96960. defines.OPACITYFRESNEL = this._opacityFresnel;
  96961. }
  96962. else {
  96963. defines.DIFFUSE = false;
  96964. defines.DIFFUSEHASALPHA = false;
  96965. defines.GAMMADIFFUSE = false;
  96966. defines.OPACITYFRESNEL = false;
  96967. }
  96968. var reflectionTexture = this._reflectionTexture;
  96969. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96970. if (!reflectionTexture.isReadyOrNotBlocking()) {
  96971. return false;
  96972. }
  96973. defines.REFLECTION = true;
  96974. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  96975. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  96976. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  96977. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  96978. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  96979. defines.REFLECTIONBGR = this.switchToBGR;
  96980. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  96981. defines.INVERTCUBICMAP = true;
  96982. }
  96983. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  96984. switch (reflectionTexture.coordinatesMode) {
  96985. case BABYLON.Texture.EXPLICIT_MODE:
  96986. defines.REFLECTIONMAP_EXPLICIT = true;
  96987. break;
  96988. case BABYLON.Texture.PLANAR_MODE:
  96989. defines.REFLECTIONMAP_PLANAR = true;
  96990. break;
  96991. case BABYLON.Texture.PROJECTION_MODE:
  96992. defines.REFLECTIONMAP_PROJECTION = true;
  96993. break;
  96994. case BABYLON.Texture.SKYBOX_MODE:
  96995. defines.REFLECTIONMAP_SKYBOX = true;
  96996. break;
  96997. case BABYLON.Texture.SPHERICAL_MODE:
  96998. defines.REFLECTIONMAP_SPHERICAL = true;
  96999. break;
  97000. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  97001. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  97002. break;
  97003. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  97004. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  97005. break;
  97006. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  97007. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  97008. break;
  97009. case BABYLON.Texture.CUBIC_MODE:
  97010. case BABYLON.Texture.INVCUBIC_MODE:
  97011. default:
  97012. defines.REFLECTIONMAP_CUBIC = true;
  97013. break;
  97014. }
  97015. if (this.reflectionFresnel) {
  97016. defines.REFLECTIONFRESNEL = true;
  97017. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  97018. this._reflectionControls.x = this.reflectionAmount;
  97019. this._reflectionControls.y = this.reflectionReflectance0;
  97020. this._reflectionControls.z = this.reflectionReflectance90;
  97021. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  97022. }
  97023. else {
  97024. defines.REFLECTIONFRESNEL = false;
  97025. defines.REFLECTIONFALLOFF = false;
  97026. }
  97027. }
  97028. else {
  97029. defines.REFLECTION = false;
  97030. defines.REFLECTIONFRESNEL = false;
  97031. defines.REFLECTIONFALLOFF = false;
  97032. defines.REFLECTIONBLUR = false;
  97033. defines.REFLECTIONMAP_3D = false;
  97034. defines.REFLECTIONMAP_SPHERICAL = false;
  97035. defines.REFLECTIONMAP_PLANAR = false;
  97036. defines.REFLECTIONMAP_CUBIC = false;
  97037. defines.REFLECTIONMAP_PROJECTION = false;
  97038. defines.REFLECTIONMAP_SKYBOX = false;
  97039. defines.REFLECTIONMAP_EXPLICIT = false;
  97040. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  97041. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  97042. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  97043. defines.INVERTCUBICMAP = false;
  97044. defines.REFLECTIONMAP_OPPOSITEZ = false;
  97045. defines.LODINREFLECTIONALPHA = false;
  97046. defines.GAMMAREFLECTION = false;
  97047. }
  97048. }
  97049. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  97050. defines.USERGBCOLOR = this._useRGBColor;
  97051. defines.NOISE = this._enableNoise;
  97052. }
  97053. if (defines._areLightsDirty) {
  97054. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  97055. }
  97056. if (defines._areImageProcessingDirty) {
  97057. if (!this._imageProcessingConfiguration.isReady()) {
  97058. return false;
  97059. }
  97060. this._imageProcessingConfiguration.prepareDefines(defines);
  97061. }
  97062. // Misc.
  97063. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  97064. // Values that need to be evaluated on every frame
  97065. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  97066. // Attribs
  97067. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  97068. if (mesh) {
  97069. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  97070. mesh.createNormals(true);
  97071. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  97072. }
  97073. }
  97074. }
  97075. // Get correct effect
  97076. if (defines.isDirty) {
  97077. defines.markAsProcessed();
  97078. scene.resetCachedMaterial();
  97079. // Fallbacks
  97080. var fallbacks = new BABYLON.EffectFallbacks();
  97081. if (defines.FOG) {
  97082. fallbacks.addFallback(0, "FOG");
  97083. }
  97084. if (defines.POINTSIZE) {
  97085. fallbacks.addFallback(1, "POINTSIZE");
  97086. }
  97087. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  97088. if (defines.NUM_BONE_INFLUENCERS > 0) {
  97089. fallbacks.addCPUSkinningFallback(0, mesh);
  97090. }
  97091. //Attributes
  97092. var attribs = [BABYLON.VertexBuffer.PositionKind];
  97093. if (defines.NORMAL) {
  97094. attribs.push(BABYLON.VertexBuffer.NormalKind);
  97095. }
  97096. if (defines.UV1) {
  97097. attribs.push(BABYLON.VertexBuffer.UVKind);
  97098. }
  97099. if (defines.UV2) {
  97100. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  97101. }
  97102. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  97103. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  97104. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  97105. "vFogInfos", "vFogColor", "pointSize",
  97106. "vClipPlane", "mBones",
  97107. "vPrimaryColor", "vPrimaryColorShadow",
  97108. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  97109. "shadowLevel", "alpha",
  97110. "vBackgroundCenter", "vReflectionControl",
  97111. "vDiffuseInfos", "diffuseMatrix",
  97112. ];
  97113. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  97114. var uniformBuffers = ["Material", "Scene"];
  97115. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  97116. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  97117. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  97118. uniformsNames: uniforms,
  97119. uniformBuffersNames: uniformBuffers,
  97120. samplers: samplers,
  97121. defines: defines,
  97122. maxSimultaneousLights: this._maxSimultaneousLights
  97123. });
  97124. var onCompiled = function (effect) {
  97125. if (_this.onCompiled) {
  97126. _this.onCompiled(effect);
  97127. }
  97128. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  97129. };
  97130. var join = defines.toString();
  97131. subMesh.setEffect(scene.getEngine().createEffect("background", {
  97132. attributes: attribs,
  97133. uniformsNames: uniforms,
  97134. uniformBuffersNames: uniformBuffers,
  97135. samplers: samplers,
  97136. defines: join,
  97137. fallbacks: fallbacks,
  97138. onCompiled: onCompiled,
  97139. onError: this.onError,
  97140. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  97141. }, engine), defines);
  97142. this.buildUniformLayout();
  97143. }
  97144. if (!subMesh.effect || !subMesh.effect.isReady()) {
  97145. return false;
  97146. }
  97147. defines._renderId = scene.getRenderId();
  97148. this._wasPreviouslyReady = true;
  97149. return true;
  97150. };
  97151. /**
  97152. * Compute the primary color according to the chosen perceptual color.
  97153. */
  97154. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  97155. if (!this.__perceptualColor) {
  97156. return;
  97157. }
  97158. this._primaryColor.copyFrom(this.__perceptualColor);
  97159. // Revert gamma space.
  97160. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  97161. // Revert image processing configuration.
  97162. if (this._imageProcessingConfiguration) {
  97163. // Revert Exposure.
  97164. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  97165. }
  97166. this._computePrimaryColors();
  97167. };
  97168. /**
  97169. * Compute the highlights and shadow colors according to their chosen levels.
  97170. */
  97171. BackgroundMaterial.prototype._computePrimaryColors = function () {
  97172. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  97173. return;
  97174. }
  97175. // Find the highlight color based on the configuration.
  97176. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  97177. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  97178. // Find the shadow color based on the configuration.
  97179. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  97180. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  97181. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  97182. };
  97183. /**
  97184. * Build the uniform buffer used in the material.
  97185. */
  97186. BackgroundMaterial.prototype.buildUniformLayout = function () {
  97187. // Order is important !
  97188. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  97189. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  97190. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  97191. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  97192. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  97193. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  97194. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  97195. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  97196. this._uniformBuffer.addUniform("pointSize", 1);
  97197. this._uniformBuffer.addUniform("shadowLevel", 1);
  97198. this._uniformBuffer.addUniform("alpha", 1);
  97199. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  97200. this._uniformBuffer.addUniform("vReflectionControl", 4);
  97201. this._uniformBuffer.create();
  97202. };
  97203. /**
  97204. * Unbind the material.
  97205. */
  97206. BackgroundMaterial.prototype.unbind = function () {
  97207. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  97208. this._uniformBuffer.setTexture("diffuseSampler", null);
  97209. }
  97210. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  97211. this._uniformBuffer.setTexture("reflectionSampler", null);
  97212. }
  97213. _super.prototype.unbind.call(this);
  97214. };
  97215. /**
  97216. * Bind only the world matrix to the material.
  97217. * @param world The world matrix to bind.
  97218. */
  97219. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  97220. this._activeEffect.setMatrix("world", world);
  97221. };
  97222. /**
  97223. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  97224. * @param world The world matrix to bind.
  97225. * @param subMesh The submesh to bind for.
  97226. */
  97227. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  97228. var scene = this.getScene();
  97229. var defines = subMesh._materialDefines;
  97230. if (!defines) {
  97231. return;
  97232. }
  97233. var effect = subMesh.effect;
  97234. if (!effect) {
  97235. return;
  97236. }
  97237. this._activeEffect = effect;
  97238. // Matrices
  97239. this.bindOnlyWorldMatrix(world);
  97240. // Bones
  97241. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  97242. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  97243. if (mustRebind) {
  97244. this._uniformBuffer.bindToEffect(effect, "Material");
  97245. this.bindViewProjection(effect);
  97246. var reflectionTexture = this._reflectionTexture;
  97247. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  97248. // Texture uniforms
  97249. if (scene.texturesEnabled) {
  97250. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97251. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  97252. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  97253. }
  97254. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97255. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  97256. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  97257. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  97258. }
  97259. }
  97260. if (this.shadowLevel > 0) {
  97261. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  97262. }
  97263. this._uniformBuffer.updateFloat("alpha", this.alpha);
  97264. // Point size
  97265. if (this.pointsCloud) {
  97266. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  97267. }
  97268. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  97269. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  97270. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  97271. }
  97272. else {
  97273. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  97274. }
  97275. }
  97276. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  97277. // Textures
  97278. if (scene.texturesEnabled) {
  97279. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  97280. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  97281. }
  97282. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  97283. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  97284. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  97285. }
  97286. else if (!defines.REFLECTIONBLUR) {
  97287. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  97288. }
  97289. else {
  97290. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  97291. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  97292. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  97293. }
  97294. if (defines.REFLECTIONFRESNEL) {
  97295. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  97296. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  97297. }
  97298. }
  97299. }
  97300. // Clip plane
  97301. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  97302. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  97303. }
  97304. if (mustRebind || !this.isFrozen) {
  97305. if (scene.lightsEnabled) {
  97306. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  97307. }
  97308. // View
  97309. this.bindView(effect);
  97310. // Fog
  97311. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  97312. // image processing
  97313. this._imageProcessingConfiguration.bind(this._activeEffect);
  97314. }
  97315. this._uniformBuffer.update();
  97316. this._afterBind(mesh);
  97317. };
  97318. /**
  97319. * Dispose the material.
  97320. * @param forceDisposeEffect Force disposal of the associated effect.
  97321. * @param forceDisposeTextures Force disposal of the associated textures.
  97322. */
  97323. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  97324. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  97325. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  97326. if (forceDisposeTextures) {
  97327. if (this.diffuseTexture) {
  97328. this.diffuseTexture.dispose();
  97329. }
  97330. if (this.reflectionTexture) {
  97331. this.reflectionTexture.dispose();
  97332. }
  97333. }
  97334. this._renderTargets.dispose();
  97335. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  97336. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  97337. }
  97338. _super.prototype.dispose.call(this, forceDisposeEffect);
  97339. };
  97340. /**
  97341. * Clones the material.
  97342. * @param name The cloned name.
  97343. * @returns The cloned material.
  97344. */
  97345. BackgroundMaterial.prototype.clone = function (name) {
  97346. var _this = this;
  97347. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  97348. };
  97349. /**
  97350. * Serializes the current material to its JSON representation.
  97351. * @returns The JSON representation.
  97352. */
  97353. BackgroundMaterial.prototype.serialize = function () {
  97354. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97355. serializationObject.customType = "BABYLON.BackgroundMaterial";
  97356. return serializationObject;
  97357. };
  97358. /**
  97359. * Gets the class name of the material
  97360. * @returns "BackgroundMaterial"
  97361. */
  97362. BackgroundMaterial.prototype.getClassName = function () {
  97363. return "BackgroundMaterial";
  97364. };
  97365. /**
  97366. * Parse a JSON input to create back a background material.
  97367. * @param source The JSON data to parse
  97368. * @param scene The scene to create the parsed material in
  97369. * @param rootUrl The root url of the assets the material depends upon
  97370. * @returns the instantiated BackgroundMaterial.
  97371. */
  97372. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  97373. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  97374. };
  97375. /**
  97376. * Standard reflectance value at parallel view angle.
  97377. */
  97378. BackgroundMaterial.StandardReflectance0 = 0.05;
  97379. /**
  97380. * Standard reflectance value at grazing angle.
  97381. */
  97382. BackgroundMaterial.StandardReflectance90 = 0.5;
  97383. __decorate([
  97384. BABYLON.serializeAsColor3()
  97385. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  97386. __decorate([
  97387. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97388. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  97389. __decorate([
  97390. BABYLON.serializeAsColor3()
  97391. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  97392. __decorate([
  97393. BABYLON.serialize()
  97394. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  97395. __decorate([
  97396. BABYLON.serialize()
  97397. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  97398. __decorate([
  97399. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97400. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  97401. __decorate([
  97402. BABYLON.serializeAsTexture()
  97403. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  97404. __decorate([
  97405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97406. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  97407. __decorate([
  97408. BABYLON.serialize()
  97409. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  97410. __decorate([
  97411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97412. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  97413. __decorate([
  97414. BABYLON.serializeAsTexture()
  97415. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  97416. __decorate([
  97417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97418. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  97419. __decorate([
  97420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97421. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  97422. __decorate([
  97423. BABYLON.serialize()
  97424. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  97425. __decorate([
  97426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97427. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  97428. __decorate([
  97429. BABYLON.serializeAsVector3()
  97430. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  97431. __decorate([
  97432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97433. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  97434. __decorate([
  97435. BABYLON.serialize()
  97436. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  97437. __decorate([
  97438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97439. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  97440. __decorate([
  97441. BABYLON.serialize()
  97442. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  97443. __decorate([
  97444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97445. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  97446. __decorate([
  97447. BABYLON.serialize()
  97448. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  97449. __decorate([
  97450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97451. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  97452. __decorate([
  97453. BABYLON.serialize()
  97454. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  97455. __decorate([
  97456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97457. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  97458. __decorate([
  97459. BABYLON.serialize()
  97460. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  97461. __decorate([
  97462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97463. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  97464. __decorate([
  97465. BABYLON.serialize()
  97466. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  97467. __decorate([
  97468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97469. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  97470. __decorate([
  97471. BABYLON.serialize()
  97472. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  97473. __decorate([
  97474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97475. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  97476. __decorate([
  97477. BABYLON.serialize()
  97478. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  97479. __decorate([
  97480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97481. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  97482. __decorate([
  97483. BABYLON.serialize()
  97484. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  97485. __decorate([
  97486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97487. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  97488. __decorate([
  97489. BABYLON.serializeAsImageProcessingConfiguration()
  97490. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  97491. return BackgroundMaterial;
  97492. }(BABYLON.PushMaterial));
  97493. BABYLON.BackgroundMaterial = BackgroundMaterial;
  97494. })(BABYLON || (BABYLON = {}));
  97495. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  97496. var __assign = (this && this.__assign) || Object.assign || function(t) {
  97497. for (var s, i = 1, n = arguments.length; i < n; i++) {
  97498. s = arguments[i];
  97499. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  97500. t[p] = s[p];
  97501. }
  97502. return t;
  97503. };
  97504. var BABYLON;
  97505. (function (BABYLON) {
  97506. /**
  97507. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  97508. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  97509. * It also helps with the default setup of your imageProcessing configuration.
  97510. */
  97511. var EnvironmentHelper = /** @class */ (function () {
  97512. /**
  97513. * constructor
  97514. * @param options
  97515. * @param scene The scene to add the material to
  97516. */
  97517. function EnvironmentHelper(options, scene) {
  97518. var _this = this;
  97519. this._errorHandler = function (message, exception) {
  97520. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  97521. };
  97522. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  97523. this._scene = scene;
  97524. this.onErrorObservable = new BABYLON.Observable();
  97525. this._setupBackground();
  97526. this._setupImageProcessing();
  97527. }
  97528. /**
  97529. * Creates the default options for the helper.
  97530. */
  97531. EnvironmentHelper._getDefaultOptions = function () {
  97532. return {
  97533. createGround: true,
  97534. groundSize: 15,
  97535. groundTexture: this._groundTextureCDNUrl,
  97536. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97537. groundOpacity: 0.9,
  97538. enableGroundShadow: true,
  97539. groundShadowLevel: 0.5,
  97540. enableGroundMirror: false,
  97541. groundMirrorSizeRatio: 0.3,
  97542. groundMirrorBlurKernel: 64,
  97543. groundMirrorAmount: 1,
  97544. groundMirrorFresnelWeight: 1,
  97545. groundMirrorFallOffDistance: 0,
  97546. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  97547. groundYBias: 0.00001,
  97548. createSkybox: true,
  97549. skyboxSize: 20,
  97550. skyboxTexture: this._skyboxTextureCDNUrl,
  97551. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97552. backgroundYRotation: 0,
  97553. sizeAuto: true,
  97554. rootPosition: BABYLON.Vector3.Zero(),
  97555. setupImageProcessing: true,
  97556. environmentTexture: this._environmentTextureCDNUrl,
  97557. cameraExposure: 0.8,
  97558. cameraContrast: 1.2,
  97559. toneMappingEnabled: true,
  97560. };
  97561. };
  97562. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  97563. /**
  97564. * Gets the root mesh created by the helper.
  97565. */
  97566. get: function () {
  97567. return this._rootMesh;
  97568. },
  97569. enumerable: true,
  97570. configurable: true
  97571. });
  97572. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  97573. /**
  97574. * Gets the skybox created by the helper.
  97575. */
  97576. get: function () {
  97577. return this._skybox;
  97578. },
  97579. enumerable: true,
  97580. configurable: true
  97581. });
  97582. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  97583. /**
  97584. * Gets the skybox texture created by the helper.
  97585. */
  97586. get: function () {
  97587. return this._skyboxTexture;
  97588. },
  97589. enumerable: true,
  97590. configurable: true
  97591. });
  97592. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  97593. /**
  97594. * Gets the skybox material created by the helper.
  97595. */
  97596. get: function () {
  97597. return this._skyboxMaterial;
  97598. },
  97599. enumerable: true,
  97600. configurable: true
  97601. });
  97602. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  97603. /**
  97604. * Gets the ground mesh created by the helper.
  97605. */
  97606. get: function () {
  97607. return this._ground;
  97608. },
  97609. enumerable: true,
  97610. configurable: true
  97611. });
  97612. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  97613. /**
  97614. * Gets the ground texture created by the helper.
  97615. */
  97616. get: function () {
  97617. return this._groundTexture;
  97618. },
  97619. enumerable: true,
  97620. configurable: true
  97621. });
  97622. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  97623. /**
  97624. * Gets the ground mirror created by the helper.
  97625. */
  97626. get: function () {
  97627. return this._groundMirror;
  97628. },
  97629. enumerable: true,
  97630. configurable: true
  97631. });
  97632. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  97633. /**
  97634. * Gets the ground mirror render list to helps pushing the meshes
  97635. * you wish in the ground reflection.
  97636. */
  97637. get: function () {
  97638. if (this._groundMirror) {
  97639. return this._groundMirror.renderList;
  97640. }
  97641. return null;
  97642. },
  97643. enumerable: true,
  97644. configurable: true
  97645. });
  97646. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  97647. /**
  97648. * Gets the ground material created by the helper.
  97649. */
  97650. get: function () {
  97651. return this._groundMaterial;
  97652. },
  97653. enumerable: true,
  97654. configurable: true
  97655. });
  97656. /**
  97657. * Updates the background according to the new options
  97658. * @param options
  97659. */
  97660. EnvironmentHelper.prototype.updateOptions = function (options) {
  97661. var newOptions = __assign({}, this._options, options);
  97662. if (this._ground && !newOptions.createGround) {
  97663. this._ground.dispose();
  97664. this._ground = null;
  97665. }
  97666. if (this._groundMaterial && !newOptions.createGround) {
  97667. this._groundMaterial.dispose();
  97668. this._groundMaterial = null;
  97669. }
  97670. if (this._groundTexture) {
  97671. if (this._options.groundTexture != newOptions.groundTexture) {
  97672. this._groundTexture.dispose();
  97673. this._groundTexture = null;
  97674. }
  97675. }
  97676. if (this._skybox && !newOptions.createSkybox) {
  97677. this._skybox.dispose();
  97678. this._skybox = null;
  97679. }
  97680. if (this._skyboxMaterial && !newOptions.createSkybox) {
  97681. this._skyboxMaterial.dispose();
  97682. this._skyboxMaterial = null;
  97683. }
  97684. if (this._skyboxTexture) {
  97685. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  97686. this._skyboxTexture.dispose();
  97687. this._skyboxTexture = null;
  97688. }
  97689. }
  97690. if (this._groundMirror && !newOptions.enableGroundMirror) {
  97691. this._groundMirror.dispose();
  97692. this._groundMirror = null;
  97693. }
  97694. if (this._scene.environmentTexture) {
  97695. if (this._options.environmentTexture != newOptions.environmentTexture) {
  97696. this._scene.environmentTexture.dispose();
  97697. }
  97698. }
  97699. this._options = newOptions;
  97700. this._setupBackground();
  97701. this._setupImageProcessing();
  97702. };
  97703. /**
  97704. * Sets the primary color of all the available elements.
  97705. * @param color the main color to affect to the ground and the background
  97706. */
  97707. EnvironmentHelper.prototype.setMainColor = function (color) {
  97708. if (this.groundMaterial) {
  97709. this.groundMaterial.primaryColor = color;
  97710. }
  97711. if (this.skyboxMaterial) {
  97712. this.skyboxMaterial.primaryColor = color;
  97713. }
  97714. if (this.groundMirror) {
  97715. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  97716. }
  97717. };
  97718. /**
  97719. * Setup the image processing according to the specified options.
  97720. */
  97721. EnvironmentHelper.prototype._setupImageProcessing = function () {
  97722. if (this._options.setupImageProcessing) {
  97723. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  97724. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  97725. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  97726. this._setupEnvironmentTexture();
  97727. }
  97728. };
  97729. /**
  97730. * Setup the environment texture according to the specified options.
  97731. */
  97732. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  97733. if (this._scene.environmentTexture) {
  97734. return;
  97735. }
  97736. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  97737. this._scene.environmentTexture = this._options.environmentTexture;
  97738. return;
  97739. }
  97740. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  97741. this._scene.environmentTexture = environmentTexture;
  97742. };
  97743. /**
  97744. * Setup the background according to the specified options.
  97745. */
  97746. EnvironmentHelper.prototype._setupBackground = function () {
  97747. if (!this._rootMesh) {
  97748. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  97749. }
  97750. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  97751. var sceneSize = this._getSceneSize();
  97752. if (this._options.createGround) {
  97753. this._setupGround(sceneSize);
  97754. this._setupGroundMaterial();
  97755. this._setupGroundDiffuseTexture();
  97756. if (this._options.enableGroundMirror) {
  97757. this._setupGroundMirrorTexture(sceneSize);
  97758. }
  97759. this._setupMirrorInGroundMaterial();
  97760. }
  97761. if (this._options.createSkybox) {
  97762. this._setupSkybox(sceneSize);
  97763. this._setupSkyboxMaterial();
  97764. this._setupSkyboxReflectionTexture();
  97765. }
  97766. this._rootMesh.position.x = sceneSize.rootPosition.x;
  97767. this._rootMesh.position.z = sceneSize.rootPosition.z;
  97768. this._rootMesh.position.y = sceneSize.rootPosition.y;
  97769. };
  97770. /**
  97771. * Get the scene sizes according to the setup.
  97772. */
  97773. EnvironmentHelper.prototype._getSceneSize = function () {
  97774. var _this = this;
  97775. var groundSize = this._options.groundSize;
  97776. var skyboxSize = this._options.skyboxSize;
  97777. var rootPosition = this._options.rootPosition;
  97778. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  97779. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97780. }
  97781. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  97782. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  97783. });
  97784. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97785. if (this._options.sizeAuto) {
  97786. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  97787. this._scene.activeCamera.upperRadiusLimit) {
  97788. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  97789. skyboxSize = groundSize;
  97790. }
  97791. var sceneDiagonalLenght = sceneDiagonal.length();
  97792. if (sceneDiagonalLenght > groundSize) {
  97793. groundSize = sceneDiagonalLenght * 2;
  97794. skyboxSize = groundSize;
  97795. }
  97796. // 10 % bigger.
  97797. groundSize *= 1.1;
  97798. skyboxSize *= 1.5;
  97799. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  97800. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  97801. }
  97802. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97803. };
  97804. /**
  97805. * Setup the ground according to the specified options.
  97806. */
  97807. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  97808. var _this = this;
  97809. if (!this._ground) {
  97810. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  97811. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  97812. this._ground.parent = this._rootMesh;
  97813. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  97814. }
  97815. this._ground.receiveShadows = this._options.enableGroundShadow;
  97816. };
  97817. /**
  97818. * Setup the ground material according to the specified options.
  97819. */
  97820. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  97821. if (!this._groundMaterial) {
  97822. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  97823. }
  97824. this._groundMaterial.alpha = this._options.groundOpacity;
  97825. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  97826. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  97827. this._groundMaterial.primaryColor = this._options.groundColor;
  97828. this._groundMaterial.useRGBColor = false;
  97829. this._groundMaterial.enableNoise = true;
  97830. if (this._ground) {
  97831. this._ground.material = this._groundMaterial;
  97832. }
  97833. };
  97834. /**
  97835. * Setup the ground diffuse texture according to the specified options.
  97836. */
  97837. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  97838. if (!this._groundMaterial) {
  97839. return;
  97840. }
  97841. if (this._groundTexture) {
  97842. return;
  97843. }
  97844. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  97845. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  97846. return;
  97847. }
  97848. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97849. diffuseTexture.gammaSpace = false;
  97850. diffuseTexture.hasAlpha = true;
  97851. this._groundMaterial.diffuseTexture = diffuseTexture;
  97852. };
  97853. /**
  97854. * Setup the ground mirror texture according to the specified options.
  97855. */
  97856. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  97857. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97858. if (!this._groundMirror) {
  97859. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  97860. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  97861. this._groundMirror.anisotropicFilteringLevel = 1;
  97862. this._groundMirror.wrapU = wrapping;
  97863. this._groundMirror.wrapV = wrapping;
  97864. this._groundMirror.gammaSpace = false;
  97865. if (this._groundMirror.renderList) {
  97866. for (var i = 0; i < this._scene.meshes.length; i++) {
  97867. var mesh = this._scene.meshes[i];
  97868. if (mesh !== this._ground &&
  97869. mesh !== this._skybox &&
  97870. mesh !== this._rootMesh) {
  97871. this._groundMirror.renderList.push(mesh);
  97872. }
  97873. }
  97874. }
  97875. }
  97876. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  97877. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  97878. };
  97879. /**
  97880. * Setup the ground to receive the mirror texture.
  97881. */
  97882. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  97883. if (this._groundMaterial) {
  97884. this._groundMaterial.reflectionTexture = this._groundMirror;
  97885. this._groundMaterial.reflectionFresnel = true;
  97886. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  97887. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  97888. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  97889. }
  97890. };
  97891. /**
  97892. * Setup the skybox according to the specified options.
  97893. */
  97894. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  97895. var _this = this;
  97896. if (!this._skybox) {
  97897. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  97898. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  97899. }
  97900. this._skybox.parent = this._rootMesh;
  97901. };
  97902. /**
  97903. * Setup the skybox material according to the specified options.
  97904. */
  97905. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  97906. if (!this._skybox) {
  97907. return;
  97908. }
  97909. if (!this._skyboxMaterial) {
  97910. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  97911. }
  97912. this._skyboxMaterial.useRGBColor = false;
  97913. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  97914. this._skyboxMaterial.enableNoise = true;
  97915. this._skybox.material = this._skyboxMaterial;
  97916. };
  97917. /**
  97918. * Setup the skybox reflection texture according to the specified options.
  97919. */
  97920. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  97921. if (!this._skyboxMaterial) {
  97922. return;
  97923. }
  97924. if (this._skyboxTexture) {
  97925. return;
  97926. }
  97927. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  97928. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  97929. return;
  97930. }
  97931. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97932. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  97933. this._skyboxTexture.gammaSpace = false;
  97934. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  97935. };
  97936. /**
  97937. * Dispose all the elements created by the Helper.
  97938. */
  97939. EnvironmentHelper.prototype.dispose = function () {
  97940. if (this._groundMaterial) {
  97941. this._groundMaterial.dispose(true, true);
  97942. }
  97943. if (this._skyboxMaterial) {
  97944. this._skyboxMaterial.dispose(true, true);
  97945. }
  97946. this._rootMesh.dispose(false);
  97947. };
  97948. /**
  97949. * Default ground texture URL.
  97950. */
  97951. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  97952. /**
  97953. * Default skybox texture URL.
  97954. */
  97955. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  97956. /**
  97957. * Default environment texture URL.
  97958. */
  97959. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  97960. return EnvironmentHelper;
  97961. }());
  97962. BABYLON.EnvironmentHelper = EnvironmentHelper;
  97963. })(BABYLON || (BABYLON = {}));
  97964. //# sourceMappingURL=babylon.environmentHelper.js.map
  97965. var BABYLON;
  97966. (function (BABYLON) {
  97967. /**
  97968. * This class is made for on one-liner static method to help creating particle systems.
  97969. */
  97970. var ParticleHelper = /** @class */ (function () {
  97971. function ParticleHelper() {
  97972. }
  97973. /**
  97974. * This is the main static method (one-liner) of this helper to create different particle systems.
  97975. * @param type This string represents the type to the particle system to create
  97976. * @param emitter The object where the particle system will start to emit from.
  97977. * @param scene The scene where the particle system should live.
  97978. * @param gpu If the system will use gpu.
  97979. * @returns the ParticleSystem created.
  97980. */
  97981. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  97982. var _this = this;
  97983. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  97984. if (gpu === void 0) { gpu = false; }
  97985. return new Promise(function (resolve, reject) {
  97986. if (scene) {
  97987. _this._scene = scene;
  97988. }
  97989. else {
  97990. return reject("A particle system need a scene.");
  97991. }
  97992. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  97993. return reject("Particle system with GPU is not supported.");
  97994. }
  97995. _this._emitter = emitter;
  97996. BABYLON.Tools.LoadFile(_this._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  97997. var newData = JSON.parse(data.toString());
  97998. return resolve(_this._createSystem(newData));
  97999. }, undefined, undefined, undefined, function (req, exception) {
  98000. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  98001. });
  98002. });
  98003. };
  98004. ParticleHelper._createSystem = function (data) {
  98005. // Create a particle system
  98006. var system = new BABYLON.ParticleSystem(data.type, data.capacity, this._scene);
  98007. // Texture of each particle
  98008. system.particleTexture = new BABYLON.Texture(this._baseAssetsUrl + "/textures/" + data.textureFile, this._scene);
  98009. // Where the particles come from
  98010. system.emitter = this._emitter; // the starting object, the emitter
  98011. // Colors of all particles
  98012. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  98013. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  98014. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  98015. // Size of each particle (random between...
  98016. system.minSize = data.minSize;
  98017. system.maxSize = data.maxSize;
  98018. // Life time of each particle (random between...
  98019. system.minLifeTime = data.minLifeTime;
  98020. system.maxLifeTime = data.maxLifeTime;
  98021. // Emission rate
  98022. system.emitRate = data.emitRate;
  98023. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  98024. system.blendMode = data.blendMode;
  98025. // Set the gravity of all particles
  98026. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  98027. // Angular speed, in radians
  98028. system.minAngularSpeed = data.minAngularSpeed;
  98029. system.maxAngularSpeed = data.maxAngularSpeed;
  98030. // Speed
  98031. system.minEmitPower = data.minEmitPower;
  98032. system.maxEmitPower = data.maxEmitPower;
  98033. system.updateSpeed = data.updateSpeed;
  98034. switch (data.emitterType) {
  98035. case "box":
  98036. if (!data.direction1 || !data.direction2) {
  98037. throw new Error("Directions are missing in this particle system.");
  98038. }
  98039. if (!data.minEmitBox || !data.maxEmitBox) {
  98040. throw new Error("EmitBox is missing in this particle system.");
  98041. }
  98042. system.createBoxEmitter(new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z), new BABYLON.Vector3(data.minEmitBox.x, data.minEmitBox.y, data.minEmitBox.z), new BABYLON.Vector3(data.maxEmitBox.x, data.maxEmitBox.y, data.maxEmitBox.z));
  98043. break;
  98044. case "sphere":
  98045. system.createSphereEmitter(data.radius);
  98046. break;
  98047. case "directed_sphere":
  98048. if (!data.direction1 || !data.direction2) {
  98049. throw new Error("Directions are missing in this particle system.");
  98050. }
  98051. system.createDirectedSphereEmitter(data.radius, new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z));
  98052. break;
  98053. case "cone":
  98054. system.createConeEmitter(data.radius, data.angle);
  98055. break;
  98056. default:
  98057. break;
  98058. }
  98059. return system;
  98060. };
  98061. /**
  98062. * Base Assets URL.
  98063. */
  98064. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  98065. return ParticleHelper;
  98066. }());
  98067. BABYLON.ParticleHelper = ParticleHelper;
  98068. })(BABYLON || (BABYLON = {}));
  98069. //# sourceMappingURL=babylon.particleHelper.js.map
  98070. var BABYLON;
  98071. (function (BABYLON) {
  98072. /**
  98073. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  98074. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  98075. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  98076. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  98077. */
  98078. var VideoDome = /** @class */ (function (_super) {
  98079. __extends(VideoDome, _super);
  98080. /**
  98081. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  98082. * @param name Element's name, child elements will append suffixes for their own names.
  98083. * @param urlsOrVideo
  98084. * @param options An object containing optional or exposed sub element properties:
  98085. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  98086. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  98087. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  98088. * @param options **loop=true** Automatically loop video on end.
  98089. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  98090. */
  98091. function VideoDome(name, urlsOrVideo, options, scene) {
  98092. var _this = _super.call(this, name, scene) || this;
  98093. // set defaults and manage values
  98094. name = name || "videoDome";
  98095. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  98096. options.clickToPlay = Boolean(options.clickToPlay);
  98097. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  98098. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  98099. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  98100. // create
  98101. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  98102. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  98103. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  98104. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  98105. flat: false,
  98106. radius: options.size,
  98107. subdivisions: options.resolution,
  98108. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  98109. }, scene);
  98110. // configure material
  98111. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  98112. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  98113. material.reflectionTexture = _this._videoTexture;
  98114. material.useEquirectangularFOV = true;
  98115. material.fovMultiplier = 1.0;
  98116. // configure mesh
  98117. _this._mesh.material = material;
  98118. _this._mesh.parent = _this;
  98119. // optional configuration
  98120. if (options.clickToPlay) {
  98121. scene.onPointerUp = function () {
  98122. _this._videoTexture.video.play();
  98123. };
  98124. }
  98125. return _this;
  98126. }
  98127. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  98128. /**
  98129. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  98130. * Also see the options.resolution property.
  98131. */
  98132. get: function () {
  98133. return this._material.fovMultiplier;
  98134. },
  98135. set: function (value) {
  98136. this._material.fovMultiplier = value;
  98137. },
  98138. enumerable: true,
  98139. configurable: true
  98140. });
  98141. /**
  98142. * Releases resources associated with this node.
  98143. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  98144. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  98145. */
  98146. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  98147. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  98148. this._videoTexture.dispose();
  98149. this._mesh.dispose();
  98150. this._material.dispose();
  98151. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  98152. };
  98153. return VideoDome;
  98154. }(BABYLON.Node));
  98155. BABYLON.VideoDome = VideoDome;
  98156. })(BABYLON || (BABYLON = {}));
  98157. //# sourceMappingURL=babylon.videoDome.js.map
  98158. 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(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=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; \nvec2 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\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); \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;\nin vec2 angle;\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);\nvec2 cornerPos=offset*size;\n\nvec4 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.z=0.;\nrotatedCorner.w=0.;\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+rotatedCorner);\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;\nuniform vec2 angleRange;\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 coneAngle;\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;\nin vec2 angle;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nout vec2 outAngle;\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;\noutAngle=angle;\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\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=0.;\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 (coneAngle == 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;\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\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;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\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"};
  98159. 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 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  98160. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  98161. globalObject["BABYLON"] = BABYLON;
  98162. //backwards compatibility
  98163. if(typeof earcut !== 'undefined') {
  98164. globalObject["Earcut"] = {
  98165. earcut: earcut
  98166. };
  98167. }
  98168. return BABYLON;
  98169. });